Delete default route via WinAPI - winapi

I would like to implement deletion of the default route via WinAPI:
route delete 0.0.0.0
It looks like route is doing via undocumented Nsi* calls. Is there an easier way to do that?

DeleteIpForwardEntry does the trick:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
// Execute as admin
int main()
{
ULONG size = 10000;
PMIB_IPFORWARDTABLE table = (PMIB_IPFORWARDTABLE)malloc(size);
memset(table, 0, size);
GetIpForwardTable(table,&size,true);
for (int i = 0; i < (int) table->dwNumEntries; i++) {
// Default route 0.0.0.0
if(table->table[i].dwForwardDest == 0)
{
DWORD ret = DeleteIpForwardEntry(&table->table[i]);
printf("Ret: %X\n", ret);
break;
}
}
return 0;
}

Related

How can I decrypt a string using CryptUnprotectData

I have been trying to decrypt some encrypted data (AES key encrypting chrome cookies) via the c++ CryptUnprotectData function for a short while now, but I cant seem to get it working. Currently the function will fail and return an error code of 13 (meaning "The parameter is incorrect."). Here is my code so far:
#include <iostream>
#include <Windows.h>
#include <wincrypt.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
std::string GetLastErrorAsString()
{
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string();
}
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
int main()
{
string data = "(data I want to decode)";
cout << data;
DATA_BLOB DataBytes;
DataBytes.pbData = (BYTE*)data.data();
DataBytes.cbData = (DWORD)data.size()+1;
DATA_BLOB output;
output.pbData = NULL;
output.cbData = (DWORD)data.size();
CryptUnprotectData(&DataBytes, NULL, NULL, NULL, NULL, 0, &output);
cout << GetLastErrorAsString() << endl;
cout << output.pbData;
LocalFree(output.pbData);
return 0;
}
If anyone can provide any help, that would be greatly appreciated.
I have tried different variations of the data types the parameters are stored in, although it still returns this error.
I modified your code, which is as follows. It only implements simple decryption.
And the data is not encrypted, so CryptUnprotectData() does not return the correct value.
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#pragma comment (lib, "Crypt32.lib")
int main()
{
// Decrypt data from DATA_BLOB DataOut to DATA_BLOB DataVerify.
//--------------------------------------------------------------------
// Declare and initialize variables.
string data = ("data I want to decode \n");
cout << data;
LPWSTR pDescrOut = NULL;
DATA_BLOB DataBytes;
BYTE* pbDataOutput = (BYTE*)data.data();
DWORD cbDataOutput = strlen((char*)pbDataOutput) + 1;
DataBytes.pbData = pbDataOutput;
DataBytes.cbData = cbDataOutput;
//DATA_BLOB DataVerify;
//--------------------------------------------------------------------
// The buffer DataOut would be created using the CryptProtectData
// function. If may have been read in from a file.
//--------------------------------------------------------------------
// Begin unprotect phase.
BOOL res = CryptUnprotectData(
&DataBytes,
&pDescrOut,
NULL, // Optional entropy
NULL, // Reserved
NULL, // Here, the optional
// prompt structure is not
// used.
0,
&DataBytes);
if (res==1)
{
printf("The decrypted data is: %s\n", DataBytes.pbData);
printf("The description of the data was: %s\n", pDescrOut);
}
else
{
printf("Decryption error!");
}
// LocalFree(DataVerify.pbData);
LocalFree(pDescrOut);
//LocalFree(DataBytes.pbData);
}
It is recommended to refer to Microsoft's official documentation when you add additional code.

ipref3 dll for windows

