├── nc.exe ├── readme.rodneybeede.txt ├── makefile ├── makewin.cmd ├── getopt.h ├── readme.txt ├── generic.h ├── README ├── doexec.c ├── license.txt ├── getopt.c └── hobbit.txt /nc.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/diegocr/netcat/HEAD/nc.exe -------------------------------------------------------------------------------- /readme.rodneybeede.txt: -------------------------------------------------------------------------------- 1 | This version was compiled without the -e (GAPING_SECURITY_HOLE) option which can trigger anti-virus programs false positives. 2 | 3 | 4 | makewin.cmd is the script that was used to compile. 5 | 6 | 7 | Build Environment: 8 | Gcc 3.4.5 (MinGW version 5.1.4) 9 | Windows 7 Ultimate 64-bit RC build 7100 10 | 11 | 12 | Original NT version comes from http://joncraton.org/blog/46#disqus_thread 13 | 14 | 15 | Rodney Beede 16 | http://www.rodneybeede.com/ 17 | contactme@rodneybeede.com -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | 2 | cc=cl 3 | link=link 4 | 5 | cflags=/nologo /ML /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "TELNET" /D "GAPING_SECURITY_HOLE" /YX /FD /c 6 | lflags=kernel32.lib user32.lib wsock32.lib winmm.lib /nologo /subsystem:console /incremental:yes /machine:I386 /out:nc.exe 7 | 8 | all: nc.exe 9 | 10 | getopt.obj: getopt.c 11 | $(cc) $(cflags) getopt.c 12 | 13 | doexec.obj: doexec.c 14 | $(cc) $(cflags) doexec.c 15 | 16 | netcat.obj: netcat.c 17 | $(cc) $(cflags) netcat.c 18 | 19 | 20 | nc.exe: getopt.obj doexec.obj netcat.obj 21 | $(link) getopt.obj doexec.obj netcat.obj $(lflags) 22 | -------------------------------------------------------------------------------- /makewin.cmd: -------------------------------------------------------------------------------- 1 | @REM Build script to compile Netcat on WIN32 using MinGW 2 | @REM 3 | @REM Rodney Beede (http://www.rodneybeede.com) 4 | @REM 5 | @REM 2009-09-02 6 | @REM 7 | @REM Tested with gcc 3.4.5 and MinGW version 5.1.4 8 | @REM 9 | @REM [[ diegocr ]] 10 | @REM 11 | @REM 2010-12-14 12 | @REM 13 | @REM Tested with gcc 4.5.0 and MinGW version 3.1.8(?) 14 | @REM Added more compiler options and strip usage 15 | @echo off 16 | 17 | SET PROGRAM=nc.exe 18 | SET PCOPY=COPY /Y %PROGRAM% c:\windows\system32 19 | 20 | SET COMPILER=c:\MinGW\bin\gcc.exe 21 | SET STRIP=c:\MinGW\bin\strip.exe 22 | SET LIB_DIR=c:\MinGW\lib 23 | 24 | @REM not needed? SET CFLAGS=-c -DWIN32 -DNDEBUG -D_CONSOLE -DTELNET 25 | SET XFLAGS=-O3 -march=i686 26 | SET CFLAGS=-c %XFLAGS% -DTELNET 27 | SET LFLAGS=%XFLAGS% 28 | 29 | del *.o 30 | del nc.exe 31 | 32 | "%COMPILER%" %CFLAGS% getopt.c 33 | 34 | "%COMPILER%" %CFLAGS% doexec.c 35 | 36 | "%COMPILER%" %CFLAGS% netcat.c 37 | 38 | @REM Note that the -l libraries MUST come at the very end or linking will fail 39 | "%COMPILER%" getopt.o doexec.o netcat.o -o %PROGRAM% %LFLAGS% -Wl,-L"%LIB_DIR%",-lkernel32,-luser32,-lwinmm,-lws2_32 40 | "%STRIP%" -s %PROGRAM% 41 | %PCOPY% 42 | 43 | echo Operation Completed 44 | -------------------------------------------------------------------------------- /getopt.h: -------------------------------------------------------------------------------- 1 | /* Declarations for getopt. 2 | Copyright (C) 1989, 90, 91, 92, 93, 94 Free Software Foundation, Inc. 3 | 4 | This file is part of the GNU C Library. Its master source is NOT part of 5 | the C library, however. The master source lives in /gd/gnu/lib. 6 | 7 | The GNU C Library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Library General Public License as 9 | published by the Free Software Foundation; either version 2 of the 10 | License, or (at your option) any later version. 11 | 12 | The GNU C Library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Library General Public License for more details. 16 | 17 | You should have received a copy of the GNU Library General Public 18 | License along with the GNU C Library; see the file COPYING.LIB. If 19 | not, write to the Free Software Foundation, Inc., 675 Mass Ave, 20 | Cambridge, MA 02139, USA. */ 21 | 22 | #ifndef _GETOPT_H 23 | #define _GETOPT_H 1 24 | 25 | #ifdef __cplusplus 26 | extern "C" { 27 | #endif 28 | 29 | /* For communication from `getopt' to the caller. 30 | When `getopt' finds an option that takes an argument, 31 | the argument value is returned here. 32 | Also, when `ordering' is RETURN_IN_ORDER, 33 | each non-option ARGV-element is returned here. */ 34 | 35 | extern char *optarg; 36 | 37 | /* Index in ARGV of the next element to be scanned. 38 | This is used for communication to and from the caller 39 | and for communication between successive calls to `getopt'. 40 | 41 | On entry to `getopt', zero means this is the first call; initialize. 42 | 43 | When `getopt' returns EOF, this is the index of the first of the 44 | non-option elements that the caller should itself scan. 45 | 46 | Otherwise, `optind' communicates from one call to the next 47 | how much of ARGV has been scanned so far. */ 48 | 49 | extern int optind; 50 | 51 | /* Callers store zero here to inhibit the error message `getopt' prints 52 | for unrecognized options. */ 53 | 54 | extern int opterr; 55 | 56 | /* Set to an option character which was unrecognized. */ 57 | 58 | extern int optopt; 59 | 60 | /* Describe the long-named options requested by the application. 61 | The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector 62 | of `struct option' terminated by an element containing a name which is 63 | zero. 64 | 65 | The field `has_arg' is: 66 | no_argument (or 0) if the option does not take an argument, 67 | required_argument (or 1) if the option requires an argument, 68 | optional_argument (or 2) if the option takes an optional argument. 69 | 70 | If the field `flag' is not NULL, it points to a variable that is set 71 | to the value given in the field `val' when the option is found, but 72 | left unchanged if the option is not found. 73 | 74 | To have a long-named option do something other than set an `int' to 75 | a compiled-in constant, such as set a value from `optarg', set the 76 | option's `flag' field to zero and its `val' field to a nonzero 77 | value (the equivalent single-letter option character, if there is 78 | one). For long options that have a zero `flag' field, `getopt' 79 | returns the contents of the `val' field. */ 80 | 81 | struct option 82 | { 83 | #if defined (__STDC__) && __STDC__ 84 | const char *name; 85 | #else 86 | char *name; 87 | #endif 88 | /* has_arg can't be an enum because some compilers complain about 89 | type mismatches in all the code that assumes it is an int. */ 90 | int has_arg; 91 | int *flag; 92 | int val; 93 | }; 94 | 95 | /* Names for the values of the `has_arg' field of `struct option'. */ 96 | 97 | #define no_argument 0 98 | #define required_argument 1 99 | #define optional_argument 2 100 | 101 | #if defined (__STDC__) && __STDC__ 102 | #ifdef __GNU_LIBRARY__ 103 | /* Many other libraries have conflicting prototypes for getopt, with 104 | differences in the consts, in stdlib.h. To avoid compilation 105 | errors, only prototype getopt for the GNU C library. */ 106 | extern int getopt (int argc, char *const *argv, const char *shortopts); 107 | #else /* not __GNU_LIBRARY__ */ 108 | extern int getopt (); 109 | #endif /* __GNU_LIBRARY__ */ 110 | extern int getopt_long (int argc, char *const *argv, const char *shortopts, 111 | const struct option *longopts, int *longind); 112 | extern int getopt_long_only (int argc, char *const *argv, 113 | const char *shortopts, 114 | const struct option *longopts, int *longind); 115 | 116 | /* Internal only. Users should not call this directly. */ 117 | extern int _getopt_internal (int argc, char *const *argv, 118 | const char *shortopts, 119 | const struct option *longopts, int *longind, 120 | int long_only); 121 | #else /* not __STDC__ */ 122 | extern int getopt (); 123 | extern int getopt_long (); 124 | extern int getopt_long_only (); 125 | 126 | extern int _getopt_internal (); 127 | #endif /* __STDC__ */ 128 | 129 | #ifdef __cplusplus 130 | } 131 | #endif 132 | 133 | #endif /* _GETOPT_H */ 134 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | 2 | UPDATE 12/27/04 security fix in -e option for Windows 3 | 4 | Netcat 1.11 for NT - nc111nt.zip 5 | 6 | The original version of Netcat was written by *hobbit* 7 | The NT version was done by Weld Pond 8 | 9 | Netcat for NT is the tcp/ip "Swiss Army knife" that never made it into any 10 | of the resource kits. It has proved to be an extremely versatile tool on 11 | the unix platform. So why should NT always be unix's poor cousin when it 12 | comes to tcp/ip testing and exploration? I bet many NT admins out there 13 | keep a unix box around to use tools such as Netcat or to test their systems 14 | with the unix version of an NT vulnerability exploit. With Netcat for NT 15 | part of that feeling disempowerment is over. 16 | 17 | Included with this release is Hobbit's original description of the powers 18 | of Netcat. In this document I will briefly describe some of the things an 19 | NT admin might want to do and know about with Netcat on NT. For more 20 | detailed technical information please read hobbit.txt included in the 21 | nc11nt.zip archive. 22 | 23 | Basic Features 24 | 25 | * Outbound or inbound connections, TCP or UDP, to or from any ports 26 | * Full DNS forward/reverse checking, with appropriate warnings 27 | * Ability to use any local source port 28 | * Ability to use any locally-configured network source address 29 | * Built-in port-scanning capabilities, with randomizer 30 | * Can read command line arguments from standard input 31 | * Slow-send mode, one line every N seconds 32 | * Hex dump of transmitted and received data 33 | * Ability to let another program service established 34 | connections 35 | * Telnet-options responder 36 | 37 | New for NT 38 | 39 | * Ability to run in the background without a console window 40 | * Ability to restart as a single-threaded server to handle a new 41 | connection 42 | 43 | 44 | A simple example of using Netcat is to pull down a web page from a web 45 | server. With Netcat you get to see the full HTTP header so you can see 46 | which web server a particular site is running. 47 | 48 | Since NT has a rather anemic command processor, some of the things that are 49 | easy in unix may be a bit more clunky in NT. For the web page example first 50 | create a file get.txt that contains the following line and then a blank 51 | line: 52 | 53 | GET / HTTP/1.0 54 | 55 | To use Netcat to retrieve the home page of a web site use the command: 56 | nc -v www.website.com 80 < get.txt 57 | 58 | You will see Netcat make a connection to port 80, send the text contained 59 | in the file get.txt, and then output the web server's response to stdout. 60 | The -v is for verbose. It tells you a little info about the connection 61 | when it starts. 62 | 63 | It is a bit easier to just open the connection and then type at the console 64 | to do the same thing. 65 | nc -v www.website.com 80 66 | 67 | Then just type in GET / HTTP/1.0 and hit a couple of returns. You will 68 | see the same thing as above. 69 | 70 | A far more exciting thing to do is to get a quick shell going on a remote 71 | machine by using the -l or "listen" option and the -e or "execute" 72 | option. You run Netcat listening on particular port for a connection. 73 | When a connection is made, Netcat executes the program of your choice 74 | and connects the stdin and stdout of the program to the network connection. 75 | 76 | nc -l -p 23 -t -e cmd.exe 77 | 78 | will get Netcat listening on port 23 (telnet). When it gets connected to 79 | by a client it will spawn a shell (cmd.exe). The -t option tells Netcat 80 | to handle any telnet negotiation the client might expect. 81 | 82 | This will allow you to telnet to the machine you have Netcat listening on 83 | and get a cmd.exe shell when you connect. You could just as well use 84 | Netcat instead of telnet: 85 | 86 | nc xxx.xxx.xxx.xxx 23 87 | 88 | will get the job done. There is no authentication on the listening side 89 | so be a bit careful here. The shell is running with the permissions of the 90 | process that started Netcat so be very careful. If you were to use the 91 | AT program to schedule Netcat to run listening on a port with the 92 | -e cmd.exe option, when you connected you would get a shell with user 93 | NT AUTHORITY\SYSTEM. 94 | 95 | The beauty of Netcat really shines when you realize that you can get it 96 | listening on ANY port doing the same thing. Do a little exploring and 97 | see if the firewall you may be behind lets port 53 through. Run Netcat 98 | listening behind the firewall on port 53. 99 | 100 | nc -L -p 53 -e cmd.exe 101 | 102 | Then from outside the firewall connect to the listening machine: 103 | 104 | nc -v xxx.xxx.xxx.xx 53 105 | 106 | If you get a command prompt then you are executing commands on the 107 | listening machine. Use 'exit' at the command prompt for a clean 108 | disconnect. The -L (note the capital L) option will restart Netcat with 109 | the same command line when the connection is terminated. This way you can 110 | connect over and over to the same Netcat process. 111 | 112 | A new feature for the NT version is the -d or detach from console flag. 113 | This will let Netcat run without an ugly console window cluttering up the 114 | screen or showing up in the task list. 115 | 116 | You can even get Netcat to listen on the NETBIOS ports that are probably 117 | running on most NT machines. This way you can get a connection to a 118 | machine that may have port filtering enabled in the TCP/IP Security Network 119 | control panel. Unlike Unix, NT does not seem to have any security around 120 | which ports that user programs are allowed to bind to. This means any 121 | user can run a program that will bind to the NETBIOS ports. 122 | 123 | You will need to bind "in front of" some services that may already be 124 | listening on those ports. An example is the NETBIOS Session Service that 125 | is running on port 139 of NT machines that are sharing files. You need 126 | to bind to a specific source address (one of the IP addresses of the 127 | machine) to accomplish this. This gives Netcat priority over the NETBIOS 128 | service which is at a lower priority because it is bound to ANY IP address. 129 | This is done with the Netcat -s option: 130 | 131 | nc -v -L -e cmd.exe -p 139 -s xxx.xxx.xxx.xxx 132 | 133 | Now you can connect to the machine on port 139 and Netcat will field 134 | the connection before NETBIOS does. You have effectively shut off 135 | file sharing on this machine by the way. You have done this with just 136 | user privileges to boot. 137 | 138 | PROBLEMS with Netcat 1.1 for NT 139 | 140 | There are a few known problems that will eventually be fixed. One is 141 | the -w or timeout option. This works for final net reads but not 142 | for connections. Another problem is using the -e option in UDP mode. 143 | You may find that some of the features work on Windows 95. Most 144 | of the listening features will not work on Windows 95 however. These will 145 | be fixed in a later release. 146 | 147 | Netcat is distributed with full source code so that people can build 148 | upon this work. If you add something useful or discover something 149 | interesting about NT TCP/IP let met know. 150 | 151 | Weld Pond , 2/2/98 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /generic.h: -------------------------------------------------------------------------------- 1 | /* generic.h -- anything you don't #undef at the end remains in effect. 2 | The ONLY things that go in here are generic indicator flags; it's up 3 | to your programs to declare and call things based on those flags. 4 | 5 | You should only need to make changes via a minimal system-specific section 6 | at the end of this file. To build a new section, rip through this and 7 | check everything it mentions on your platform, and #undef that which needs 8 | it. If you generate a system-specific section you didn't find in here, 9 | please mail me a copy so I can update the "master". 10 | 11 | I realize I'm probably inventing another pseudo-standard here, but 12 | goddamnit, everybody ELSE has already, and I can't include all of their 13 | hairball schemes too. HAVE_xx conforms to the gnu/autoconf usage and 14 | seems to be the most common format. In fact, I dug a lot of these out 15 | of autoconf and tried to common them all together using "stupidh" to 16 | collect data from platforms. 17 | 18 | In disgust... _H* 940910, 941115. Pseudo-version: 1.1 */ 19 | 20 | #ifndef GENERIC_H /* only run through this once */ 21 | #define GENERIC_H 22 | 23 | /* =============================== */ 24 | /* System calls, lib routines, etc */ 25 | /* =============================== */ 26 | 27 | /* How does your system declare malloc, void or char? Usually void, but go 28 | ask the SunOS people why they had to be different... */ 29 | #define VOID_MALLOC 30 | 31 | /* notably from fwtk/firewall.h: posix locking? */ 32 | #define HAVE_FLOCK /* otherwise it's lockf() */ 33 | 34 | /* if you don't have setsid(), you might have setpgrp(). 35 | #define HAVE_SETSID */ 36 | 37 | /* random() is generally considered better than rand() */ 38 | /* xxx: rand48? */ 39 | #define HAVE_RANDOM 40 | 41 | /* if your machine doesn't have lstat(), it should have stat() [dos...] */ 42 | #define HAVE_LSTAT 43 | 44 | /* different kinds of term ioctls. How to recognize them, very roughly: 45 | sysv/POSIX_ME_HARDER: termio[s].h, struct termio[s], tty.c_*[] 46 | bsd/old stuff: sgtty.h, ioctl(TIOCSETP), sgttyb.sg_*, tchars.t_* 47 | #define HAVE_TERMIOS */ 48 | 49 | /* dbm vs ndbm */ 50 | #define HAVE_NDBM 51 | 52 | /* extended utmp/wtmp stuff. MOST machines still do NOT have this SV-ism */ 53 | #define UTMPX 54 | 55 | /* some systems have nice() which takes *relative* values... [resource.h] */ 56 | #define HAVE_SETPRIORITY 57 | 58 | /* a sysvism, I think, but ... */ 59 | #define HAVE_SYSINFO 60 | 61 | /* punted for now: setown / siocspgrp ... see firewall.h */ 62 | 63 | /* ============= */ 64 | /* Include files */ 65 | /* ============= */ 66 | 67 | /* Presence of these can be determined via a script that sniffs them 68 | out if you aren't sure. */ 69 | 70 | /* stdlib comes with most modern compilers, but ya never know */ 71 | #define HAVE_STDLIB_H 72 | 73 | /* not on a DOS box! */ 74 | #define HAVE_UNISTD_H 75 | 76 | /* stdarg is a weird one */ 77 | #define HAVE_STDARG_H 78 | 79 | /* dir.h or maybe ndir.h otherwise. */ 80 | #define HAVE_DIRENT_H 81 | 82 | /* string or strings */ 83 | #define HAVE_STRINGS_H 84 | 85 | /* if you don't have lastlog.h, what you want might be in login.h */ 86 | #define HAVE_LASTLOG_H 87 | 88 | /* predefines for _PATH_various */ 89 | #define HAVE_PATHS_H 90 | 91 | /* assorted others */ 92 | #define HAVE_PARAM_H 93 | #define HAVE_SYSMACROS_H /* in sys/! */ 94 | #define HAVE_TTYENT_H /* securetty et al */ 95 | 96 | /* ==================== */ 97 | 98 | /* Still maybe have to do something about the following, if it's even 99 | worth it. I just grepped a lot of these out of various code, without 100 | looking them up yet: 101 | 102 | #define HAVE_EINPROGRESS 103 | #define HAVE_F_SETOWN 104 | #define HAVE_SETENV ... now *there's* a hairy one; **environ is portable 105 | #define BIG_ENDIAN/little_endian ... *please* try to avoid this stupidity 106 | #define HAVE_GETUSERSHELL ... you could always pull it out of getpwent() 107 | #define HAVE_SETE[UG]ID ... lib or syscall, it varies on diff platforms 108 | #define HAVE_STRCHR ... should actually be handled by string/strings 109 | #define HAVE_PSTAT 110 | #define HAVE_ST_BLKSIZE ... a stat() thing? 111 | #define HAVE_IP_TOS 112 | #define HAVE_STRFTIME ... screw this, we should just INCLUDE one for lame 113 | old boxes that don't have it [sunos 3.x, early 4.x?] 114 | #define HAVE_VFPRINTF 115 | #define HAVE_SHADOW_PASSWD ... in its multitudinous schemes?? ... how 116 | about sumpin' like #define SHADOW_PASSWD_TYPE ... could get grody. 117 | #define SIG* ... what a swamp, punt for now; should all be in signal.h 118 | #define HAVE_STRCSPN ... see larry wall's comment in the fwtk regex code 119 | #define ULTRIX_AUTH ... bwahaha. 120 | #define HAVE_YP or NIS or whatever you wanna call it this week 121 | randomness about VARARGS?? 122 | 123 | There's also the issue about WHERE various .h files live, sys/ or otherwise. 124 | There's a BIG swamp lurking where network code of any sort lives. 125 | 126 | */ 127 | 128 | /* ======================== */ 129 | /* System-specific sections */ 130 | /* ======================== */ 131 | 132 | /* By turning OFF various bits of the above, you can customize for 133 | a given platform. */ 134 | 135 | /* DOS boxes, with MSC; you may need to adapt to a different compiler. */ 136 | #ifdef MSDOS 137 | #undef HAVE_FLOCK 138 | #undef HAVE_RANDOM 139 | #undef HAVE_LSTAT 140 | #undef HAVE_TERMIOS 141 | #undef UTMPX 142 | #undef HAVE_SYSINFO 143 | #undef HAVE_UNISTD_H 144 | #undef HAVE_DIRENT_H /* unless you have the k00l little wrapper from L5!! */ 145 | #undef HAVE_STRINGS_H 146 | #undef HAVE_LASTLOG_H 147 | #undef HAVE_PATHS_H 148 | #undef HAVE_PARAM_H 149 | #undef HAVE_SYSMACROS_H 150 | #undef HAVE_TTYENT_H 151 | #endif /* MSDOS */ 152 | 153 | /* buglix 4.x; dunno about 3.x on down. should be bsd4.2. */ 154 | #ifdef ULTRIX 155 | #undef UTMPX 156 | #undef HAVE_PATHS_H 157 | #undef HAVE_SYSMACROS_H 158 | #endif /* buglix */ 159 | 160 | /* some of this might still be broken on older sunoses */ 161 | #ifdef SUNOS 162 | #undef VOID_MALLOC 163 | #undef UTMPX 164 | #undef HAVE_PATHS_H 165 | #endif /* sunos */ 166 | 167 | /* "contact your vendor for a fix" */ 168 | #ifdef SOLARIS 169 | /* has UTMPX */ 170 | #undef HAVE_SETPRIORITY 171 | #undef HAVE_STRINGS_H /* this is genuinely the case, go figure */ 172 | #undef HAVE_PATHS_H 173 | #undef HAVE_TTYENT_H 174 | #endif /* SOLARIS */ 175 | 176 | /* whatever aix variant MIT had at the time */ 177 | #ifdef AIX 178 | #undef UTMPX 179 | #undef HAVE_LASTLOG_H 180 | #define HAVE_LOGIN_H /* "special", in the educational sense */ 181 | #endif /* aix */ 182 | 183 | /* linux, which is trying as desperately as the gnu folks can to be 184 | POSIXLY_CORRECT. I think I'm gonna hurl... */ 185 | #ifdef LINUX 186 | #undef UTMPX 187 | #undef HAVE_SYSINFO 188 | #undef HAVE_TTYENT_H 189 | #endif /* linux */ 190 | 191 | /* irix 5.x; may not be correct for earlier ones */ 192 | #ifdef IRIX 193 | /* wow, does irix really have everything?! */ 194 | #endif /* irix */ 195 | 196 | /* osf on alphas */ 197 | #ifdef OSF 198 | #undef UTMPX 199 | #endif /* osf */ 200 | 201 | /* they's some FUCKED UP paths in this one! */ 202 | #ifdef FREEBSD 203 | #undef UTMPX 204 | #undef HAVE_SYSINFO 205 | #undef HAVE_LASTLOG_H 206 | #undef HAVE_SYSMACROS_H 207 | #endif /* freebsd */ 208 | 209 | /* From the sidewinder site, of all places; may be unreliable */ 210 | #ifdef BSDI 211 | #undef UTMPX 212 | #undef HAVE_LASTLOG_H 213 | #undef HAVE_SYSMACROS_H 214 | #undef HAVE_TTYENT_H 215 | /* and their malloc.h was in sys/ ?! */ 216 | #endif /* bsdi */ 217 | 218 | /* netbsd/44lite, jives with amiga-netbsd from cactus */ 219 | #ifdef NETBSD 220 | #undef UTMPX 221 | #undef HAVE_SYSINFO 222 | #undef HAVE_LASTLOG_H 223 | #endif /* netbsd */ 224 | 225 | /* Make some "generic" assumptions if all else fails */ 226 | #ifdef GENERIC 227 | #undef HAVE_FLOCK 228 | #if defined(SYSV) && (SYSV < 4) /* TW leftover: old SV doesnt have symlinks */ 229 | #undef HAVE_LSTAT 230 | #endif /* old SYSV */ 231 | #undef HAVE_TERMIOS 232 | #undef UTMPX 233 | #undef HAVE_PATHS_H 234 | #endif /* generic */ 235 | 236 | /* ================ */ 237 | #endif /* GENERIC_H */ 238 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | 2 | )\ )\ )\.---. .-,.-.,-. )\.-. /`-. .-,.-.,-. 3 | ( \, / ( ,-._( ) ,, ,. ( ,' ,-,_) ,' _ \ ) ,, ,. ( 4 | ) \ ( \ '-, \( |( )/ ( . _ ( '-' ( \( |( )/ 5 | ( ( \ \ ) ,-` ) \ ) '..' ) ) _ ) ) \ 6 | `.)/ ) ( ``-. \ ( ( , ( ( ,' ) \ \ ( 7 | '.( )..-.( )/ )/'._.' )/ )/ )/ for Windows 8 | ----------------------------------------------------------------------- 9 | 10 | This NetCat for Windows was originally created by Rodney Beede, it's 11 | a version compiled without the GAPING_SECURITY_HOLE option (-e switch) 12 | which can trigger false positives in anti-virus programs. Check the 13 | file readme.rodneybeede.txt for further details. 14 | 15 | Why am I creating this version, you may ask? Well, during some of my 16 | telnet sessions i've noticed extraneous characters being returned and 17 | such, so... basically, this version should fix those issues. 18 | 19 | You can also find there a nc.exe executable, which was compiled 20 | using GCC 4.8.1 and tested under Windows 7 (HP) 32-bits. 21 | 22 | SHA1(nc.exe)= c5e19c02a9a1362c67ea87c1e049ce9056425788 23 | 24 | If you have some question, feel free to contact me. 25 | 26 | Sincerely, 27 | Diego Casorran. 28 | 29 | 30 | Just for the sake of, you'll find below the original NetCat README file: 31 | 32 | 33 | UPDATE 12/27/04 security fix in -e option for Windows 34 | 35 | Netcat 1.11 for NT - nc111nt.zip 36 | 37 | The original version of Netcat was written by *hobbit* 38 | The NT version was done by Weld Pond 39 | 40 | Netcat for NT is the tcp/ip "Swiss Army knife" that never made it into any 41 | of the resource kits. It has proved to be an extremely versatile tool on 42 | the unix platform. So why should NT always be unix's poor cousin when it 43 | comes to tcp/ip testing and exploration? I bet many NT admins out there 44 | keep a unix box around to use tools such as Netcat or to test their systems 45 | with the unix version of an NT vulnerability exploit. With Netcat for NT 46 | part of that feeling disempowerment is over. 47 | 48 | Included with this release is Hobbit's original description of the powers 49 | of Netcat. In this document I will briefly describe some of the things an 50 | NT admin might want to do and know about with Netcat on NT. For more 51 | detailed technical information please read hobbit.txt included in the 52 | nc11nt.zip archive. 53 | 54 | Basic Features 55 | 56 | * Outbound or inbound connections, TCP or UDP, to or from any ports 57 | * Full DNS forward/reverse checking, with appropriate warnings 58 | * Ability to use any local source port 59 | * Ability to use any locally-configured network source address 60 | * Built-in port-scanning capabilities, with randomizer 61 | * Can read command line arguments from standard input 62 | * Slow-send mode, one line every N seconds 63 | * Hex dump of transmitted and received data 64 | * Ability to let another program service established 65 | connections 66 | * Telnet-options responder 67 | 68 | New for NT 69 | 70 | * Ability to run in the background without a console window 71 | * Ability to restart as a single-threaded server to handle a new 72 | connection 73 | 74 | 75 | A simple example of using Netcat is to pull down a web page from a web 76 | server. With Netcat you get to see the full HTTP header so you can see 77 | which web server a particular site is running. 78 | 79 | Since NT has a rather anemic command processor, some of the things that are 80 | easy in unix may be a bit more clunky in NT. For the web page example first 81 | create a file get.txt that contains the following line and then a blank 82 | line: 83 | 84 | GET / HTTP/1.0 85 | 86 | To use Netcat to retrieve the home page of a web site use the command: 87 | nc -v www.website.com 80 < get.txt 88 | 89 | You will see Netcat make a connection to port 80, send the text contained 90 | in the file get.txt, and then output the web server's response to stdout. 91 | The -v is for verbose. It tells you a little info about the connection 92 | when it starts. 93 | 94 | It is a bit easier to just open the connection and then type at the console 95 | to do the same thing. 96 | nc -v www.website.com 80 97 | 98 | Then just type in GET / HTTP/1.0 and hit a couple of returns. You will 99 | see the same thing as above. 100 | 101 | A far more exciting thing to do is to get a quick shell going on a remote 102 | machine by using the -l or "listen" option and the -e or "execute" 103 | option. You run Netcat listening on particular port for a connection. 104 | When a connection is made, Netcat executes the program of your choice 105 | and connects the stdin and stdout of the program to the network connection. 106 | 107 | nc -l -p 23 -t -e cmd.exe 108 | 109 | will get Netcat listening on port 23 (telnet). When it gets connected to 110 | by a client it will spawn a shell (cmd.exe). The -t option tells Netcat 111 | to handle any telnet negotiation the client might expect. 112 | 113 | This will allow you to telnet to the machine you have Netcat listening on 114 | and get a cmd.exe shell when you connect. You could just as well use 115 | Netcat instead of telnet: 116 | 117 | nc xxx.xxx.xxx.xxx 23 118 | 119 | will get the job done. There is no authentication on the listening side 120 | so be a bit careful here. The shell is running with the permissions of the 121 | process that started Netcat so be very careful. If you were to use the 122 | AT program to schedule Netcat to run listening on a port with the 123 | -e cmd.exe option, when you connected you would get a shell with user 124 | NT AUTHORITY\SYSTEM. 125 | 126 | The beauty of Netcat really shines when you realize that you can get it 127 | listening on ANY port doing the same thing. Do a little exploring and 128 | see if the firewall you may be behind lets port 53 through. Run Netcat 129 | listening behind the firewall on port 53. 130 | 131 | nc -L -p 53 -e cmd.exe 132 | 133 | Then from outside the firewall connect to the listening machine: 134 | 135 | nc -v xxx.xxx.xxx.xx 53 136 | 137 | If you get a command prompt then you are executing commands on the 138 | listening machine. Use 'exit' at the command prompt for a clean 139 | disconnect. The -L (note the capital L) option will restart Netcat with 140 | the same command line when the connection is terminated. This way you can 141 | connect over and over to the same Netcat process. 142 | 143 | A new feature for the NT version is the -d or detach from console flag. 144 | This will let Netcat run without an ugly console window cluttering up the 145 | screen or showing up in the task list. 146 | 147 | You can even get Netcat to listen on the NETBIOS ports that are probably 148 | running on most NT machines. This way you can get a connection to a 149 | machine that may have port filtering enabled in the TCP/IP Security Network 150 | control panel. Unlike Unix, NT does not seem to have any security around 151 | which ports that user programs are allowed to bind to. This means any 152 | user can run a program that will bind to the NETBIOS ports. 153 | 154 | You will need to bind "in front of" some services that may already be 155 | listening on those ports. An example is the NETBIOS Session Service that 156 | is running on port 139 of NT machines that are sharing files. You need 157 | to bind to a specific source address (one of the IP addresses of the 158 | machine) to accomplish this. This gives Netcat priority over the NETBIOS 159 | service which is at a lower priority because it is bound to ANY IP address. 160 | This is done with the Netcat -s option: 161 | 162 | nc -v -L -e cmd.exe -p 139 -s xxx.xxx.xxx.xxx 163 | 164 | Now you can connect to the machine on port 139 and Netcat will field 165 | the connection before NETBIOS does. You have effectively shut off 166 | file sharing on this machine by the way. You have done this with just 167 | user privileges to boot. 168 | 169 | PROBLEMS with Netcat 1.1 for NT 170 | 171 | There are a few known problems that will eventually be fixed. One is 172 | the -w or timeout option. This works for final net reads but not 173 | for connections. Another problem is using the -e option in UDP mode. 174 | You may find that some of the features work on Windows 95. Most 175 | of the listening features will not work on Windows 95 however. These will 176 | be fixed in a later release. 177 | 178 | Netcat is distributed with full source code so that people can build 179 | upon this work. If you add something useful or discover something 180 | interesting about NT TCP/IP let met know. 181 | 182 | Weld Pond , 2/2/98 183 | -------------------------------------------------------------------------------- /doexec.c: -------------------------------------------------------------------------------- 1 | // for license see license.txt 2 | 3 | // Modified 12/27/2004 by Chris Wysopal 4 | // fixed vulnerability found by hat-squad 5 | 6 | // portions Copyright (C) 1994 Nathaniel W. Mishkin 7 | // code taken from rlogind.exe 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #ifdef GAPING_SECURITY_HOLE 14 | 15 | 16 | #define BUFFER_SIZE 200 17 | 18 | extern char * pr00gie; 19 | void holler(char * str, char * p1, char * p2, char * p3, char * p4, char * p5, char * p6); 20 | char smbuff[20]; 21 | // 22 | // Structure used to describe each session 23 | // 24 | typedef struct { 25 | 26 | // 27 | // These fields are filled in at session creation time 28 | // 29 | HANDLE ReadPipeHandle; // Handle to shell stdout pipe 30 | HANDLE WritePipeHandle; // Handle to shell stdin pipe 31 | HANDLE ProcessHandle; // Handle to shell process 32 | 33 | // 34 | // 35 | // These fields are filled in at session connect time and are only 36 | // valid when the session is connected 37 | // 38 | SOCKET ClientSocket; 39 | HANDLE ReadShellThreadHandle; // Handle to session shell-read thread 40 | HANDLE WriteShellThreadHandle; // Handle to session shell-read thread 41 | 42 | } SESSION_DATA, *PSESSION_DATA; 43 | 44 | 45 | // 46 | // Private prototypes 47 | // 48 | 49 | static HANDLE 50 | StartShell( 51 | HANDLE StdinPipeHandle, 52 | HANDLE StdoutPipeHandle 53 | ); 54 | 55 | static VOID 56 | SessionReadShellThreadFn( 57 | LPVOID Parameter 58 | ); 59 | 60 | static VOID 61 | SessionWriteShellThreadFn( 62 | LPVOID Parameter 63 | ); 64 | 65 | 66 | 67 | // ********************************************************************** 68 | // 69 | // CreateSession 70 | // 71 | // Creates a new session. Involves creating the shell process and establishing 72 | // pipes for communication with it. 73 | // 74 | // Returns a handle to the session or NULL on failure. 75 | // 76 | 77 | static PSESSION_DATA 78 | CreateSession( 79 | VOID 80 | ) 81 | { 82 | PSESSION_DATA Session = NULL; 83 | BOOL Result; 84 | SECURITY_ATTRIBUTES SecurityAttributes; 85 | HANDLE ShellStdinPipe = NULL; 86 | HANDLE ShellStdoutPipe = NULL; 87 | 88 | // 89 | // Allocate space for the session data 90 | // 91 | Session = (PSESSION_DATA) malloc(sizeof(SESSION_DATA)); 92 | if (Session == NULL) { 93 | return(NULL); 94 | } 95 | 96 | // 97 | // Reset fields in preparation for failure 98 | // 99 | Session->ReadPipeHandle = NULL; 100 | Session->WritePipeHandle = NULL; 101 | 102 | 103 | // 104 | // Create the I/O pipes for the shell 105 | // 106 | SecurityAttributes.nLength = sizeof(SecurityAttributes); 107 | SecurityAttributes.lpSecurityDescriptor = NULL; // Use default ACL 108 | SecurityAttributes.bInheritHandle = TRUE; // Shell will inherit handles 109 | 110 | Result = CreatePipe(&Session->ReadPipeHandle, &ShellStdoutPipe, 111 | &SecurityAttributes, 0); 112 | if (!Result) { 113 | holler("Failed to create shell stdout pipe, error = %s", 114 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 115 | goto Failure; 116 | } 117 | Result = CreatePipe(&ShellStdinPipe, &Session->WritePipeHandle, 118 | &SecurityAttributes, 0); 119 | 120 | if (!Result) { 121 | holler("Failed to create shell stdin pipe, error = %s", 122 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 123 | goto Failure; 124 | } 125 | // 126 | // Start the shell 127 | // 128 | Session->ProcessHandle = StartShell(ShellStdinPipe, ShellStdoutPipe); 129 | 130 | // 131 | // We're finished with our copy of the shell pipe handles 132 | // Closing the runtime handles will close the pipe handles for us. 133 | // 134 | CloseHandle(ShellStdinPipe); 135 | CloseHandle(ShellStdoutPipe); 136 | 137 | // 138 | // Check result of shell start 139 | // 140 | if (Session->ProcessHandle == NULL) { 141 | holler("Failed to execute shell", NULL, 142 | NULL, NULL, NULL, NULL, NULL); 143 | 144 | goto Failure; 145 | } 146 | 147 | // 148 | // The session is not connected, initialize variables to indicate that 149 | // 150 | Session->ClientSocket = INVALID_SOCKET; 151 | 152 | // 153 | // Success, return the session pointer as a handle 154 | // 155 | return(Session); 156 | 157 | Failure: 158 | 159 | // 160 | // We get here for any failure case. 161 | // Free up any resources and exit 162 | // 163 | 164 | if (ShellStdinPipe != NULL) 165 | CloseHandle(ShellStdinPipe); 166 | if (ShellStdoutPipe != NULL) 167 | CloseHandle(ShellStdoutPipe); 168 | if (Session->ReadPipeHandle != NULL) 169 | CloseHandle(Session->ReadPipeHandle); 170 | if (Session->WritePipeHandle != NULL) 171 | CloseHandle(Session->WritePipeHandle); 172 | 173 | free(Session); 174 | 175 | return(NULL); 176 | } 177 | 178 | 179 | 180 | BOOL 181 | doexec( 182 | SOCKET ClientSocket 183 | ) 184 | { 185 | PSESSION_DATA Session = CreateSession(); 186 | SECURITY_ATTRIBUTES SecurityAttributes; 187 | DWORD ThreadId; 188 | HANDLE HandleArray[3]; 189 | int i; 190 | 191 | SecurityAttributes.nLength = sizeof(SecurityAttributes); 192 | SecurityAttributes.lpSecurityDescriptor = NULL; // Use default ACL 193 | SecurityAttributes.bInheritHandle = FALSE; // No inheritance 194 | 195 | // 196 | // Store the client socket handle in the session structure so the thread 197 | // can get at it. This also signals that the session is connected. 198 | // 199 | Session->ClientSocket = ClientSocket; 200 | 201 | // 202 | // Create the session threads 203 | // 204 | Session->ReadShellThreadHandle = 205 | CreateThread(&SecurityAttributes, 0, 206 | (LPTHREAD_START_ROUTINE) SessionReadShellThreadFn, 207 | (LPVOID) Session, 0, &ThreadId); 208 | 209 | if (Session->ReadShellThreadHandle == NULL) { 210 | holler("Failed to create ReadShell session thread, error = %s", 211 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 212 | 213 | // 214 | // Reset the client pipe handle to indicate this session is disconnected 215 | // 216 | Session->ClientSocket = INVALID_SOCKET; 217 | return(FALSE); 218 | } 219 | 220 | Session->WriteShellThreadHandle = 221 | CreateThread(&SecurityAttributes, 0, 222 | (LPTHREAD_START_ROUTINE) SessionWriteShellThreadFn, 223 | (LPVOID) Session, 0, &ThreadId); 224 | 225 | if (Session->WriteShellThreadHandle == NULL) { 226 | holler("Failed to create ReadShell session thread, error = %s", 227 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 228 | 229 | // 230 | // Reset the client pipe handle to indicate this session is disconnected 231 | // 232 | Session->ClientSocket = INVALID_SOCKET; 233 | 234 | TerminateThread(Session->WriteShellThreadHandle, 0); 235 | return(FALSE); 236 | } 237 | 238 | // 239 | // Wait for either thread or the shell process to finish 240 | // 241 | 242 | HandleArray[0] = Session->ReadShellThreadHandle; 243 | HandleArray[1] = Session->WriteShellThreadHandle; 244 | HandleArray[2] = Session->ProcessHandle; 245 | 246 | 247 | i = WaitForMultipleObjects(3, HandleArray, FALSE, 0xffffffff); 248 | 249 | 250 | switch (i) { 251 | case WAIT_OBJECT_0 + 0: 252 | TerminateThread(Session->WriteShellThreadHandle, 0); 253 | TerminateProcess(Session->ProcessHandle, 1); 254 | break; 255 | 256 | case WAIT_OBJECT_0 + 1: 257 | TerminateThread(Session->ReadShellThreadHandle, 0); 258 | TerminateProcess(Session->ProcessHandle, 1); 259 | break; 260 | case WAIT_OBJECT_0 + 2: 261 | TerminateThread(Session->WriteShellThreadHandle, 0); 262 | TerminateThread(Session->ReadShellThreadHandle, 0); 263 | break; 264 | 265 | default: 266 | holler("WaitForMultipleObjects error: %s", 267 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 268 | 269 | break; 270 | } 271 | 272 | 273 | // Close my handles to the threads, the shell process, and the shell pipes 274 | shutdown(Session->ClientSocket, SD_BOTH); 275 | closesocket(Session->ClientSocket); 276 | 277 | DisconnectNamedPipe(Session->ReadPipeHandle); 278 | CloseHandle(Session->ReadPipeHandle); 279 | 280 | DisconnectNamedPipe(Session->WritePipeHandle); 281 | CloseHandle(Session->WritePipeHandle); 282 | 283 | 284 | CloseHandle(Session->ReadShellThreadHandle); 285 | CloseHandle(Session->WriteShellThreadHandle); 286 | 287 | CloseHandle(Session->ProcessHandle); 288 | 289 | free(Session); 290 | 291 | return(TRUE); 292 | } 293 | 294 | 295 | // ********************************************************************** 296 | // 297 | // StartShell 298 | // 299 | // Execs the shell with the specified handle as stdin, stdout/err 300 | // 301 | // Returns process handle or NULL on failure 302 | // 303 | 304 | static HANDLE 305 | StartShell( 306 | HANDLE ShellStdinPipeHandle, 307 | HANDLE ShellStdoutPipeHandle 308 | ) 309 | { 310 | PROCESS_INFORMATION ProcessInformation; 311 | STARTUPINFO si; 312 | HANDLE ProcessHandle = NULL; 313 | 314 | // 315 | // Initialize process startup info 316 | // 317 | si.cb = sizeof(STARTUPINFO); 318 | si.lpReserved = NULL; 319 | si.lpTitle = NULL; 320 | si.lpDesktop = NULL; 321 | si.dwX = si.dwY = si.dwXSize = si.dwYSize = 0L; 322 | si.wShowWindow = SW_HIDE; 323 | si.lpReserved2 = NULL; 324 | si.cbReserved2 = 0; 325 | 326 | si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; 327 | 328 | si.hStdInput = ShellStdinPipeHandle; 329 | si.hStdOutput = ShellStdoutPipeHandle; 330 | 331 | DuplicateHandle(GetCurrentProcess(), ShellStdoutPipeHandle, 332 | GetCurrentProcess(), &si.hStdError, 333 | DUPLICATE_SAME_ACCESS, TRUE, 0); 334 | 335 | if (CreateProcess(NULL, pr00gie, NULL, NULL, TRUE, 0, NULL, NULL, 336 | &si, &ProcessInformation)) 337 | { 338 | ProcessHandle = ProcessInformation.hProcess; 339 | CloseHandle(ProcessInformation.hThread); 340 | } 341 | else 342 | holler("Failed to execute shell, error = %s", 343 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 344 | 345 | 346 | return(ProcessHandle); 347 | } 348 | 349 | 350 | // ********************************************************************** 351 | // SessionReadShellThreadFn 352 | // 353 | // The read thread procedure. Reads from the pipe connected to the shell 354 | // process, writes to the socket. 355 | // 356 | 357 | static VOID 358 | SessionReadShellThreadFn( 359 | LPVOID Parameter 360 | ) 361 | { 362 | PSESSION_DATA Session = Parameter; 363 | BYTE Buffer[BUFFER_SIZE]; 364 | BYTE Buffer2[BUFFER_SIZE*2+30]; 365 | DWORD BytesRead; 366 | 367 | // this bogus peek is here because win32 won't let me close the pipe if it is 368 | // in waiting for input on a read. 369 | while (PeekNamedPipe(Session->ReadPipeHandle, Buffer, sizeof(Buffer), 370 | &BytesRead, NULL, NULL)) 371 | { 372 | DWORD BufferCnt, BytesToWrite; 373 | BYTE PrevChar = 0; 374 | 375 | if (BytesRead > 0) 376 | { 377 | ReadFile(Session->ReadPipeHandle, Buffer, sizeof(Buffer), 378 | &BytesRead, NULL); 379 | } 380 | else 381 | { 382 | Sleep(50); 383 | continue; 384 | } 385 | 386 | 387 | 388 | // 389 | // Process the data we got from the shell: replace any naked LF's 390 | // with CR-LF pairs. 391 | // 392 | for (BufferCnt = 0, BytesToWrite = 0; BufferCnt < BytesRead; BufferCnt++) { 393 | if (Buffer[BufferCnt] == '\n' && PrevChar != '\r') 394 | Buffer2[BytesToWrite++] = '\r'; 395 | PrevChar = Buffer2[BytesToWrite++] = Buffer[BufferCnt]; 396 | } 397 | 398 | if (send(Session->ClientSocket, Buffer2, BytesToWrite, 0) <= 0) 399 | break; 400 | } 401 | 402 | if (GetLastError() != ERROR_BROKEN_PIPE) 403 | holler("SessionReadShellThreadFn exitted, error = %s", 404 | itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL); 405 | 406 | ExitThread(0); 407 | } 408 | 409 | 410 | // ********************************************************************** 411 | // SessionWriteShellThreadFn 412 | // 413 | // The write thread procedure. Reads from socket, writes to pipe connected 414 | // to shell process. 415 | 416 | 417 | static VOID 418 | SessionWriteShellThreadFn( 419 | LPVOID Parameter 420 | ) 421 | { 422 | PSESSION_DATA Session = Parameter; 423 | BYTE RecvBuffer[1]; 424 | BYTE Buffer[BUFFER_SIZE]; 425 | DWORD BytesWritten; 426 | DWORD BufferCnt; 427 | 428 | BufferCnt = 0; 429 | 430 | // 431 | // Loop, reading one byte at a time from the socket. 432 | // 433 | while (recv(Session->ClientSocket, RecvBuffer, sizeof(RecvBuffer), 0) != 0) { 434 | 435 | Buffer[BufferCnt++] = RecvBuffer[0]; 436 | if (RecvBuffer[0] == '\r') 437 | Buffer[BufferCnt++] = '\n'; 438 | 439 | 440 | // Trap exit as it causes problems 441 | if (strnicmp(Buffer, "exit\r\n", 6) == 0) 442 | ExitThread(0); 443 | 444 | 445 | // 446 | // If we got a CR, it's time to send what we've buffered up down to the 447 | // shell process. 448 | // SECURITY FIX: CW 12/27/04 Add BufferCnt size check. If we hit end of buffer, flush it 449 | if (RecvBuffer[0] == '\n' || RecvBuffer[0] == '\r' || BufferCnt > BUFFER_SIZE-1) { 450 | if (! WriteFile(Session->WritePipeHandle, Buffer, BufferCnt, 451 | &BytesWritten, NULL)) 452 | { 453 | break; 454 | } 455 | BufferCnt = 0; 456 | } 457 | } 458 | 459 | ExitThread(0); 460 | } 461 | 462 | #endif -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /getopt.c: -------------------------------------------------------------------------------- 1 | /* Getopt for GNU. 2 | NOTE: getopt is now part of the C library, so if you don't know what 3 | "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu 4 | before changing it! 5 | 6 | Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94 7 | Free Software Foundation, Inc. 8 | 9 | This file is part of the GNU C Library. Its master source is NOT part of 10 | the C library, however. The master source lives in /gd/gnu/lib. 11 | 12 | The GNU C Library is free software; you can redistribute it and/or 13 | modify it under the terms of the GNU Library General Public License as 14 | published by the Free Software Foundation; either version 2 of the 15 | License, or (at your option) any later version. 16 | 17 | The GNU C Library is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | Library General Public License for more details. 21 | 22 | You should have received a copy of the GNU Library General Public 23 | License along with the GNU C Library; see the file COPYING.LIB. If 24 | not, write to the Free Software Foundation, Inc., 675 Mass Ave, 25 | Cambridge, MA 02139, USA. */ 26 | 27 | /* This tells Alpha OSF/1 not to define a getopt prototype in . 28 | Ditto for AIX 3.2 and . */ 29 | #ifndef _NO_PROTO 30 | #define _NO_PROTO 31 | #endif 32 | 33 | #ifdef HAVE_CONFIG_H 34 | #include 35 | #endif 36 | 37 | #if !defined (__STDC__) || !__STDC__ 38 | /* This is a separate conditional since some stdc systems 39 | reject `defined (const)'. */ 40 | #ifndef const 41 | #define const 42 | #endif 43 | #endif 44 | 45 | #include 46 | 47 | #ifdef WIN32 48 | #include 49 | #endif 50 | 51 | /* Comment out all this code if we are using the GNU C Library, and are not 52 | actually compiling the library itself. This code is part of the GNU C 53 | Library, but also included in many other GNU distributions. Compiling 54 | and linking in this code is a waste when using the GNU C library 55 | (especially if it is a shared library). Rather than having every GNU 56 | program understand `configure --with-gnu-libc' and omit the object files, 57 | it is simpler to just do this in the source for each such file. */ 58 | 59 | #if defined (_LIBC) || !defined (__GNU_LIBRARY__) 60 | 61 | 62 | /* This needs to come after some library #include 63 | to get __GNU_LIBRARY__ defined. */ 64 | #ifdef __GNU_LIBRARY__ 65 | /* Don't include stdlib.h for non-GNU C libraries because some of them 66 | contain conflicting prototypes for getopt. */ 67 | #include 68 | #endif /* GNU C library. */ 69 | 70 | /* This version of `getopt' appears to the caller like standard Unix `getopt' 71 | but it behaves differently for the user, since it allows the user 72 | to intersperse the options with the other arguments. 73 | 74 | As `getopt' works, it permutes the elements of ARGV so that, 75 | when it is done, all the options precede everything else. Thus 76 | all application programs are extended to handle flexible argument order. 77 | 78 | Setting the environment variable POSIXLY_CORRECT disables permutation. 79 | Then the behavior is completely standard. 80 | 81 | GNU application programs can use a third alternative mode in which 82 | they can distinguish the relative order of options and other arguments. */ 83 | 84 | #include "getopt.h" 85 | 86 | /* For communication from `getopt' to the caller. 87 | When `getopt' finds an option that takes an argument, 88 | the argument value is returned here. 89 | Also, when `ordering' is RETURN_IN_ORDER, 90 | each non-option ARGV-element is returned here. */ 91 | 92 | char *optarg = NULL; 93 | 94 | /* Index in ARGV of the next element to be scanned. 95 | This is used for communication to and from the caller 96 | and for communication between successive calls to `getopt'. 97 | 98 | On entry to `getopt', zero means this is the first call; initialize. 99 | 100 | When `getopt' returns EOF, this is the index of the first of the 101 | non-option elements that the caller should itself scan. 102 | 103 | Otherwise, `optind' communicates from one call to the next 104 | how much of ARGV has been scanned so far. */ 105 | 106 | /* XXX 1003.2 says this must be 1 before any call. */ 107 | int optind = 0; 108 | 109 | /* The next char to be scanned in the option-element 110 | in which the last option character we returned was found. 111 | This allows us to pick up the scan where we left off. 112 | 113 | If this is zero, or a null string, it means resume the scan 114 | by advancing to the next ARGV-element. */ 115 | 116 | static char *nextchar; 117 | 118 | /* Callers store zero here to inhibit the error message 119 | for unrecognized options. */ 120 | 121 | int opterr = 1; 122 | 123 | /* Set to an option character which was unrecognized. 124 | This must be initialized on some systems to avoid linking in the 125 | system's own getopt implementation. */ 126 | 127 | int optopt = '?'; 128 | 129 | /* Describe how to deal with options that follow non-option ARGV-elements. 130 | 131 | If the caller did not specify anything, 132 | the default is REQUIRE_ORDER if the environment variable 133 | POSIXLY_CORRECT is defined, PERMUTE otherwise. 134 | 135 | REQUIRE_ORDER means don't recognize them as options; 136 | stop option processing when the first non-option is seen. 137 | This is what Unix does. 138 | This mode of operation is selected by either setting the environment 139 | variable POSIXLY_CORRECT, or using `+' as the first character 140 | of the list of option characters. 141 | 142 | PERMUTE is the default. We permute the contents of ARGV as we scan, 143 | so that eventually all the non-options are at the end. This allows options 144 | to be given in any order, even with programs that were not written to 145 | expect this. 146 | 147 | RETURN_IN_ORDER is an option available to programs that were written 148 | to expect options and other ARGV-elements in any order and that care about 149 | the ordering of the two. We describe each non-option ARGV-element 150 | as if it were the argument of an option with character code 1. 151 | Using `-' as the first character of the list of option characters 152 | selects this mode of operation. 153 | 154 | The special argument `--' forces an end of option-scanning regardless 155 | of the value of `ordering'. In the case of RETURN_IN_ORDER, only 156 | `--' can cause `getopt' to return EOF with `optind' != ARGC. */ 157 | 158 | static enum 159 | { 160 | REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER 161 | } ordering; 162 | 163 | /* Value of POSIXLY_CORRECT environment variable. */ 164 | static char *posixly_correct; 165 | 166 | #ifdef __GNU_LIBRARY__ 167 | /* We want to avoid inclusion of string.h with non-GNU libraries 168 | because there are many ways it can cause trouble. 169 | On some systems, it contains special magic macros that don't work 170 | in GCC. */ 171 | #include 172 | #define my_index strchr 173 | #else 174 | 175 | /* Avoid depending on library functions or files 176 | whose names are inconsistent. */ 177 | 178 | char *getenv (); 179 | 180 | static char * 181 | my_index (str, chr) 182 | const char *str; 183 | int chr; 184 | { 185 | while (*str) 186 | { 187 | if (*str == chr) 188 | return (char *) str; 189 | str++; 190 | } 191 | return 0; 192 | } 193 | 194 | /* If using GCC, we can safely declare strlen this way. 195 | If not using GCC, it is ok not to declare it. */ 196 | #ifdef __GNUC__ 197 | /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. 198 | That was relevant to code that was here before. */ 199 | #if !defined (__STDC__) || !__STDC__ 200 | /* gcc with -traditional declares the built-in strlen to return int, 201 | and has done so at least since version 2.4.5. -- rms. */ 202 | extern int strlen (const char *); 203 | #endif /* not __STDC__ */ 204 | #endif /* __GNUC__ */ 205 | 206 | #endif /* not __GNU_LIBRARY__ */ 207 | 208 | /* Handle permutation of arguments. */ 209 | 210 | /* Describe the part of ARGV that contains non-options that have 211 | been skipped. `first_nonopt' is the index in ARGV of the first of them; 212 | `last_nonopt' is the index after the last of them. */ 213 | 214 | static int first_nonopt; 215 | static int last_nonopt; 216 | 217 | /* Exchange two adjacent subsequences of ARGV. 218 | One subsequence is elements [first_nonopt,last_nonopt) 219 | which contains all the non-options that have been skipped so far. 220 | The other is elements [last_nonopt,optind), which contains all 221 | the options processed since those non-options were skipped. 222 | 223 | `first_nonopt' and `last_nonopt' are relocated so that they describe 224 | the new indices of the non-options in ARGV after they are moved. */ 225 | 226 | static void 227 | exchange (argv) 228 | char **argv; 229 | { 230 | int bottom = first_nonopt; 231 | int middle = last_nonopt; 232 | int top = optind; 233 | char *tem; 234 | 235 | /* Exchange the shorter segment with the far end of the longer segment. 236 | That puts the shorter segment into the right place. 237 | It leaves the longer segment in the right place overall, 238 | but it consists of two parts that need to be swapped next. */ 239 | 240 | while (top > middle && middle > bottom) 241 | { 242 | if (top - middle > middle - bottom) 243 | { 244 | /* Bottom segment is the short one. */ 245 | int len = middle - bottom; 246 | register int i; 247 | 248 | /* Swap it with the top part of the top segment. */ 249 | for (i = 0; i < len; i++) 250 | { 251 | tem = argv[bottom + i]; 252 | argv[bottom + i] = argv[top - (middle - bottom) + i]; 253 | argv[top - (middle - bottom) + i] = tem; 254 | } 255 | /* Exclude the moved bottom segment from further swapping. */ 256 | top -= len; 257 | } 258 | else 259 | { 260 | /* Top segment is the short one. */ 261 | int len = top - middle; 262 | register int i; 263 | 264 | /* Swap it with the bottom part of the bottom segment. */ 265 | for (i = 0; i < len; i++) 266 | { 267 | tem = argv[bottom + i]; 268 | argv[bottom + i] = argv[middle + i]; 269 | argv[middle + i] = tem; 270 | } 271 | /* Exclude the moved top segment from further swapping. */ 272 | bottom += len; 273 | } 274 | } 275 | 276 | /* Update records for the slots the non-options now occupy. */ 277 | 278 | first_nonopt += (optind - last_nonopt); 279 | last_nonopt = optind; 280 | } 281 | 282 | /* Initialize the internal data when the first call is made. */ 283 | 284 | static const char * 285 | _getopt_initialize (optstring) 286 | const char *optstring; 287 | { 288 | /* Start processing options with ARGV-element 1 (since ARGV-element 0 289 | is the program name); the sequence of previously skipped 290 | non-option ARGV-elements is empty. */ 291 | 292 | first_nonopt = last_nonopt = optind = 1; 293 | 294 | nextchar = NULL; 295 | 296 | posixly_correct = getenv ("POSIXLY_CORRECT"); 297 | 298 | /* Determine how to handle the ordering of options and nonoptions. */ 299 | 300 | if (optstring[0] == '-') 301 | { 302 | ordering = RETURN_IN_ORDER; 303 | ++optstring; 304 | } 305 | else if (optstring[0] == '+') 306 | { 307 | ordering = REQUIRE_ORDER; 308 | ++optstring; 309 | } 310 | else if (posixly_correct != NULL) 311 | ordering = REQUIRE_ORDER; 312 | else 313 | ordering = PERMUTE; 314 | 315 | return optstring; 316 | } 317 | 318 | /* Scan elements of ARGV (whose length is ARGC) for option characters 319 | given in OPTSTRING. 320 | 321 | If an element of ARGV starts with '-', and is not exactly "-" or "--", 322 | then it is an option element. The characters of this element 323 | (aside from the initial '-') are option characters. If `getopt' 324 | is called repeatedly, it returns successively each of the option characters 325 | from each of the option elements. 326 | 327 | If `getopt' finds another option character, it returns that character, 328 | updating `optind' and `nextchar' so that the next call to `getopt' can 329 | resume the scan with the following option character or ARGV-element. 330 | 331 | If there are no more option characters, `getopt' returns `EOF'. 332 | Then `optind' is the index in ARGV of the first ARGV-element 333 | that is not an option. (The ARGV-elements have been permuted 334 | so that those that are not options now come last.) 335 | 336 | OPTSTRING is a string containing the legitimate option characters. 337 | If an option character is seen that is not listed in OPTSTRING, 338 | return '?' after printing an error message. If you set `opterr' to 339 | zero, the error message is suppressed but we still return '?'. 340 | 341 | If a char in OPTSTRING is followed by a colon, that means it wants an arg, 342 | so the following text in the same ARGV-element, or the text of the following 343 | ARGV-element, is returned in `optarg'. Two colons mean an option that 344 | wants an optional arg; if there is text in the current ARGV-element, 345 | it is returned in `optarg', otherwise `optarg' is set to zero. 346 | 347 | If OPTSTRING starts with `-' or `+', it requests different methods of 348 | handling the non-option ARGV-elements. 349 | See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. 350 | 351 | Long-named options begin with `--' instead of `-'. 352 | Their names may be abbreviated as long as the abbreviation is unique 353 | or is an exact match for some defined option. If they have an 354 | argument, it follows the option name in the same ARGV-element, separated 355 | from the option name by a `=', or else the in next ARGV-element. 356 | When `getopt' finds a long-named option, it returns 0 if that option's 357 | `flag' field is nonzero, the value of the option's `val' field 358 | if the `flag' field is zero. 359 | 360 | The elements of ARGV aren't really const, because we permute them. 361 | But we pretend they're const in the prototype to be compatible 362 | with other systems. 363 | 364 | LONGOPTS is a vector of `struct option' terminated by an 365 | element containing a name which is zero. 366 | 367 | LONGIND returns the index in LONGOPT of the long-named option found. 368 | It is only valid when a long-named option has been found by the most 369 | recent call. 370 | 371 | If LONG_ONLY is nonzero, '-' as well as '--' can introduce 372 | long-named options. */ 373 | 374 | int 375 | _getopt_internal (argc, argv, optstring, longopts, longind, long_only) 376 | int argc; 377 | char *const *argv; 378 | const char *optstring; 379 | const struct option *longopts; 380 | int *longind; 381 | int long_only; 382 | { 383 | optarg = NULL; 384 | 385 | if (optind == 0) 386 | optstring = _getopt_initialize (optstring); 387 | 388 | if (nextchar == NULL || *nextchar == '\0') 389 | { 390 | /* Advance to the next ARGV-element. */ 391 | 392 | if (ordering == PERMUTE) 393 | { 394 | /* If we have just processed some options following some non-options, 395 | exchange them so that the options come first. */ 396 | 397 | if (first_nonopt != last_nonopt && last_nonopt != optind) 398 | exchange ((char **) argv); 399 | else if (last_nonopt != optind) 400 | first_nonopt = optind; 401 | 402 | /* Skip any additional non-options 403 | and extend the range of non-options previously skipped. */ 404 | 405 | while (optind < argc 406 | && (argv[optind][0] != '-' || argv[optind][1] == '\0')) 407 | optind++; 408 | last_nonopt = optind; 409 | } 410 | 411 | /* The special ARGV-element `--' means premature end of options. 412 | Skip it like a null option, 413 | then exchange with previous non-options as if it were an option, 414 | then skip everything else like a non-option. */ 415 | 416 | if (optind != argc && !strcmp (argv[optind], "--")) 417 | { 418 | optind++; 419 | 420 | if (first_nonopt != last_nonopt && last_nonopt != optind) 421 | exchange ((char **) argv); 422 | else if (first_nonopt == last_nonopt) 423 | first_nonopt = optind; 424 | last_nonopt = argc; 425 | 426 | optind = argc; 427 | } 428 | 429 | /* If we have done all the ARGV-elements, stop the scan 430 | and back over any non-options that we skipped and permuted. */ 431 | 432 | if (optind == argc) 433 | { 434 | /* Set the next-arg-index to point at the non-options 435 | that we previously skipped, so the caller will digest them. */ 436 | if (first_nonopt != last_nonopt) 437 | optind = first_nonopt; 438 | return EOF; 439 | } 440 | 441 | /* If we have come to a non-option and did not permute it, 442 | either stop the scan or describe it to the caller and pass it by. */ 443 | 444 | if ((argv[optind][0] != '-' || argv[optind][1] == '\0')) 445 | { 446 | if (ordering == REQUIRE_ORDER) 447 | return EOF; 448 | optarg = argv[optind++]; 449 | return 1; 450 | } 451 | 452 | /* We have found another option-ARGV-element. 453 | Skip the initial punctuation. */ 454 | 455 | nextchar = (argv[optind] + 1 456 | + (longopts != NULL && argv[optind][1] == '-')); 457 | } 458 | 459 | /* Decode the current option-ARGV-element. */ 460 | 461 | /* Check whether the ARGV-element is a long option. 462 | 463 | If long_only and the ARGV-element has the form "-f", where f is 464 | a valid short option, don't consider it an abbreviated form of 465 | a long option that starts with f. Otherwise there would be no 466 | way to give the -f short option. 467 | 468 | On the other hand, if there's a long option "fubar" and 469 | the ARGV-element is "-fu", do consider that an abbreviation of 470 | the long option, just like "--fu", and not "-f" with arg "u". 471 | 472 | This distinction seems to be the most useful approach. */ 473 | 474 | if (longopts != NULL 475 | && (argv[optind][1] == '-' 476 | || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) 477 | { 478 | char *nameend; 479 | const struct option *p; 480 | const struct option *pfound = NULL; 481 | int exact = 0; 482 | int ambig = 0; 483 | int indfound; 484 | int option_index; 485 | 486 | for (nameend = nextchar; *nameend && *nameend != '='; nameend++) 487 | /* Do nothing. */ ; 488 | 489 | /* Test all long options for either exact match 490 | or abbreviated matches. */ 491 | for (p = longopts, option_index = 0; p->name; p++, option_index++) 492 | if (!strncmp (p->name, nextchar, nameend - nextchar)) 493 | { 494 | if ((unsigned int)(nameend - nextchar) == (unsigned int)strlen (p->name)) 495 | { 496 | /* Exact match found. */ 497 | pfound = p; 498 | indfound = option_index; 499 | exact = 1; 500 | break; 501 | } 502 | else if (pfound == NULL) 503 | { 504 | /* First nonexact match found. */ 505 | pfound = p; 506 | indfound = option_index; 507 | } 508 | else 509 | /* Second or later nonexact match found. */ 510 | ambig = 1; 511 | } 512 | 513 | if (ambig && !exact) 514 | { 515 | if (opterr) 516 | fprintf (stderr, "%s: option `%s' is ambiguous\n", 517 | argv[0], argv[optind]); 518 | nextchar += strlen (nextchar); 519 | optind++; 520 | return '?'; 521 | } 522 | 523 | if (pfound != NULL) 524 | { 525 | option_index = indfound; 526 | optind++; 527 | if (*nameend) 528 | { 529 | /* Don't test has_arg with >, because some C compilers don't 530 | allow it to be used on enums. */ 531 | if (pfound->has_arg) 532 | optarg = nameend + 1; 533 | else 534 | { 535 | if (opterr) 536 | { 537 | if (argv[optind - 1][1] == '-') 538 | /* --option */ 539 | fprintf (stderr, 540 | "%s: option `--%s' doesn't allow an argument\n", 541 | argv[0], pfound->name); 542 | else 543 | /* +option or -option */ 544 | fprintf (stderr, 545 | "%s: option `%c%s' doesn't allow an argument\n", 546 | argv[0], argv[optind - 1][0], pfound->name); 547 | } 548 | nextchar += strlen (nextchar); 549 | return '?'; 550 | } 551 | } 552 | else if (pfound->has_arg == 1) 553 | { 554 | if (optind < argc) 555 | optarg = argv[optind++]; 556 | else 557 | { 558 | if (opterr) 559 | fprintf (stderr, "%s: option `%s' requires an argument\n", 560 | argv[0], argv[optind - 1]); 561 | nextchar += strlen (nextchar); 562 | return optstring[0] == ':' ? ':' : '?'; 563 | } 564 | } 565 | nextchar += strlen (nextchar); 566 | if (longind != NULL) 567 | *longind = option_index; 568 | if (pfound->flag) 569 | { 570 | *(pfound->flag) = pfound->val; 571 | return 0; 572 | } 573 | return pfound->val; 574 | } 575 | 576 | /* Can't find it as a long option. If this is not getopt_long_only, 577 | or the option starts with '--' or is not a valid short 578 | option, then it's an error. 579 | Otherwise interpret it as a short option. */ 580 | if (!long_only || argv[optind][1] == '-' 581 | || my_index (optstring, *nextchar) == NULL) 582 | { 583 | if (opterr) 584 | { 585 | if (argv[optind][1] == '-') 586 | /* --option */ 587 | fprintf (stderr, "%s: unrecognized option `--%s'\n", 588 | argv[0], nextchar); 589 | else 590 | /* +option or -option */ 591 | fprintf (stderr, "%s: unrecognized option `%c%s'\n", 592 | argv[0], argv[optind][0], nextchar); 593 | } 594 | nextchar = (char *) ""; 595 | optind++; 596 | return '?'; 597 | } 598 | } 599 | 600 | /* Look at and handle the next short option-character. */ 601 | 602 | { 603 | char c = *nextchar++; 604 | char *temp = my_index (optstring, c); 605 | 606 | /* Increment `optind' when we start to process its last character. */ 607 | if (*nextchar == '\0') 608 | ++optind; 609 | 610 | if (temp == NULL || c == ':') 611 | { 612 | if (opterr) 613 | { 614 | if (posixly_correct) 615 | /* 1003.2 specifies the format of this message. */ 616 | fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c); 617 | else 618 | fprintf (stderr, "%s: invalid option -- %c\n", argv[0], c); 619 | } 620 | optopt = c; 621 | return '?'; 622 | } 623 | if (temp[1] == ':') 624 | { 625 | if (temp[2] == ':') 626 | { 627 | /* This is an option that accepts an argument optionally. */ 628 | if (*nextchar != '\0') 629 | { 630 | optarg = nextchar; 631 | optind++; 632 | } 633 | else 634 | optarg = NULL; 635 | nextchar = NULL; 636 | } 637 | else 638 | { 639 | /* This is an option that requires an argument. */ 640 | if (*nextchar != '\0') 641 | { 642 | optarg = nextchar; 643 | /* If we end this ARGV-element by taking the rest as an arg, 644 | we must advance to the next element now. */ 645 | optind++; 646 | } 647 | else if (optind == argc) 648 | { 649 | if (opterr) 650 | { 651 | /* 1003.2 specifies the format of this message. */ 652 | fprintf (stderr, "%s: option requires an argument -- %c\n", 653 | argv[0], c); 654 | } 655 | optopt = c; 656 | if (optstring[0] == ':') 657 | c = ':'; 658 | else 659 | c = '?'; 660 | } 661 | else 662 | /* We already incremented `optind' once; 663 | increment it again when taking next ARGV-elt as argument. */ 664 | optarg = argv[optind++]; 665 | nextchar = NULL; 666 | } 667 | } 668 | return c; 669 | } 670 | } 671 | 672 | int 673 | getopt (argc, argv, optstring) 674 | int argc; 675 | char *const *argv; 676 | const char *optstring; 677 | { 678 | return _getopt_internal (argc, argv, optstring, 679 | (const struct option *) 0, 680 | (int *) 0, 681 | 0); 682 | } 683 | 684 | #endif /* _LIBC or not __GNU_LIBRARY__. */ 685 | 686 | #ifdef TEST 687 | 688 | /* Compile with -DTEST to make an executable for use in testing 689 | the above definition of `getopt'. */ 690 | 691 | int 692 | main (argc, argv) 693 | int argc; 694 | char **argv; 695 | { 696 | int c; 697 | int digit_optind = 0; 698 | 699 | while (1) 700 | { 701 | int this_option_optind = optind ? optind : 1; 702 | 703 | c = getopt (argc, argv, "abc:d:0123456789"); 704 | if (c == EOF) 705 | break; 706 | 707 | switch (c) 708 | { 709 | case '0': 710 | case '1': 711 | case '2': 712 | case '3': 713 | case '4': 714 | case '5': 715 | case '6': 716 | case '7': 717 | case '8': 718 | case '9': 719 | if (digit_optind != 0 && digit_optind != this_option_optind) 720 | printf ("digits occur in two different argv-elements.\n"); 721 | digit_optind = this_option_optind; 722 | printf ("option %c\n", c); 723 | break; 724 | 725 | case 'a': 726 | printf ("option a\n"); 727 | break; 728 | 729 | case 'b': 730 | printf ("option b\n"); 731 | break; 732 | 733 | case 'c': 734 | printf ("option c with value `%s'\n", optarg); 735 | break; 736 | 737 | case '?': 738 | break; 739 | 740 | default: 741 | printf ("?? getopt returned character code 0%o ??\n", c); 742 | } 743 | } 744 | 745 | if (optind < argc) 746 | { 747 | printf ("non-option ARGV-elements: "); 748 | while (optind < argc) 749 | printf ("%s ", argv[optind++]); 750 | printf ("\n"); 751 | } 752 | 753 | exit (0); 754 | } 755 | 756 | #endif /* TEST */ 757 | -------------------------------------------------------------------------------- /hobbit.txt: -------------------------------------------------------------------------------- 1 | Netcat 1.10 2 | =========== /\_/\ 3 | / 0 0 \ 4 | Netcat is a simple Unix utility which reads and writes data ====v==== 5 | across network connections, using TCP or UDP protocol. \ W / 6 | It is designed to be a reliable "back-end" tool that can | | _ 7 | be used directly or easily driven by other programs and / ___ \ / 8 | scripts. At the same time, it is a feature-rich network / / \ \ | 9 | debugging and exploration tool, since it can create almost (((-----)))-' 10 | any kind of connection you would need and has several / 11 | interesting built-in capabilities. Netcat, or "nc" as the ( ___ 12 | actual program is named, should have been supplied long ago \__.=|___E 13 | as another one of those cryptic but standard Unix tools. / 14 | 15 | In the simplest usage, "nc host port" creates a TCP connection to the given 16 | port on the given target host. Your standard input is then sent to the host, 17 | and anything that comes back across the connection is sent to your standard 18 | output. This continues indefinitely, until the network side of the connection 19 | shuts down. Note that this behavior is different from most other applications 20 | which shut everything down and exit after an end-of-file on the standard input. 21 | 22 | Netcat can also function as a server, by listening for inbound connections 23 | on arbitrary ports and then doing the same reading and writing. With minor 24 | limitations, netcat doesn't really care if it runs in "client" or "server" 25 | mode -- it still shovels data back and forth until there isn't any more left. 26 | In either mode, shutdown can be forced after a configurable time of inactivity 27 | on the network side. 28 | 29 | And it can do this via UDP too, so netcat is possibly the "udp telnet-like" 30 | application you always wanted for testing your UDP-mode servers. UDP, as the 31 | "U" implies, gives less reliable data transmission than TCP connections and 32 | some systems may have trouble sending large amounts of data that way, but it's 33 | still a useful capability to have. 34 | 35 | You may be asking "why not just use telnet to connect to arbitrary ports?" 36 | Valid question, and here are some reasons. Telnet has the "standard input 37 | EOF" problem, so one must introduce calculated delays in driving scripts to 38 | allow network output to finish. This is the main reason netcat stays running 39 | until the *network* side closes. Telnet also will not transfer arbitrary 40 | binary data, because certain characters are interpreted as telnet options and 41 | are thus removed from the data stream. Telnet also emits some of its 42 | diagnostic messages to standard output, where netcat keeps such things 43 | religiously separated from its *output* and will never modify any of the real 44 | data in transit unless you *really* want it to. And of course telnet is 45 | incapable of listening for inbound connections, or using UDP instead. Netcat 46 | doesn't have any of these limitations, is much smaller and faster than telnet, 47 | and has many other advantages. 48 | 49 | Some of netcat's major features are: 50 | 51 | Outbound or inbound connections, TCP or UDP, to or from any ports 52 | Full DNS forward/reverse checking, with appropriate warnings 53 | Ability to use any local source port 54 | Ability to use any locally-configured network source address 55 | Built-in port-scanning capabilities, with randomizer 56 | Built-in loose source-routing capability 57 | Can read command line arguments from standard input 58 | Slow-send mode, one line every N seconds 59 | Hex dump of transmitted and received data 60 | Optional ability to let another program service established connections 61 | Optional telnet-options responder 62 | 63 | Efforts have been made to have netcat "do the right thing" in all its various 64 | modes. If you believe that it is doing the wrong thing under whatever 65 | circumstances, please notify me and tell me how you think it should behave. 66 | If netcat is not able to do some task you think up, minor tweaks to the code 67 | will probably fix that. It provides a basic and easily-modified template for 68 | writing other network applications, and I certainly encourage people to make 69 | custom mods and send in any improvements they make to it. This is the second 70 | release; the overall differences from 1.00 are relatively minor and have mostly 71 | to do with portability and bugfixes. Many people provided greatly appreciated 72 | fixes and comments on the 1.00 release. Continued feedback from the Internet 73 | community is always welcome! 74 | 75 | Netcat is entirely my own creation, although plenty of other code was used as 76 | examples. It is freely given away to the Internet community in the hope that 77 | it will be useful, with no restrictions except giving credit where it is due. 78 | No GPLs, Berkeley copyrights or any of that nonsense. The author assumes NO 79 | responsibility for how anyone uses it. If netcat makes you rich somehow and 80 | you're feeling generous, mail me a check. If you are affiliated in any way 81 | with Microsoft Network, get a life. Always ski in control. Comments, 82 | questions, and patches to hobbit@avian.org. 83 | 84 | Building 85 | ======== 86 | 87 | Compiling is fairly straightforward. Examine the Makefile for a SYSTYPE that 88 | matches yours, and do "make ". The executable "nc" should appear. 89 | If there is no relevant SYSTYPE section, try "generic". If you create new 90 | sections for generic.h and Makefile to support another platform, please follow 91 | the given format and mail back the diffs. 92 | 93 | There are a couple of other settable #defines in netcat.c, which you can 94 | include as DFLAGS="-DTHIS -DTHAT" to your "make" invocation without having to 95 | edit the Makefile. See the following discussions for what they are and do. 96 | 97 | If you want to link against the resolver library on SunOS [recommended] and 98 | you have BIND 4.9.x, you may need to change XLIBS=-lresolv in the Makefile to 99 | XLIBS="-lresolv -l44bsd". 100 | 101 | Linux sys/time.h does not really support presetting of FD_SETSIZE; a harmless 102 | warning is issued. 103 | 104 | Some systems may warn about pointer types for signal(). No problem, though. 105 | 106 | Exploration of features 107 | ======================= 108 | 109 | Where to begin? Netcat is at the same time so simple and versatile, it's like 110 | trying to describe everything you can do with your Swiss Army knife. This will 111 | go over the basics; you should also read the usage examples and notes later on 112 | which may give you even more ideas about what this sort of tool is good for. 113 | 114 | If no command arguments are given at all, netcat asks for them, reads a line 115 | from standard input, and breaks it up into arguments internally. This can be 116 | useful when driving netcat from certain types of scripts, with the side effect 117 | of hiding your command line arguments from "ps" displays. 118 | 119 | The host argument can be a name or IP address. If -n is specified, netcat 120 | will only accept numeric IP addresses and do no DNS lookups for anything. If 121 | -n is not given and -v is turned on, netcat will do a full forward and reverse 122 | name and address lookup for the host, and warn you about the all-too-common 123 | problem of mismatched names in the DNS. This often takes a little longer for 124 | connection setup, but is useful to know about. There are circumstances under 125 | which this can *save* time, such as when you want to know the name for some IP 126 | address and also connect there. Netcat will just tell you all about it, saving 127 | the manual steps of looking up the hostname yourself. Normally mismatch- 128 | checking is case-insensitive per the DNS spec, but you can define ANAL at 129 | compile time to make it case-sensitive -- sometimes useful for uncovering minor 130 | errors in your own DNS files while poking around your networks. 131 | 132 | A port argument is required for outbound connections, and can be numeric or a 133 | name as listed in /etc/services. If -n is specified, only numeric arguments 134 | are valid. Special syntax and/or more than one port argument cause different 135 | behavior -- see details below about port-scanning. 136 | 137 | The -v switch controls the verbosity level of messages sent to standard error. 138 | You will probably want to run netcat most of the time with -v turned on, so you 139 | can see info about the connections it is trying to make. You will probably 140 | also want to give a smallish -w argument, which limits the time spent trying to 141 | make a connection. I usually alias "nc" to "nc -v -w 3", which makes it 142 | function just about the same for things I would otherwise use telnet to do. 143 | The timeout is easily changed by a subsequent -w argument which overrides the 144 | earlier one. Specifying -v more than once makes diagnostic output MORE 145 | verbose. If -v is not specified at all, netcat silently does its work unless 146 | some error happens, whereupon it describes the error and exits with a nonzero 147 | status. Refused network connections are generally NOT considered to be errors, 148 | unless you only asked for a single TCP port and it was refused. 149 | 150 | Note that -w also sets the network inactivity timeout. This does not have any 151 | effect until standard input closes, but then if nothing further arrives from 152 | the network in the next seconds, netcat tries to read the net once 153 | more for good measure, and then closes and exits. There are a lot of network 154 | services now that accept a small amount of input and return a large amount of 155 | output, such as Gopher and Web servers, which is the main reason netcat was 156 | written to "block" on the network staying open rather than standard input. 157 | Handling the timeout this way gives uniform behavior with network servers that 158 | *don't* close by themselves until told to. 159 | 160 | UDP connections are opened instead of TCP when -u is specified. These aren't 161 | really "connections" per se since UDP is a connectionless protocol, although 162 | netcat does internally use the "connected UDP socket" mechanism that most 163 | kernels support. Although netcat claims that an outgoing UDP connection is 164 | "open" immediately, no data is sent until something is read from standard 165 | input. Only thereafter is it possible to determine whether there really is a 166 | UDP server on the other end, and often you just can't tell. Most UDP protocols 167 | use timeouts and retries to do their thing and in many cases won't bother 168 | answering at all, so you should specify a timeout and hope for the best. You 169 | will get more out of UDP connections if standard input is fed from a source 170 | of data that looks like various kinds of server requests. 171 | 172 | To obtain a hex dump file of the data sent either way, use "-o logfile". The 173 | dump lines begin with "<" or ">" to respectively indicate "from the net" or 174 | "to the net", and contain the total count per direction, and hex and ascii 175 | representations of the traffic. Capturing a hex dump naturally slows netcat 176 | down a bit, so don't use it where speed is critical. 177 | 178 | Netcat can bind to any local port, subject to privilege restrictions and ports 179 | that are already in use. It is also possible to use a specific local network 180 | source address if it is that of a network interface on your machine. [Note: 181 | this does not work correctly on all platforms.] Use "-p portarg" to grab a 182 | specific local port, and "-s ip-addr" or "-s name" to have that be your source 183 | IP address. This is often referred to as "anchoring the socket". Root users 184 | can grab any unused source port including the "reserved" ones less than 1024. 185 | Absence of -p will bind to whatever unused port the system gives you, just like 186 | any other normal client connection, unless you use -r [see below]. 187 | 188 | Listen mode will cause netcat to wait for an inbound connection, and then the 189 | same data transfer happens. Thus, you can do "nc -l -p 1234 < filename" and 190 | when someone else connects to your port 1234, the file is sent to them whether 191 | they wanted it or not. Listen mode is generally used along with a local port 192 | argument -- this is required for UDP mode, while TCP mode can have the system 193 | assign one and tell you what it is if -v is turned on. If you specify a target 194 | host and optional port in listen mode, netcat will accept an inbound connection 195 | only from that host and if you specify one, only from that foreign source port. 196 | In verbose mode you'll be informed about the inbound connection, including what 197 | address and port it came from, and since listening on "any" applies to several 198 | possibilities, which address it came *to* on your end. If the system supports 199 | IP socket options, netcat will attempt to retrieve any such options from an 200 | inbound connection and print them out in hex. 201 | 202 | If netcat is compiled with -DGAPING_SECURITY_HOLE, the -e argument specifies 203 | a program to exec after making or receiving a successful connection. In the 204 | listening mode, this works similarly to "inetd" but only for a single instance. 205 | Use with GREAT CARE. This piece of the code is normally not enabled; if you 206 | know what you're doing, have fun. This hack also works in UDP mode. Note that 207 | you can only supply -e with the name of the program, but no arguments. If you 208 | want to launch something with an argument list, write a two-line wrapper script 209 | or just use inetd like always. 210 | 211 | If netcat is compiled with -DTELNET, the -t argument enables it to respond 212 | to telnet option negotiation [always in the negative, i.e. DONT or WONT]. 213 | This allows it to connect to a telnetd and get past the initial negotiation 214 | far enough to get a login prompt from the server. Since this feature has 215 | the potential to modify the data stream, it is not enabled by default. You 216 | have to understand why you might need this and turn on the #define yourself. 217 | 218 | Data from the network connection is always delivered to standard output as 219 | efficiently as possible, using large 8K reads and writes. Standard input is 220 | normally sent to the net the same way, but the -i switch specifies an "interval 221 | time" which slows this down considerably. Standard input is still read in 222 | large batches, but netcat then tries to find where line breaks exist and sends 223 | one line every interval time. Note that if standard input is a terminal, data 224 | is already read line by line, so unless you make the -i interval rather long, 225 | what you type will go out at a fairly normal rate. -i is really designed 226 | for use when you want to "measure out" what is read from files or pipes. 227 | 228 | Port-scanning is a popular method for exploring what's out there. Netcat 229 | accepts its commands with options first, then the target host, and everything 230 | thereafter is interpreted as port names or numbers, or ranges of ports in M-N 231 | syntax. CAVEAT: some port names in /etc/services contain hyphens -- netcat 232 | currently will not correctly parse those, so specify ranges using numbers if 233 | you can. If more than one port is thus specified, netcat connects to *all* of 234 | them, sending the same batch of data from standard input [up to 8K worth] to 235 | each one that is successfully connected to. Specifying multiple ports also 236 | suppresses diagnostic messages about refused connections, unless -v is 237 | specified twice for "more verbosity". This way you normally get notified only 238 | about genuinely open connections. Example: "nc -v -w 2 -z target 20-30" will 239 | try connecting to every port between 20 and 30 [inclusive] at the target, and 240 | will likely inform you about an FTP server, telnet server, and mailer along the 241 | way. The -z switch prevents sending any data to a TCP connection and very 242 | limited probe data to a UDP connection, and is thus useful as a fast scanning 243 | mode just to see what ports the target is listening on. To limit scanning 244 | speed if desired, -i will insert a delay between each port probe. There are 245 | some pitfalls with regard to UDP scanning, described later, but in general it 246 | works well. 247 | 248 | For each range of ports specified, scanning is normally done downward within 249 | that range. If the -r switch is used, scanning hops randomly around within 250 | that range and reports open ports as it finds them. [If you want them listed 251 | in order regardless, pipe standard error through "sort"...] In addition, if 252 | random mode is in effect, the local source ports are also randomized. This 253 | prevents netcat from exhibiting any kind of regular pattern in its scanning. 254 | You can exert fairly fine control over your scan by judicious use of -r and 255 | selected port ranges to cover. If you use -r for a single connection, the 256 | source port will have a random value above 8192, rather than the next one the 257 | kernel would have assigned you. Note that selecting a specific local port 258 | with -p overrides any local-port randomization. 259 | 260 | Many people are interested in testing network connectivity using IP source 261 | routing, even if it's only to make sure their own firewalls are blocking 262 | source-routed packets. On systems that support it, the -g switch can be used 263 | multiple times [up to 8] to construct a loose-source-routed path for your 264 | connection, and the -G argument positions the "hop pointer" within the list. 265 | If your network allows source-routed traffic in and out, you can test 266 | connectivity to your own services via remote points in the internet. Note that 267 | although newer BSD-flavor telnets also have source-routing capability, it isn't 268 | clearly documented and the command syntax is somewhat clumsy. Netcat's 269 | handling of "-g" is modeled after "traceroute". 270 | 271 | Netcat tries its best to behave just like "cat". It currently does nothing to 272 | terminal input modes, and does no end-of-line conversion. Standard input from 273 | a terminal is read line by line with normal editing characters in effect. You 274 | can freely suspend out of an interactive connection and resume. ^C or whatever 275 | your interrupt character is will make netcat close the network connection and 276 | exit. A switch to place the terminal in raw mode has been considered, but so 277 | far has not been necessary. You can send raw binary data by reading it out of 278 | a file or piping from another program, so more meaningful effort would be spent 279 | writing an appropriate front-end driver. 280 | 281 | Netcat is not an "arbitrary packet generator", but the ability to talk to raw 282 | sockets and/or nit/bpf/dlpi may appear at some point. Such things are clearly 283 | useful; I refer you to Darren Reed's excellent ip_filter package, which now 284 | includes a tool to construct and send raw packets with any contents you want. 285 | 286 | Example uses -- the light side 287 | ============================== 288 | 289 | Again, this is a very partial list of possibilities, but it may get you to 290 | think up more applications for netcat. Driving netcat with simple shell or 291 | expect scripts is an easy and flexible way to do fairly complex tasks, 292 | especially if you're not into coding network tools in C. My coding isn't 293 | particularly strong either [although undoubtedly better after writing this 294 | thing!], so I tend to construct bare-metal tools like this that I can trivially 295 | plug into other applications. Netcat doubles as a teaching tool -- one can 296 | learn a great deal about more complex network protocols by trying to simulate 297 | them through raw connections! 298 | 299 | An example of netcat as a backend for something else is the shell-script 300 | Web browser, which simply asks for the relevant parts of a URL and pipes 301 | "GET /what/ever" into a netcat connection to the server. I used to do this 302 | with telnet, and had to use calculated sleep times and other stupidity to 303 | kludge around telnet's limitations. Netcat guarantees that I get the whole 304 | page, and since it transfers all the data unmodified, I can even pull down 305 | binary image files and display them elsewhere later. Some folks may find the 306 | idea of a shell-script web browser silly and strange, but it starts up and 307 | gets me my info a hell of a lot faster than a GUI browser and doesn't hide 308 | any contents of links and forms and such. This is included, as scripts/web, 309 | along with several other web-related examples. 310 | 311 | Netcat is an obvious replacement for telnet as a tool for talking to daemons. 312 | For example, it is easier to type "nc host 25", talk to someone's mailer, and 313 | just ^C out than having to type ^]c or QUIT as telnet would require you to do. 314 | You can quickly catalog the services on your network by telling netcat to 315 | connect to well-known services and collect greetings, or at least scan for open 316 | ports. You'll probably want to collect netcat's diagnostic messages in your 317 | output files, so be sure to include standard error in the output using 318 | `>& file' in *csh or `> file 2>&1' in bourne shell. 319 | 320 | A scanning example: "echo QUIT | nc -v -w 5 target 20-250 500-600 5990-7000" 321 | will inform you about a target's various well-known TCP servers, including 322 | r-services, X, IRC, and maybe a few you didn't expect. Sending in QUIT and 323 | using the timeout will almost guarantee that you see some kind of greeting or 324 | error from each service, which usually indicates what it is and what version. 325 | [Beware of the "chargen" port, though...] SATAN uses exactly this technique to 326 | collect host information, and indeed some of the ideas herein were taken from 327 | the SATAN backend tools. If you script this up to try every host in your 328 | subnet space and just let it run, you will not only see all the services, 329 | you'll find out about hosts that aren't correctly listed in your DNS. Then you 330 | can compare new snapshots against old snapshots to see changes. For going 331 | after particular services, a more intrusive example is in scripts/probe. 332 | 333 | Netcat can be used as a simple data transfer agent, and it doesn't really 334 | matter which end is the listener and which end is the client -- input at one 335 | side arrives at the other side as output. It is helpful to start the listener 336 | at the receiving side with no timeout specified, and then give the sending side 337 | a small timeout. That way the listener stays listening until you contact it, 338 | and after data stops flowing the client will time out, shut down, and take the 339 | listener with it. Unless the intervening network is fraught with problems, 340 | this should be completely reliable, and you can always increase the timeout. A 341 | typical example of something "rsh" is often used for: on one side, 342 | 343 | nc -l -p 1234 | uncompress -c | tar xvfp - 344 | 345 | and then on the other side 346 | 347 | tar cfp - /some/dir | compress -c | nc -w 3 othermachine 1234 348 | 349 | will transfer the contents of a directory from one machine to another, without 350 | having to worry about .rhosts files, user accounts, or inetd configurations 351 | at either end. Again, it matters not which is the listener or receiver; the 352 | "tarring" machine could just as easily be running the listener instead. One 353 | could conceivably use a scheme like this for backups, by having cron-jobs fire 354 | up listeners and backup handlers [which can be restricted to specific addresses 355 | and ports between each other] and pipe "dump" or "tar" on one machine to "dd 356 | of=/dev/tapedrive" on another as usual. Since netcat returns a nonzero exit 357 | status for a denied listener connection, scripts to handle such tasks could 358 | easily log and reject connect attempts from third parties, and then retry. 359 | 360 | Another simple data-transfer example: shipping things to a PC that doesn't have 361 | any network applications yet except a TCP stack and a web browser. Point the 362 | browser at an arbitrary port on a Unix server by telling it to download 363 | something like http://unixbox:4444/foo, and have a listener on the Unix side 364 | ready to ship out a file when the connect comes in. The browser may pervert 365 | binary data when told to save the URL, but you can dig the raw data out of 366 | the on-disk cache. 367 | 368 | If you build netcat with GAPING_SECURITY_HOLE defined, you can use it as an 369 | "inetd" substitute to test experimental network servers that would otherwise 370 | run under "inetd". A script or program will have its input and output hooked 371 | to the network the same way, perhaps sans some fancier signal handling. Given 372 | that most network services do not bind to a particular local address, whether 373 | they are under "inetd" or not, it is possible for netcat avoid the "address 374 | already in use" error by binding to a specific address. This lets you [as 375 | root, for low ports] place netcat "in the way" of a standard service, since 376 | inbound connections are generally sent to such specifically-bound listeners 377 | first and fall back to the ones bound to "any". This allows for a one-off 378 | experimental simulation of some service, without having to screw around with 379 | inetd.conf. Running with -v turned on and collecting a connection log from 380 | standard error is recommended. 381 | 382 | Netcat as well can make an outbound connection and then run a program or script 383 | on the originating end, with input and output connected to the same network 384 | port. This "inverse inetd" capability could enhance the backup-server concept 385 | described above or help facilitate things such as a "network dialback" concept. 386 | The possibilities are many and varied here; if such things are intended as 387 | security mechanisms, it may be best to modify netcat specifically for the 388 | purpose instead of wrapping such functions in scripts. 389 | 390 | Speaking of inetd, netcat will function perfectly well *under* inetd as a TCP 391 | connection redirector for inbound services, like a "plug-gw" without the 392 | authentication step. This is very useful for doing stuff like redirecting 393 | traffic through your firewall out to other places like web servers and mail 394 | hubs, while posing no risk to the firewall machine itself. Put netcat behind 395 | inetd and tcp_wrappers, perhaps thusly: 396 | 397 | www stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80 398 | 399 | and you have a simple and effective "application relay" with access control 400 | and logging. Note use of the wait time as a "safety" in case realwww isn't 401 | reachable or the calling user aborts the connection -- otherwise the relay may 402 | hang there forever. 403 | 404 | You can use netcat to generate huge amounts of useless network data for 405 | various performance testing. For example, doing 406 | 407 | yes AAAAAAAAAAAAAAAAAAAAAA | nc -v -v -l -p 2222 > /dev/null 408 | 409 | on one side and then hitting it with 410 | 411 | yes BBBBBBBBBBBBBBBBBBBBBB | nc othermachine 2222 > /dev/null 412 | 413 | from another host will saturate your wires with A's and B's. The "very 414 | verbose" switch usage will tell you how many of each were sent and received 415 | after you interrupt either side. Using UDP mode produces tremendously MORE 416 | trash per unit time in the form of fragmented 8 Kbyte mobygrams -- enough to 417 | stress-test kernels and network interfaces. Firing random binary data into 418 | various network servers may help expose bugs in their input handling, which 419 | nowadays is a popular thing to explore. A simple example data-generator is 420 | given in data/data.c included in this package, along with a small collection 421 | of canned input files to generate various packet contents. This program is 422 | documented in its beginning comments, but of interest here is using "%r" to 423 | generate random bytes at well-chosen points in a data stream. If you can 424 | crash your daemon, you likely have a security problem. 425 | 426 | The hex dump feature may be useful for debugging odd network protocols, 427 | especially if you don't have any network monitoring equipment handy or aren't 428 | root where you'd need to run "tcpdump" or something. Bind a listening netcat 429 | to a local port, and have it run a script which in turn runs another netcat 430 | to the real service and captures the hex dump to a log file. This sets up a 431 | transparent relay between your local port and wherever the real service is. 432 | Be sure that the script-run netcat does *not* use -v, or the extra info it 433 | sends to standard error may confuse the protocol. Note also that you cannot 434 | have the "listen/exec" netcat do the data capture, since once the connection 435 | arrives it is no longer netcat that is running. 436 | 437 | Binding to an arbitrary local port allows you to simulate things like r-service 438 | clients, if you are root locally. For example, feeding "^@root^@joe^@pwd^@" 439 | [where ^@ is a null, and root/joe could be any other local/remote username 440 | pair] into a "rsh" or "rlogin" server, FROM your port 1023 for example, 441 | duplicates what the server expects to receive. Thus, you can test for insecure 442 | .rhosts files around your network without having to create new user accounts on 443 | your client machine. The program data/rservice.c can aid this process by 444 | constructing the "rcmd" protocol bytes. Doing this also prevents "rshd" from 445 | trying to create that separate standard-error socket and still gives you an 446 | input path, as opposed to the usual action of "rsh -n". Using netcat for 447 | things like this can be really useful sometimes, because rsh and rlogin 448 | generally want a host *name* as an argument and won't accept IP addresses. If 449 | your client-end DNS is hosed, as may be true when you're trying to extract 450 | backup sets on to a dumb client, "netcat -n" wins where normal rsh/rlogin is 451 | useless. 452 | 453 | If you are unsure that a remote syslogger is working, test it with netcat. 454 | Make a UDP connection to port 514 and type in "<0>message", which should 455 | correspond to "kern.emerg" and cause syslogd to scream into every file it has 456 | open [and possibly all over users' terminals]. You can tame this down by 457 | using a different number and use netcat inside routine scripts to send syslog 458 | messages to places that aren't configured in syslog.conf. For example, 459 | "echo '<38>message' | nc -w 1 -u loggerhost 514" should send to auth.notice 460 | on loggerhost. The exact number may vary; check against your syslog.h first. 461 | 462 | Netcat provides several ways for you to test your own packet filters. If you 463 | bind to a port normally protected against outside access and make a connection 464 | to somewhere outside your own network, the return traffic will be coming to 465 | your chosen port from the "outside" and should be blocked. TCP may get through 466 | if your filter passes all "ack syn", but it shouldn't be even doing that to low 467 | ports on your network. Remember to test with UDP traffic as well! If your 468 | filter passes at least outbound source-routed IP packets, bouncing a connection 469 | back to yourself via some gateway outside your network will create "incoming" 470 | traffic with your source address, which should get dropped by a correctly 471 | configured anti-spoofing filter. This is a "non-test" if you're also dropping 472 | source-routing, but it's good to be able to test for that too. Any packet 473 | filter worth its salt will be blocking source-routed packets in both 474 | directions, but you never know what interesting quirks you might turn up by 475 | playing around with source ports and addresses and watching the wires with a 476 | network monitor. 477 | 478 | You can use netcat to protect your own workstation's X server against outside 479 | access. X is stupid enough to listen for connections on "any" and never tell 480 | you when new connections arrive, which is one reason it is so vulnerable. Once 481 | you have all your various X windows up and running you can use netcat to bind 482 | just to your ethernet address and listen to port 6000. Any new connections 483 | from outside the machine will hit netcat instead your X server, and you get a 484 | log of who's trying. You can either tell netcat to drop the connection, or 485 | perhaps run another copy of itself to relay to your actual X server on 486 | "localhost". This may not work for dedicated X terminals, but it may be 487 | possible to authorize your X terminal only for its boot server, and run a relay 488 | netcat over on the server that will in turn talk to your X terminal. Since 489 | netcat only handles one listening connection per run, make sure that whatever 490 | way you rig it causes another one to run and listen on 6000 soon afterward, or 491 | your real X server will be reachable once again. A very minimal script just 492 | to protect yourself could be 493 | 494 | while true ; do 495 | nc -v -l -s -p 6000 localhost 2 496 | done 497 | 498 | which causes netcat to accept and then close any inbound connection to your 499 | workstation's normal ethernet address, and another copy is immediately run by 500 | the script. Send standard error to a file for a log of connection attempts. 501 | If your system can't do the "specific bind" thing all is not lost; run your 502 | X server on display ":1" or port 6001, and netcat can still function as a probe 503 | alarm by listening on 6000. 504 | 505 | Does your shell-account provider allow personal Web pages, but not CGI scripts? 506 | You can have netcat listen on a particular port to execute a program or script 507 | of your choosing, and then just point to the port with a URL in your homepage. 508 | The listener could even exist on a completely different machine, avoiding the 509 | potential ire of the homepage-host administrators. Since the script will get 510 | the raw browser query as input it won't look like a typical CGI script, and 511 | since it's running under your UID you need to write it carefully. You may want 512 | to write a netcat-based script as a wrapper that reads a query and sets up 513 | environment variables for a regular CGI script. The possibilities for using 514 | netcat and scripts to handle Web stuff are almost endless. Again, see the 515 | examples under scripts/. 516 | 517 | Example uses -- the dark side 518 | ============================= 519 | 520 | Equal time is deserved here, since a versatile tool like this can be useful 521 | to any Shade of Hat. I could use my Victorinox to either fix your car or 522 | disassemble it, right? You can clearly use something like netcat to attack 523 | or defend -- I don't try to govern anyone's social outlook, I just build tools. 524 | Regardless of your intentions, you should still be aware of these threats to 525 | your own systems. 526 | 527 | The first obvious thing is scanning someone *else's* network for vulnerable 528 | services. Files containing preconstructed data, be it exploratory or 529 | exploitive, can be fed in as standard input, including command-line arguments 530 | to netcat itself to keep "ps" ignorant of your doings. The more random the 531 | scanning, the less likelihood of detection by humans, scan-detectors, or 532 | dynamic filtering, and with -i you'll wait longer but avoid loading down the 533 | target's network. Some examples for crafting various standard UDP probes are 534 | given in data/*.d. 535 | 536 | Some configurations of packet filters attempt to solve the FTP-data problem by 537 | just allowing such connections from the outside. These come FROM port 20, TO 538 | high TCP ports inside -- if you locally bind to port 20, you may find yourself 539 | able to bypass filtering in some cases. Maybe not to low ports "inside", but 540 | perhaps to TCP NFS servers, X servers, Prospero, ciscos that listen on 200x 541 | and 400x... Similar bypassing may be possible for UDP [and maybe TCP too] if a 542 | connection comes from port 53; a filter may assume it's a nameserver response. 543 | 544 | Using -e in conjunction with binding to a specific address can enable "server 545 | takeover" by getting in ahead of the real ones, whereupon you can snarf data 546 | sent in and feed your own back out. At the very least you can log a hex dump 547 | of someone else's session. If you are root, you can certainly use -s and -e to 548 | run various hacked daemons without having to touch inetd.conf or the real 549 | daemons themselves. You may not always have the root access to deal with low 550 | ports, but what if you are on a machine that also happens to be an NFS server? 551 | You might be able to collect some interesting things from port 2049, including 552 | local file handles. There are several other servers that run on high ports 553 | that are likely candidates for takeover, including many of the RPC services on 554 | some platforms [yppasswdd, anyone?]. Kerberos tickets, X cookies, and IRC 555 | traffic also come to mind. RADIUS-based terminal servers connect incoming 556 | users to shell-account machines on a high port, usually 1642 or thereabouts. 557 | SOCKS servers run on 1080. Do "netstat -a" and get creative. 558 | 559 | There are some daemons that are well-written enough to bind separately to all 560 | the local interfaces, possibly with an eye toward heading off this sort of 561 | problem. Named from recent BIND releases, and NTP, are two that come to mind. 562 | Netstat will show these listening on address.53 instead of *.53. You won't 563 | be able to get in front of these on any of the real interface addresses, which 564 | of course is especially interesting in the case of named, but these servers 565 | sometimes forget about things like "alias" interface addresses or interfaces 566 | that appear later on such as dynamic PPP links. There are some hacked web 567 | servers and versions of "inetd" floating around that specifically bind as well, 568 | based on a configuration file -- these generally *are* bound to alias addresses 569 | to offer several different address-based services from one machine. 570 | 571 | Using -e to start a remote backdoor shell is another obvious sort of thing, 572 | easier than constructing a file for inetd to listen on "ingreslock" or 573 | something, and you can access-control it against other people by specifying a 574 | client host and port. Experience with this truly demonstrates how fragile the 575 | barrier between being "logged in" or not really is, and is further expressed by 576 | scripts/bsh. If you're already behind a firewall, it may be easier to make an 577 | *outbound* connection and then run a shell; a small wrapper script can 578 | periodically try connecting to a known place and port, you can later listen 579 | there until the inbound connection arrives, and there's your shell. Running 580 | a shell via UDP has several interesting features, although be aware that once 581 | "connected", the UDP stub sockets tend to show up in "netstat" just like TCP 582 | connections and may not be quite as subtle as you wanted. Packets may also be 583 | lost, so use TCP if you need reliable connections. But since UDP is 584 | connectionless, a hookup of this sort will stick around almost forever, even if 585 | you ^C out of netcat or do a reboot on your side, and you only need to remember 586 | the ports you used on both ends to reestablish. And outbound UDP-plus-exec 587 | connection creates the connected socket and starts the program immediately. On 588 | a listening UDP connection, the socket is created once a first packet is 589 | received. In either case, though, such a "connection" has the interesting side 590 | effect that only your client-side IP address and [chosen?] source port will 591 | thereafter be able to talk to it. Instant access control! A non-local third 592 | party would have to do ALL of the following to take over such a session: 593 | 594 | forge UDP with your source address [trivial to do; see below] 595 | guess the port numbers of BOTH ends, or sniff the wire for them 596 | arrange to block ICMP or UDP return traffic between it and your real 597 | source, so the session doesn't die with a network write error. 598 | 599 | The companion program data/rservice.c is helpful in scripting up any sort of 600 | r-service username or password guessing attack. The arguments to "rservice" 601 | are simply the strings that get null-terminated and passed over an "rcmd"-style 602 | connection, with the assumption that the client does not need a separate 603 | standard-error port. Brute-force password banging is best done via "rexec" if 604 | it is available since it is less likely to log failed attempts. Thus, doing 605 | "rservice joe joespass pwd | nc target exec" should return joe's home dir if 606 | the password is right, or "Permission denied." Plug in a dictionary and go to 607 | town. If you're attacking rsh/rlogin, remember to be root and bind to a port 608 | between 512 and 1023 on your end, and pipe in "rservice joe joe pwd" and such. 609 | 610 | Netcat can prevent inadvertently sending extra information over a telnet 611 | connection. Use "nc -t" in place of telnet, and daemons that try to ask for 612 | things like USER and TERM environment variables will get no useful answers, as 613 | they otherwise would from a more recent telnet program. Some telnetds actually 614 | try to collect this stuff and then plug the USER variable into "login" so that 615 | the caller is then just asked for a password! This mechanism could cause a 616 | login attempt as YOUR real username to be logged over there if you use a 617 | Borman-based telnet instead of "nc -t". 618 | 619 | Got an unused network interface configured in your kernel [e.g. SLIP], or 620 | support for alias addresses? Ifconfig one to be any address you like, and bind 621 | to it with -s to enable all sorts of shenanigans with bogus source addresses. 622 | The interface probably has to be UP before this works; some SLIP versions 623 | need a far-end address before this is true. Hammering on UDP services is then 624 | a no-brainer. What you can do to an unfiltered syslog daemon should be fairly 625 | obvious; trimming the conf file can help protect against it. Many routers out 626 | there still blindly believe what they receive via RIP and other routing 627 | protocols. Although most UDP echo and chargen servers check if an incoming 628 | packet was sent from *another* "internal" UDP server, there are many that still 629 | do not, any two of which [or many, for that matter] could keep each other 630 | entertained for hours at the expense of bandwidth. And you can always make 631 | someone wonder why she's being probed by nsa.gov. 632 | 633 | Your TCP spoofing possibilities are mostly limited to destinations you can 634 | source-route to while locally bound to your phony address. Many sites block 635 | source-routed packets these days for precisely this reason. If your kernel 636 | does oddball things when sending source-routed packets, try moving the pointer 637 | around with -G. You may also have to fiddle with the routing on your own 638 | machine before you start receiving packets back. Warning: some machines still 639 | send out traffic using the source address of the outbound interface, regardless 640 | of your binding, especially in the case of localhost. Check first. If you can 641 | open a connection but then get no data back from it, the target host is 642 | probably killing the IP options on its end [this is an option inside TCP 643 | wrappers and several other packages], which happens after the 3-way handshake 644 | is completed. If you send some data and observe the "send-q" side of "netstat" 645 | for that connection increasing but never getting sent, that's another symptom. 646 | Beware: if Sendmail 8.7.x detects a source-routed SMTP connection, it extracts 647 | the hop list and sticks it in the Received: header! 648 | 649 | SYN bombing [sometimes called "hosing"] can disable many TCP servers, and if 650 | you hit one often enough, you can keep it unreachable for days. As is true of 651 | many other denial-of-service attacks, there is currently no defense against it 652 | except maybe at the human level. Making kernel SOMAXCONN considerably larger 653 | than the default and the half-open timeout smaller can help, and indeed some 654 | people running large high-performance web servers have *had* to do that just to 655 | handle normal traffic. Taking out mailers and web servers is sociopathic, but 656 | on the other hand it is sometimes useful to be able to, say, disable a site's 657 | identd daemon for a few minutes. If someone realizes what is going on, 658 | backtracing will still be difficult since the packets have a phony source 659 | address, but calls to enough ISP NOCs might eventually pinpoint the source. 660 | It is also trivial for a clueful ISP to watch for or even block outgoing 661 | packets with obviously fake source addresses, but as we know many of them are 662 | not clueful or willing to get involved in such hassles. Besides, outbound 663 | packets with an [otherwise unreachable] source address in one of their net 664 | blocks would look fairly legitimate. 665 | 666 | Notes 667 | ===== 668 | 669 | A discussion of various caveats, subtleties, and the design of the innards. 670 | 671 | As of version 1.07 you can construct a single file containing command arguments 672 | and then some data to transfer. Netcat is now smart enough to pick out the 673 | first line and build the argument list, and send any remaining data across the 674 | net to one or multiple ports. The first release of netcat had trouble with 675 | this -- it called fgets() for the command line argument, which behind the 676 | scenes does a large read() from standard input, perhaps 4096 bytes or so, and 677 | feeds that out to the fgets() library routine. By the time netcat 1.00 started 678 | directly read()ing stdin for more data, 4096 bytes of it were gone. It now 679 | uses raw read() everywhere and does the right thing whether reading from files, 680 | pipes, or ttys. If you use this for multiple-port connections, the single 681 | block of data will now be a maximum of 8K minus the first line. Improvements 682 | have been made to the logic in sending the saved chunk to each new port. Note 683 | that any command-line arguments hidden using this mechanism could still be 684 | extracted from a core dump. 685 | 686 | When netcat receives an inbound UDP connection, it creates a "connected socket" 687 | back to the source of the connection so that it can also send out data using 688 | normal write(). Using this mechanism instead of recvfrom/sendto has several 689 | advantages -- the read/write select loop is simplified, and ICMP errors can in 690 | effect be received by non-root users. However, it has the subtle side effect 691 | that if further UDP packets arrive from the caller but from different source 692 | ports, the listener will not receive them. UDP listen mode on a multihomed 693 | machine may have similar quirks unless you specifically bind to one of its 694 | addresses. It is not clear that kernel support for UDP connected sockets 695 | and/or my understanding of it is entirely complete here, so experiment... 696 | 697 | You should be aware of some subtleties concerning UDP scanning. If -z is on, 698 | netcat attempts to send a single null byte to the target port, twice, with a 699 | small time in between. You can either use the -w timeout, or netcat will try 700 | to make a "sideline" TCP connection to the target to introduce a small time 701 | delay equal to the round-trip time between you and the target. Note that if 702 | you have a -w timeout and -i timeout set, BOTH take effect and you wait twice 703 | as long. The TCP connection is to a normally refused port to minimize traffic, 704 | but if you notice a UDP fast-scan taking somewhat longer than it should, it 705 | could be that the target is actually listening on the TCP port. Either way, 706 | any ICMP port-unreachable messages from the target should have arrived in the 707 | meantime. The second single-byte UDP probe is then sent. Under BSD kernels, 708 | the ICMP error is delivered to the "connected socket" and the second write 709 | returns an error, which tells netcat that there is NOT a UDP service there. 710 | While Linux seems to be a fortunate exception, under many SYSV derived kernels 711 | the ICMP is not delivered, and netcat starts reporting that *all* the ports are 712 | "open" -- clearly wrong. [Some systems may not even *have* the "udp connected 713 | socket" concept, and netcat in its current form will not work for UDP at all.] 714 | If -z is specified and only one UDP port is probed, netcat's exit status 715 | reflects whether the connection was "open" or "refused" as with TCP. 716 | 717 | It may also be that UDP packets are being blocked by filters with no ICMP error 718 | returns, in which case everything will time out and return "open". This all 719 | sounds backwards, but that's how UDP works. If you're not sure, try "echo 720 | w00gumz | nc -u -w 2 target 7" to see if you can reach its UDP echo port at 721 | all. You should have no trouble using a BSD-flavor system to scan for UDP 722 | around your own network, although flooding a target with the high activity that 723 | -z generates will cause it to occasionally drop packets and indicate false 724 | "opens". A more "correct" way to do this is collect and analyze the ICMP 725 | errors, as does SATAN's "udp_scan" backend, but then again there's no guarantee 726 | that the ICMP gets back to you either. Udp_scan also does the zero-byte 727 | probes but is excruciatingly careful to calculate its own round-trip timing 728 | average and dynamically set its own response timeouts along with decoding any 729 | ICMP received. Netcat uses a much sleazier method which is nonetheless quite 730 | effective. Cisco routers are known to have a "dead time" in between ICMP 731 | responses about unreachable UDP ports, so a fast scan of a cisco will show 732 | almost everything "open". If you are looking for a specific UDP service, you 733 | can construct a file containing the right bytes to trigger a response from the 734 | other end and send that as standard input. Netcat will read up to 8K of the 735 | file and send the same data to every UDP port given. Note that you must use a 736 | timeout in this case [as would any other UDP client application] since the 737 | two-write probe only happens if -z is specified. 738 | 739 | Many telnet servers insist on a specific set of option negotiations before 740 | presenting a login banner. On a raw connection you will see this as small 741 | amount of binary gook. My attempts to create fixed input bytes to make a 742 | telnetd happy worked some places but failed against newer BSD-flavor ones, 743 | possibly due to timing problems, but there are a couple of much better 744 | workarounds. First, compile with -DTELNET and use -t if you just want to get 745 | past the option negotiation and talk to something on a telnet port. You will 746 | still see the binary gook -- in fact you'll see a lot more of it as the options 747 | are responded to behind the scenes. The telnet responder does NOT update the 748 | total byte count, or show up in the hex dump -- it just responds negatively to 749 | any options read from the incoming data stream. If you want to use a normal 750 | full-blown telnet to get to something but also want some of netcat's features 751 | involved like settable ports or timeouts, construct a tiny "foo" script: 752 | 753 | #! /bin/sh 754 | exec nc -otheroptions targethost 23 755 | 756 | and then do 757 | 758 | nc -l -p someport -e foo localhost & 759 | telnet localhost someport 760 | 761 | and your telnet should connect transparently through the exec'ed netcat to 762 | the target, using whatever options you supplied in the "foo" script. Don't 763 | use -t inside the script, or you'll wind up sending *two* option responses. 764 | 765 | I've observed inconsistent behavior under some Linuxes [perhaps just older 766 | ones?] when binding in listen mode. Sometimes netcat binds only to "localhost" 767 | if invoked with no address or port arguments, and sometimes it is unable to 768 | bind to a specific address for listening if something else is already listening 769 | on "any". The former problem can be worked around by specifying "-s 0.0.0.0", 770 | which will do the right thing despite netcat claiming that it's listening on 771 | [127.0.0.1]. This is a known problem -- for example, there's a mention of it 772 | in the makefile for SOCKS. On the flip side, binding to localhost and sending 773 | packets to some other machine doesn't work as you'd expect -- they go out with 774 | the source address of the sending interface instead. The Linux kernel contains 775 | a specific check to ensure that packets from 127.0.0.1 are never sent to the 776 | wire; other kernels may contain similar code. Linux, of course, *still* 777 | doesn't support source-routing, but they claim that it and many other network 778 | improvements are at least breathing hard. 779 | 780 | There are several possible errors associated with making TCP connections, but 781 | to specifically see anything other than "refused", one must wait the full 782 | kernel-defined timeout for a connection to fail. Netcat's mechanism of 783 | wrapping an alarm timer around the connect prevents the *real* network error 784 | from being returned -- "errno" at that point indicates "interrupted system 785 | call" since the connect attempt was interrupted. Some old 4.3 BSD kernels 786 | would actually return things like "host unreachable" immediately if that was 787 | the case, but most newer kernels seem to wait the full timeout and *then* pass 788 | back the real error. Go figure. In this case, I'd argue that the old way was 789 | better, despite those same kernels generally being the ones that tear down 790 | *established* TCP connections when ICMP-bombed. 791 | 792 | Incoming socket options are passed to applications by the kernel in the 793 | kernel's own internal format. The socket-options structure for source-routing 794 | contains the "first-hop" IP address first, followed by the rest of the real 795 | options list. The kernel uses this as is when sending reply packets -- the 796 | structure is therefore designed to be more useful to the kernel than to humans, 797 | but the hex dump of it that netcat produces is still useful to have. 798 | 799 | Kernels treat source-routing options somewhat oddly, but it sort of makes sense 800 | once one understands what's going on internally. The options list of addresses 801 | must contain hop1, hop2, ..., destination. When a source-routed packet is sent 802 | by the kernel [at least BSD], the actual destination address becomes irrelevant 803 | because it is replaced with "hop1", "hop1" is removed from the options list, 804 | and all the other addresses in the list are shifted up to fill the hole. Thus 805 | the outbound packet is sent from your chosen source address to the first 806 | *gateway*, and the options list now contains hop2, ..., destination. During 807 | all this address shuffling, the kernel does NOT change the pointer value, which 808 | is why it is useful to be able to set the pointer yourself -- you can construct 809 | some really bizarre return paths, and send your traffic fairly directly to the 810 | target but around some larger loop on the way back. Some Sun kernels seem to 811 | never flip the source-route around if it contains less than three hops, never 812 | reset the pointer anyway, and tries to send the packet [with options containing 813 | a "completed" source route!!] directly back to the source. This is way broken, 814 | of course. [Maybe ipforwarding has to be on? I haven't had an opportunity to 815 | beat on it thoroughly yet.] 816 | 817 | "Credits" section: The original idea for netcat fell out of a long-standing 818 | desire and fruitless search for a tool resembling it and having the same 819 | features. After reading some other network code and realizing just how many 820 | cool things about sockets could be controlled by the calling user, I started 821 | on the basics and the rest fell together pretty quickly. Some port-scanning 822 | ideas were taken from Venema/Farmer's SATAN tool kit, and Pluvius' "pscan" 823 | utility. Healthy amounts of BSD kernel source were perused in an attempt to 824 | dope out socket options and source-route handling; additional help was obtained 825 | from Dave Borman's telnet sources. The select loop is loosely based on fairly 826 | well-known code from "rsh" and Richard Stevens' "sock" program [which itself is 827 | sort of a "netcat" with more obscure features], with some more paranoid 828 | sanity-checking thrown in to guard against the distinct likelihood that there 829 | are subtleties about such things I still don't understand. I found the 830 | argument-hiding method cleanly implemented in Barrett's "deslogin"; reading the 831 | line as input allows greater versatility and is much less prone to cause 832 | bizarre problems than the more common trick of overwriting the argv array. 833 | After the first release, several people contributed portability fixes; they are 834 | credited in generic.h and the Makefile. Lauren Burka inspired the ascii art 835 | for this revised document. Dean Gaudet at Wired supplied a precursor to 836 | the hex-dump code, and mudge@l0pht.com originally experimented with and 837 | supplied code for the telnet-options responder. Outbound "-e " resulted 838 | from a need to quietly bypass a firewall installation. Other suggestions and 839 | patches have rolled in for which I am always grateful, but there are only 26 840 | hours per day and a discussion of feature creep near the end of this document. 841 | 842 | Netcat was written with the Russian railroad in mind -- conservatively built 843 | and solid, but it *will* get you there. While the coding style is fairly 844 | "tight", I have attempted to present it cleanly [keeping *my* lines under 80 845 | characters, dammit] and put in plenty of comments as to why certain things 846 | are done. Items I know to be questionable are clearly marked with "XXX". 847 | Source code was made to be modified, but determining where to start is 848 | difficult with some of the tangles of spaghetti code that are out there. 849 | Here are some of the major points I feel are worth mentioning about netcat's 850 | internal design, whether or not you agree with my approach. 851 | 852 | Except for generic.h, which changes to adapt more platforms, netcat is a single 853 | source file. This has the distinct advantage of only having to include headers 854 | once and not having to re-declare all my functions in a billion different 855 | places. I have attempted to contain all the gross who's-got-what-.h-file 856 | things in one small dumping ground. Functions are placed "dependencies-first", 857 | such that when the compiler runs into the calls later, it already knows the 858 | type and arguments and won't complain. No function prototyping -- not even the 859 | __P(()) crock -- is used, since it is more portable and a file of this size is 860 | easy enough to check manually. Each function has a standard-format comment 861 | ahead of it, which is easily found using the regexp " :$". I freely use gotos. 862 | Loops and if-clauses are made as small and non-nested as possible, and the ends 863 | of same *marked* for clarity [I wish everyone would do this!!]. 864 | 865 | Large structures and buffers are all malloc()ed up on the fly, slightly larger 866 | than the size asked for and zeroed out. This reduces the chances of damage 867 | from those "end of the buffer" fencepost errors or runaway pointers escaping 868 | off the end. These things are permanent per run, so nothing needs to be freed 869 | until the program exits. 870 | 871 | File descriptor zero is always expected to be standard input, even if it is 872 | closed. If a new network descriptor winds up being zero, a different one is 873 | asked for which will be nonzero, and fd zero is simply left kicking around 874 | for the rest of the run. Why? Because everything else assumes that stdin is 875 | always zero and "netfd" is always positive. This may seem silly, but it was a 876 | lot easier to code. The new fd is obtained directly as a new socket, because 877 | trying to simply dup() a new fd broke subsequent socket-style use of the new fd 878 | under Solaris' stupid streams handling in the socket library. 879 | 880 | The catch-all message and error handlers are implemented with an ample list of 881 | phoney arguments to get around various problems with varargs. Varargs seems 882 | like deliberate obfuscation in the first place, and using it would also 883 | require use of vfprintf() which not all platforms support. The trailing 884 | sleep in bail() is to allow output to flush, which is sometimes needed if 885 | netcat is already on the other end of a network connection. 886 | 887 | The reader may notice that the section that does DNS lookups seems much 888 | gnarlier and more confusing than other parts. This is NOT MY FAULT. The 889 | sockaddr and hostent abstractions are an abortion that forces the coder to 890 | deal with it. Then again, a lot of BSD kernel code looks like similar 891 | struct-pointer hell. I try to straighten it out somewhat by defining my own 892 | HINF structure, containing names, ascii-format IP addresses, and binary IP 893 | addresses. I fill this structure exactly once per host argument, and squirrel 894 | everything safely away and handy for whatever wants to reference it later. 895 | 896 | Where many other network apps use the FIONBIO ioctl to set non-blocking I/O 897 | on network sockets, netcat uses straightforward blocking I/O everywhere. 898 | This makes everything very lock-step, relying on the network and filesystem 899 | layers to feed in data when needed. Data read in is completely written out 900 | before any more is fetched. This may not be quite the right thing to do under 901 | some OSes that don't do timed select() right, but this remains to be seen. 902 | 903 | The hexdump routine is written to be as fast as possible, which is why it does 904 | so much work itself instead of just sprintf()ing everything together. Each 905 | dump line is built into a single buffer and atomically written out using the 906 | lowest level I/O calls. Further improvements could undoubtedly be made by 907 | using writev() and eliminating all sprintf()s, but it seems to fly right along 908 | as is. If both exec-a-prog mode and a hexdump file is asked for, the hexdump 909 | flag is deliberately turned off to avoid creating random zero-length files. 910 | Files are opened in "truncate" mode; if you want "append" mode instead, change 911 | the open flags in main(). 912 | 913 | main() may look a bit hairy, but that's only because it has to go down the 914 | argv list and handle multiple ports, random mode, and exit status. Efforts 915 | have been made to place a minimum of code inside the getopt() loop. Any real 916 | work is sent off to functions in what is hopefully a straightforward way. 917 | 918 | Obligatory vendor-bash: If "nc" had become a standard utility years ago, 919 | the commercial vendors would have likely packaged it setuid root and with 920 | -DGAPING_SECURITY_HOLE turned on but not documented. It is hoped that netcat 921 | will aid people in finding and fixing the no-brainer holes of this sort that 922 | keep appearing, by allowing easier experimentation with the "bare metal" of 923 | the network layer. 924 | 925 | It could be argued that netcat already has too many features. I have tried 926 | to avoid "feature creep" by limiting netcat's base functionality only to those 927 | things which are truly relevant to making network connections and the everyday 928 | associated DNS lossage we're used to. Option switches already have slightly 929 | overloaded functionality. Random port mode is sort of pushing it. The 930 | hex-dump feature went in later because it *is* genuinely useful. The 931 | telnet-responder code *almost* verges on the gratuitous, especially since it 932 | mucks with the data stream, and is left as an optional piece. Many people have 933 | asked for example "how 'bout adding encryption?" and my response is that such 934 | things should be separate entities that could pipe their data *through* netcat 935 | instead of having their own networking code. I am therefore not completely 936 | enthusiastic about adding any more features to this thing, although you are 937 | still free to send along any mods you think are useful. 938 | 939 | Nonetheless, at this point I think of netcat as my tcp/ip swiss army knife, 940 | and the numerous companion programs and scripts to go with it as duct tape. 941 | Duct tape of course has a light side and a dark side and binds the universe 942 | together, and if I wrap enough of it around what I'm trying to accomplish, 943 | it *will* work. Alternatively, if netcat is a large hammer, there are many 944 | network protocols that are increasingly looking like nails by now... 945 | 946 | _H* 960320 v1.10 RELEASE -- happy spring! 947 | --------------------------------------------------------------------------------