home *** CD-ROM | disk | FTP | other *** search
/ The Hacker's Encyclopedia 1998 / hackers_encyclopedia.iso / zines / phrack2 / phrack51.011 < prev    next >
Encoding:
Text File  |  2003-06-11  |  88.0 KB  |  2,494 lines

  1.  
  2. ---[  Phrack Magazine   Volume 7, Issue 51 September 01, 1997, article 11 of 17
  3.  
  4.  
  5. -------------------------[  The Art of Port Scanning
  6.  
  7.  
  8. --------[  Fyodor <fyodor@dhp.com>
  9.  
  10.  
  11. [ Abstract ]
  12.  
  13. This paper details many of the techniques used to determine what ports (or
  14. similar protocol abstraction) of a host are listening for connections.  These
  15. ports represent potential communication channels.  Mapping their existence
  16. facilitates the exchange of information with the host, and thus it is quite
  17. useful for anyone wishing to explore their networked environment, including
  18. hackers.  Despite what you have heard from the media, the Internet is NOT
  19. all about TCP port 80.  Anyone who relies exclusively on the WWW for
  20. information gathering is likely to gain the same level of proficiency as your
  21. average AOLer, who does the same.  This paper is also meant to serve as an
  22. introduction to and ancillary documentation for a coding project I have been
  23. working on.  It is a full featured, robust port scanner which (I hope) solves
  24. some of the problems I have encountered when dealing with other scanners and
  25. when working to scan massive networks.  The tool, nmap, supports the following:
  26.  
  27.     - vanilla TCP connect() scanning,
  28.     - TCP SYN (half open) scanning,
  29.     - TCP FIN (stealth) scanning,
  30.     - TCP ftp proxy (bounce attack) scanning
  31.     - SYN/FIN scanning using IP fragments (bypasses packet filters),
  32.     - UDP recvfrom() scanning,
  33.     - UDP raw ICMP port unreachable scanning,
  34.     - ICMP scanning (ping-sweep), and
  35.     - reverse-ident scanning.
  36.  
  37. The freely distributable source code is appended to this paper.
  38.  
  39.  
  40.  
  41. [ Introduction ]
  42.  
  43. Scanning, as a method for discovering exploitable communication channels, has
  44. been around for ages.  The idea is to probe as many listeners as possible, and
  45. keep track of the ones that are receptive or useful to your particular need.
  46. Much of the field of advertising is based on this paradigm, and the "to current
  47. resident" brute force style of bulk mail is an almost perfect parallel to what
  48. we will discuss.  Just stick a message in every mailbox and wait for the
  49. responses to trickle back.
  50.  
  51. Scanning entered the h/p world along with the phone systems.  Here we have this
  52. tremendous global telecommunications network, all reachable through codes on
  53. our telephone.  Millions of numbers are reachable locally, yet we may only
  54. be interested in 0.5% of these numbers, perhaps those that answer with a
  55. carrier.
  56.  
  57. The logical solution to finding those numbers that interest us is to try them
  58. all.  Thus the field of "wardialing" arose.  Excellent programs like Toneloc
  59. were developed to facilitate the probing of entire exchanges and more.  The
  60. basic idea is simple.  If you dial a number and your modem gives you a CONNECT,
  61. you record it.  Otherwise the computer hangs up and tirelessly dials the next
  62. one.
  63.  
  64. While wardialing is still useful, we are now finding that many of the computers
  65. we wish to communicate with are connected through networks such as the Internet
  66. rather than analog phone dialups.  Scanning these machines involves the same
  67. brute force technique.  We send a blizzard of packets for various protocols,
  68. and we deduce which services are listening from the responses we receive (or
  69. don't receive).
  70.  
  71.  
  72.  
  73. [ Techniques ]
  74.  
  75. Over time, a number of techniques have been developed for surveying the
  76. protocols and ports on which a target machine is listening.  They all offer
  77. different benefits and problems.  Here is a line up of the most common:
  78.  
  79. - TCP connect() scanning : This is the most basic form of TCP scanning.  The
  80. connect() system call provided by your operating system is used to open a
  81. connection to every interesting port on the machine.  If the port is listening,
  82. connect() will succeed, otherwise the port isn't reachable.  One strong
  83. advantage to this technique is that you don't need any special privileges.  Any
  84. user on most UNIX boxes is free to use this call.  Another advantage is speed.
  85. While making a separate connect() call for every targeted port in a linear
  86. fashion would take ages over a slow connection, you can hasten the scan by
  87. using many sockets in parallel.  Using non-blocking I/O allows you to set a low
  88. time-out period and watch all the sockets at once.  This is the fastest
  89. scanning method supported by nmap, and is available with the -t (TCP) option.
  90. The big downside is that this sort of scan is easily detectable and filterable.
  91. The target hosts logs will show a bunch of connection and error messages for
  92. the services which take the connection and then have it immediately shutdown.
  93.  
  94.  
  95. - TCP SYN scanning : This technique is often referred to as "half-open"
  96. scanning, because you don't open a full TCP connection.  You send a SYN packet,
  97. as if you are going to open a real connection and wait for a response.  A
  98. SYN|ACK indicates the port is listening.  A RST is indicative of a non-
  99. listener.  If a SYN|ACK is received, you immediately send a RST to tear down
  100. the connection (actually the kernel does this for us).  The primary advantage
  101. to this scanning technique is that fewer sites will log it.  Unfortunately you
  102. need root privileges to build these custom SYN packets.  SYN scanning is the -s
  103. option of nmap.
  104.  
  105.  
  106. - TCP FIN scanning : There are times when even SYN scanning isn't clandestine
  107. enough.  Some firewalls and packet filters watch for SYNs to an unallowed port,
  108. and programs like synlogger and Courtney are available to detect these scans.
  109. FIN packets, on the other hand, may be able to pass through unmolested.  This
  110. scanning technique was featured in detail by Uriel Maimon in Phrack 49, article
  111. 15.  The idea is that closed ports tend to reply to your FIN packet with the
  112. proper RST.  Open ports, on the other hand, tend to ignore the packet in
  113. question.  This is a bug in TCP implementations and so it isn't 100% reliable
  114. (some systems, notably Micro$oft boxes, seem to be immune).  It works well on
  115. most other systems I've tried.  FIN scanning is the -U (Uriel) option of nmap.
  116.  
  117.  
  118. - Fragmentation scanning : This is not a new scanning method in and of itself,
  119. but a modification of other techniques.  Instead of just sending the probe
  120. packet, you break it into a couple of small IP fragments.  You are splitting
  121. up the TCP header over several packets to make it harder for packet filters
  122. and so forth to detect what you are doing.  Be careful with this!  Some
  123. programs have trouble handling these tiny packets.  My favorite sniffer
  124. segmentation faulted immediately upon receiving the first 36-byte fragment.
  125. After that comes a 24 byte one!  While this method won't get by packet filters
  126. and firewalls that queue all IP fragments (like the CONFIG_IP_ALWAYS_DEFRAG
  127. option in Linux), a lot of networks can't afford the performance hit this
  128. causes.  This feature is rather unique to scanners (at least I haven't seen
  129. any others that do this).  Thanks to daemon9 for suggesting it.  The -f
  130. instructs the specified SYN or FIN scan to use tiny fragmented packets.
  131.  
  132.  
  133. - TCP reverse ident scanning : As noted by Dave Goldsmith in a 1996 Bugtraq
  134. post, the ident protocol (rfc1413) allows for the disclosure of the username of
  135. the owner of any process connected via TCP, even if that process didn't
  136. initiate the connection.  So you can, for example, connect to the http port
  137. and then use identd to find out whether the server is running as root.  This
  138. can only be done with a full TCP connection to the target port (i.e. the -t
  139. option).  nmap's -i option queries identd for the owner of all listen()ing
  140. ports.
  141.  
  142.  
  143. - FTP bounce attack : An interesting "feature" of the ftp protocol (RFC 959) is
  144. support for "proxy" ftp connections.  In other words, I should be able to
  145. connect from evil.com to the FTP server-PI (protocol interpreter) of target.com
  146. to establish the control communication connection.  Then I should be able to
  147. request that the server-PI initiate an active server-DTP (data transfer
  148. process) to send a file ANYWHERE on the internet!  Presumably to a User-DTP,
  149. although the RFC specifically states that asking one server to send a file to
  150. another is OK.  Now this may have worked well in 1985 when the RFC was just
  151. written.  But nowadays, we can't have people hijacking ftp servers and
  152. requesting that data be spit out to arbitrary points on the internet.  As
  153. *Hobbit* wrote back in 1995, this protocol flaw "can be used to post virtually
  154. untraceable mail and news, hammer on servers at various sites, fill up disks,
  155. try to hop firewalls, and generally be annoying and hard to track down at the
  156. same time."  What we will exploit this for is to (surprise, surprise) scan TCP
  157. ports from a "proxy" ftp server.  Thus you could connect to an ftp server
  158. behind a firewall, and then scan ports that are more likely to be blocked (139
  159. is a good one).  If the ftp server allows reading from and writing to a
  160. directory (such as /incoming), you can send arbitrary data to ports that you do
  161. find open.
  162.  
  163. For port scanning, our technique is to use the PORT command to declare that
  164. our passive "User-DTP" is listening on the target box at a certain port number.
  165.  Then we try to LIST the current directory, and the result is sent over the
  166. Server-DTP channel.  If our target host is listening on the specified port, the
  167. transfer will be successful (generating a 150 and a 226 response).  Otherwise
  168. we will get "425 Can't build data connection: Connection refused."  Then we
  169. issue another PORT command to try the next port on the target host.  The
  170. advantages to this approach are obvious (harder to trace, potential to bypass
  171. firewalls).  The main disadvantages are that it is slow, and that some FTP
  172. servers have finally got a clue and disabled the proxy "feature".  For what it
  173. is worth, here is a list of banners from sites where it does/doesn't work:
  174.  
  175. *Bounce attacks worked:*
  176.  
  177. 220 xxxxxxx.com FTP server (Version wu-2.4(3) Wed Dec 14 ...) ready.
  178. 220 xxx.xxx.xxx.edu FTP server ready.
  179. 220 xx.Telcom.xxxx.EDU FTP server (Version wu-2.4(3) Tue Jun 11 ...) ready.
  180. 220 lem FTP server (SunOS 4.1) ready.
  181. 220 xxx.xxx.es FTP server (Version wu-2.4(11) Sat Apr 27 ...) ready.
  182. 220 elios FTP server (SunOS 4.1) ready
  183.  
  184. *Bounce attack failed:*
  185.  
  186. 220 wcarchive.cdrom.com FTP server (Version DG-2.0.39 Sun May 4 ...) ready.
  187. 220 xxx.xx.xxxxx.EDU Version wu-2.4.2-academ[BETA-12](1) Fri Feb 7
  188. 220 ftp Microsoft FTP Service (Version 3.0).
  189. 220 xxx FTP server (Version wu-2.4.2-academ[BETA-11](1) Tue Sep 3 ...) ready.
  190. 220 xxx.unc.edu FTP server (Version wu-2.4.2-academ[BETA-13](6) ...) ready.
  191.  
  192. The 'x's are partly there to protect those guilty of running a flawed server,
  193. but mostly just to make the lines fit in 80 columns.  Same thing with the
  194. ellipse points.  The bounce attack is available with the -b <proxy_server>
  195. option of nmap.  proxy_server can be specified in standard URL format,
  196. username:password@server:port , with everything but server being optional.
  197.  
  198.  
  199. - UDP ICMP port unreachable scanning : This scanning method varies from the
  200. above in that we are using the UDP protocol instead of TCP.  While this
  201. protocol is simpler, scanning it is actually significantly more difficult.
  202. This is because open ports don't have to send an acknowledgement in response to
  203. our probe, and closed ports aren't even required to send an error packet.
  204. Fortunately, most hosts do send an ICMP_PORT_UNREACH error when you send a
  205. packet to a closed UDP port.  Thus you can find out if a port is NOT open, and
  206. by exclusion determine which ports which are.  Neither UDP packets, nor the
  207. ICMP errors are guaranteed to arrive, so UDP scanners of this sort must also
  208. implement retransmission of packets that appear to be lost (or you will get a
  209. bunch of false positives).  Also, this scanning technique is slow because of
  210. compensation for machines that took RFC 1812 section 4.3.2.8 to heart and limit
  211. ICMP error message rate.  For example, the Linux kernel (in net/ipv4/icmp.h)
  212. limits destination unreachable message generation to 80 per 4 seconds, with a
  213. 1/4 second penalty if that is exceeded.  At some point I will add a better
  214. algorithm to nmap for detecting this.  Also, you will need to be root for
  215. access to the raw ICMP socket necessary for reading the port unreachable.  The
  216. -u (UDP) option of nmap implements this scanning method for root users.
  217.  
  218. Some people think UDP scanning is lame and pointless.  I usually remind them of
  219. the recent Solaris rcpbind hole.  Rpcbind can be found hiding on an
  220. undocumented UDP port somewhere above 32770.  So it doesn't matter that 111 is
  221. blocked by the firewall.  But can you find which of the more than 30,000 high
  222. ports it is listening on?  With a UDP scanner you can!
  223.  
  224.  
  225. - UDP recvfrom() and write() scanning : While non-root users can't read
  226. port unreachable errors directly, Linux is cool enough to inform the user
  227. indirectly when they have been received.  For example a second write()
  228. call to a closed port will usually fail.  A lot of scanners such as netcat
  229. and Pluvius' pscan.c does this.  I have also noticed that recvfrom() on
  230. non-blocking UDP sockets usually return EAGAIN ("Try Again", errno 13) if
  231. the ICMP error hasn't been received, and ECONNREFUSED ("Connection refused",
  232. errno 111) if it has.  This is the technique used for determining open ports
  233. when non-root users use -u (UDP).  Root users can also use the -l (lamer
  234. UDP scan) options to force this, but it is a really dumb idea.
  235.  
  236.  
  237. - ICMP echo scanning : This isn't really port scanning, since ICMP doesn't have
  238. a port abstraction.  But it is sometimes useful to determine what hosts in a
  239. network are up by pinging them all.  the -P option does this.  Also you might
  240. want to adjust the PING_TIMEOUT #define if you are scanning a large
  241. network. nmap supports a host/bitmask notation to make this sort of thing
  242. easier.  For example 'nmap -P cert.org/24 152.148.0.0/16' would scan CERT's
  243. class C network and whatever class B entity 152.148.* represents.  Host/26 is
  244. useful for 6-bit subnets within an organization.
  245.  
  246.  
  247.  
  248. [ Features ]
  249.  
  250. Prior to writing nmap, I spent a lot of time with other scanners exploring the
  251. Internet and various private networks (note the avoidance of the "intranet"
  252. buzzword).  I have used many of the top scanners available today, including
  253. strobe by Julian Assange, netcat by *Hobbit*, stcp by Uriel Maimon, pscan by
  254. Pluvius, ident-scan by Dave Goldsmith, and the SATAN tcp/udp scanners by
  255. Wietse Venema.  These are all excellent scanners!  In fact, I ended up hacking
  256. most of them to support the best features of the others.  Finally I decided
  257. to write a whole new scanner, rather than rely on hacked versions of a dozen
  258. different scanners in my /usr/local/sbin.  While I wrote all the code, nmap
  259. uses a lot of good ideas from its predecessors.  I also incorporated some new
  260. stuff like fragmentation scanning and options that were on my "wish list" for
  261. other scanners.  Here are some of the (IMHO) useful features of nmap:
  262.  
  263. - dynamic delay time calculations: Some scanners require that you supply a
  264. delay time between sending packets.  Well how should I know what to use?
  265. Sure, I can ping them, but that is a pain, and plus the response time of many
  266. hosts changes dramatically when they are being flooded with requests.  nmap
  267. tries to determine the best delay time for you.  It also tries to keep track
  268. of packet retransmissions, etc. so that it can modify this delay time during
  269. the course of the scan.  For root users, the primary technique for finding an
  270. initial delay is to time the internal "ping" function.  For non-root users, it
  271. times an attempted connect() to a closed port on the target.  It can also pick
  272. a reasonable default value.  Again, people who want to specify a delay
  273. themselves can do so with -w (wait), but you shouldn't have to.
  274.  
  275. - retransmission: Some scanners just send out all the query packets, and
  276. collect the responses.  But this can lead to false positives or negatives in
  277. the case where packets are dropped.  This is especially important for
  278. "negative" style scans like UDP and FIN, where what you are looking for is a
  279. port that does NOT respond.  In most cases, nmap implements a configurable
  280. number of retransmissions for ports that don't respond.
  281.  
  282. - parallel port scanning:  Some scanners simply scan ports linearly, one at a
  283. time, until they do all 65535.  This actually works for TCP on a very fast
  284. local network, but the speed of this is not at all acceptable on a wide area
  285. network like the Internet.  nmap uses non-blocking i/o and parallel scanning
  286. in all TCP and UDP modes.  The number of scans in parallel is configurable
  287. with the -M (Max sockets) option.  On a very fast network you will actually
  288. decrease performance if you do more than 18 or so.  On slow networks, high
  289. values increase performance dramatically.
  290.  
  291. - Flexible port specification:  I don't always want to just scan all 65535
  292. ports.  Also, the scanners which only allow you to scan ports 1 - N sometimes
  293. fall short of my need.  The -p option allows you to specify an arbitrary
  294. number of ports and ranges for scanning.  For example, '-p 21-25,80,113,
  295. 60000-' does what you would expect (a trailing hyphen means up to 65536, a
  296. leading hyphen means 1 through).  You can also use the -F (fast) option, which
  297. scans all the ports registered in your /etc/services (a la strobe).
  298.  
  299. - Flexible target specification:  I often want to scan more then one host,
  300. and I certainly don't want to list every single host on a large network to
  301. scan.  Everything that isn't an option (or option argument) in nmap is
  302. treated as a target host.  As mentioned before, you can optionally append
  303. /mask to a hostname or IP address in order to scan all hosts with the same
  304. initial <mask> bits of the 32 bit IP address.
  305.  
  306. - detection of down hosts:  Some scanners allow you to scan large networks, but
  307. they waste a huge amount of time scanning 65535 ports of a dead host!  By
  308. default, nmap pings each host to make sure it is up before wasting time on it.
  309. It is also capable of bailing on hosts that seem down based on strange port
  310. scanning errors.  It is also meant to be tolerant of people who accidentally scan
  311. network addresses, broadcast addresses, etc.
  312.  
  313. - detection of your IP address: For some reason, a lot of scanners ask you to
  314. type in your IP address as one of the parameters.  Jeez, I don't want to have
  315. to 'ifconfig' and figure out my current address every time I scan.  Of course,
  316. this is better then the scanners I've seen which require recompilation every
  317. time you change your address!  nmap first tries to detect your address during
  318. the ping stage.  It uses the address that the echo response is received on, as
  319. that is the interface it should almost always be routed through.  If it can't
  320. do this (like if you don't have host pinging enabled), nmap tries to detect
  321. your primary interface and uses that address.  You can also use -S to specify
  322. it directly, but you shouldn't have to (unless you want to make it look like
  323. someone ELSE is SYN or FIN scanning a host.
  324.  
  325.  
  326. Some other, more minor options:
  327.  
  328.  -v (verbose): This is highly recommended for interactive use.  Among other
  329. useful messages, you will see ports come up as they are found, rather than
  330. having to wait for the sorted summary list.
  331.  
  332.  -r (randomize): This will randomize the order in which the target host's
  333. ports are scanned.
  334.  
  335.  -q (quash argv): This changes argv[0] to FAKE_ARGV ("pine" by default).
  336. It also eliminates all other arguments, so you won't look too suspicious in
  337. 'w' or 'ps' listings.
  338.  
  339.  -h for an options summary.
  340.  
  341. Also look for http://www.dhp.com/~fyodor/nmap/, which is the web site I plan to
  342. put future versions and more information on.  In fact, you would be well
  343. advised to check there right now.
  344.  
  345.  
  346. [ Greets ]
  347.  
  348. Of course this paper would not be complete without a shout out to all the
  349. people who made it possible.
  350.  
  351. * Congratulations to the people at Phrack for getting this thing going again!
  352. * Greets to the whole dc-stuff crew.
  353. * Greets to the STUPH, Turntec, L0pht, TACD, the Guild, cDc, and all the other
  354.   groups who help keep the scene alive.
  355. * Shout out to _eci for disclosing the coolest Windows bug in recent history.
  356. * Thanks to the Data Haven Project (dhp.com) admins for providing such great
  357.   service for $10/month.
  358. * And a special shout out goes to all my friends.  You know who
  359.   you are and some of you (wisely) stay out of the spotlight, so I'll keep you
  360.   anonymous ... except of course for Ken and Jay, and Avenger, Grog, Cash
  361.   Monies, Ethernet Kid, Zos, JuICe, Mother Prednisone, and Karen.
  362.  
  363.  
  364. And finally, we get to ...
  365.  
  366.  
  367. [ The code ]
  368.  
  369. This should compile fine on any Linux box with 'gcc -O6 -o nmap nmap.c -lm'.
  370. It is distrubuted under the terms of the GNU GENERAL PUBLIC LICENSE.  If you
  371. have problems or comments, feel free to mail me (fyodor@dhp.com).
  372.  
  373. <++> nmap/Makefile
  374. # A trivial makefile for Network Mapper
  375. nmap: nmap.c nmap.h
  376.     gcc -Wall -O6 -o nmap nmap.c -lm
  377. <-->
  378.  
  379. <++> nmap/nmap.h
  380. #ifndef NMAP_H
  381. #define NMAP_H
  382.  
  383. /************************INCLUDES**********************************/
  384. #include <stdio.h>
  385. #include <stdlib.h>
  386. #include <string.h>
  387. #include <sys/types.h>
  388. #include <rpc/types.h>
  389. #include <sys/socket.h>
  390. #include <sys/socket.h>
  391. #include <sys/stat.h>
  392. #include <netinet/in.h>
  393. #include <unistd.h>
  394. #include <netdb.h>
  395. #include <time.h>
  396. #include <fcntl.h>
  397. #include <signal.h>
  398. #include <signal.h>
  399. #include <linux/ip.h> /*<netinet/ip.h>*/
  400. #include <linux/icmp.h> /*<netinet/ip_icmp.h>*/
  401. #include <arpa/inet.h>
  402. #include <math.h>
  403. #include <time.h>
  404. #include <sys/time.h>
  405. #include <asm/byteorder.h>
  406. #include <netinet/ip_tcp.h>
  407.  
  408. /************************DEFINES************************************/
  409.  
  410. /* #define to zero if you don't want to    ignore hosts of the form
  411.    xxx.xxx.xxx.{0,255} (usually network and broadcast addresses) */
  412. #define IGNORE_ZERO_AND_255_HOSTS 1
  413.  
  414. #define DEBUGGING 0
  415.  
  416. /* Default number of ports in paralell.  Doesn't always involve actual
  417.    sockets.  Can also adjust with the -M command line option.  */
  418. #define MAX_SOCKETS 36
  419. /* If reads of a UDP port keep returning EAGAIN (errno 13), do we want to
  420.    count the port as valid? */
  421. #define RISKY_UDP_SCAN 0
  422.  /* This ideally should be a port that isn't in use for any protocol on our machine or on the target */
  423. #define MAGIC_PORT 49724
  424. /* How many udp sends without a ICMP port unreachable error does it take before we consider the port open? */
  425. #define UDP_MAX_PORT_RETRIES 4
  426.  /*How many seconds before we give up on a host being alive? */
  427. #define PING_TIMEOUT 2
  428. #define FAKE_ARGV "pine" /* What ps and w should show if you use -q */
  429. /* How do we want to log into ftp sites for */
  430. #define FTPUSER "anonymous"
  431. #define FTPPASS "-wwwuser@"
  432. #define FTP_RETRIES 2 /* How many times should we relogin if we lose control
  433.                          connection? */
  434.  
  435. #define UC(b)   (((int)b)&0xff)
  436. #define MORE_FRAGMENTS 8192 /*NOT a user serviceable parameter*/
  437. #define fatal(x) { fprintf(stderr, "%s\n", x); exit(-1); }
  438. #define error(x) fprintf(stderr, "%s\n", x);
  439.  
  440. /***********************STRUCTURES**********************************/
  441.  
  442. typedef struct port {
  443.   unsigned short portno;
  444.   unsigned char proto;
  445.   char *owner;
  446.   struct port *next;
  447. } port;
  448.  
  449. struct ftpinfo {
  450.   char user[64];
  451.   char pass[256]; /* methinks you're paranoid if you need this much space */
  452.   char server_name[MAXHOSTNAMELEN + 1];
  453.   struct in_addr server;
  454.   unsigned short port;
  455.   int sd; /* socket descriptor */
  456. };
  457.  
  458. typedef port *portlist;
  459.  
  460. /***********************PROTOTYPES**********************************/
  461.  
  462. /* print usage information */
  463. void printusage(char *name);
  464.  
  465. /* our scanning functions */
  466. portlist tcp_scan(struct in_addr target, unsigned short *portarray,
  467.           portlist *ports);
  468. portlist syn_scan(struct in_addr target, unsigned short *portarray,
  469.           struct in_addr *source, int fragment, portlist *ports);
  470. portlist fin_scan(struct in_addr target, unsigned short *portarray,
  471.           struct in_addr *source, int fragment, portlist *ports);
  472. portlist udp_scan(struct in_addr target, unsigned short *portarray,
  473.           portlist *ports);
  474. portlist lamer_udp_scan(struct in_addr target, unsigned short *portarray,
  475.             portlist *ports);
  476. portlist bounce_scan(struct in_addr target, unsigned short *portarray,
  477.              struct ftpinfo *ftp, portlist *ports);
  478.  
  479. /* Scan helper functions */
  480. unsigned long calculate_sleep(struct in_addr target);
  481. int check_ident_port(struct in_addr target);
  482. int getidentinfoz(struct in_addr target, int localport, int remoteport,
  483.           char *owner);
  484. int parse_bounce(struct ftpinfo *ftp, char *url);
  485. int ftp_anon_connect(struct ftpinfo *ftp);
  486.  
  487. /* port manipulators */
  488. unsigned short *getpts(char *expr); /* someone stole the name getports()! */
  489. unsigned short *getfastports(int tcpscan, int udpscan);
  490. int addport(portlist *ports, unsigned short portno, unsigned short protocol,
  491.         char *owner);
  492. int deleteport(portlist *ports, unsigned short portno, unsigned short protocol);
  493. void printandfreeports(portlist ports);
  494. int shortfry(unsigned short *ports);
  495.  
  496. /* socket manipulation functions */
  497. void init_socket(int sd);
  498. int unblock_socket(int sd);
  499. int block_socket(int sd);
  500. int recvtime(int sd, char *buf, int len, int seconds);
  501.  
  502. /* RAW packet building/dissasembling stuff */
  503. int send_tcp_raw( int sd, struct in_addr *source,
  504.           struct in_addr *victim, unsigned short sport,
  505.           unsigned short dport, unsigned long seq,
  506.           unsigned long ack, unsigned char flags,
  507.           unsigned short window, char *data,
  508.           unsigned short datalen);
  509. int isup(struct in_addr target);
  510. unsigned short in_cksum(unsigned short *ptr,int nbytes);
  511. int send_small_fragz(int sd, struct in_addr *source, struct in_addr *victim,
  512.              int sport, int dport, int flags);
  513. int readtcppacket(char *packet, int readdata);
  514. int listen_icmp(int icmpsock, unsigned short outports[],
  515.         unsigned short numtries[], int *num_out,
  516.         struct in_addr target, portlist *ports);
  517.  
  518. /* general helper functions */
  519. void hdump(unsigned char *packet, int len);
  520. void *safe_malloc(int size);
  521. #endif /* NMAP_H */
  522. <-->
  523.  
  524. <++> nmap/nmap.c
  525.  
  526. #include "nmap.h"
  527.  
  528. /* global options */
  529. short debugging = DEBUGGING;
  530. short verbose = 0;
  531. int number_of_ports  = 0; /* How many ports do we scan per machine? */
  532. int max_parallel_sockets = MAX_SOCKETS;
  533. extern char *optarg;
  534. extern int optind;
  535. short isr00t = 0;
  536. short identscan = 0;
  537. char current_name[MAXHOSTNAMELEN + 1];
  538. unsigned long global_delay = 0;
  539. unsigned long global_rtt = 0;
  540. struct in_addr ouraddr = { 0 };
  541.  
  542. int main(int argc, char *argv[]) {
  543. int i, j, arg, argvlen;
  544. short fastscan=0, tcpscan=0, udpscan=0, synscan=0, randomize=0;
  545. short fragscan = 0, finscan = 0, quashargv = 0, pingscan = 0, lamerscan = 0;
  546. short bouncescan = 0;
  547. short *ports = NULL, mask;
  548. struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { 0 }, 21, 0};
  549. portlist openports = NULL;
  550. struct hostent *target = 0;
  551. unsigned long int lastip, currentip, longtmp;
  552. char *target_net, *p;
  553. struct in_addr current_in, *source=NULL;
  554. int hostup = 0;
  555. char *fakeargv[argc + 1];
  556.  
  557. /* argv faking silliness */
  558. for(i=0; i < argc; i++) {
  559.   fakeargv[i] = safe_malloc(strlen(argv[i]) + 1);
  560.   strncpy(fakeargv[i], argv[i], strlen(argv[i]) + 1);
  561. }
  562. fakeargv[argc] = NULL;
  563.  
  564. if (argc < 2 ) printusage(argv[0]);
  565.  
  566. /* OK, lets parse these args! */
  567. while((arg = getopt(argc,fakeargv,"b:dFfhilM:Pp:qrS:stUuw:v")) != EOF) {
  568.   switch(arg) {
  569.   case 'b':
  570.     bouncescan++;
  571.     if (parse_bounce(&ftp, optarg) < 0 ) {
  572.       fprintf(stderr, "Your argument to -b is fucked up. Use the normal url style:  user:pass@server:port or just use server and use default anon login\n  Use -h for help\n");
  573.     }
  574.     break;
  575.   case 'd': debugging++; break;
  576.   case 'F': fastscan++; break;
  577.   case 'f': fragscan++; break;
  578.   case 'h':
  579.   case '?': printusage(argv[0]);
  580.   case 'i': identscan++; break;
  581.   case 'l': lamerscan++; udpscan++; break;
  582.   case 'M': max_parallel_sockets = atoi(optarg); break;
  583.   case 'P': pingscan++; break;
  584.   case 'p':
  585.     if (ports)
  586.       fatal("Only 1 -p option allowed, seperate multiple ranges with commas.");
  587.     ports = getpts(optarg); break;
  588.   case 'r': randomize++; break;
  589.   case 's': synscan++; break;
  590.   case 'S':
  591.     if (source)
  592.       fatal("You can only use the source option once!\n");
  593.     source = safe_malloc(sizeof(struct in_addr));
  594.     if (!inet_aton(optarg, source))
  595.       fatal("You must give the source address in dotted deciman, currently.\n");
  596.     break;
  597.   case 't': tcpscan++; break;
  598.   case 'U': finscan++; break;
  599.   case 'u': udpscan++; break;
  600.   case 'q': quashargv++; break;
  601.   case 'w': global_delay = atoi(optarg); break;
  602.   case 'v': verbose++;
  603.   }
  604. }
  605.  
  606. /* Take care of user wierdness */
  607. isr00t = !(geteuid()|geteuid());
  608. if (tcpscan && synscan)
  609.   fatal("The -t and -s options can't be used together.\
  610.  If you are trying to do TCP SYN scanning, just use -s.\
  611.  For normal connect() style scanning, use -t");
  612. if ((synscan || finscan || fragscan || pingscan) && !isr00t)
  613.   fatal("Options specified require r00t privileges.  You don't have them!");
  614. if (!tcpscan && !udpscan && !synscan && !finscan && !bouncescan && !pingscan) {
  615.   tcpscan++;
  616.   if (verbose) error("No scantype specified, assuming vanilla tcp connect()\
  617.  scan. Use -P if you really don't want to portscan.");
  618. if (fastscan && ports)
  619.   fatal("You can use -F (fastscan) OR -p for explicit port specification.\
  620.   Not both!\n");
  621. }
  622. /* If he wants to bounce of an ftp site, that site better damn well be reachable! */
  623. if (bouncescan) {
  624.   if (!inet_aton(ftp.server_name, &ftp.server)) {
  625.     if ((target = gethostbyname(ftp.server_name)))
  626.       memcpy(&ftp.server, target->h_addr_list[0], 4);
  627.     else {
  628.       fprintf(stderr, "Failed to resolve ftp bounce proxy hostname/IP: %s\n",
  629.           ftp.server_name);
  630.       exit(1);
  631.     }
  632.   }  else if (verbose)
  633.     printf("Resolved ftp bounce attack proxy to %s (%s).\n",
  634.        target->h_name, inet_ntoa(ftp.server));
  635. }
  636. printf("\nStarting nmap V 1.21 by Fyodor (fyodor@dhp.com, www.dhp.com/~fyodor/nmap/\n");
  637. if (!verbose)
  638.   error("Hint: The -v option notifies you of open ports as they are found.\n");
  639. if (fastscan)
  640.   ports = getfastports(synscan|tcpscan|fragscan|finscan|bouncescan,
  641.                        udpscan|lamerscan);
  642. if (!ports) ports = getpts("1-1024");
  643.  
  644. /* more fakeargv junk, BTW malloc'ing extra space in argv[0] doesn't work */
  645. if (quashargv) {
  646.   argvlen = strlen(argv[0]);
  647.   if (argvlen < strlen(FAKE_ARGV))
  648.     fatal("If you want me to fake your argv, you need to call the program with a longer name.  Try the full pathname, or rename it fyodorssuperdedouperportscanner");
  649.   strncpy(argv[0], FAKE_ARGV, strlen(FAKE_ARGV));
  650.   for(i = strlen(FAKE_ARGV); i < argvlen; i++) argv[0][i] = '\0';
  651.   for(i=1; i < argc; i++) {
  652.     argvlen = strlen(argv[i]);
  653.     for(j=0; j <= argvlen; j++)
  654.       argv[i][j] = '\0';
  655.   }
  656. }
  657.  
  658. srand(time(NULL));
  659.  
  660. while(optind < argc) {
  661.  
  662.   /* Time to parse the allowed mask */
  663.   target = NULL;
  664.   target_net = strtok(strdup(fakeargv[optind]), "/");
  665.   mask = (p = strtok(NULL,""))? atoi(p) : 32;
  666.   if (debugging)
  667.     printf("Target network is %s, scanmask is %d\n", target_net, mask);
  668.  
  669.   if (!inet_aton(target_net, ¤t_in)) {
  670.     if ((target = gethostbyname(target_net)))
  671.       memcpy(¤tip, target->h_addr_list[0], 4);
  672.     else {
  673.       fprintf(stderr, "Failed to resolve given hostname/IP: %s\n", target_net);
  674.     }
  675.   } else currentip = current_in.s_addr;
  676.  
  677.   longtmp = ntohl(currentip);
  678.   currentip = longtmp & (unsigned long) (0 - pow(2,32 - mask));
  679.   lastip = longtmp | (unsigned long) (pow(2,32 - mask) - 1);
  680.   while (currentip <= lastip) {
  681.     openports = NULL;
  682.     longtmp = htonl(currentip);
  683.     target = gethostbyaddr((char *) &longtmp, 4, AF_INET);
  684.     current_in.s_addr = longtmp;
  685.     if (target)
  686.       strncpy(current_name, target->h_name, MAXHOSTNAMELEN);
  687.     else current_name[0] = '\0';
  688.     current_name[MAXHOSTNAMELEN + 1] = '\0';
  689.     if (randomize)
  690.       shortfry(ports);
  691. #ifdef IGNORE_ZERO_AND_255_HOSTS
  692.     if (IGNORE_ZERO_AND_255_HOSTS
  693.     && (!(currentip % 256) || currentip % 256 == 255))
  694.       {
  695.     printf("Skipping host %s because IGNORE_ZERO_AND_255_HOSTS is set in the source.\n", inet_ntoa(current_in));
  696.     hostup = 0;
  697.       }
  698.     else{
  699. #endif
  700.       if (isr00t) {
  701.     if (!(hostup = isup(current_in))) {
  702.       if (!pingscan)
  703.         printf("Host %s (%s) appears to be down, skipping scan.\n",
  704.            current_name, inet_ntoa(current_in));
  705.       else
  706.         printf("Host %s (%s) appears to be  down\n",
  707.            current_name, inet_ntoa(current_in));
  708.     } else if (debugging || pingscan)
  709.       printf("Host %s (%s) appears to be up ... good.\n",
  710.                  current_name, inet_ntoa(current_in));
  711.       }
  712.       else hostup = 1; /* We don't really check because the lamer isn't root.*/
  713.     }
  714.  
  715.     /* Time for some actual scanning! */
  716.     if (hostup) {
  717.       if (tcpscan) tcp_scan(current_in, ports, &openports);
  718.  
  719.       if (synscan) syn_scan(current_in, ports, source, fragscan, &openports);
  720.  
  721.       if (finscan) fin_scan(current_in, ports, source, fragscan, &openports);
  722.  
  723.       if (bouncescan) {
  724.     if (ftp.sd <= 0) ftp_anon_connect(&ftp);
  725.     if (ftp.sd > 0) bounce_scan(current_in, ports, &ftp, &openports);
  726.       }
  727.       if (udpscan) {
  728.     if (!isr00t || lamerscan)
  729.       lamer_udp_scan(current_in, ports, &openports);
  730.  
  731.     else udp_scan(current_in, ports, &openports);
  732.       }
  733.  
  734.       if (!openports && !pingscan)
  735.     printf("No ports open for host %s (%s)\n", current_name,
  736.            inet_ntoa(current_in));
  737.       if (openports) {
  738.     printf("Open ports on %s (%s):\n", current_name,
  739.            inet_ntoa(current_in));
  740.     printandfreeports(openports);
  741.       }
  742.     }
  743.     currentip++;
  744.   }
  745.   optind++;
  746. }
  747.  
  748. return 0;
  749. }
  750.  
  751. __inline__ int unblock_socket(int sd) {
  752. int options;
  753. /*Unblock our socket to prevent recvfrom from blocking forever
  754.   on certain target ports. */
  755. options = O_NONBLOCK | fcntl(sd, F_GETFL);
  756. fcntl(sd, F_SETFL, options);
  757. return 1;
  758. }
  759.  
  760. __inline__ int block_socket(int sd) {
  761. int options;
  762. options = (~O_NONBLOCK) & fcntl(sd, F_GETFL);
  763. fcntl(sd, F_SETFL, options);
  764. return 1;
  765. }
  766.  
  767. /* Currently only sets SO_LINGER, I haven't seen any evidence that this
  768.    helps.  I'll do more testing before dumping it. */
  769. __inline__ void init_socket(int sd) {
  770. struct linger l;
  771.  
  772. l.l_onoff = 1;
  773. l.l_linger = 0;
  774.  
  775. if (setsockopt(sd, SOL_SOCKET, SO_LINGER,  &l, sizeof(struct linger)))
  776.   {
  777.    fprintf(stderr, "Problem setting socket SO_LINGER, errno: %d\n", errno);
  778.    perror("setsockopt");
  779.   }
  780. }
  781.  
  782. /* Convert a string like "-100,200-1024,3000-4000,60000-" into an array
  783.    of port numbers*/
  784. unsigned short *getpts(char *origexpr) {
  785. int exlen = strlen(origexpr);
  786. char *p,*q;
  787. unsigned short *tmp, *ports;
  788. int i=0, j=0,start,end;
  789. char *expr = strdup(origexpr);
  790. ports = safe_malloc(65536 * sizeof(short));
  791. i++;
  792. i--;
  793. for(;j < exlen; j++)
  794.   if (expr[j] != ' ') expr[i++] = expr[j];
  795. expr[i] = '\0';
  796. exlen = i + 1;
  797. i=0;
  798. while((p = strchr(expr,','))) {
  799.   *p = '\0';
  800.   if (*expr == '-') {start = 1; end = atoi(expr+ 1);}
  801.   else {
  802.     start = end = atoi(expr);
  803.     if ((q = strchr(expr,'-')) && *(q+1) ) end = atoi(q + 1);
  804.     else if (q && !*(q+1)) end = 65535;
  805.   }
  806.   if (debugging)
  807.     printf("The first port is %d, and the last one is %d\n", start, end);
  808.   if (start < 1 || start > end) fatal("Your port specifications are illegal!");
  809.   for(j=start; j <= end; j++)
  810.     ports[i++] = j;
  811.   expr = p + 1;
  812. }
  813. if (*expr == '-') {
  814.   start = 1;
  815.   end = atoi(expr+ 1);
  816. }
  817. else {
  818.   start = end = atoi(expr);
  819.   if ((q =  strchr(expr,'-')) && *(q+1) ) end = atoi(q+1);
  820.   else if (q && !*(q+1)) end = 65535;
  821. }
  822. if (debugging)
  823.   printf("The first port is %d, and the last one is %d\n", start, end);
  824. if (start < 1 || start > end) fatal("Your port specifications are illegal!");
  825. for(j=start; j <= end; j++)
  826.   ports[i++] = j;
  827. number_of_ports = i;
  828. ports[i++] = 0;
  829. tmp = realloc(ports, i * sizeof(short));
  830.   free(expr);
  831.   return tmp;
  832. }
  833.  
  834. unsigned short *getfastports(int tcpscan, int udpscan) {
  835.   int portindex = 0, res, lastport = 0;
  836.   unsigned int portno = 0;
  837.   unsigned short *ports;
  838.   char proto[10];
  839.   char line[81];
  840.   FILE *fp;
  841.   ports = safe_malloc(65535 * sizeof(unsigned short));
  842.   proto[0] = '\0';
  843.   if (!(fp = fopen("/etc/services", "r"))) {
  844.     printf("We can't open /etc/services for reading!  Fix your system or don't use -f\n");
  845.     perror("fopen");
  846.     exit(1);
  847.   }
  848.  
  849.   while(fgets(line, 80, fp)) {
  850.     res = sscanf(line, "%*s %u/%s", &portno, proto);
  851.     if (res == 2 && portno != 0 && portno != lastport) {
  852.       lastport = portno;
  853.       if (tcpscan && proto[0] == 't')
  854.     ports[portindex++] = portno;
  855.       else if (udpscan && proto[0] == 'u')
  856.     ports[portindex++] = portno;
  857.     }
  858.   }
  859.  
  860.  
  861. number_of_ports = portindex;
  862. ports[portindex++] = 0;
  863. return realloc(ports, portindex * sizeof(unsigned short));
  864. }
  865.  
  866. void printusage(char *name) {
  867. printf("%s [options] [hostname[/mask] . . .]
  868. options (none are required, most can be combined):
  869.    -t tcp connect() port scan
  870.    -s tcp SYN stealth port scan (must be root)
  871.    -u UDP port scan, will use MUCH better version if you are root
  872.    -U Uriel Maimon (P49-15) style FIN stealth scan.
  873.    -l Do the lamer UDP scan even if root.  Less accurate.
  874.    -P ping \"scan\". Find which hosts on specified network(s) are up.
  875.    -b <ftp_relay_host> ftp \"bounce attack\" port scan
  876.    -f use tiny fragmented packets for SYN or FIN scan.
  877.    -i Get identd (rfc 1413) info on listening TCP processes.
  878.    -p <range> ports: ex: \'-p 23\' will only try port 23 of the host(s)
  879.                   \'-p 20-30,63000-\' scans 20-30 and 63000-65535 default: 1-1024
  880.    -F fast scan. Only scans ports in /etc/services, a la strobe(1).
  881.    -r randomize target port scanning order.
  882.    -h help, print this junk.  Also see http://www.dhp.com/~fyodor/nmap/
  883.    -S If you want to specify the source address of SYN or FYN scan.
  884.    -v Verbose.  Its use is recommended.  Use twice for greater effect.
  885.    -w <n> delay.  n microsecond delay. Not recommended unless needed.
  886.    -M <n> maximum number of parallel sockets.  Larger isn't always better.
  887.    -q quash argv to something benign, currently set to \"%s\".
  888. Hostnames specified as internet hostname or IP address.  Optional '/mask' specifies subnet. cert.org/24 or 192.88.209.5/24 scan CERT's Class C.\n",
  889.        name, FAKE_ARGV);
  890. exit(1);
  891. }
  892.  
  893. portlist tcp_scan(struct in_addr target, unsigned short *portarray, portlist *ports) {
  894.  
  895. int starttime, current_out = 0, res , deadindex = 0, i=0, j=0, k=0, max=0;
  896. struct sockaddr_in sock, stranger, mysock;
  897. int sockaddr_in_len = sizeof(struct sockaddr_in);
  898. int sockets[max_parallel_sockets], deadstack[max_parallel_sockets];
  899. unsigned short portno[max_parallel_sockets];
  900. char owner[513], buf[65536];
  901. int tryident = identscan, current_socket /*actually it is a socket INDEX*/;
  902. fd_set fds_read, fds_write;
  903. struct timeval nowait = {0,0},  longwait = {7,0};
  904.  
  905. signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our 'write 0 bytes' test
  906.                  doesn't crash our program!*/
  907. owner[0] = '\0';
  908. starttime = time(NULL);
  909. bzero((char *)&sock,sizeof(struct sockaddr_in));
  910. sock.sin_addr.s_addr = target.s_addr;
  911. if (verbose || debugging)
  912.   printf("Initiating TCP connect() scan against %s (%s)\n",
  913.      current_name,  inet_ntoa(sock.sin_addr));
  914. sock.sin_family=AF_INET;
  915. FD_ZERO(&fds_read);
  916. FD_ZERO(&fds_write);
  917.  
  918. if (tryident)
  919.   tryident = check_ident_port(target);
  920.  
  921. /* Initially, all of our sockets are "dead" */
  922. for(i = 0 ; i < max_parallel_sockets; i++) {
  923.   deadstack[deadindex++] = i;
  924.   portno[i] = 0;
  925. }
  926.  
  927. deadindex--;
  928. /* deadindex always points to the most recently added dead socket index */
  929.  
  930. while(portarray[j]) {
  931.   longwait.tv_sec = 7;
  932.   longwait.tv_usec = nowait.tv_sec = nowait.tv_usec = 0;
  933.  
  934.   for(i=current_out; i < max_parallel_sockets && portarray[j]; i++, j++) {
  935.     current_socket = deadstack[deadindex--];
  936.     if ((sockets[current_socket] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  937.       {perror("Socket troubles"); exit(1);}
  938.     if (sockets[current_socket] > max) max = sockets[current_socket];
  939.     current_out++;
  940.     unblock_socket(sockets[current_socket]);
  941.     init_socket(sockets[current_socket]);
  942.     portno[current_socket] = portarray[j];
  943.     sock.sin_port = htons(portarray[j]);
  944.     if ((res = connect(sockets[current_socket],(struct sockaddr *)&sock,sizeof(struct sockaddr)))!=-1)
  945.       printf("WTF???? I think we got a successful connection in non-blocking!!@#$\n");
  946.     else {
  947.       switch(errno) {
  948.       case EINPROGRESS: /* The one I always see */
  949.       case EAGAIN:
  950.     block_socket(sockets[current_socket]);
  951.     FD_SET(sockets[current_socket], &fds_write);
  952.     FD_SET(sockets[current_socket], &fds_read);
  953.     break;
  954.       default:
  955.     printf("Strange error from connect: (%d)", errno);
  956.     perror(""); /*falling through intentionally*/
  957.       case ECONNREFUSED:
  958.     if (max == sockets[current_socket]) max--;
  959.     deadstack[++deadindex] = current_socket;
  960.     current_out--;
  961.     portno[current_socket] = 0;
  962.     close(sockets[current_socket]);
  963.     break;
  964.       }
  965.     }
  966.   }
  967.   if (!portarray[j]) sleep(1); /*wait a second for any last packets*/
  968.   while((res = select(max + 1, &fds_read, &fds_write, NULL,
  969.               (current_out < max_parallel_sockets)?
  970.               &nowait : &longwait)) > 0) {
  971.     for(k=0; k < max_parallel_sockets; k++)
  972.       if (portno[k]) {
  973.     if (FD_ISSET(sockets[k], &fds_write)
  974.         && FD_ISSET(sockets[k], &fds_read)) {
  975.       /*printf("Socket at port %hi is selectable for r & w.", portno[k]);*/
  976.       res = recvfrom(sockets[k], buf, 65536, 0, (struct sockaddr *)
  977.              & stranger, &sockaddr_in_len);
  978.       if (res >= 0) {
  979.         if (debugging || verbose)
  980.           printf("Adding TCP port %hi due to successful read.\n",
  981.              portno[k]);
  982.         if (tryident) {
  983.           if ( getsockname(sockets[k], (struct sockaddr *) &mysock,
  984.                    &sockaddr_in_len ) ) {
  985.         perror("getsockname");
  986.         exit(1);
  987.           }
  988.           tryident = getidentinfoz(target, ntohs(mysock.sin_port),
  989.                        portno[k], owner);
  990.         }    
  991.         addport(ports, portno[k], IPPROTO_TCP, owner);
  992.       }
  993.       if (max == sockets[k])
  994.         max--;
  995.       FD_CLR(sockets[k], &fds_read);
  996.       FD_CLR(sockets[k], &fds_write);
  997.       deadstack[++deadindex] = k;
  998.       current_out--;
  999.       portno[k] = 0;
  1000.       close(sockets[k]);
  1001.     }
  1002.     else if(FD_ISSET(sockets[k], &fds_write)) {
  1003.       /*printf("Socket at port %hi is selectable for w only.VERIFYING\n",
  1004.         portno[k]);*/
  1005.       res = send(sockets[k], buf, 0, 0);
  1006.       if (res < 0 ) {
  1007.         signal(SIGPIPE, SIG_IGN);
  1008.         if (debugging > 1)
  1009.           printf("Bad port %hi caught by 0-byte write!\n", portno[k]);
  1010.       }
  1011.       else {
  1012.         if (debugging || verbose)
  1013.           printf("Adding TCP port %hi due to successful 0-byte write!\n",
  1014.              portno[k]);
  1015.         if (tryident) {
  1016.           if ( getsockname(sockets[k], (struct sockaddr *) &mysock ,
  1017.                    &sockaddr_in_len ) ) {
  1018.         perror("getsockname");
  1019.         exit(1);
  1020.           }
  1021.           tryident = getidentinfoz(target, ntohs(mysock.sin_port),
  1022.                        portno[k], owner);
  1023.         }    
  1024.         addport(ports, portno[k], IPPROTO_TCP, owner);    
  1025.       }
  1026.       if (max == sockets[k]) max--;
  1027.       FD_CLR(sockets[k], &fds_write);
  1028.       deadstack[++deadindex] = k;
  1029.       current_out--;
  1030.       portno[k] = 0;
  1031.       close(sockets[k]);
  1032.     }
  1033.     else if ( FD_ISSET(sockets[k], &fds_read) ) {
  1034.       printf("Socket at port %hi is selectable for r only.  This is very wierd.\n", portno[k]);
  1035.       if (max == sockets[k]) max--;
  1036.       FD_CLR(sockets[k], &fds_read);
  1037.       deadstack[++deadindex] = k;
  1038.       current_out--;
  1039.       portno[k] = 0;
  1040.       close(sockets[k]);
  1041.     }
  1042.     else {
  1043.       /*printf("Socket at port %hi not selecting, readding.\n",portno[k]);*/
  1044.       FD_SET(sockets[k], &fds_write);
  1045.       FD_SET(sockets[k], &fds_read);
  1046.     }
  1047.       }
  1048.   }
  1049. }
  1050.  
  1051. if (debugging || verbose)
  1052.   printf("Scanned %d ports in %ld seconds with %d parallel sockets.\n",
  1053.      number_of_ports, time(NULL) - starttime, max_parallel_sockets);
  1054. return *ports;
  1055. }
  1056.  
  1057. /* gawd, my next project will be in c++ so I don't have to deal with
  1058.    this crap ... simple linked list implementation */
  1059. int addport(portlist *ports, unsigned short portno, unsigned short protocol,
  1060.         char *owner) {
  1061. struct port *current, *tmp;
  1062. int len;
  1063.  
  1064. if (*ports) {
  1065.   current = *ports;
  1066.   /* case 1: we add to the front of the list */
  1067.   if (portno <= current->portno) {
  1068.     if (current->portno == portno && current->proto == protocol) {
  1069.       if (debugging || verbose)
  1070.     printf("Duplicate port (%hi/%s)\n", portno ,
  1071.            (protocol == IPPROTO_TCP)? "tcp": "udp");
  1072.       return -1;
  1073.     }
  1074.     tmp = current;
  1075.     *ports = safe_malloc(sizeof(struct port));
  1076.     (*ports)->next = tmp;
  1077.     current = *ports;
  1078.     current->portno = portno;
  1079.     current->proto = protocol;
  1080.     if (owner && *owner) {
  1081.       len = strlen(owner);
  1082.       current->owner = malloc(sizeof(char) * (len + 1));
  1083.       strncpy(current->owner, owner, len + 1);
  1084.     }
  1085.     else current->owner = NULL;
  1086.   }
  1087.   else { /* case 2: we add somewhere in the middle or end of the list */
  1088.     while( current->next  && current->next->portno < portno)
  1089.       current = current->next;
  1090.     if (current->next && current->next->portno == portno
  1091.     && current->next->proto == protocol) {
  1092.       if (debugging || verbose)
  1093.     printf("Duplicate port (%hi/%s)\n", portno ,
  1094.            (protocol == IPPROTO_TCP)? "tcp": "udp");
  1095.       return -1;
  1096.     }
  1097.     tmp = current->next;
  1098.     current->next = safe_malloc(sizeof(struct port));
  1099.     current->next->next = tmp;
  1100.     tmp = current->next;
  1101.     tmp->portno = portno;
  1102.     tmp->proto = protocol;
  1103.     if (owner && *owner) {
  1104.       len = strlen(owner);
  1105.       tmp->owner = malloc(sizeof(char) * (len + 1));
  1106.       strncpy(tmp->owner, owner, len + 1);
  1107.     }
  1108.     else tmp->owner = NULL;
  1109.   }
  1110. }
  1111.  
  1112. else { /* Case 3, list is null */
  1113.   *ports = safe_malloc(sizeof(struct port));
  1114.   tmp = *ports;
  1115.   tmp->portno = portno;
  1116.   tmp->proto = protocol;
  1117.   if (owner && *owner) {
  1118.     len = strlen(owner);
  1119.     tmp->owner = safe_malloc(sizeof(char) * (len + 1));
  1120.     strncpy(tmp->owner, owner, len + 1);
  1121.   }
  1122.   else tmp->owner = NULL;
  1123.   tmp->next = NULL;
  1124. }
  1125. return 0; /*success */
  1126. }
  1127.  
  1128. int deleteport(portlist *ports, unsigned short portno,
  1129.            unsigned short protocol) {
  1130.   portlist current, tmp;
  1131.  
  1132.   if (!*ports) {
  1133.     if (debugging > 1) error("Tried to delete from empty port list!");
  1134.     return -1;
  1135.   }
  1136.   /* Case 1, deletion from front of list*/
  1137.   if ((*ports)->portno == portno && (*ports)->proto == protocol) {
  1138.     tmp = (*ports)->next;
  1139.     if ((*ports)->owner) free((*ports)->owner);
  1140.     free(*ports);
  1141.     *ports = tmp;
  1142.   }
  1143.   else {
  1144.     current = *ports;
  1145.     for(;current->next && (current->next->portno != portno || current->next->proto != protocol); current = current->next);
  1146.     if (!current->next)
  1147.       return -1;
  1148.     tmp = current->next;
  1149.     current->next = tmp->next;
  1150.     if (tmp->owner) free(tmp->owner);
  1151.     free(tmp);
  1152. }
  1153.   return 0; /* success */
  1154. }
  1155.  
  1156.  
  1157. void *safe_malloc(int size)
  1158. {
  1159.   void *mymem;
  1160.   if (size < 0)
  1161.     fatal("Tried to malloc negative amount of memmory!!!");
  1162.   if ((mymem = malloc(size)) == NULL)
  1163.     fatal("Malloc Failed! Probably out of space.");
  1164.   return mymem;
  1165. }
  1166.  
  1167. void printandfreeports(portlist ports) {
  1168.   char protocol[4];
  1169.   struct servent *service;
  1170.   port *current = ports, *tmp;
  1171.  
  1172.   printf("Port Number  Protocol  Service");
  1173.   printf("%s", (identscan)?"         Owner\n":"\n");
  1174.   while(current != NULL) {
  1175.     strcpy(protocol,(current->proto == IPPROTO_TCP)? "tcp": "udp");
  1176.     service = getservbyport(htons(current->portno), protocol);
  1177.     printf("%-13d%-11s%-16s%s\n", current->portno, protocol,
  1178.        (service)? service->s_name: "unknown",
  1179.        (current->owner)? current->owner : "");
  1180.     tmp = current;
  1181.     current = current->next;
  1182.     if (tmp->owner) free(tmp->owner);
  1183.     free(tmp);
  1184.   }
  1185.   printf("\n");
  1186. }
  1187.  
  1188. /* This is the version of udp_scan that uses raw ICMP sockets and requires
  1189.    root priviliges.*/
  1190. portlist udp_scan(struct in_addr target, unsigned short *portarray,
  1191.           portlist *ports) {
  1192.   int icmpsock, udpsock, tmp, done=0, retries, bytes = 0, res,  num_out = 0;
  1193.   int i=0,j=0, k=0, icmperrlimittime, max_tries = UDP_MAX_PORT_RETRIES;
  1194.   unsigned short outports[max_parallel_sockets], numtries[max_parallel_sockets];
  1195.   struct sockaddr_in her;
  1196.   char senddata[] = "blah\n";
  1197.   unsigned long starttime, sleeptime;
  1198.   struct timeval shortwait = {1, 0 };
  1199.   fd_set  fds_read, fds_write;
  1200.  
  1201.   bzero(outports, max_parallel_sockets * sizeof(unsigned short));
  1202.   bzero(numtries, max_parallel_sockets * sizeof(unsigned short));
  1203.  
  1204.    /* Some systems (like linux) follow the advice of rfc1812 and limit
  1205.     * the rate at which they will respons with icmp error messages
  1206.     * (like port unreachable).  icmperrlimittime is to compensate for that.
  1207.     */
  1208.   icmperrlimittime = 60000;
  1209.  
  1210.   sleeptime = (global_delay)? global_delay : (global_rtt)? (1.2 * global_rtt) + 30000 : 1e5;
  1211. if (global_delay) icmperrlimittime = global_delay;
  1212.  
  1213. starttime = time(NULL);
  1214.  
  1215. FD_ZERO(&fds_read);
  1216. FD_ZERO(&fds_write);
  1217.  
  1218. if (verbose || debugging)
  1219.   printf("Initiating UDP (raw ICMP version) scan against %s (%s) using wait delay of %li usecs.\n", current_name,  inet_ntoa(target), sleeptime);
  1220.  
  1221. if ((icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
  1222.   perror("Opening ICMP RAW socket");
  1223. if ((udpsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  1224.   perror("Opening datagram socket");
  1225.  
  1226. unblock_socket(icmpsock);
  1227. her.sin_addr = target;
  1228. her.sin_family = AF_INET;
  1229.  
  1230. while(!done) {
  1231.   tmp = num_out;
  1232.   for(i=0; (i < max_parallel_sockets && portarray[j]) || i < tmp; i++) {
  1233.     close(udpsock);
  1234.     if ((udpsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  1235.       perror("Opening datagram socket");
  1236.     if ((i > tmp && portarray[j]) || numtries[i] > 1) {
  1237.       if (i > tmp) her.sin_port = htons(portarray[j++]);
  1238.       else her.sin_port = htons(outports[i]);
  1239.       FD_SET(udpsock, &fds_write);
  1240.       FD_SET(icmpsock, &fds_read);
  1241.       shortwait.tv_sec = 1; shortwait.tv_usec = 0;
  1242.       usleep(icmperrlimittime);
  1243.       res = select(udpsock + 1, NULL, &fds_write, NULL, &shortwait);
  1244.        if (FD_ISSET(udpsock, &fds_write))
  1245.       bytes = sendto(udpsock, senddata, sizeof(senddata), 0,
  1246.              (struct sockaddr *) &her, sizeof(struct sockaddr_in));
  1247.       else {
  1248.     printf("udpsock not set for writing port %d!",  ntohs(her.sin_port));
  1249.     return *ports;
  1250.       }
  1251.       if (bytes <= 0) {
  1252.     if (errno == ECONNREFUSED) {
  1253.       retries = 10;
  1254.       do {    
  1255.         /* This is from when I was using the same socket and would
  1256.          * (rather often) get strange connection refused errors, it
  1257.          * shouldn't happen now that I create a new udp socket for each
  1258.          * port.  At some point I will probably go back to 1 socket again.
  1259.          */
  1260.         printf("sendto said connection refused on port %d but trying again anyway.\n", ntohs(her.sin_port));
  1261.         usleep(icmperrlimittime);
  1262.         bytes = sendto(udpsock, senddata, sizeof(senddata), 0,
  1263.               (struct sockaddr *) &her, sizeof(struct sockaddr_in));
  1264.         printf("This time it returned %d\n", bytes);
  1265.       } while(bytes <= 0 && retries-- > 0);
  1266.     }
  1267.     if (bytes <= 0) {
  1268.       printf("sendto returned %d.", bytes);
  1269.       fflush(stdout);
  1270.       perror("sendto");
  1271.     }
  1272.       }
  1273.       if (bytes > 0 && i > tmp) {
  1274.     num_out++;
  1275.     outports[i] = portarray[j-1];
  1276.       }
  1277.     }
  1278.   }
  1279.   usleep(sleeptime);
  1280.   tmp = listen_icmp(icmpsock, outports, numtries, &num_out, target, ports);
  1281.   if (debugging) printf("listen_icmp caught %d bad ports.\n", tmp);
  1282.   done = !portarray[j];
  1283.   for (i=0,k=0; i < max_parallel_sockets; i++)
  1284.     if (outports[i]) {
  1285.       if (++numtries[i] > max_tries - 1) {
  1286.     if (debugging || verbose)
  1287.       printf("Adding port %d for 0 unreachable port generations\n",
  1288.          outports[i]);
  1289.     addport(ports, outports[i], IPPROTO_UDP, NULL);
  1290.     num_out--;
  1291.     outports[i] = numtries[i] = 0;
  1292.       }
  1293.       else {
  1294.     done = 0;
  1295.     outports[k] = outports[i];
  1296.     numtries[k] = numtries[i];
  1297.     if (k != i)
  1298.       outports[i] = numtries[i] = 0;
  1299.     k++;
  1300.       }
  1301.     }
  1302.   if (num_out == max_parallel_sockets) {
  1303.   printf("Numout is max sockets, that is a problem!\n");
  1304.   sleep(1); /* Give some time for responses to trickle back,
  1305.            and possibly to reset the hosts ICMP error limit */
  1306.   }
  1307. }
  1308.  
  1309.  
  1310. if (debugging || verbose)
  1311.   printf("The UDP raw ICMP scanned %d ports in  %ld seconds with %d parallel sockets.\n", number_of_ports, time(NULL) - starttime, max_parallel_sockets);
  1312. close(icmpsock);
  1313. close(udpsock);
  1314. return *ports;
  1315. }
  1316.  
  1317. int listen_icmp(int icmpsock,  unsigned short outports[],
  1318.         unsigned short numtries[], int *num_out, struct in_addr target,
  1319.         portlist *ports) {
  1320.   char response[1024];
  1321.   struct sockaddr_in stranger;
  1322.   int sockaddr_in_size = sizeof(struct sockaddr_in);
  1323.   struct in_addr bs;
  1324.   struct iphdr *ip = (struct iphdr *) response;
  1325.   struct icmphdr *icmp = (struct icmphdr *) (response + sizeof(struct iphdr));
  1326.   struct iphdr *ip2;
  1327.   unsigned short *data;
  1328.   int badport, numcaught=0, bytes, i, tmptry=0, found=0;
  1329.  
  1330.   while  ((bytes = recvfrom(icmpsock, response, 1024, 0,
  1331.                 (struct sockaddr *) &stranger,
  1332.                 &sockaddr_in_size)) > 0) {
  1333.   numcaught++;
  1334.   bs.s_addr = ip->saddr;
  1335.   if (ip->saddr == target.s_addr && ip->protocol == IPPROTO_ICMP
  1336.       && icmp->type == 3 && icmp->code == 3) {
  1337.     ip2 = (struct iphdr *) (response + 4 * ip->ihl + sizeof(struct icmphdr));
  1338.     data = (unsigned short *) ((char *)ip2 + 4 * ip2->ihl);
  1339.     badport = ntohs(data[1]);
  1340.     /*delete it from our outports array */
  1341.     found = 0;
  1342.     for(i=0; i < max_parallel_sockets; i++)
  1343.       if (outports[i] == badport) {
  1344.     found = 1;
  1345.     tmptry = numtries[i];
  1346.     outports[i] = numtries[i] = 0;
  1347.     (*num_out)--;
  1348.     break;
  1349.       }
  1350.     if (debugging && found && tmptry > 0)
  1351.       printf("Badport: %d on try number %d\n", badport, tmptry);
  1352.     if (!found) {
  1353.       if (debugging)
  1354.     printf("Badport %d came in late, deleting from portlist.\n", badport);
  1355.       if (deleteport(ports, badport, IPPROTO_UDP) < 0)
  1356.     if (debugging) printf("Port deletion failed.\n");
  1357.     }
  1358.   }
  1359.   else {
  1360.     printf("Funked up packet!\n");
  1361.   }
  1362. }
  1363.   return numcaught;
  1364. }
  1365.  
  1366. /* This fucntion is nonsens.  I wrote it all, really optimized etc.  Then
  1367.    found out that many hosts limit the rate at which they send icmp errors :(
  1368.    I will probably totally rewrite it to be much simpler at some point.  For
  1369.    now I won't worry about it since it isn't a very important functions (UDP
  1370.    is lame, plus there is already a much better function for people who
  1371.    are r00t */
  1372. portlist lamer_udp_scan(struct in_addr target, unsigned short *portarray,
  1373.             portlist *ports) {
  1374. int sockaddr_in_size = sizeof(struct sockaddr_in),i=0,j=0,k=0, bytes;
  1375. int sockets[max_parallel_sockets], trynum[max_parallel_sockets];
  1376. unsigned short portno[max_parallel_sockets];
  1377. int last_open = 0;
  1378. char response[1024];
  1379. struct sockaddr_in her, stranger;
  1380. char data[] = "\nhelp\nquit\n";
  1381. unsigned long sleeptime;
  1382. unsigned int starttime;
  1383.  
  1384. /* Initialize our target sockaddr_in */
  1385. bzero((char *) &her, sizeof(struct sockaddr_in));
  1386. her.sin_family = AF_INET;
  1387. her.sin_addr = target;
  1388.  
  1389. if (global_delay) sleeptime = global_delay;
  1390. else sleeptime =  calculate_sleep(target) + 60000; /*large to be on the
  1391.                             safe side */
  1392.  
  1393. if (verbose || debugging)
  1394.   printf("Initiating UDP scan against %s (%s), sleeptime: %li\n", current_name,
  1395.      inet_ntoa(target), sleeptime);
  1396.  
  1397. starttime = time(NULL);
  1398.  
  1399. for(i = 0 ; i < max_parallel_sockets; i++)
  1400.   trynum[i] =  portno[i] = 0;
  1401.  
  1402. while(portarray[j]) {
  1403.   for(i=0; i < max_parallel_sockets && portarray[j]; i++, j++) {
  1404.     if (i >= last_open) {
  1405.       if ((sockets[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
  1406.         {perror("datagram socket troubles"); exit(1);}
  1407.       block_socket(sockets[i]);
  1408.       portno[i] = portarray[j];
  1409.     }
  1410.     her.sin_port = htons(portarray[j]);
  1411.     bytes = sendto(sockets[i], data, sizeof(data), 0, (struct sockaddr *) &her,
  1412.            sizeof(struct sockaddr_in));
  1413.     usleep(5000);
  1414.     if (debugging > 1)
  1415.       printf("Sent %d bytes on socket %d to port %hi, try number %d.\n",
  1416.          bytes, sockets[i], portno[i], trynum[i]);
  1417.     if (bytes < 0 ) {
  1418.       printf("Sendto returned %d the FIRST TIME!@#$!, errno %d\n", bytes,
  1419.          errno);
  1420.       perror("");
  1421.       trynum[i] = portno[i] = 0;
  1422.       close(sockets[i]);
  1423.     }
  1424.   }
  1425.   last_open = i;
  1426.   /* Might need to change this to 1e6 if you are having problems*/
  1427.   usleep(sleeptime + 5e5);
  1428.   for(i=0; i < last_open ; i++) {
  1429.     if (portno[i]) {
  1430.       unblock_socket(sockets[i]);
  1431.       if ((bytes = recvfrom(sockets[i], response, 1024, 0,
  1432.                 (struct sockaddr *) &stranger,
  1433.                 &sockaddr_in_size)) == -1)
  1434.         {
  1435.           if (debugging > 1)
  1436.         printf("2nd recvfrom on port %d returned %d with errno %d.\n",
  1437.            portno[i], bytes, errno);
  1438.           if (errno == EAGAIN /*11*/)
  1439.             {
  1440.               if (trynum[i] < 2) trynum[i]++;
  1441.               else {
  1442.         if (RISKY_UDP_SCAN) {    
  1443.           printf("Adding port %d after 3 EAGAIN errors.\n", portno[i]);
  1444.           addport(ports, portno[i], IPPROTO_UDP, NULL);
  1445.         }
  1446.         else if (debugging)
  1447.           printf("Skipping possible false positive, port %d\n",
  1448.              portno[i]);
  1449.                 trynum[i] = portno[i] = 0;
  1450.                 close(sockets[i]);
  1451.               }
  1452.             }
  1453.           else if (errno == ECONNREFUSED /*111*/) {
  1454.             if (debugging > 1)
  1455.           printf("Closing socket for port %d, ECONNREFUSED received.\n",
  1456.              portno[i]);
  1457.             trynum[i] = portno[i] = 0;
  1458.             close(sockets[i]);
  1459.           }
  1460.           else {
  1461.             printf("Curious recvfrom error (%d) on port %hi: ",
  1462.            errno, portno[i]);
  1463.             perror("");
  1464.             trynum[i] = portno[i] = 0;
  1465.             close(sockets[i]);
  1466.           }
  1467.         }
  1468.       else /*bytes is positive*/ {
  1469.         if (debugging || verbose)
  1470.       printf("Adding UDP port %d due to positive read!\n", portno[i]);
  1471.         addport(ports,portno[i], IPPROTO_UDP, NULL);
  1472.         trynum[i] = portno[i] = 0;
  1473.         close(sockets[i]);
  1474.       }
  1475.     }
  1476.   }
  1477.   /* Update last_open, we need to create new sockets.*/
  1478.   for(i=0, k=0; i < last_open; i++)
  1479.     if (portno[i]) {
  1480.       close(sockets[i]);
  1481.       sockets[k] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  1482.       /*      unblock_socket(sockets[k]);*/
  1483.       portno[k] = portno[i];
  1484.       trynum[k] = trynum[i];
  1485.       k++;
  1486.     }
  1487.  last_open = k;
  1488.   for(i=k; i < max_parallel_sockets; i++)
  1489.     trynum[i] = sockets[i] = portno[i] = 0;
  1490. }
  1491. if (debugging)
  1492.   printf("UDP scanned %d ports in %ld seconds with %d parallel sockets\n",
  1493.      number_of_ports, time(NULL) - starttime, max_parallel_sockets);
  1494. return *ports;
  1495. }
  1496.  
  1497. /* This attempts to calculate the round trip time (rtt) to a host by timing a
  1498.    connect() to a port which isn't listening.  A better approach is to time a
  1499.    ping (since it is more likely to get through firewalls.  This is now
  1500.    implemented in isup() for users who are root.  */
  1501. unsigned long calculate_sleep(struct in_addr target) {
  1502. struct timeval begin, end;
  1503. int sd;
  1504. struct sockaddr_in sock;
  1505. int res;
  1506.  
  1507. if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  1508.   {perror("Socket troubles"); exit(1);}
  1509.  
  1510. sock.sin_family = AF_INET;
  1511. sock.sin_addr.s_addr = target.s_addr;
  1512. sock.sin_port = htons(MAGIC_PORT);
  1513.  
  1514. gettimeofday(&begin, NULL);
  1515. if ((res = connect(sd, (struct sockaddr *) &sock,
  1516.            sizeof(struct sockaddr_in))) != -1)
  1517.   printf("You might want to change MAGIC_PORT in the include file, it seems to be listening on the target host!\n");
  1518. close(sd);
  1519. gettimeofday(&end, NULL);
  1520. if (end.tv_sec - begin.tv_sec > 5 ) /*uh-oh!*/
  1521.   return 0;
  1522. return (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec);
  1523. }
  1524.  
  1525. /* Checks whether the identd port (113) is open on the target machine.  No
  1526.    sense wasting time trying it for each good port if it is down! */
  1527. int check_ident_port(struct in_addr target) {
  1528. int sd;
  1529. struct sockaddr_in sock;
  1530. int res;
  1531.  
  1532. if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  1533.   {perror("Socket troubles"); exit(1);}
  1534.  
  1535. sock.sin_family = AF_INET;
  1536. sock.sin_addr.s_addr = target.s_addr;
  1537. sock.sin_port = htons(113); /*should use getservbyname(3), yeah, yeah */
  1538. res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  1539. close(sd);
  1540. if (res < 0 ) {
  1541.   if (debugging || verbose) printf("identd port not active\n");
  1542.   return 0;
  1543. }
  1544. if (debugging || verbose) printf("identd port is active\n");
  1545. return 1;
  1546. }
  1547.  
  1548. int getidentinfoz(struct in_addr target, int localport, int remoteport,
  1549.           char *owner) {
  1550. int sd;
  1551. struct sockaddr_in sock;
  1552. int res;
  1553. char request[15];
  1554. char response[1024];
  1555. char *p,*q;
  1556. char  *os;
  1557.  
  1558. owner[0] = '\0';
  1559. if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  1560.   {perror("Socket troubles"); exit(1);}
  1561.  
  1562. sock.sin_family = AF_INET;
  1563. sock.sin_addr.s_addr = target.s_addr;
  1564. sock.sin_port = htons(113);
  1565. usleep(50000);   /* If we aren't careful, we really MIGHT take out inetd,
  1566.             some are very fragile */
  1567. res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  1568.  
  1569. if (res < 0 ) {
  1570.   if (debugging || verbose)
  1571.     printf("identd port not active now for some reason ... hope we didn't break it!\n");
  1572.   close(sd);
  1573.   return 0;
  1574. }
  1575. sprintf(request,"%hi,%hi\r\n", remoteport, localport);
  1576. if (debugging > 1) printf("Connected to identd, sending request: %s", request);
  1577. if (write(sd, request, strlen(request) + 1) == -1) {
  1578.   perror("identd write");
  1579.   close(sd);
  1580.   return 0;
  1581. }
  1582. else if ((res = read(sd, response, 1024)) == -1) {
  1583.   perror("reading from identd");
  1584.   close(sd);
  1585.   return 0;
  1586. }
  1587. else {
  1588.   close(sd);
  1589.   if (debugging > 1) printf("Read %d bytes from identd: %s\n", res, response);
  1590.   if ((p = strchr(response, ':'))) {
  1591.     p++;
  1592.     if ((q = strtok(p, " :"))) {
  1593.       if (!strcasecmp( q, "error")) {
  1594.     if (debugging || verbose) printf("ERROR returned from identd\n");
  1595.     return 0;
  1596.       }
  1597.       if ((os = strtok(NULL, " :"))) {
  1598.     if ((p = strtok(NULL, " :"))) {
  1599.       if ((q = strchr(p, '\r'))) *q = '\0';
  1600.       if ((q = strchr(p, '\n'))) *q = '\0';
  1601.       strncpy(owner, p, 512);
  1602.       owner[512] = '\0';
  1603.     }
  1604.       }
  1605.     }
  1606.   }
  1607. }
  1608. return 1;
  1609. }
  1610.  
  1611. /* A relatively fast (or at least short ;) ping function.  Doesn't require a
  1612.    seperate checksum function */
  1613. int isup(struct in_addr target) {
  1614.   int res, retries = 3;
  1615.   struct sockaddr_in sock;
  1616.   /*type(8bit)=8, code(8)=0 (echo REQUEST), checksum(16)=34190, id(16)=31337 */
  1617. #ifdef __LITTLE_ENDIAN_BITFIELD
  1618.   unsigned char ping[64] = { 0x8, 0x0, 0x8e, 0x85, 0x69, 0x7A };
  1619. #else
  1620.   unsigned char ping[64] = { 0x8, 0x0, 0x85, 0x8e, 0x7A, 0x69 };
  1621. #endif
  1622.   int sd;
  1623.   struct timeval tv;
  1624.   struct timeval start, end;
  1625.  fd_set fd_read;
  1626.   struct {
  1627.     struct iphdr ip;
  1628.     unsigned char type;
  1629.     unsigned char code;
  1630.     unsigned short checksum;
  1631.     unsigned short identifier;
  1632.     char crap[16536];
  1633.   }  response;
  1634.  
  1635. sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  1636.  
  1637. bzero((char *)&sock,sizeof(struct sockaddr_in));
  1638. sock.sin_family=AF_INET;
  1639. sock.sin_addr = target;
  1640. if (debugging > 1) printf(" Sending 3 64 byte raw pings to host.\n");
  1641. gettimeofday(&start, NULL);
  1642. while(--retries) {
  1643.   if ((res = sendto(sd,(char *) ping,64,0,(struct sockaddr *)&sock,
  1644.             sizeof(struct sockaddr))) != 64) {
  1645.     fprintf(stderr, "sendto in isup returned %d! skipping host.\n", res);
  1646.     return 0;
  1647.   }
  1648.   FD_ZERO(&fd_read);
  1649.   FD_SET(sd, &fd_read);
  1650.   tv.tv_sec = 0;
  1651.   tv.tv_usec = 1e6 * (PING_TIMEOUT / 3.0);
  1652.   while(1) {
  1653.     if ((res = select(sd + 1, &fd_read, NULL, NULL, &tv)) != 1)
  1654.       break;
  1655.     else {
  1656.       read(sd,&response,sizeof(response));
  1657.       if  (response.ip.saddr == target.s_addr &&  !response.type
  1658.        && !response.code   && response.identifier == 31337) {
  1659.     gettimeofday(&end, NULL);
  1660.     global_rtt = (end.tv_sec - start.tv_sec) * 1e6 + end.tv_usec - start.tv_usec;
  1661.     ouraddr.s_addr = response.ip.daddr;
  1662.     close(sd);
  1663.     return 1;
  1664.       }
  1665.     }
  1666.   }
  1667. }
  1668. close(sd);
  1669. return 0;
  1670. }
  1671.  
  1672.  
  1673. portlist syn_scan(struct in_addr target, unsigned short *portarray,
  1674.           struct in_addr *source, int fragment, portlist *ports) {
  1675. int i=0, j=0, received, bytes, starttime;
  1676. struct sockaddr_in from;
  1677. int fromsize = sizeof(struct sockaddr_in);
  1678. int sockets[max_parallel_sockets];
  1679. struct timeval tv;
  1680. char packet[65535];
  1681. struct iphdr *ip = (struct iphdr *) packet;
  1682. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct iphdr));
  1683. fd_set fd_read, fd_write;
  1684. int res;
  1685. struct hostent *myhostent;
  1686. char myname[MAXHOSTNAMELEN + 1];
  1687. int source_malloc = 0;
  1688.  
  1689. FD_ZERO(&fd_read);
  1690. FD_ZERO(&fd_write);
  1691.  
  1692. tv.tv_sec = 7;
  1693. tv.tv_usec = 0;
  1694.  
  1695. if ((received = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) < 0 )
  1696.   perror("socket trobles in syn_scan");
  1697. unblock_socket(received);
  1698. FD_SET(received, &fd_read);
  1699.  
  1700. /* First we take what is given to us as source.  If that isn't valid, we take
  1701.    what should have swiped from the echo reply in our ping function.  If THAT
  1702.    doesn't work either, we try to determine our address with gethostname and
  1703.    gethostbyname.  Whew! */
  1704. if (!source) {
  1705.   if (ouraddr.s_addr) {
  1706.     source = &ouraddr;
  1707.   }
  1708.   else {
  1709.   source = safe_malloc(sizeof(struct in_addr));
  1710.   source_malloc = 1;
  1711.   if (gethostname(myname, MAXHOSTNAMELEN) ||
  1712.       !(myhostent = gethostbyname(myname)))
  1713.     fatal("Your system is fucked up.\n");
  1714.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  1715.   }
  1716.   if (debugging)
  1717.     printf("We skillfully deduced that your address is %s\n",
  1718.        inet_ntoa(*source));
  1719. }
  1720.  
  1721. starttime = time(NULL);
  1722.  
  1723. do {
  1724.   for(i=0; i < max_parallel_sockets && portarray[j]; i++) {
  1725.     if ((sockets[i] = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  1726.       perror("socket trobles in syn_scan");
  1727.     else {
  1728.       if (fragment)
  1729.     send_small_fragz(sockets[i], source, &target, MAGIC_PORT,
  1730.              portarray[j++], TH_SYN);
  1731.       else send_tcp_raw(sockets[i], source , &target, MAGIC_PORT,
  1732.             portarray[j++],0,0,TH_SYN,0,0,0);
  1733.       usleep(10000);
  1734.     }
  1735.   }
  1736.   if ((res = select(received + 1, &fd_read, NULL, NULL, &tv)) < 0)
  1737.     perror("select problems in syn_scan");
  1738.   else if (res > 0) {
  1739.     while  ((bytes = recvfrom(received, packet, 65535, 0,
  1740.                   (struct sockaddr *)&from, &fromsize)) > 0 ) {
  1741.       if (ip->saddr == target.s_addr) {
  1742.     if (tcp->th_flags & TH_RST) {
  1743.       if (debugging > 1) printf("Nothing open on port %d\n",
  1744.                     ntohs(tcp->th_sport));
  1745.     }
  1746.     else /*if (tcp->th_flags & TH_SYN && tcp->th_flags & TH_ACK)*/ {
  1747.       if (debugging || verbose) {    
  1748.         printf("Possible catch on port %d!  Here it is:\n",
  1749.            ntohs(tcp->th_sport));
  1750.         readtcppacket(packet,1);
  1751.       }
  1752.       addport(ports, ntohs(tcp->th_sport), IPPROTO_TCP, NULL);     
  1753.     }
  1754.       }
  1755.     }
  1756.   }
  1757.   for(i=0; i < max_parallel_sockets && portarray[j]; i++) close(sockets[i]);
  1758.  
  1759. } while (portarray[j]);
  1760. if (debugging || verbose)
  1761.   printf("The TCP SYN scan took %ld seconds to scan %d ports.\n",
  1762.      time(NULL) - starttime, number_of_ports);
  1763. if (source_malloc) free(source);  /* Gotta save those 4 bytes! ;) */
  1764. close(received);
  1765. return *ports;
  1766. }
  1767.  
  1768.  
  1769. int send_tcp_raw( int sd, struct in_addr *source,
  1770.           struct in_addr *victim, unsigned short sport,
  1771.           unsigned short dport, unsigned long seq,
  1772.           unsigned long ack, unsigned char flags,
  1773.           unsigned short window, char *data,
  1774.           unsigned short datalen)
  1775. {
  1776.  
  1777. struct pseudo_header {
  1778.   /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  1779.   unsigned long s_addr;
  1780.   unsigned long d_addr;
  1781.   char zer0;
  1782.   unsigned char protocol;
  1783.   unsigned short length;
  1784. };
  1785. char packet[sizeof(struct iphdr) + sizeof(struct tcphdr) + datalen];
  1786.  /*With these placement we get data and some field alignment so we aren't
  1787.    wasting too much in computing the checksum */
  1788. struct iphdr *ip = (struct iphdr *) packet;
  1789. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct iphdr));
  1790. struct pseudo_header *pseudo =  (struct pseudo_header *) (packet + sizeof(struct iphdr) - sizeof(struct pseudo_header));
  1791. int res;
  1792. struct sockaddr_in sock;
  1793. char myname[MAXHOSTNAMELEN + 1];
  1794. struct hostent *myhostent;
  1795. int source_malloced = 0;
  1796.  
  1797. /* check that required fields are there and not too silly */
  1798. if ( !victim || !sport || !dport || sd < 0) {
  1799.   fprintf(stderr, "send_tcp_raw: One or more of your parameters suck!\n");
  1800.   return -1;
  1801. }
  1802.  
  1803. /* if they didn't give a source address, fill in our first address */
  1804. if (!source) {
  1805.   source_malloced = 1;
  1806.   source = safe_malloc(sizeof(struct in_addr));
  1807.   if (gethostname(myname, MAXHOSTNAMELEN) ||
  1808.       !(myhostent = gethostbyname(myname)))
  1809.     fatal("Your system is fucked up.\n");
  1810.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  1811.   if (debugging > 1)
  1812.     printf("We skillfully deduced that your address is %s\n",
  1813.        inet_ntoa(*source));
  1814. }
  1815.  
  1816.  
  1817. /*do we even have to fill out this damn thing?  This is a raw packet,
  1818.   after all */
  1819. sock.sin_family = AF_INET;
  1820. sock.sin_port = htons(dport);
  1821. sock.sin_addr.s_addr = victim->s_addr;
  1822.  
  1823. bzero(packet, sizeof(struct iphdr) + sizeof(struct tcphdr));
  1824.  
  1825. pseudo->s_addr = source->s_addr;
  1826. pseudo->d_addr = victim->s_addr;
  1827. pseudo->protocol = IPPROTO_TCP;
  1828. pseudo->length = htons(sizeof(struct tcphdr) + datalen);
  1829.  
  1830. tcp->th_sport = htons(sport);
  1831. tcp->th_dport = htons(dport);
  1832. if (seq)
  1833.   tcp->th_seq = htonl(seq);
  1834. else tcp->th_seq = rand() + rand();
  1835.  
  1836. if (flags & TH_ACK && ack)
  1837.   tcp->th_ack = htonl(seq);
  1838. else if (flags & TH_ACK)
  1839.   tcp->th_ack = rand() + rand();
  1840.  
  1841. tcp->th_off = 5 /*words*/;
  1842. tcp->th_flags = flags;
  1843.  
  1844. if (window)
  1845.   tcp->th_win = window;
  1846. else tcp->th_win = htons(2048); /* Who cares */
  1847.  
  1848. tcp->th_sum = in_cksum((unsigned short *)pseudo, sizeof(struct tcphdr) +
  1849.                sizeof(struct pseudo_header) + datalen);
  1850.  
  1851. /* Now for the ip header */
  1852. bzero(packet, sizeof(struct iphdr));
  1853. ip->version = 4;
  1854. ip->ihl = 5;
  1855. ip->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + datalen);
  1856. ip->id = rand();
  1857. ip->ttl = 255;
  1858. ip->protocol = IPPROTO_TCP;
  1859. ip->saddr = source->s_addr;
  1860. ip->daddr = victim->s_addr;
  1861. ip->check = in_cksum((unsigned short *)ip, sizeof(struct iphdr));
  1862.  
  1863. if (debugging > 1) {
  1864. printf("Raw TCP packet creation completed!  Here it is:\n");
  1865. readtcppacket(packet,ntohs(ip->tot_len));
  1866. }
  1867. if (debugging > 1)
  1868.   printf("\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n",
  1869.      sd, ntohs(ip->tot_len), inet_ntoa(*victim),
  1870.      sizeof(struct sockaddr_in));
  1871. if ((res = sendto(sd, packet, ntohs(ip->tot_len), 0,
  1872.           (struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)
  1873.   {
  1874.     perror("sendto in send_tcp_raw");
  1875.     if (source_malloced) free(source);
  1876.     return -1;
  1877.   }
  1878. if (debugging > 1) printf("successfully sent %d bytes of raw_tcp!\n", res);
  1879.  
  1880. if (source_malloced) free(source);
  1881. return res;
  1882. }
  1883.  
  1884. /* A simple program I wrote to help in debugging, shows the important fields
  1885.    of a TCP packet*/
  1886. int readtcppacket(char *packet, int readdata) {
  1887. struct iphdr *ip = (struct iphdr *) packet;
  1888. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct iphdr));
  1889. char *data = packet +  sizeof(struct iphdr) + sizeof(struct tcphdr);
  1890. int tot_len;
  1891. struct in_addr bullshit, bullshit2;
  1892. char sourcehost[16];
  1893. int i;
  1894.  
  1895. if (!packet) {
  1896.   fprintf(stderr, "readtcppacket: packet is NULL!\n");
  1897.   return -1;
  1898.     }
  1899. bullshit.s_addr = ip->saddr; bullshit2.s_addr = ip->daddr;
  1900. tot_len = ntohs(ip->tot_len);
  1901. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  1902. i =  4 * (ntohs(ip->ihl) + ntohs(tcp->th_off));
  1903. if (ip->protocol == IPPROTO_TCP)
  1904.   if (ip->frag_off) printf("Packet is fragmented, offset field: %u",
  1905.                ip->frag_off);
  1906.   else {
  1907.     printf("TCP packet: %s:%d -> %s:%d (total: %d bytes)\n", sourcehost,
  1908.        ntohs(tcp->th_sport), inet_ntoa(bullshit2),
  1909.        ntohs(tcp->th_dport), tot_len);
  1910.     printf("Flags: ");
  1911.     if (!tcp->th_flags) printf("(none)");
  1912.     if (tcp->th_flags & TH_RST) printf("RST ");
  1913.     if (tcp->th_flags & TH_SYN) printf("SYN ");
  1914.     if (tcp->th_flags & TH_ACK) printf("ACK ");
  1915.     if (tcp->th_flags & TH_PUSH) printf("PSH ");
  1916.     if (tcp->th_flags & TH_FIN) printf("FIN ");
  1917.     if (tcp->th_flags & TH_URG) printf("URG ");
  1918.     printf("\n");
  1919.     printf("ttl: %hi ", ip->ttl);
  1920.     if (tcp->th_flags & (TH_SYN | TH_ACK)) printf("Seq: %lu\tAck: %lu\n",
  1921.                           tcp->th_seq, tcp->th_ack);
  1922.     else if (tcp->th_flags & TH_SYN) printf("Seq: %lu\n", ntohl(tcp->th_seq));
  1923.     else if (tcp->th_flags & TH_ACK) printf("Ack: %lu\n", ntohl(tcp->th_ack));
  1924.   }
  1925. if (readdata && i < tot_len) {
  1926. printf("Data portion:\n");
  1927. while(i < tot_len)  printf("%2X%c", data[i], (++i%16)? ' ' : '\n');
  1928. printf("\n");
  1929. }
  1930. return 0;
  1931. }
  1932.  
  1933. /* We don't exactly need real crypto here (thank god!)\n"*/
  1934. int shortfry(unsigned short *ports) {
  1935. int num;
  1936. unsigned short tmp;
  1937. int i;
  1938.  
  1939. for(i=0; i < number_of_ports; i++) {
  1940.   num = rand() % (number_of_ports);
  1941.   tmp = ports[i];
  1942.   ports[i] = ports[num];
  1943.   ports[num] = tmp;
  1944. }
  1945. return 1;
  1946. }
  1947.  
  1948.  
  1949. /* Much of this is swiped from my send_tcp_raw function above, which
  1950.    doesn't support fragmentation */
  1951. int send_small_fragz(int sd, struct in_addr *source, struct in_addr *victim,
  1952.              int sport, int dport, int flags) {
  1953.  
  1954. struct pseudo_header {
  1955. /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  1956.   unsigned long s_addr;
  1957.   unsigned long d_addr;
  1958.   char zer0;
  1959.   unsigned char protocol;
  1960.   unsigned short length;
  1961. };
  1962. /*In this placement we get data and some field alignment so we aren't wasting
  1963.   too much to compute the TCP checksum.*/
  1964. char packet[sizeof(struct iphdr) + sizeof(struct tcphdr) + 100];
  1965. struct iphdr *ip = (struct iphdr *) packet;
  1966. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct iphdr));
  1967. struct pseudo_header *pseudo = (struct pseudo_header *) (packet + sizeof(struct iphdr) - sizeof(struct pseudo_header));
  1968. char *frag2 = packet + sizeof(struct iphdr) + 16;
  1969. struct iphdr *ip2 = (struct iphdr *) (frag2 - sizeof(struct iphdr));
  1970. int res;
  1971. struct sockaddr_in sock;
  1972. int id;
  1973.  
  1974. /*Why do we have to fill out this damn thing? This is a raw packet, after all */
  1975. sock.sin_family = AF_INET;
  1976. sock.sin_port = htons(dport);
  1977. sock.sin_addr.s_addr = victim->s_addr;
  1978.  
  1979. bzero(packet, sizeof(struct iphdr) + sizeof(struct tcphdr));
  1980.  
  1981. pseudo->s_addr = source->s_addr;
  1982. pseudo->d_addr = victim->s_addr;
  1983. pseudo->protocol = IPPROTO_TCP;
  1984. pseudo->length = htons(sizeof(struct tcphdr));
  1985.  
  1986. tcp->th_sport = htons(sport);
  1987. tcp->th_dport = htons(dport);
  1988. tcp->th_seq = rand() + rand();
  1989.  
  1990. tcp->th_off = 5 /*words*/;
  1991. tcp->th_flags = flags;
  1992.  
  1993. tcp->th_win = htons(2048); /* Who cares */
  1994.  
  1995. tcp->th_sum = in_cksum((unsigned short *)pseudo,
  1996.                sizeof(struct tcphdr) + sizeof(struct pseudo_header));
  1997.  
  1998. /* Now for the ip header of frag1 */
  1999. bzero(packet, sizeof(struct iphdr));
  2000. ip->version = 4;
  2001. ip->ihl = 5;
  2002. /*RFC 791 allows 8 octet frags, but I get "operation not permitted" (EPERM)
  2003.   when I try that.  */
  2004. ip->tot_len = htons(sizeof(struct iphdr) + 16);
  2005. id = ip->id = rand();
  2006. ip->frag_off = htons(MORE_FRAGMENTS);
  2007. ip->ttl = 255;
  2008. ip->protocol = IPPROTO_TCP;
  2009. ip->saddr = source->s_addr;
  2010. ip->daddr = victim->s_addr;
  2011. ip->check = in_cksum((unsigned short *)ip, sizeof(struct iphdr));
  2012.  
  2013. if (debugging > 1) {
  2014.   printf("Raw TCP packet fragment #1 creation completed!  Here it is:\n");
  2015.   hdump(packet,20);
  2016. }
  2017. if (debugging > 1)
  2018.   printf("\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n",
  2019.      sd, ntohs(ip->tot_len), inet_ntoa(*victim),
  2020.      sizeof(struct sockaddr_in));
  2021. if ((res = sendto(sd, packet, ntohs(ip->tot_len), 0,
  2022.           (struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)
  2023.   {
  2024.     perror("sendto in send_syn_fragz");
  2025.     return -1;
  2026.   }
  2027. if (debugging > 1) printf("successfully sent %d bytes of raw_tcp!\n", res);
  2028.  
  2029. /* Create the second fragment */
  2030. bzero(ip2, sizeof(struct iphdr));
  2031. ip2->version = 4;
  2032. ip2->ihl = 5;
  2033. ip2->tot_len = htons(sizeof(struct iphdr) + 4); /* the rest of our TCP packet */
  2034. ip2->id = id;
  2035. ip2->frag_off = htons(2);
  2036. ip2->ttl = 255;
  2037. ip2->protocol = IPPROTO_TCP;
  2038. ip2->saddr = source->s_addr;
  2039. ip2->daddr = victim->s_addr;
  2040. ip2->check = in_cksum((unsigned short *)ip2, sizeof(struct iphdr));
  2041. if (debugging > 1) {
  2042.   printf("Raw TCP packet fragment creation completed!  Here it is:\n");
  2043.   hdump(packet,20);
  2044. }
  2045. if (debugging > 1)
  2046.   printf("\nTrying sendto(%d , ip2, %d, 0 , %s , %d)\n", sd,
  2047.      ntohs(ip2->tot_len), inet_ntoa(*victim), sizeof(struct sockaddr_in));
  2048. if ((res = sendto(sd, ip2, ntohs(ip2->tot_len), 0,
  2049.           (struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)
  2050.   {
  2051.     perror("sendto in send_tcp_raw");
  2052.     return -1;
  2053.   }
  2054. return 1;
  2055. }
  2056.  
  2057. /* Hex dump */
  2058. void hdump(unsigned char *packet, int len) {
  2059. unsigned int i=0, j=0;
  2060.  
  2061. printf("Here it is:\n");
  2062.  
  2063. for(i=0; i < len; i++){
  2064.   j = (unsigned) (packet[i]);
  2065.   printf("%-2X ", j);
  2066.   if (!((i+1)%16))
  2067.     printf("\n");
  2068.   else if (!((i+1)%4))
  2069.     printf("  ");
  2070. }
  2071. printf("\n");
  2072. }
  2073.  
  2074.  
  2075. portlist fin_scan(struct in_addr target, unsigned short *portarray,
  2076.           struct in_addr *source, int fragment, portlist *ports) {
  2077.  
  2078. int rawsd, tcpsd;
  2079. int done = 0, badport, starttime, someleft, i, j=0, retries=2;
  2080. int source_malloc = 0;
  2081. int waiting_period = retries, sockaddr_in_size = sizeof(struct sockaddr_in);
  2082. int bytes, dupesinarow = 0;
  2083. unsigned long timeout;
  2084. struct hostent *myhostent;
  2085. char response[65535], myname[513];
  2086. struct iphdr *ip = (struct iphdr *) response;
  2087. struct tcphdr *tcp;
  2088. unsigned short portno[max_parallel_sockets], trynum[max_parallel_sockets];
  2089. struct sockaddr_in stranger;
  2090.  
  2091.  
  2092. timeout = (global_delay)? global_delay : (global_rtt)? (1.2 * global_rtt) + 10000 : 1e5;
  2093. bzero(&stranger, sockaddr_in_size);
  2094. bzero(portno, max_parallel_sockets * sizeof(unsigned short));
  2095. bzero(trynum, max_parallel_sockets * sizeof(unsigned short));
  2096. starttime = time(NULL);
  2097.  
  2098.  
  2099. if (debugging || verbose)
  2100.   printf("Initiating FIN stealth scan against %s (%s), sleep delay: %ld useconds\n", current_name, inet_ntoa(target), timeout);
  2101.  
  2102. if (!source) {
  2103.   if (ouraddr.s_addr) {
  2104.     source = &ouraddr;
  2105.   }
  2106.   else {
  2107.   source = safe_malloc(sizeof(struct in_addr));
  2108.   source_malloc = 1;
  2109.   if (gethostname(myname, MAXHOSTNAMELEN) ||
  2110.       !(myhostent = gethostbyname(myname)))
  2111.     fatal("Your system is fucked up.\n");
  2112.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  2113.   }
  2114.   if (debugging || verbose)
  2115.     printf("We skillfully deduced that your address is %s\n",
  2116.        inet_ntoa(*source));
  2117. }
  2118.  
  2119. if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  2120.   perror("socket trobles in fin_scan");
  2121.  
  2122. if ((tcpsd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) < 0 )
  2123.   perror("socket trobles in fin_scan");
  2124.  
  2125. unblock_socket(tcpsd);
  2126. while(!done) {
  2127.   for(i=0; i <  max_parallel_sockets; i++) {
  2128.     if (!portno[i] && portarray[j]) {
  2129.       portno[i] = portarray[j++];
  2130.     }
  2131.     if (portno[i]) {
  2132.     if (fragment)
  2133.       send_small_fragz(rawsd, source, &target, MAGIC_PORT, portno[i], TH_FIN);
  2134.     else send_tcp_raw(rawsd, source , &target, MAGIC_PORT,
  2135.               portno[i], 0, 0, TH_FIN, 0, 0, 0);
  2136.     usleep(10000); /* *WE* normally do not need this, but the target
  2137.               lamer often does */
  2138.     }
  2139.   }
  2140.  
  2141.   usleep(timeout);
  2142.   dupesinarow = 0;
  2143.   while ((bytes = recvfrom(tcpsd, response, 65535, 0, (struct sockaddr *)
  2144.                &stranger, &sockaddr_in_size)) > 0)
  2145.     if (ip->saddr == target.s_addr) {
  2146.       tcp = (struct tcphdr *) (response + 4 * ip->ihl);
  2147.       if (tcp->th_flags & TH_RST) {
  2148.     badport = ntohs(tcp->th_sport);
  2149.     if (debugging > 1) printf("Nothing open on port %d\n", badport);
  2150.     /* delete the port from active scanning */
  2151.     for(i=0; i < max_parallel_sockets; i++)
  2152.       if (portno[i] == badport) {
  2153.         if (debugging && trynum[i] > 0)
  2154.           printf("Bad port %d caught on fin scan, try number %d\n",
  2155.              badport, trynum[i] + 1);
  2156.         trynum[i] = 0;
  2157.         portno[i] = 0;
  2158.         break;
  2159.       }
  2160.     if (i == max_parallel_sockets) {
  2161.       if (debugging)
  2162.         printf("Late packet or dupe, deleting port %d.\n", badport);
  2163.       dupesinarow++;
  2164.       if (ports) deleteport(ports, badport, IPPROTO_TCP);
  2165.     }
  2166.       }
  2167.       else
  2168.     if (debugging > 1) {    
  2169.       printf("Strange packet from target%d!  Here it is:\n",
  2170.          ntohs(tcp->th_sport));
  2171.       if (bytes >= 40) readtcppacket(response,1);
  2172.       else hdump(response,bytes);
  2173.     }
  2174.     }
  2175.  
  2176.   /* adjust waiting time if neccessary */
  2177.   if (dupesinarow > 6) {
  2178.     if (debugging || verbose)
  2179.       printf("Slowing down send frequency due to multiple late packets.\n");
  2180.     if (timeout < 10 * ((global_delay)? global_delay: global_rtt + 20000)) timeout *= 1.5;
  2181.     else {
  2182.       printf("Too many late packets despite send frequency decreases, skipping scan.\n");
  2183.       if (source_malloc) free(source);
  2184.       return *ports;
  2185.     }
  2186.   }
  2187.  
  2188.  
  2189.   /* Ok, collect good ports (those that we haven't received responses too
  2190.      after all our retries */
  2191.   someleft = 0;
  2192.   for(i=0; i < max_parallel_sockets; i++)
  2193.     if (portno[i]) {
  2194.       if (++trynum[i] >= retries) {
  2195.     if (verbose || debugging)
  2196.       printf("Good port %d detected by fin_scan!\n", portno[i]);
  2197.     addport(ports, portno[i], IPPROTO_TCP, NULL);
  2198.     send_tcp_raw( rawsd, source, &target, MAGIC_PORT, portno[i], 0, 0,
  2199.           TH_FIN, 0, 0, 0);
  2200.     portno[i] = trynum[i] = 0;
  2201.       }
  2202.       else someleft = 1;
  2203.     }
  2204.  
  2205.   if (!portarray[j] && (!someleft || --waiting_period <= 0)) done++;
  2206. }
  2207.  
  2208. if (debugging || verbose)
  2209.   printf("The TCP stealth FIN scan took %ld seconds to scan %d ports.\n",
  2210.      time(NULL) - starttime, number_of_ports);
  2211. if (source_malloc) free(source);
  2212. close(tcpsd);
  2213. close(rawsd);
  2214. return *ports;
  2215. }
  2216.  
  2217. int ftp_anon_connect(struct ftpinfo *ftp) {
  2218. int sd;
  2219. struct sockaddr_in sock;
  2220. int res;
  2221. char recvbuf[2048];
  2222. char command[512];
  2223.  
  2224. if (verbose || debugging)
  2225.   printf("Attempting connection to ftp://%s:%s@%s:%i\n", ftp->user, ftp->pass,
  2226.      ftp->server_name, ftp->port);
  2227.  
  2228. if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
  2229.   perror("Couldn't create ftp_anon_connect socket");
  2230.   return 0;
  2231. }
  2232.  
  2233. sock.sin_family = AF_INET;
  2234. sock.sin_addr.s_addr = ftp->server.s_addr;
  2235. sock.sin_port = htons(ftp->port);
  2236. res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  2237. if (res < 0 ) {
  2238.   printf("Your ftp bounce proxy server won't talk to us!\n");
  2239.   exit(1);
  2240. }
  2241. if (verbose || debugging) printf("Connected:");
  2242. while ((res = recvtime(sd, recvbuf, 2048,7)) > 0)
  2243.   if (debugging || verbose) {
  2244.     recvbuf[res] = '\0';
  2245.     printf("%s", recvbuf);
  2246.   }
  2247. if (res < 0) {
  2248.   perror("recv problem from ftp bounce server");
  2249.   exit(1);
  2250. }
  2251.  
  2252. snprintf(command, 511, "USER %s\r\n", ftp->user);
  2253. send(sd, command, strlen(command), 0);
  2254. res = recvtime(sd, recvbuf, 2048,12);
  2255. if (res <= 0) {
  2256.   perror("recv problem from ftp bounce server");
  2257.   exit(1);
  2258. }
  2259. recvbuf[res] = '\0';
  2260. if (debugging) printf("sent username, received: %s", recvbuf);
  2261. if (recvbuf[0] == '5') {
  2262.   printf("Your ftp bounce server doesn't like the username \"%s\"\n",
  2263.      ftp->user);
  2264.   exit(1);
  2265. }
  2266. snprintf(command, 511, "PASS %s\r\n", ftp->pass);
  2267. send(sd, command, strlen(command), 0);
  2268. res = recvtime(sd, recvbuf, 2048,12);
  2269. if (res < 0) {
  2270.   perror("recv problem from ftp bounce server\n");
  2271.   exit(1);
  2272. }
  2273. if (!res) printf("Timeout from bounce server ...");
  2274. else {
  2275. recvbuf[res] = '\0';
  2276. if (debugging) printf("sent password, received: %s", recvbuf);
  2277. if (recvbuf[0] == '5') {
  2278.   fprintf(stderr, "Your ftp bounce server refused login combo (%s/%s)\n",
  2279.      ftp->user, ftp->pass);
  2280.   exit(1);
  2281. }
  2282. }
  2283. while ((res = recvtime(sd, recvbuf, 2048,2)) > 0)
  2284.   if (debugging) {
  2285.     recvbuf[res] = '\0';
  2286.     printf("%s", recvbuf);
  2287.   }
  2288. if (res < 0) {
  2289.   perror("recv problem from ftp bounce server");
  2290.   exit(1);
  2291. }
  2292. if (verbose) printf("Login credentials accepted by ftp server!\n");
  2293.  
  2294. ftp->sd = sd;
  2295. return sd;
  2296. }
  2297.  
  2298. int recvtime(int sd, char *buf, int len, int seconds) {
  2299.  
  2300. int res;
  2301. struct timeval timeout = {seconds, 0};
  2302. fd_set readfd;
  2303.  
  2304. FD_ZERO(&readfd);
  2305. FD_SET(sd, &readfd);
  2306. res = select(sd + 1, &readfd, NULL, NULL, &timeout);
  2307. if (res > 0 ) {
  2308. res = recv(sd, buf, len, 0);
  2309. if (res >= 0) return res;
  2310. perror("recv in recvtime");
  2311. return 0;
  2312. }
  2313. else if (!res) return 0;
  2314. perror("select() in recvtime");
  2315. return -1;
  2316. }
  2317.  
  2318. portlist bounce_scan(struct in_addr target, unsigned short *portarray,
  2319.              struct ftpinfo *ftp, portlist *ports) {
  2320. int starttime,  res , sd = ftp->sd,  i=0;
  2321. char *t = (char *)⌖
  2322. int retriesleft = FTP_RETRIES;
  2323. char recvbuf[2048];
  2324. char targetstr[20];
  2325. char command[512];
  2326. snprintf(targetstr, 20, "%d,%d,%d,%d,0,", UC(t[0]), UC(t[1]), UC(t[2]), UC(t[3]));
  2327. starttime = time(NULL);
  2328. if (verbose || debugging)
  2329.   printf("Initiating TCP ftp bounce scan against %s (%s)\n",
  2330.      current_name,  inet_ntoa(target));
  2331. for(i=0; portarray[i]; i++) {
  2332.   snprintf(command, 512, "PORT %s%i\r\n", targetstr, portarray[i]);
  2333.   if (send(sd, command, strlen(command), 0) < 0 ) {
  2334.     perror("send in bounce_scan");
  2335.     if (retriesleft) {
  2336.       if (verbose || debugging)
  2337.     printf("Our ftp proxy server hung up on us!  retrying\n");
  2338.       retriesleft--;
  2339.       close(sd);
  2340.       ftp->sd = ftp_anon_connect(ftp);
  2341.       if (ftp->sd < 0) return *ports;
  2342.       sd = ftp->sd;
  2343.       i--;
  2344.     }
  2345.     else {
  2346.       fprintf(stderr, "Our socket descriptor is dead and we are out of retries. Giving up.\n");
  2347.       close(sd);
  2348.       ftp->sd = -1;
  2349.       return *ports;
  2350.     }
  2351.   } else { /* Our send is good */
  2352.     res = recvtime(sd, recvbuf, 2048,15);
  2353.     if (res <= 0) perror("recv problem from ftp bounce server\n");
  2354.  
  2355.     else { /* our recv is good */
  2356.       recvbuf[res] = '\0';
  2357.       if (debugging) printf("result of port query on port %i: %s",
  2358.                 portarray[i],  recvbuf);
  2359.       if (recvbuf[0] == '5') {
  2360.     if (portarray[i] > 1023) {
  2361.     fprintf(stderr, "Your ftp bounce server sucks, it won't let us feed bogus ports!\n");
  2362.     exit(1);
  2363.       }
  2364.       else {
  2365.     fprintf(stderr, "Your ftp bounce server doesn't allow priviliged ports, skipping them.\n");
  2366.     while(portarray[i] && portarray[i] < 1024) i++;
  2367.     if (!portarray[i]) {
  2368.       fprintf(stderr, "And you didn't want to scan any unpriviliged ports.  Giving up.\n");
  2369.       /*      close(sd);
  2370.       ftp->sd = -1;
  2371.       return *ports;*/
  2372.       /* screw this gentle return crap!  This is an emergency! */
  2373.       exit(1);
  2374.     }
  2375.       }
  2376.       }
  2377.     else  /* Not an error message */
  2378.       if (send(sd, "LIST\r\n", 6, 0) > 0 ) {
  2379.     res = recvtime(sd, recvbuf, 2048,12);
  2380.     if (res <= 0)  perror("recv problem from ftp bounce server\n");
  2381.     else {
  2382.       recvbuf[res] = '\0';
  2383.       if (debugging) printf("result of LIST: %s", recvbuf);
  2384.       if (!strncmp(recvbuf, "500", 3)) {
  2385.         /* fuck, we are not aligned properly */
  2386.         if (verbose || debugging)
  2387.           printf("misalignment detected ... correcting.\n");
  2388.          res = recvtime(sd, recvbuf, 2048,10);
  2389.       }
  2390.       if (recvbuf[0] == '1' || recvbuf[0] == '2') {
  2391.         if (verbose || debugging) printf("Port number %i appears good.\n",
  2392.                 portarray[i]);
  2393.         addport(ports, portarray[i], IPPROTO_TCP, NULL);
  2394.         if (recvbuf[0] == '1') {
  2395.         res = recvtime(sd, recvbuf, 2048,5);
  2396.         recvbuf[res] = '\0';
  2397.         if ((res > 0) && debugging) printf("nxt line: %s", recvbuf);
  2398.         }
  2399.       }
  2400.     }
  2401.       }
  2402.     }
  2403.   }
  2404. }
  2405. if (debugging || verbose)
  2406.   printf("Scanned %d ports in %ld seconds via the Bounce scan.\n",
  2407.      number_of_ports, time(NULL) - starttime);
  2408. return *ports;
  2409. }
  2410.  
  2411. /* parse a URL stype ftp string of the form user:pass@server:portno */
  2412. int parse_bounce(struct ftpinfo *ftp, char *url) {
  2413. char *p = url,*q, *s;
  2414.  
  2415. if ((q = strrchr(url, '@'))) /*we have username and/or pass */ {
  2416.   *(q++) = '\0';
  2417.   if ((s = strchr(q, ':')))
  2418.     { /* has portno */
  2419.       *(s++) = '\0';
  2420.       strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
  2421.       ftp->port = atoi(s);
  2422.     }
  2423.   else  strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
  2424.  
  2425.   if ((s = strchr(p, ':'))) { /* User AND pass given */
  2426.     *(s++) = '\0';
  2427.     strncpy(ftp->user, p, 63);
  2428.     strncpy(ftp->pass, s, 255);
  2429.   }
  2430.   else { /* Username ONLY given */
  2431.     printf("Assuming %s is a username, and using the default password: %s\n",
  2432.        p, ftp->pass);
  2433.     strncpy(ftp->user, p, 63);
  2434.   }
  2435. }
  2436. else /* no username or password given */
  2437.   if ((s = strchr(url, ':'))) { /* portno is given */
  2438.     *(s++) = '\0';
  2439.     strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
  2440.     ftp->port = atoi(s);
  2441.   }
  2442.   else  /* default case, no username, password, or portnumber */
  2443.     strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
  2444.  
  2445. ftp->user[63] = ftp->pass[255] = ftp->server_name[MAXHOSTNAMELEN] = 0;
  2446.  
  2447. return 1;
  2448. }
  2449.  
  2450.  
  2451.  
  2452. /*
  2453.  *      I'll bet you've never seen this function before (yeah right)!
  2454.  *      standard swiped checksum routine.
  2455.  */
  2456. unsigned short in_cksum(unsigned short *ptr,int nbytes) {
  2457.  
  2458. register long           sum;            /* assumes long == 32 bits */
  2459. u_short                 oddbyte;
  2460. register u_short        answer;         /* assumes u_short == 16 bits */
  2461.  
  2462. /*
  2463.  * Our algorithm is simple, using a 32-bit accumulator (sum),
  2464.  * we add sequential 16-bit words to it, and at the end, fold back
  2465.  * all the carry bits from the top 16 bits into the lower 16 bits.
  2466.  */
  2467.  
  2468. sum = 0;
  2469. while (nbytes > 1)  {
  2470. sum += *ptr++;
  2471. nbytes -= 2;
  2472. }
  2473.  
  2474. /* mop up an odd byte, if necessary */
  2475. if (nbytes == 1) {
  2476. oddbyte = 0;            /* make sure top half is zero */
  2477. *((u_char *) &oddbyte) = *(u_char *)ptr;   /* one byte only */
  2478. sum += oddbyte;
  2479. }
  2480.  
  2481. /*
  2482.  * Add back carry outs from top 16 bits to low 16 bits.
  2483.  */
  2484.  
  2485. sum  = (sum >> 16) + (sum & 0xffff);    /* add high-16 to low-16 */
  2486. sum += (sum >> 16);                     /* add carry */
  2487. answer = ~sum;          /* ones-complement, then truncate to 16 bits */
  2488. return(answer);
  2489. }
  2490. <-->
  2491.  
  2492.  
  2493. ----[  EOF
  2494.