I try to build ipref3.dll for windows
I found How to compile iperf3 for Windows
Built it but i got only iperf3.exe and libiperf.a
I found, how create dll manual
gcc -s -shared -o iperf3.dll units.o timer.o tcp_window_size.o tcp_info.o net.o iperf_util.o iperf_sctp.o iperf_udp.o iperf_tcp.o iperf_server_api.o iperf_locale.o iperf_client_api.o iperf_error.o iperf_api.o cjson.o -Wl,--enable-auto-import,--export-all-symbols,--subsystem,windows
after i found how need to initialize
HMODULE h = LoadLibrary(TEXT("cygwin1.dll"));
PFN_CYGWIN_DLL_INIT init = (PFN_CYGWIN_DLL_INIT)GetProcAddress(h, "cygwin_dll_init");
init();
Now i can load dll and make initialization but when i start test iperf_run_client application is crashed
Unhandled exception at 0x611537C0 (cygwin1.dll) in iprerf-server.exe:
0xC0000005: Access violation reading location 0x00740000.
How can solve this problem?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <WinSock2.h>
//#include <unistd.h>
#include <string.h>
//#include <sysexits.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include "iperf_api.h"
#ifdef WIN64
#pragma comment(lib, "iperf3_64.lib")
#else
#pragma comment(lib, "iperf3.lib")
#endif
#pragma comment(lib, "ws2_32.lib")
typedef void *register_frame();
typedef int *hello_f();
typedef int(*PFN_HELLO)();
typedef void(*PFN_CYGWIN_DLL_INIT)();
#pragma pack(push, 1)
int main(int argc, char** argv)
{
WSADATA wsaData;
int wsaErr = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (wsaErr != 0) {
printf("WSAStartup failed with error: %d\n", wsaErr);
return 1;
}
//PFN_HELLO fnHello;
HMODULE /*hLib, */h = LoadLibrary(TEXT("cygwin1.dll"));
PFN_CYGWIN_DLL_INIT init = (PFN_CYGWIN_DLL_INIT)GetProcAddress(h, "cygwin_dll_init");
init();
char* argv0;
char* host;
int port;
struct iperf_test *test;
argv0 = strrchr(argv[0], '/');
if (argv0 != (char*)0)
++argv0;
else
argv0 = argv[0];
if (argc != 3) {
fprintf(stderr, "usage: %s [host] [port]\n", argv0);
exit(EXIT_FAILURE);
}
host = argv[1];
port = atoi(argv[2]);
test = iperf_new_test();
if (test == NULL) {
fprintf(stderr, "%s: failed to create test\n", argv0);
exit(EXIT_FAILURE);
}
iperf_defaults(test);
iperf_set_verbose(test, 1);
iperf_set_test_role(test, 'c');
iperf_set_test_server_hostname(test, host);
iperf_set_test_server_port(test, port);
/* iperf_set_test_reverse( test, 1 ); */
iperf_set_test_omit(test, 3);
iperf_set_test_duration(test, 5);
iperf_set_test_reporter_interval(test, 1);
iperf_set_test_stats_interval(test, 1);
/* iperf_set_test_json_output( test, 1 ); */
if (iperf_run_client(test) < 0) {
fprintf(stderr, "%s: error - %s\n", argv0, iperf_strerror(i_errno));
exit(EXIT_FAILURE);
}
if (iperf_get_test_json_output_string(test)) {
fprintf(iperf_get_test_outfile(test), "%zd bytes of JSON emitted\n",
strlen(iperf_get_test_json_output_string(test)));
}
iperf_free_test(test);
exit(EXIT_SUCCESS);
}
The reason why the shared lib is not built is:
libtool: warning: undefined symbols not allowed in x86_64-unknown-cygwin
shared libraries; building static only
the easy way to bypass it, in a clean build is to use:
$ make libiperf_la_LIBADD="-no-undefined"
The build will include the shared libray and the import library
$ find . -name "*dll*"
./src/.libs/cygiperf-0.dll
./src/.libs/libiperf.dll.a
For what I see to make a build on cygwin is also needed to remove a definition
in src/iperf_config.h after running configure
/* #define HAVE_SETPROCESSAFFINITYMASK 1 */
PS #1: iperf-2.0.5-1 is available as cygwin package
PS #2: your code is Windows-like while Cygwin is a Unix-like system, you can not mix them
I found solution
1) It need to create addition dll: my_crt0.dll
#include <sys/cygwin.h>
#include <stdlib.h>
typedef int (*MainFunc) (int argc, char *argv[], char **env);
void my_crt0 (MainFunc f)
{
cygwin_crt0(f);
}
gcc -c my_crt0.c
gcc -o my_crt0.dll my_crt0.o -s -shared -Wl,--subsystem,windows,--enable-auto-import,--export-all-symbols,--out-implib,my_crt0.lib
2) Modify main code
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <WinSock2.h>
#include <string.h>
#include "iperf_api.h"
#pragma comment(lib, "iperf3.lib")
#pragma comment(lib, "ws2_32.lib")
typedef int(*MainFunc) (int argc, char *argv[], char **env);
typedef void(*my_crt0)(MainFunc f);
int main2(int argc, char** argv, char **env)
{
char* argv0;
char* host;
int port;
struct iperf_test *test;
host = (char*)"127.0.0.1";
port = 4000;
test = iperf_new_test();
if (test == NULL) {
exit(EXIT_FAILURE);
}
iperf_defaults(test);
iperf_set_verbose(test, 1);
iperf_set_test_role(test, 'c');
iperf_set_test_server_hostname(test, host);
iperf_set_test_server_port(test, port);
/* iperf_set_test_reverse( test, 1 ); */
iperf_set_test_omit(test, 3);
iperf_set_test_duration(test, 5);
iperf_set_test_reporter_interval(test, 1);
iperf_set_test_stats_interval(test, 1);
/* iperf_set_test_json_output( test, 1 ); */
iperf_strerror(0);
if (iperf_run_client(test) < 0) {
fprintf(stderr, "%s: error - %s\n", argv0, iperf_strerror(i_errno));
exit(EXIT_FAILURE);
}
if (iperf_get_test_json_output_string(test)) {
fprintf(iperf_get_test_outfile(test), "%zd bytes of JSON emitted\n",
strlen(iperf_get_test_json_output_string(test)));
}
iperf_free_test(test);
exit(EXIT_SUCCESS);
return 1;
}
int main(int argc, char** argv)
{
WSADATA wsaData;
int wsaErr = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (wsaErr != 0) {
printf("WSAStartup failed with error: %d\n", wsaErr);
return 1;
}
{
HMODULE /*hLib, */h = LoadLibrary(TEXT("my_crt0.dll"));
my_crt0 init = (my_crt0)GetProcAddress(h, "my_crt0");
init(main2);
}
exit(EXIT_SUCCESS);
}
Now it compiled and worked to VS 2015

dcmtk display image Qt example

I would like to be able to display in a Dicom image in a Qt project with the same render as a Dicom Viewer Program could give.
I was able to do it but with a very bad contrast. I heard you need to operate on the pixels but I'm not sure. Do you have a working example ?
EDIT: I add my code in case it helps you, I commented a lot of things because I noticed the result was exactly the same
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#undef UNICODE
#undef _UNICODE
#include <dcmtk/config/osconfig.h>
#include <dcmtk/dcmdata/dctk.h>
#include <dcmtk/dcmimgle/dcmimage.h>
#include <QPixmap>
#include <QLabel>
#include <QImageReader>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//int sizeX = 600;
// int sizeY = 600;
//initialize random seed
//srand (time(NULL));
//QImage image = QImage( sizeX, sizeY, QImage::Format_RGB32 );
/*for( int l=0; l<sizeX; l++ )
{
for( int c=0; c<sizeY; c++ )
{
///Random color for each pixel
//image.setPixel( l, c, qRgb(rand() % 256, rand() % 256, rand() % 256) );
///Fixed color for each pixel
image.setPixel( l, c, qRgb(100, 150, 200) );
}
}*/
const char *file = "/home/x4rkz/project/Laura/QTImage/IMG00000";
DicomImage *image = new DicomImage(file);
if (image != NULL)
{
if (image->getStatus() == EIS_Normal)
{
Uint8 *pixelData = (Uint8 *)(image->getOutputData(8 )); // bits per sample
// Uint8 is a pointer to internal memory buffer
if (pixelData != NULL)
{
// do something useful with the pixel data
QImage img(pixelData,image->getWidth(), image->getHeight(), QImage::Format_Indexed8 );
/*QColor color;
QImage *img;
void *pDicomDibits;
uchar *px;
// uchar pixel[4];
const int width = (int)(image->getWidth());
const int height = (int)(image->getHeight());
if (image->isMonochrome()){
img = new QImage(width, height, QImage::Format_Indexed8);
img->setColorCount(256);
// define gray palette here
for (int i=0; i<256; i++) {
color.setRgb(i, i, i);
img->setColor(i, color.rgb());
}
image->createWindowsDIB(pDicomDibits, 0, 0, 8, 0, 1);
unsigned char * pd;
pd=(unsigned char *)pDicomDibits;
for (int y=0; y < (long) height; y++)
{
px = img->scanLine(y);
for (int x=0; x < (long) width; x++)
{
px[x] = (unsigned char) (*pd);
pd++;
}
}*/
QGraphicsScene * graphic = new QGraphicsScene( this );
graphic->addPixmap( QPixmap::fromImage( img ) );
ui->graphicsView->setScene(graphic);
/* }else
cout << "Non monochrome image" << endl;*/
}
} else
cerr << "Error: cannot load DICOM image (" << DicomImage::getString(image->getStatus()) << ")" << endl;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
#include "mainwindow.h"
#include <QApplication>
#include <iostream>
#undef UNICODE
#undef _UNICODE
#include <dcmtk/config/osconfig.h>
#include <dcmtk/dcmdata/dctk.h>
#include <dcmtk/dcmimgle/dcmimage.h>
#include <QPixmap>
#include <QLabel>
#include <QImageReader>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
As you cant see, the result has no constrast.
As you cant see, the result has no constrast.
If the rendered image has such a low contrast, you should try to set an appropriate VOI (Value of Interest) window, e.g. using image->setMinMaxWndow(). See API documentation for details.

register_kretprobe fails with a return value of -2

I have written a kretprobe to hook on to the randomize_stack_top() function mentioned in fs/binfmt_elf.c file. On loading the LKM with insmod the register_kretprobe() call fails with a return value of -2. How do I go about debugging/rectifying that in order to get my module started ?
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kprobes.h>
#include <linux/binfmts.h>
#include <linux/elf.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/current.h>
#include <asm/param.h>
/* Global variables */
int randomize_stack_retval;
// randomize_stack_top() kretprobe specific declarations
static char stack_name[NAME_MAX] = "randomize_stack_top";
static int randomize_stack_top_entry_handler(struct kretprobe_instance *ri, struct pt_regs *regs)
{
return 0;
}
static int randomize_stack_top_ret_handler(struct kretprobe_instance *ri, struct pt_regs *regs)
{
randomize_stack_retval = regs_return_value(regs); //store in global variable
printk(KERN_INFO "%d\n",randomize_stack_retval);
return 0;
}
//randomize_stack_top return probe
static struct kretprobe randomize_kretprobe = {
.handler = randomize_stack_top_ret_handler,
.entry_handler = randomize_stack_top_entry_handler,
.maxactive = NR_CPUS,
};
/* Register kretprobe */
static int __init kretprobe_init(void)
{
int ret;
randomize_kretprobe.kp.symbol_name = stack_name;
ret = register_kretprobe(&randomize_kretprobe);
if (ret < 0) {
printk(KERN_INFO "register_kretprobe failed, returned %d\n",
ret);
return -1;
}
printk(KERN_INFO "Planted return probe at %s: %p\n",
randomize_kretprobe.kp.symbol_name, randomize_kretprobe.kp.addr);
return 0;
}
/* Unregister kretprobe */
static void __exit kretprobe_exit(void)
{
unregister_kretprobe(&randomize_kretprobe);
printk(KERN_INFO "kretprobe at %p unregistered\n",
randomize_kretprobe.kp.addr);
// nmissed > 0 suggests that maxactive was set too low.
printk(KERN_INFO "Missed probing %d instances of %s\n",
randomize_kretprobe.nmissed, randomize_kretprobe.kp.symbol_name);
}
module_init(kretprobe_init);
module_exit(kretprobe_exit);
MODULE_LICENSE("GPL");
-2 corresponds to -ENOENT (you can check that in include/uapi/asm-generic/errno-base.h). Probably, it means that kprobe cannot find symbol with given name.
Note, that randomize_stack_top is static function with a short implementation and it is used only once. So it can be inlined by the gcc.

Multicast problem on Windows XP

I'm testing out multicast with the two programs below. The client run well on linux and in wine on two of my machines, but it won't work properly on my windows machine (in Virtualbox).
Strangely, if I start up vlc in windows and open the udp stream, the client program receives the packets - and when I stop vlc, the client goes silent again.
What am I doing wrong?
Here is the the server program:
/*
* server.c - multicast server program.
*/
#include <sys/types.h>
#ifdef WINDOWS
#include <winsock.h>
#include <windows.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <time.h>
#include <string.h>
#include <stdio.h>
#define HELLO_PORT 5004
#define HELLO_GROUP "224.0.0.1"
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd, cnt, numbytes;
struct ip_mreq mreq;
char message[100];
#ifdef WINDOWS
WSADATA wsaData; /* Windows socket DLL structure */
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
fprintf(stderr, "WSAStartup() failed");
return 1;
}
#endif
/* create what looks like an ordinary UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "failed to create socket.\n");
return 1;
}
/* set up destination address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(HELLO_GROUP);
addr.sin_port = htons(HELLO_PORT);
/* now just sendto() our destination! */
cnt = 0;
while (1) {
numbytes = sprintf(message, "%d", cnt);
if (sendto(fd, message, numbytes, 0, (struct sockaddr*)&addr,
sizeof(addr)) < 0) {
fprintf(stderr, "sendto failed.\n");
return 1;
}
#ifdef WINDOWS
Sleep(1000);
#else
sleep(1);
#endif
cnt++;
}
return 0;
}
and here's the client program:
/*
* client.c -- client program for udp multicast data.
*/
#include <sys/types.h>
#ifdef WINDOWS
#include <winsock.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <time.h>
#include <string.h>
#include <stdio.h>
#define HELLO_GROUP "224.0.0.1"
#define HELLO_PORT 5004
#define MSGBUFSIZE 256
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd, nbytes,addrlen;
struct ip_mreq mreq;
char msgbuf[MSGBUFSIZE];
u_int yes = 1;
#ifdef WINDOWS
WSADATA wsaData; /* Windows socket DLL structure */
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
fprintf(stderr, "WSAStartup() failed");
return 1;
}
#endif
/* create what looks like an ordinary UDP socket */
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
fprintf(stderr, "failed to create socket.\n");
return 1;
}
/* allow multiple sockets to use the same PORT number */
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes)) != 0) {
fprintf(stderr, "failed to reuse port number.\n");
return 1;
}
/* set up destination address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(HELLO_PORT);
/* bind to receive address */
if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
fprintf(stderr, "failed to bind socket.\n");
return 1;
}
/* use setsockopt() to request that the kernel join a multicast group */
mreq.imr_multiaddr.s_addr = inet_addr(HELLO_GROUP);
mreq.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) != 0) {
fprintf(stderr, "failed to join the multicast group.\n");
return 1;
}
/* now just enter a read-print loop */
while (1) {
addrlen = sizeof(addr);
nbytes = recvfrom(fd, msgbuf, MSGBUFSIZE, 0,
(struct sockaddr*)&addr, &addrlen);
if (nbytes < 0) {
fprintf(stderr, "recfrom failed, %d\n", nbytes);
return 1;
}
msgbuf[nbytes] = '\0';
puts(msgbuf);
}
return 0;
}
Thanks,
Oskar
Ok, so apparently the firewall blocked the packets. Turning it off fixes the issue.

Resources