-->
Nmap Cheat Sheet: From Uncovering To Exploits, Usage 2: Advance Port Scanning Amongst Nmap Too Custom Idle Scan

Nmap Cheat Sheet: From Uncovering To Exploits, Usage 2: Advance Port Scanning Amongst Nmap Too Custom Idle Scan

Nmap Cheat Sheet: From Uncovering To Exploits, Usage 2: Advance Port Scanning Amongst Nmap Too Custom Idle Scan

This is our minute installment of Nmap cheat sheet. Basically, nosotros volition verbalize over some advanced techniques for Nmap scanning as well as nosotros volition send a Man In The Middle Attack (MITM). Let’s start our game now.

TCP SYN Scan
SYN scan is the default as well as most pop scan option, for goodness reasons. It tin live performed quickly, scanning thousands of ports per minute on a fast network non hampered past times restrictive firewalls. It is also relatively unobtrusive as well as stealthy, since it never completes TCP connections.
Command: nmap –sS target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
TCP Connect Scan
TCP connect scan is the default TCP scan type when SYN scan is non an option. This is the instance when a user does non conduct hold raw package privileges. Instead of writing raw packets equally most other scan types do, Nmap asks the underlying operating scheme to institute a connexion amongst the target machine as well as port past times issuing the connect scheme call.
Command: nmap –sT target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
UDP SCANS
While most pop services on the Internet run over the TCP protocol, UDP services are widely deployed. DNS, SNMP, as well as DHCP (registered ports 53, 161/162, as well as 67/68) are iii of the most common. Because UDP scanning is to a greater extent than frequently than non slower as well as to a greater extent than hard than TCP, some safety auditors ignore these ports. This is a mistake, equally exploitable UDP services are quite mutual as well as attackers sure don’t ignore the whole protocol.
Command: nmap –sU target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
The –data-length alternative tin live used to send a fixed-length random payload to every port or (if yous specify a value of 0) to disable payloads. If an ICMP port unreachable error (type 3, code 3) is returned, the port is closed. Other ICMP unreachable errors (type 3, codes 1, 2, 9, 10, or 13) grade the port equally filtered. Occasionally, a service volition respond amongst a UDP packet, proving that it is open. If no answer is received after retransmissions, the port is classified equally open|filtered.
Command: nmap –sU –data-length=value target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
SCTP INIT Scan
SCTP is a relatively novel alternative to the TCP as well as UDP protocols, combining most characteristics of TCP as well as UDP, as well as also adding novel features similar multi-homing as well as multi-streaming. It is mostly beingness used for SS7/SIGTRAN related services but has the potential to live used for other applications equally well. SCTP INIT scan is the SCTP equivalent of a TCP SYN scan. It tin live performed quickly, scanning thousands of ports per minute on a fast network non hampered past times restrictive firewalls. Like SYN scan, INIT scan is relatively unobtrusive as well as stealthy, since it never completes SCTP associations.
Command: nmap –sY target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
TCP NULL, FIN, as well as Xmas scans
  • NULL scan (-sN)
    Does non laid whatsoever bits (TCP flag header is 0).
  • FIN scan (-sF)
    Sets just the TCP FIN bit.
  • Xmas scan (-sX)
    Sets the FIN, PSH, as well as URG flags, lighting the package upward similar a Christmas tree.
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    TCP ACK Scan
    This scan is dissimilar than the others discussed so far inward that it never determines opened upward (or fifty-fifty open|filtered) ports. It is used to map out firewall rulesets, determining whether they are stateful or not, as well as which ports are filtered.
    Command: nmap –scanflags=value –sAtarget
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    The ACK scan probe package has exclusively the ACK flag laid (unless yous occupation –scanflags). When scanning unfiltered systems, opened upward as well as closed ports volition both render a RST packet. Nmap so labels them equally unfiltered, pregnant that they are reachable past times the ACK packet.
    TCP Window Scan
    Window scan is just the same equally ACK scan, except that it exploits an implementation exceptional of sure systems to differentiate opened upward ports from closed ones, rather than ever printing unfiltered when an RST is returned.
    Command: nmap –sW target
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    See the valuable as well as juicy information which is useful for a hacker to laid on further:
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    TCP Maimon Scan
    The Maimon scan is named after its discoverer, Uriel Maimon. He described the technique inward Phrack Magazine number #49 (November 1996). Nmap, which included this technique, was released 2 issues later. This technique is just the same equally NULL, FIN, as well as Xmas scans, except that the probe is FIN/ACK.
    Command: nmap –sM target
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan

    Custom TCP Scan Using –scanflag Options
    For advance pentesting, a pentester volition non occupation a full general TCP scan similar ACK, FIN, etc. because these things may live blocked past times IDS/IPS. So they volition occupation some dissimilar techniques past times specifying “-scanflag” options. This also tin live used for firewall evading.

    The –scanflags declaration tin live a numerical flag value such equally ix (PSH as well as FIN), but using symbolic names is easier. Just squash together whatsoever combination of URG, ACK, PSH, RST, SYN, as well as FIN. For example, –scanflags URGACKPSHRSTSYNFIN sets everything, though it’s non rattling useful for scanning.
    Command: nmap –-scanflags target
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    SCTP COOKIE ECHO Scan
    SCTP COOKIE ECHO scan is a to a greater extent than advanced SCTP scan. It takes payoff of the fact that SCTP implementations should silently drib packets containing COOKIE ECHO chunks on opened upward ports, but send an ABORT if the port is closed. The payoff of this scan type is that it is non equally obvious a port scan equally an INIT scan. Also, in that location may live non-stateful firewall rulesets blocking INIT chunks, but non COOKIE ECHO chunks. Influenza A virus subtype H5N1 goodness IDS volition live able to notice SCTP COOKIE ECHO scans too. The downside is that SCTP COOKIE ECHO scans cannot differentiate betwixt opened upward as well as filtered ports, leaving yous amongst the solid soil open|filtered inward both cases.
    Command: nmap –-sZ target
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
    TCP Idle Scan
    This advanced scan method allows for a really blind TCP port scan of the target (meaning no packets are sent to the target from your existent IP address). Instead, a unique side-channel laid on exploits predictable IP fragmentation ID sequence generation on the zombie host to glean information almost the opened upward ports on the target. IDS systems volition display the scan equally coming from the zombie machine yous specify. This is rattling useful for conducting MITM (Man In The Middle Attack).
    Command: nmap –sI zombie target
    This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan

    Victim sentiment that Zombie was the Attacker machine, which it was really not. So hither the Attacker tried to fool the Victim.
  • Here Zombie agency the middle homo that yous conduct hold trusted. Zombie tin live whatsoever machine which acts similar a middle machine betwixt Attacker as well as Victim.However, nosotros are inward advanced pentesting, so let’s seek to displace ahead amongst details regarding Idle Scan.This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle ScanHistory And DetailsIn 1998, safety researcher Antirez (who also wrote the hping2 tool used inward parts of this book) posted to the Bugtraq mailing listing an ingenious novel port scanning technique. He called it “dumb scan”. Attackers tin really scan a target without sending a unmarried package to the target from their ain IP address! Instead, a clever side-channel laid on allows for the scan to live bounced off a dumb “zombie host”. Intrusion detection scheme (IDS) reports volition finger the innocent zombie equally the attacker. Besides beingness extraordinarily stealthy, this scan type permits uncovering of IP-based trust relationships betwixt machines. What Is the Actual Game?
    Actually, for an assaulter to send this attack, he does non demand to live an skillful inward TCP/IP, but it is to a greater extent than advanced than other techniques equally discussed so far. The below steps are pose together to send this attack.
  • One way to decide whether a TCP port is opened upward is to send a SYN (session establishment) package to the port. The target machine volition respond amongst a SYN/ACK (session asking acknowledgment) package if the port is open, as well as RST (reset) if the port is closed. This is the footing of the previously discussed SYN scan.
  • Influenza A virus subtype H5N1 machine that receives an unsolicited SYN/ACK package volition respond amongst a RST. An unsolicited RST volition live ignored.
  • Every IP package on the Internet has a fragment identification number (IP ID). Since many operating systems merely increment this number for each package they send, probing for the IPID tin tell an assaulter how many packets conduct hold been sent since the in conclusion probe.
    By combining these traits, it is possible to scan a target network acre forging your identity so that it looks similar an innocent zombie machine did the scanning.
    Idle Scan Explained
    To send this attack, the next steps may live followed for successful exploitation.
  1. Probe the zombie’s IP ID as well as tape it.
  2. Forge a SYN package from the zombie as well as send it to the desired port on the target. Depending on the port state, the target’s reaction may or may non displace the zombie’s IP ID to live incremented.
  3. Probe the zombie’s IP ID again. The target port solid soil is so determined past times comparison this novel IP ID amongst the ane recorded inward mensuration 1.
    How to Determine from IP ID
    From the IP ID value, an assaulter volition seek to acquire almost port status, whether it is opened upward or filtered or closed. Read below for details:
  • After the higher upward idle scan process, the zombie’s IP ID should conduct hold increased past times either ane or two. An increment of ane indicates that the zombie hasn’t sent out whatsoever packets, except for its respond to the attacker’s probe. This lack of sent packets agency that the port is non opened upward (the target must conduct hold sent the zombie either a RST packet, which was ignored, or goose egg at all).
  • An increment of 2 indicates that the zombie sent out a package betwixt the 2 probes. This extra package usually agency that the port is opened upward (the target presumably sent the zombie a SYN/ACK package inward answer to the forged SYN, which induced a RST package from the zombie).
  • Increases larger than 2 usually signify a bad zombie host. It mightiness non conduct hold predictable IP ID numbers, or mightiness live engaged inward communication unrelated to the idle scan.
See the below images that relate Attacker, Zombie, as well as Victim, as well as how the laid on is conducted.
Idle Scan of an Open Port
Step 1: Probe The Zombie’s IP address
SYN/ACK
RST IPID=31337
The Attacker sends SYN/ACK packets to Zombie. But Zombie is non expecting to acquire these packets. So inward response, he discloses IP ID value past times responding amongst an RST package to the attacker.
Step 2: Forge SYN package from zombie
SYN asking from Zombie which is spoofed
SYN/ACK to Zombie
RST packet.IP ID:31338
The Victim sends a SYN/ACK package inward answer to the SYN package that appears to come upward from Zombie. The Zombie sends dorsum RST past times incrementing IP ID value.
Step3: Probe Zombie’s IP ID again
SYN/ACK
Zombie
RST,IP ID:31339
The Zombie’s IP ID increased past times two, which is learned from mensuration one.
So hither nosotros know that the port is opened upward from the IPID value.
Note: If the port is closed, so the IPID value volition live increased past times one. If the Zombie’s IP ID increased past times ane equally inward the initiative off step, nosotros tin say that it may live closed or filtered. In the instance of filtered, the Victim has no answer to Zombie for the SYN asking of Attacker.
In this situation, an Attacker volition acquire that in that location may live IDS/IPS which conduct hold rules to block some sure scan attempts past times Zombie machines. For that, he volition over again occupation decoy options for Nmap to evade that. We volition verbalize over that later.
Step 1: Finding Zombie Host for Idle Scan
The initiative off mensuration inward executing an IP ID idle scan is to regain an appropriate zombie. It needs to assign IP ID packets incrementally on a global (rather than per-host it communicates with) basis. It should live idle (hence the scan name), equally extraneous traffic volition bump upward its IP ID sequence, confusing the scan logic.
Influenza A virus subtype H5N1 mutual approach is to merely execute a Nmap ping scan of some network. We tin occupation Nmap’s random IP alternative trend (-iR), but that is probable to outcome inward far away zombies amongst substantial latency.
Performing a port scan as well as OS identification (-O) on the zombie candidate network, rather than just a ping scan, helps inward selecting a goodness zombie. As long equally verbose trend (-v) is enabled, OS detection volition usually decide the IP ID sequence generation method as well as impress a business such equally “IP ID Sequence Generation: Incremental”. If the type is given equally Incremental or Broken little-endian incremental, the machine is a goodness zombie candidate.
Another approach to identifying zombie candidates is to run the ipidseq NSE script against a host. This script probes a host to assort its IP ID generation method, so prints the IP ID classification, much similar the OS detection does.
Command: (nmap –script ipidseq [–script-args probeport=port] target)
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
Now nosotros tin tell that it is incremental as well as a goodness candidate for Zombie.
Using Hping
We tin also occupation hping for discovering a zombie. The hping method for idle scanning provides a lower grade instance for how idle scanning is performed. In this example, the target host (target1) volition live scanned using an idle host (target2). An opened upward as well as a closed port volition live tested to encounter how each scenario plays out.
First, institute that the idle host is really idle, send packets using hping2 as well as observe the ID numbers increment incrementally past times one. If the ID numbers increment haphazardly, the host is non really idle, or has an OS that has no predictable IP ID.
hping3 -S target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
Send a spoofed SYN package to the target host on a port yous await to live open.
hping3 –spoof Zombie -S p 22 target
*Note: Here I exercise non want to include the screenshot. Though this is a part of interrogation as well as this document is for exclusively educational purposes, the possessor of the website does non want to expose it. If yous conduct hold whatsoever dubiety yous tin contact me hither or electronic mail me.
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
As yous tin see, in that location is no answer as well as it shows 100% package loss. That agency nosotros conduct hold failed to regain the zombie. Again nosotros volition banking company check the next mensuration for confirmation.
Check the IPID value for whatsoever increment:
hping3 -S target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
No response.
It includes that the port is filtered.
Attack using Nmap
See the icon below. We are attacking the target machine using a zombie host.
Command: nmap –Pn –p- -sI zombie target
First nosotros volition exercise an Nmap scan for ports:
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
Based on that, let’s seek port 22, which is already running.
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
Here nosotros are unable to laid on to the target, equally it is showing the port is already used for some other purpose. By default, Nmap forges probes to the target from the source port fourscore of the zombie. You tin pick out a dissimilar port past times appending a colon as well as port number to the zombie yell (e.g. -sI zombie:113). The chosen port must non live filtered from the assaulter or the target. Influenza A virus subtype H5N1 SYN scan of the zombie should present the port inward the opened upward or closed state.
Here –Pn: prevents Nmap from sending the initial packets to the target machine.
-p-: volition scan all 65535 ports.
-sI: used for idle scan as well as sending spoof packets.
Here what happens, the attacker’s IDS volition retrieve that the package is coming from a zombie machine, non from the target machine. So he volition live confused.
Understanding Nmap Internally
As a pentester, nosotros must empathise internal workings of Nmap’s idle scan, so that nosotros volition arts and crafts the same affair inward our ain implementation. Even nosotros tin write our ain code based on Python to exercise the same thing. We must empathise the basic time period or algorithm of Nmap’s idle scan. For that, nosotros volition occupation package line options inward Nmap.
Command: nmap -sI Zombie:113 -Pn -p20-80,110-180 -r –packet-trace -v target
Pn is necessary for stealth, otherwise pinged packets would live sent to the target from the attacker’s existent address. Version scanning would also expose the truthful address, -sV is not specified. The -r alternative (turns off port randomization) is exclusively used to brand this instance easier.
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
As I said before, occupation a suitable zombie port for successful attack.
Process of this attack:
Nmap firsts tests Zombie’s IP ID sequence generation past times sending 6 SYN/ACK packets to it as well as analyzing the responses. Here R agency Reset packet. That agency that is non reachable through that port, though that is already used for other services. For to a greater extent than details, follow the Idle Scan past times Nmap Manual (http://nmap.org/book/idlescan.html). Here is a vulnerable machine amongst a suitable zombie for a successful attack.
So the below mentioned C code is for idle scan. Compile the C programme as well as run the code.
This is an extraordinary scan code that tin allow for completely blind scanning (eg. no packets sent to the target from your ain IP address) as well as tin also live used to penetrate firewalls as well as orbit out router ACLs.
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
#include "idle_scan.h"
#include "timing.h"
#include "osscan2.h"
#include "nmap.h"
#include "NmapOps.h"
#include "services.h"
#include "Target.h"
#include "utils.h"
#include "output.h"
 
#include "struct_ip.h"
 
#include
 
extern NmapOps o;
 
struct idle_proxy_info {   exercise a constructer as well as accept all variable into it
  Target host; /* contains name, IP, source IP, timing info, etc. */
  int seqclass; /* IP ID sequence cast (IPID_SEQ_* defined inward nmap.h) */
  u16 latestid; /* The most recent IP ID nosotros conduct hold received from the proxy */
  u16 probe_port; /* The port nosotros occupation for probing IP ID infoz */
  u16 max_groupsz; /* We won't seek out groups larger than this ... */
  u16 min_groupsz; /* We won't allow the grouping size to autumn below this
              level.  Affected past times --min-parallelism */
  double current_groupsz; /* Current grouping size beingness used ... depends on
                          conditions ... won't live higher than
                          max_groupsz */
  int senddelay; /* Delay betwixt sending pr0be SYN packets to target
                    (in microseconds) */
  int max_senddelay; /* Maximum fourth dimension nosotros are allowed to hold off between
                        sending pr0bes (when nosotros send a bunch inward a row.
                        In microseconds. */
 
  pcap_t *pd; /* Influenza A virus subtype H5N1 Pcap descriptor which (starting in
                 initialize_idleproxy) listens for TCP packets from
                 the probe_port of the proxy box */
  int rawsd; /* Socket descriptor for sending probe packets to the proxy */
  struct eth_nfo eth; // For when nosotros want to send probes via raw IP instead.
  struct eth_nfo *ethptr; // points to eth if filled out, otherwise NULL
};
 
/* Sends an IP ID probe to the proxy machine as well as returns the IP ID.
   This role handles retransmissions, as well as returns -1 if it fails.
   Proxy timing is adjusted, but proxy->latestid is NOT ADJUSTED --
   you'll conduct hold to exercise that yourself.   Probes_sent is laid to the number
   of probe packets sent during execution */
static int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
             int *probes_rcvd) {
  struct timeval tv_end;
  int tries = 0;
  int trynum;
  int sent=0, rcvd=0;
  int maxtries = 3; /* The maximum number of tries before nosotros surrender */
  struct timeval tv_sent[3], rcvdtime;
  int ipid = -1;
  int to_usec;
  unsigned int bytes;
  int base_port;
  struct ip *ip;
  struct tcp_hdr *tcp;
  static u32 seq_base = 0;
  static u32 ack = 0;
  static int packet_send_count = 0; /* Total # of probes sent past times this programme -- to ensure that our sequence # ever changes */
 
  if (o.magic_port_set)
    base_port = o.magic_port;
  else base_port = o.magic_port + get_random_u8();
 
  if (seq_base == 0) seq_base = get_random_u32();
  if (!ack) ack = get_random_u32();
 
  do {
    gettimeofday(&tv_sent[tries], NULL);
 
    /* Time to send the pr0be!*/
    send_tcp_raw(proxy->rawsd, proxy->ethptr,
            proxy->host.v4sourceip(), proxy->host.v4hostip(),
            o.ttl, false,
            o.ipoptions, o.ipoptionslen,
            base_port + tries, proxy->probe_port,
        seq_base + (packet_send_count++ * 500) + 1, ack, 0, TH_SYN|TH_ACK, 0, 0,
        (u8 *) "\x02\x04\x05\xb4", 4,
        NULL, 0);
    sent++;
    tries++;
 
    /* Now it is fourth dimension to hold off for the answer ... */
    to_usec = proxy->host.to.timeout;
    gettimeofday(&tv_end, NULL);
    while((ipid == -1 || sent > rcvd) && to_usec > 0) {
 
      to_usec = proxy->host.to.timeout - TIMEVAL_SUBTRACT(tv_end, tv_sent[tries-1]);
      if (to_usec < 0) to_usec = 0; // Final no-block poll       ip = (struct ip *) readipv4_pcap(proxy->pd, &bytes, to_usec, &rcvdtime, NULL, true);
      gettimeofday(&tv_end, NULL);
      if (ip) {
    if (bytes < ( 4 * ip->ip_hl) + 14U)
      continue;
 
    if (ip->ip_p == IPPROTO_TCP) {
 
      tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));
      if (ntohs(tcp->th_dport) < base_port || ntohs(tcp->th_dport) - base_port >= tries  || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) {
        if (ntohs(tcp->th_dport) > o.magic_port && ntohs(tcp->th_dport) < (o.magic_port + 260)) {         if (o.debugging) {        error("Received IP ID zombie probe answer which likely came from an before prober instance ... increasing rttvar from %d to %d",             proxy->host.to.rttvar, (int) (proxy->host.to.rttvar * 1.2));
          }
          proxy->host.to.rttvar = (int) (proxy->host.to.rttvar * 1.2);
          rcvd++;
        }
        else if (o.debugging > 1) {
          error("Received unexpected answer package from %s during IP ID zombie probing:", inet_ntoa(ip->ip_src));
          readtcppacket( (unsigned char *) ip,MIN(ntohs(ip->ip_len), bytes));
        }
        continue;
      }
 
      trynum = ntohs(tcp->th_dport) - base_port;
      rcvd++;
 
      ipid = ntohs(ip->ip_id);
      adjust_timeouts2(&(tv_sent[trynum]), &rcvdtime, &(proxy->host.to));
    }
      }
    }
  } while(ipid == -1 && tries < maxtries);   if (probes_sent) *probes_sent = sent;   if (probes_rcvd) *probes_rcvd = rcvd;   return ipid; } /* Returns the number of increments betwixt an early on IP ID as well as a later    one, assuming the given IP ID Sequencing class.  Returns -1 if the    distance cannot live determined */ static int ipid_distance(int seqclass , u16 startid, u16 endid) {   if (seqclass == IPID_SEQ_INCR)     return endid - startid;   if (seqclass == IPID_SEQ_BROKEN_INCR) {     /* Convert to network byte social club */     startid = htons(startid);     endid = htons(endid);     return endid - startid;   }   return -1; } static void initialize_proxy_struct(struct idle_proxy_info *proxy) {   proxy->seqclass = proxy->latestid = proxy->probe_port = 0;
  proxy->max_groupsz = proxy->min_groupsz = 0;
  proxy->current_groupsz = 0;
  proxy->senddelay = 0;
  proxy->max_senddelay = 0;
  proxy->pd = NULL;
  proxy->rawsd = -1;
  proxy->ethptr = NULL;
}
 
/* takes a proxy name/IP, resolves it if necessary, tests it for IP ID
   suitability, as well as fills out an idle_proxy_info structure.  If the
   proxy is determined to live unsuitable, the role whines as well as exits
   the programme */
#define NUM_IPID_PROBES 6
static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
              const struct in_addr *first_target, const struct scan_lists * ports) {
  int probes_sent = 0, probes_returned = 0;
  int hardtimeout = 9000000; /* Generally don't hold off to a greater extent than than ix secs total */
  unsigned int bytes, to_usec;
  int timedout = 0;
  char *p, *q;
  char *endptr = NULL;
  int seq_response_num;
  int newipid;
  int i;
  char filter[512]; /* Libpcap filter string */
  char name[MAXHOSTNAMELEN + 1];
  struct sockaddr_storage ss;
  size_t sslen;
  u32 sequence_base;
  u32 ack = 0;
  struct timeval probe_send_times[NUM_IPID_PROBES], tmptv, rcvdtime;
  u16 lastipid = 0;
  struct ip *ip;
  struct tcp_hdr *tcp;
  int distance;
  int ipids[NUM_IPID_PROBES];
  u8 probe_returned[NUM_IPID_PROBES];
  struct route_nfo rnfo;
  assert(proxy);
  assert(proxyName);
 
  ack = get_random_u32();
 
  for(i=0; i < NUM_IPID_PROBES; i++) probe_returned[i] = 0;   initialize_proxy_struct(proxy);   initialize_timeout_info(&proxy->host.to);
 
  proxy->max_groupsz = (o.max_parallelism)? o.max_parallelism : 100;
  proxy->min_groupsz = (o.min_parallelism)? o.min_parallelism : 4;
  proxy->max_senddelay = 100000;
 
  Strncpy(name, proxyName, sizeof(name));
  q = strchr(name, ':');
  if (q) {
    *q++ = '\0';
    proxy->probe_port = strtoul(q, &endptr, 10);
    if (*q==0 || !endptr || *endptr != '\0' || !proxy->probe_port) {
      fatal("Invalid port number given inward IP ID zombie specification: %s", proxyName);
    }
  } else {
    if (ports->syn_ping_count > 0) {
      proxy->probe_port = ports->syn_ping_ports[0];
    } else if (ports->ack_ping_count > 0) {
      proxy->probe_port = ports->ack_ping_ports[0];
    } else {
      u16 *ports;
      int count;
 
      getpts_simple(DEFAULT_TCP_PROBE_PORT_SPEC, SCAN_TCP_PORT, &ports, &count);
      assert(count > 0);
      proxy->probe_port = ports[0];
      free(ports);
    }
  }
 
  proxy->host.setHostName(name);
  if (resolve(name, 0, 0, &ss, &sslen, o.pf()) == 0) {
    fatal("Could non resolve idle scan zombie host: %s", name);
  }
  proxy->host.setTargetSockAddr(&ss, sslen);
 
  /* Lets figure out the appropriate source address to occupation when sending
     the pr0bez */
  proxy->host.TargetSockAddr(&ss, &sslen);
  if (!nmap_route_dst(&ss, &rnfo))
    fatal("Unable to regain appropriate source address as well as device interface to occupation when sending packets to %s", proxyName);
 
  if (o.spoofsource) {
    o.SourceSockAddr(&ss, &sslen);
    proxy->host.setSourceSockAddr(&ss, sslen);
    proxy->host.setDeviceNames(o.device, o.device);
  } else {
    proxy->host.setDeviceNames(rnfo.ii.devname, rnfo.ii.devfullname);
    proxy->host.setSourceSockAddr(&rnfo.srcaddr, sizeof(rnfo.srcaddr));
  }
  if (rnfo.direct_connect) {
    proxy->host.setDirectlyConnected(true);
  } else {
    proxy->host.setDirectlyConnected(false);
    proxy->host.setNextHop(&rnfo.nexthop,
               sizeof(rnfo.nexthop));
  }
  proxy->host.setIfType(rnfo.ii.device_type);
  if (rnfo.ii.device_type == devt_ethernet)
    proxy->host.setSrcMACAddress(rnfo.ii.mac);
 
  /* Now lets send some probes to banking company check IP ID algorithm ... */
  /* First nosotros demand a raw socket ... */
  if ((o.sendpref & PACKET_SEND_ETH) &&  proxy->host.ifType() == devt_ethernet) {
    if (!setTargetNextHopMAC(&proxy->host))
      fatal("%s: Failed to decide dst MAC address for Idle proxy",
        __func__);
    memcpy(proxy->eth.srcmac, proxy->host.SrcMACAddress(), 6);
    memcpy(proxy->eth.dstmac, proxy->host.NextHopMACAddress(), 6);
    proxy->eth.ethsd = eth_open_cached(proxy->host.deviceName());
    if (proxy->eth.ethsd == NULL)
      fatal("%s: Failed to opened upward ethernet device (%s)", __func__, proxy->host.deviceName());
    proxy->rawsd = -1;
    proxy->ethptr = &proxy->eth;
  } else {
#ifdef WIN32
    win32_fatal_raw_sockets(proxy->host.deviceName());
#endif
    if ((proxy->rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )       pfatal("socket troubles inward %s", __func__);     unblock_socket(proxy->rawsd);
    broadcast_socket(proxy->rawsd);
#ifndef WIN32
    sethdrinclude(proxy->rawsd);
#endif
    proxy->eth.ethsd = NULL;
    proxy->ethptr = NULL;
  }
 
/* Now for the pcap opening nonsense ... */
 /* Note that the snaplen is 152 = 64 byte max IPhdr + 24 byte max link_layer
  * header + 64 byte max TCP header. */
  if((proxy->pd=my_pcap_open_live(proxy->host.deviceName(), 152,  (o.spoofsource)? 1 : 0, 50))==NULL)
    fatal("%s", PCAP_OPEN_ERRMSG);
 
  p = strdup(proxy->host.targetipstr());
  q = strdup(inet_ntoa(proxy->host.v4source()));
  Snprintf(filter, sizeof(filter), "tcp as well as src host %s as well as dst host %s as well as src port %hu", p, q, proxy->probe_port);
 free(p);
 free(q);
 set_pcap_filter(proxy->host.deviceFullName(), proxy->pd,  filter);
 if (o.debugging)
   log_write(LOG_STDOUT, "Packet capture filter (device %s): %s\n", proxy->host.deviceFullName(), filter);
/* Windows nonsense -- I am non sure why this is needed, but I should
   get rid of it at sometime */
 
 sequence_base = get_random_u32();
 
 /* Yahoo!  It is finally fourth dimension to send our pr0beZ! */
 
  while(probes_sent < NUM_IPID_PROBES) {     if (o.scan_delay) enforce_scan_delay(NULL);     else if (probes_sent) usleep(30000);     /* TH_SYN|TH_ACK is what the proxy volition really live receiving from        the target, as well as is to a greater extent than probable to acquire through firewalls.  But        TH_SYN allows us to acquire a nonzero ACK dorsum so nosotros tin associate        a answer amongst the exact asking for timing purposes.  So I        retrieve I'll occupation TH_SYN, although it is a tough call. */     /* We can't occupation decoys 'cause that would screw upward the IP IDs */     send_tcp_raw(proxy->rawsd, proxy->ethptr,
            proxy->host.v4sourceip(), proxy->host.v4hostip(),
            o.ttl, false,
            o.ipoptions, o.ipoptionslen,
         o.magic_port + probes_sent + 1, proxy->probe_port,
        sequence_base + probes_sent + 1, ack, 0, TH_SYN|TH_ACK, 0, 0,
        (u8 *) "\x02\x04\x05\xb4",4,
        NULL, 0);
    gettimeofday(&probe_send_times[probes_sent], NULL);
    probes_sent++;
 
    /* Time to collect whatsoever replies */
    while(probes_returned < probes_sent && !timedout) {       to_usec = (probes_sent == NUM_IPID_PROBES)? hardtimeout : 1000;       ip = (struct ip *) readipv4_pcap(proxy->pd, &bytes, to_usec, &rcvdtime, NULL, true);
 
      gettimeofday(&tmptv, NULL);
 
      if (!ip) {
    if (probes_sent < NUM_IPID_PROBES)     break;    if (TIMEVAL_SUBTRACT(tmptv, probe_send_times[probes_sent - 1]) >= hardtimeout) {
      timedout = 1;
    }
    continue;
      } else if (TIMEVAL_SUBTRACT(tmptv, probe_send_times[probes_sent - 1]) >=
         hardtimeout)  {
    timedout = 1;
      }
 
      if (lastipid != 0 && ip->ip_id == lastipid) {
    continue; /* likely a duplicate */
      }
      lastipid = ip->ip_id;
 
      if (bytes < ( 4 * ip->ip_hl) + 14U)
    continue;
 
      if (ip->ip_p == IPPROTO_TCP) {
    tcp = ((struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl));
    if (ntohs(tcp->th_dport) < (o.magic_port+1) || ntohs(tcp->th_dport) - o.magic_port > NUM_IPID_PROBES  || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) {
      if (o.debugging > 1) error("Received unexpected answer package from %s during initial IP ID zombie testing", inet_ntoa(ip->ip_src));
      continue;
    }
 
    seq_response_num = probes_returned;
 
    /* The materials below exclusively plant when nosotros send SYN packets instead of
       SYN|ACK, but so are slightly less stealthy as well as conduct hold less chance
       of sneaking through the firewall.  Plus SYN|ACK is what they will
       be receiving dorsum from the target */
    probes_returned++;
    ipids[seq_response_num] = (u16) ntohs(ip->ip_id);
    probe_returned[seq_response_num] = 1;
    adjust_timeouts2(&probe_send_times[seq_response_num], &rcvdtime, &(proxy->host.to));
      }
    }
  }
 
  /* Yeah!  We're done sending/receiving probes ... at in ane lawsuit lets ensure all of our responses are next inward the array */
  for(i=0,probes_returned=0; i < NUM_IPID_PROBES; i++) {     if (probe_returned[i]) {       if (i > probes_returned)
    ipids[probes_returned] = ipids[i];
      probes_returned++;
    }
  }
 
  if (probes_returned == 0)
    fatal("Idle scan zombie %s (%s) port %hu cannot live used because it has non returned whatsoever of our probes -- maybe it is downwards or firewalled.",
      proxy->host.HostName(), proxy->host.targetipstr(),
      proxy->probe_port);
 
  proxy->seqclass = get_ipid_sequence(probes_returned, ipids, 0);
  switch(proxy->seqclass) {
  case IPID_SEQ_INCR:
  case IPID_SEQ_BROKEN_INCR:
    log_write(LOG_PLAIN, "Idle scan using zombie %s (%s:%hu); Class: %s\n", proxy->host.HostName(), proxy->host.targetipstr(), proxy->probe_port, ipidclass2ascii(proxy->seqclass));
    break;
  default:
    fatal("Idle scan zombie %s (%s) port %hu cannot live used because IP ID sequencability cast is: %s.  Try some other proxy.", proxy->host.HostName(), proxy->host.targetipstr(), proxy->probe_port, ipidclass2ascii(proxy->seqclass));
  }
 
  proxy->latestid = ipids[probes_returned - 1];
  proxy->current_groupsz = MIN(proxy->max_groupsz, 30);
 
  if (probes_returned < NUM_IPID_PROBES) {     /* Yikes!  We're already losing packets ... clamp downwards a chip ... */     if (o.debugging)       error("Idle scan initial zombie qualification test: %d probes sent, exclusively %d returned", NUM_IPID_PROBES, probes_returned);     proxy->current_groupsz = MIN(12, proxy->max_groupsz);
    proxy->current_groupsz = MAX(proxy->current_groupsz, proxy->min_groupsz);
    proxy->senddelay += 5000;
  }
 
  /* OK, through experimentation I conduct hold found that some hosts (*cough*
   Solaris) APPEAR to occupation elementary IP ID incrementing, but inward reality they
   assign a novel IP ID base of operations to each host which connects amongst them.  This
   is really a goodness sentiment on several fronts, but it totally
   frustrates our efforts (which rely on side-channel IP ID info
   leaking to dissimilar hosts).  The goodness tidings is that nosotros tin easily
   detect the job past times sending some spoofed packets "from" the first
   target to the zombie as well as so probing to verify that the proxy IP ID
   changed.  This volition also grab the instance where the Nmap user is
   behind an egress filter or other mensurate that prevents this kind of
   sp00fery */
  if (first_target) {
    for (probes_sent = 0; probes_sent < 4; probes_sent++) {       if (probes_sent) usleep(50000);       send_tcp_raw(proxy->rawsd, proxy->ethptr,
            first_target, proxy->host.v4hostip(),
        o.ttl, false,
        o.ipoptions, o.ipoptionslen,
        o.magic_port, proxy->probe_port,
        sequence_base + probes_sent + 1, ack, 0, TH_SYN|TH_ACK, 0, 0,
        (u8 *) "\x02\x04\x05\xb4",
        4, NULL, 0);
 
    }
 
    /* Sleep a trivial acre to give packets fourth dimension to accomplish their goal */
    usleep(300000);
    newipid = ipid_proxy_probe(proxy, NULL, NULL);
    if (newipid == -1)
      newipid = ipid_proxy_probe(proxy, NULL, NULL); /* OK, we'll give it ane to a greater extent than seek */
 
    if (newipid < 0) fatal("Your IP ID Zombie (%s; %s) is behaving strangely -- all of a precipitous cannot obtain IP ID", proxy->host.HostName(), proxy->host.targetipstr());
 
    distance = ipid_distance(proxy->seqclass, proxy->latestid, newipid);
    if (distance <= 0) {       fatal("Your IP ID Zombie (%s; %s) is behaving strangely -- all of a precipitous cannot obtain valid IP ID distance.", proxy->host.HostName(), proxy->host.targetipstr());
    } else if (distance == 1) {
      fatal("Even though your Zombie (%s; %s) appears to live vulnerable to IP ID sequence prediction (class: %s), our attempts conduct hold failed.  This to a greater extent than frequently than non agency that either the zombie uses a separate IP ID base of operations for each host (like Solaris), or because yous cannot spoof IP packets (perhaps your internet service provider has enabled egress filtering to foreclose IP spoofing), or maybe the target network recognizes the package source equally bogus as well as drops them", proxy->host.HostName(), proxy->host.targetipstr(), ipidclass2ascii(proxy->seqclass));
    }
    if (o.debugging && distance != 5) {
      error("WARNING: IP ID spoofing seek out sent 4 packets as well as expected a distance of 5, but instead got %d", distance);
    }
    proxy->latestid = newipid;
  }
 
}
 
/* Adjust timing parameters upward or downwards given that an idle scan found a
   count of 'testcount' acre the 'realcount' is equally given.  If the
   testcount was correct, timing is made to a greater extent than aggressive, acre it is
   slowed downwards inward the instance of an error */
static void adjust_idle_timing(struct idle_proxy_info *proxy,
            Target *target, int testcount,
            int realcount) {
 
  static int notidlewarning = 0;
 
  if (o.debugging > 1)
    log_write(LOG_STDOUT,
      "%s: tested/true %d/%d -- one-time grpsz/delay: %f/%d ",
      __func__, testcount, realcount, proxy->current_groupsz, proxy->senddelay);
  else if (o.debugging && testcount != realcount) {
    error("%s: testcount: %d  realcount: %d -- one-time grpsz/delay: %f/%d", __func__, testcount, realcount, proxy->current_groupsz, proxy->senddelay);
  }
 
    if (testcount < realcount) {       /* We must conduct hold missed a port -- our probe could conduct hold been     dropped, the answer to proxy could conduct hold been dropped, or we   didn't hold off long plenty before probing the proxy IP ID.  The    3rd instance is covered elsewhere inward the scan, so nosotros worry most   almost the initiative off two.  The solution is to decrease our group     size as well as add together a sending delay */ /* packets could live dropped because equally good many were sent at in ane lawsuit */       proxy->current_groupsz = MAX(proxy->min_groupsz, proxy->current_groupsz * 0.8);
      proxy->senddelay += 10000;
      proxy->senddelay = MIN(proxy->max_senddelay, proxy->senddelay);
       /* No grouping size should live greater than .5s of send delays */
      proxy->current_groupsz = MAX(proxy->min_groupsz, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay + 1)));
 
    } else if (testcount > realcount) {
      /* Perhaps the proxy host is non really idle ... */
      /* I gauge all I tin exercise is decrease the grouping size, so that if the proxy is non really idle, at to the lowest degree nosotros may live able to scan chunks to a greater extent than apace inward betwixt exterior packets */
      proxy->current_groupsz = MAX(proxy->min_groupsz, proxy->current_groupsz * 0.8);
 
      if (!notidlewarning && o.verbose) {
    notidlewarning = 1;
    error("WARNING: idle scan has erroneously detected phantom ports -- is the proxy %s (%s) really idle?", proxy->host.HostName(), proxy->host.targetipstr());
      }
    } else {
      /* W00p We got a perfect match.  That agency nosotros acquire a slight increase
     in allowed grouping size as well as nosotros tin lightly decrease the senddelay */
 
      proxy->senddelay = (int) (proxy->senddelay * 0.9);
      if (proxy->senddelay < 500) proxy->senddelay = 0;
      proxy->current_groupsz = MIN(proxy->current_groupsz * 1.1, 500000 / (proxy->senddelay + 1));
      proxy->current_groupsz = MIN(proxy->max_groupsz, proxy->current_groupsz);
 
    }
    if (o.debugging > 1)
      log_write(LOG_STDOUT, "-> %f/%d\n", proxy->current_groupsz, proxy->senddelay);
}
 
/* OK, at in ane lawsuit this is the hardcore idle scan role which really does
   the testing (most of the other cruft inward this file is just
   coordination, preparation, etc).  This role merely uses the
   idle scan technique to seek as well as count the number of opened upward ports inward the
   given port array.  The sent_time as well as rcv_time are filled inward with
   the times that the probe package & answer were sent/received.
   They tin live NULL if yous don't want to occupation them.  The purpose is for
   timing adjustments if the numbers plow out to live accurate. */
 
static int idlescan_countopen2(struct idle_proxy_info *proxy,
            Target *target, u16 *ports, int numports,
            struct timeval *sent_time, struct timeval *rcv_time)
{
 
#if 0 /* Testing code */
  int i;
  for(i=0; i < numports; i++)     if (ports[i] == 22)       return 1;   return 0; #endif   int openports;   int tries;   int proxyprobes_sent = 0; /* diff. from tries 'cause sometimes we                  skip tries */   int proxyprobes_rcvd = 0; /* To decide if packets were dr0pped */   int sent, rcvd;   int ipid_dist;   struct timeval start, end, latestchange, now;   struct timeval probe_times[4];   int pr0be;   static u32 seq = 0;   int newipid = 0;   int sleeptime;   int lasttry = 0;   int dotry3 = 0;   struct eth_nfo eth;   if (seq == 0) seq = get_random_u32();   memset(&end, 0, sizeof(end));   memset(&latestchange, 0, sizeof(latestchange));   gettimeofday(&start, NULL);   if (sent_time) memset(sent_time, 0, sizeof(*sent_time));   if (rcv_time) memset(rcv_time, 0, sizeof(*rcv_time));   if (proxy->rawsd < 0) {     if (!setTargetNextHopMAC(target))       fatal("%s: Failed to decide dst MAC address for Idle proxy",        __func__);     memcpy(eth.srcmac, target->SrcMACAddress(), 6);
    memcpy(eth.dstmac, target->NextHopMACAddress(), 6);
    eth.ethsd = eth_open_cached(target->deviceName());
    if (eth.ethsd == NULL)
      fatal("%s: Failed to opened upward ethernet device (%s)", __func__, target->deviceName());
  } else eth.ethsd = NULL;
 
  /* I start past times sending out the SYN pr0bez */
  for(pr0be = 0; pr0be < numports; pr0be++) {     if (o.scan_delay) enforce_scan_delay(NULL);     else if (proxy->senddelay && pr0be > 0) usleep(proxy->senddelay);
 
    /* Maybe I should involve decoys inward the film at some dot --
       but doing it the straightforward way (using the same decoys as
       we occupation inward probing the proxy box is risky.  I'll conduct hold to think
       about this more. */
    send_tcp_raw(proxy->rawsd, eth.ethsd? &eth : NULL,
            proxy->host.v4hostip(), target->v4hostip(),
        o.ttl, false,
        o.ipoptions, o.ipoptionslen,
        proxy->probe_port, ports[pr0be], seq, 0, 0, TH_SYN, 0, 0,
        (u8 *) "\x02\x04\x05\xb4", 4,
        o.extra_payload, o.extra_payload_length);
  }
  gettimeofday(&end, NULL);
 
  openports = -1;
  tries = 0;
  TIMEVAL_MSEC_ADD(probe_times[0], start, MAX(50, (target->to.srtt * 3/4) / 1000));
  TIMEVAL_MSEC_ADD(probe_times[1], start, target->to.srtt / 1000 );
  TIMEVAL_MSEC_ADD(probe_times[2], end, MAX(75, (2 * target->to.srtt +
                           target->to.rttvar) / 1000));
  TIMEVAL_MSEC_ADD(probe_times[3], end, MIN(4000, (2 * target->to.srtt +
                             (target->to.rttvar << 2 )) / 1000));   do {     if (tries == 2) dotry3 = (get_random_u8() > 200);
    if (tries == 3 && !dotry3)
      break; /* We usually want to skip the long-wait seek out */
    if (tries == 3 || (tries == 2 && !dotry3))
      lasttry = 1;
 
    gettimeofday(&now, NULL);
    sleeptime = TIMEVAL_SUBTRACT(probe_times[tries], now);
    if (!lasttry && proxyprobes_sent > 0 && sleeptime < 50000)
      continue; /* No dot going over again so presently */
 
    if (tries == 0 && sleeptime < 500)       sleeptime = 500;     if (o.debugging > 1) error("In grooming for idle scan probe seek #%d, sleeping for %d usecs", tries, sleeptime);
    if (sleeptime > 0)
      usleep(sleeptime);
 
    newipid = ipid_proxy_probe(proxy, &sent, &rcvd);
    proxyprobes_sent += sent;
    proxyprobes_rcvd += rcvd;
 
    if (newipid > 0) {
      ipid_dist = ipid_distance(proxy->seqclass, proxy->latestid, newipid);
      /* I used to exclusively exercise this if ipid_sit >= proxyprobes_sent, but I'd
     rather conduct hold a negative number inward that case. */
      if (ipid_dist < proxyprobes_sent) {    if (o.debugging)            error("%s: Must conduct hold lost a sent package because ipid_dist is %d acre proxyprobes_sent is %d.", __func__, ipid_dist, proxyprobes_sent);     /* I no longer whack timing hither ... done at bottom. */       }       ipid_dist -= proxyprobes_sent;       if (ipid_dist > openports) {
    openports = ipid_dist;
    gettimeofday(&latestchange, NULL);
      } else if (ipid_dist < openports && ipid_dist >= 0) {
    /* Uh-oh.  Perhaps I dropped a package this fourth dimension */
    if (o.debugging > 1) {
      error("%s: Counted %d opened upward ports inward seek #%d, but counted %d before ... likely a proxy_probe problem", __func__, ipid_dist, tries, openports);
    }
    /* I no longer whack timing hither ... done at bottom. */
      }
    }
 
    if (openports > numports || (numports <= 2 && (openports == numports)))
      break;
  } while(tries++ < 3);   if (proxyprobes_sent > proxyprobes_rcvd) {
    /* Uh-oh.  It looks similar nosotros lost at to the lowest degree ane proxy probe package */
    if (o.debugging) {
      error("%s: Sent %d probes; exclusively %d responses.  Slowing scan.", __func__, proxyprobes_sent, proxyprobes_rcvd);
    }
    proxy->senddelay += 5000;
    proxy->senddelay = MIN(proxy->max_senddelay, proxy->senddelay);
    /* No grouping size should live greater than .5s of send delays */
    proxy->current_groupsz = MAX(proxy->min_groupsz, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay+1)));
  } else {
    /* Yeah, nosotros got equally many responses equally nosotros sent probes.  This calls for a
       very lite timing acceleration ... */
    proxy->senddelay = (int) (proxy->senddelay * 0.95);
    if (proxy->senddelay < 500) proxy->senddelay = 0;
    proxy->current_groupsz = MAX(proxy->min_groupsz, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay+1)));
  }
 
  if ((openports > 0) && (openports <= numports)) {     /* Yeah, nosotros found opened upward ports... lets accommodate the timing ... */     if (o.debugging > 2) error("%s:  found %d opened upward ports (out of %d) inward %lu usecs", __func__, openports, numports, (unsigned long) TIMEVAL_SUBTRACT(latestchange, start));
    if (sent_time) *sent_time = start;
    if (rcv_time) *rcv_time = latestchange;
  }
  if (newipid > 0) proxy->latestid = newipid;
  if (eth.ethsd) { eth.ethsd = NULL; } /* don't demand to unopen it due to caching */
  return openports;
}
 
/* The project of this role is to occupation the idle scan technique to count
   the number of opened upward ports inward the given list.  Under the covers, this
   function just farms out the hard piece of work to some other function. */
static int idlescan_countopen(struct idle_proxy_info *proxy,
               Target *target, u16 *ports, int numports,
               struct timeval *sent_time, struct timeval *rcv_time) {
  int tries = 0;
  int openports;
 
  do {
    openports = idlescan_countopen2(proxy, target, ports, numports, sent_time,
                    rcv_time);
    tries++;
    if (tries == 6 || (openports >= 0 && openports <= numports))       break;     if (o.debugging) {       error("%s: In seek #%d, counted %d opened upward ports out of %d.  Retrying", __func__, tries, openports, numports);     }     /* Sleep for a trivial acre -- maybe proxy host had brief birst of        traffic or similar job */     sleep(tries * tries);     if (tries == 5)       sleep(45); /* We're gonna surrender if this fails, so nosotros volition live a bit          patient */     /* Since the host may conduct hold received packets acre nosotros were sleeping,        lets update our proxy IP ID counter */     proxy->latestid = ipid_proxy_probe(proxy, NULL, NULL);
  } while(1);
 
  if (openports < 0 || openports > numports ) {
    /* Oh f*ck!!!! */
    fatal("Idle scan is unable to obtain meaningful results from proxy %s (%s).  I'm deplorable it didn't piece of work out.", proxy->host.HostName(),
      proxy->host.targetipstr());
  }
 
  if (o.debugging > 2) error("%s: %d ports found opened upward out of %d, starting amongst %hu", __func__, openports, numports, ports[0]);
 
  return openports;
}
 
/* Recursively idle scans scans a grouping of ports using a depth-first
   divide-and-conquer strategy to regain the opened upward one(s). */
 
static int idle_treescan(struct idle_proxy_info *proxy, Target *target,
         u16 *ports, int numports, int expectedopen) {
 
  int firstHalfSz = (numports + 1)/2;
  int secondHalfSz = numports - firstHalfSz;
  int flatcount1, flatcount2;
  int deepcount1 = -1, deepcount2 = -1;
  struct timeval sentTime1, rcvTime1, sentTime2, rcvTime2;
  int retrycount = -1, retry2 = -1;
  int totalfound = 0;
  /* Scan the initiative off one-half of the make */
 
  if (o.debugging > 1) {
    error("%s: Called against %s amongst %d ports, starting amongst %hu. expectedopen: %d", __func__, target->targetipstr(), numports, ports[0], expectedopen);
    error("IDLE SCAN TIMING: grpsz: %.3f delay: %d srtt: %d rttvar: %d",
      proxy->current_groupsz, proxy->senddelay, target->to.srtt,
      target->to.rttvar);
  }
 
  flatcount1 = idlescan_countopen(proxy, target, ports, firstHalfSz,
                  &sentTime1, &rcvTime1);
 
  if (firstHalfSz > 1 && flatcount1 > 0) {
    /* Influenza A virus subtype H5N1 port appears open!  We dig downwards deeper to regain it ... */
    deepcount1 = idle_treescan(proxy, target, ports, firstHalfSz, flatcount1);
    /* Now nosotros assume deepcount1 is right, as well as accommodate timing if flatcount1 was
       wrong. */
    adjust_idle_timing(proxy, target, flatcount1, deepcount1);
  }
 
  /* I gauge nosotros had improve exercise the minute one-half equally good ... */
 
  flatcount2 = idlescan_countopen(proxy, target, ports + firstHalfSz,
                  secondHalfSz, &sentTime2, &rcvTime2);
 
  if ((secondHalfSz) > 1 && flatcount2 > 0) {
    /* Influenza A virus subtype H5N1 port appears open!  We dig downwards deeper to regain it ... */
    deepcount2 = idle_treescan(proxy, target, ports + firstHalfSz,
                   secondHalfSz, flatcount2);
    /* Now nosotros assume deepcount1 is right, as well as accommodate timing if flatcount1 was
       wrong */
    adjust_idle_timing(proxy, target, flatcount2, deepcount2);
  }
 
  totalfound = (deepcount1 == -1)? flatcount1 : deepcount1;
  totalfound += (deepcount2 == -1)? flatcount2 : deepcount2;
 
  if ((flatcount1 + flatcount2 == totalfound) &&
      (expectedopen == totalfound || expectedopen == -1)) {
 
    if (flatcount1 > 0) {
      if (o.debugging > 1) {
    error("Adjusting timing -- idlescan_countopen correctly found %d opened upward ports (out of %d, starting amongst %hu)", flatcount1, firstHalfSz, ports[0]);
      }
      adjust_timeouts2(&sentTime1, &rcvTime1, &(target->to));
    }
 
    if (flatcount2 > 0) {
      if (o.debugging > 2) {
    error("Adjusting timing -- idlescan_countopen correctly found %d opened upward ports (out of %d, starting amongst %hu)", flatcount2, secondHalfSz,
          ports[firstHalfSz]);
      }
      adjust_timeouts2(&sentTime2, &rcvTime2, &(target->to));
    }
  }
 
  if (totalfound != expectedopen) {
    if (deepcount1 == -1) {
      retrycount = idlescan_countopen(proxy, target, ports, firstHalfSz, NULL,
                      NULL);
      if (retrycount != flatcount1) {
    /* We conduct hold to exercise a deep count if novel ports were found and
       there are to a greater extent than than 1 total */
    if (firstHalfSz > 1 && retrycount > 0) {
      retry2 = retrycount;
      retrycount = idle_treescan(proxy, target, ports, firstHalfSz,
                     retrycount);
      adjust_idle_timing(proxy, target, retry2, retrycount);
    } else {
      if (o.debugging)
        error("Adjusting timing because my initiative off scan of %d ports, starting amongst %hu found %d open, acre minute scan yielded %d", firstHalfSz, ports[0], flatcount1, retrycount);
      adjust_idle_timing(proxy, target, flatcount1, retrycount);
    }
    totalfound += retrycount - flatcount1;
    flatcount1 = retrycount;
 
    /* If our initiative off count erroneously found as well as added an opened upward port,
       we must delete it */
    if (firstHalfSz == 1 && flatcount1 == 1 && retrycount == 0)
      target->ports.forgetPort(ports[0], IPPROTO_TCP);
 
      }
    }
 
    if (deepcount2 == -1) {
      retrycount = idlescan_countopen(proxy, target, ports + firstHalfSz,
                      secondHalfSz, NULL, NULL);
      if (retrycount != flatcount2) {
    if (secondHalfSz > 1 && retrycount > 0) {
      retry2 = retrycount;
      retrycount = idle_treescan(proxy, target, ports + firstHalfSz,
                     secondHalfSz, retrycount);
      adjust_idle_timing(proxy, target, retry2, retrycount);
    } else {
      if (o.debugging)
        error("Adjusting timing because my initiative off scan of %d ports, starting amongst %hu found %d open, acre minute scan yeilded %d", secondHalfSz, ports[firstHalfSz], flatcount2, retrycount);
      adjust_idle_timing(proxy, target, flatcount2, retrycount);
    }
 
    totalfound += retrycount - flatcount2;
    flatcount2 = retrycount;
 
    /* If our initiative off count erroneously found as well as added an opened upward port,
       we must delete it. */
    if (secondHalfSz == 1 && flatcount2 == 1 && retrycount == 0)
      target->ports.forgetPort(ports[firstHalfSz], IPPROTO_TCP);
 
      }
    }
  }
 
  if (firstHalfSz == 1 && flatcount1 == 1)
    target->ports.setPortState(ports[0], IPPROTO_TCP, PORT_OPEN);
 
  if ((secondHalfSz == 1) && flatcount2 == 1)
    target->ports.setPortState(ports[firstHalfSz], IPPROTO_TCP, PORT_OPEN);
  return totalfound;
 
}
 
/* The rattling top-level idle scan role -- scans the given target
   host using the given proxy -- the proxy is cached so that yous tin keep
   calling this role amongst dissimilar targets. */
void idle_scan(Target *target, u16 *portarray, int numports,
           char *proxyName, const struct scan_lists * ports) {
 
  static char lastproxy[MAXHOSTNAMELEN + 1] = ""; /* The proxy used inward whatsoever previous telephone vociferation upward */
  static struct idle_proxy_info proxy;
  int groupsz;
  int portidx = 0; /* Used for splitting the port array into chunks */
  int portsleft;
  char scanname[128];
  Snprintf(scanname, sizeof(scanname), "idle scan against %s", target->NameIP());
  ScanProgressMeter SPM(scanname);
 
  if (numports == 0) return; /* goose egg to scan for */
  if (!proxyName) fatal("idle scan requires a proxy host");
 
  if (*lastproxy && strcmp(proxyName, lastproxy))
    fatal("%s: You are non allowed to alter proxies midstream.  Sorry", __func__);
  assert(target);
 
  if (target->timedOut(NULL))
    return;
 
  if (target->ifType() == devt_loopback) {
    log_write(LOG_STDOUT, "Skipping Idle Scan against %s -- yous can't idle scan your ain machine (localhost).\n", target->NameIP());
    return;
  }
 
  target->startTimeOutClock(NULL);
 
  /* If this is the initiative off call,  */
  if (!*lastproxy) {
    initialize_idleproxy(&proxy, proxyName, target->v4hostip(), ports);
    strncpy(lastproxy, proxyName, sizeof(lastproxy));
  }
 
  /* If nosotros don't conduct hold timing infoz for the novel target, we'll occupation values
     derived from the proxy */
  if (target->to.srtt == -1 && target->to.rttvar == -1) {
    target->to.srtt = MAX(200000,2 * proxy.host.to.srtt);
    target->to.rttvar = MAX(10000, MIN(proxy.host.to.rttvar, 2000000));
    target->to.timeout = target->to.srtt + (target->to.rttvar << 2);   } else {     target->to.srtt = MAX(target->to.srtt, proxy.host.to.srtt);
    target->to.rttvar = MAX(target->to.rttvar, proxy.host.to.rttvar);
    target->to.timeout = target->to.srtt + (target->to.rttvar << 2);
  }
 
  /* Now I gauge it is fourth dimension to allow the scanning begin!  Since idle
     scan is kind of tree structured (we scan a grouping as well as so divide
     it upward as well as drill downwards inward subscans of the group), nosotros split the port
     space into smaller groups as well as so telephone vociferation upward a recursive
     divide-and-counquer role to regain the opened upward ports */
  while(portidx < numports) {
    portsleft = numports - portidx;
    /* current_groupsz is doubled below because idle_subscan cuts inward one-half */
    groupsz = MIN(portsleft, (int) (proxy.current_groupsz * 2));
    idle_treescan(&proxy, target, portarray + portidx, groupsz, -1);
    portidx += groupsz;
  }
 
  char additional_info[14];
  Snprintf(additional_info, sizeof(additional_info), "%d ports", numports);
  SPM.endTask(NULL, additional_info);
 
  /* Now nosotros become through the ports which were scanned but non determined
     to live open, as well as add together them inward the "closed|filtered" solid soil */
  for(portidx = 0; portidx < numports; portidx++) {     if (target->ports.portIsDefault(portarray[portidx], IPPROTO_TCP)) {
      target->ports.setPortState(portarray[portidx], IPPROTO_TCP, PORT_CLOSEDFILTERED);
      target->ports.setStateReason(portarray[portidx], IPPROTO_TCP, ER_NOIPIDCHANGE, 0, NULL);
    } else
      target->ports.setStateReason(portarray[portidx], IPPROTO_TCP, ER_IPIDCHANGE, 0, NULL);
  }
 
  target->stopTimeOutClock(NULL);
  return;
}
As yous tin see, this is my screenshot of the C++ source file. Just compile it as well as run it to acquire the results.
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
OK, let’s start amongst our master scan method.
IP Protocol Scan
IP protocol scan allows yous to decide which IP protocols (TCP, ICMP, IGMP, etc.) are supported past times target machines. This isn’t technically a port scan, since it cycles through IP protocol numbers rather than TCP or UDP port numbers.
Command: nmap –sO target
This is our minute installment of Nmap cheat canvas Nmap Cheat Sheet: From Discovery to Exploits, Part 2: Advance Port Scanning amongst Nmap And Custom Idle Scan
FTP Bounce Scan
This allows a user to connect to ane FTP server, so enquire that files live sent to a third-party server. Simply it asks the FTP server to send a file to each interesting port of a target host inward turn. The error message volition depict whether the port is opened upward or not. This is a goodness way to bypass firewalls, because organizational FTP servers are frequently placed where they conduct hold to a greater extent than access to other internal hosts than whatsoever one-time Internet host would. It takes an declaration of the cast <username>:<password>@<server>:<port>. <Server> is the yell or IP address of a vulnerable FTP server.
Command: nmap –b ftp rely host. Also, this tin live used for port bounce attack.
nmap -T0 -b username:password@ftpserver.tld:21 victim.tld
This uses the username “username”, the password “password”, the FTP server “ftpserver.tld” as well as port 21 on said server to scan victim.tld.
If the FTP server supports anonymous logins, just forget almost the username:password@ part as well as Nmap volition assume it allows -anonymous. You may omit :21 if the FTP port is 21, however, some people configure FTP on weird ports equally an endeavour at “security”.
Port Specification as well as Scan Order
In add-on to all of the scan methods discussed previously, Nmap offers options for specifying which ports are scanned as well as whether the scan social club is randomized or sequential. By default, Nmap scans the most mutual 1,000 ports for each protocol.
-p <port ranges> (Only scan specified ports)
This alternative specifies which ports yous want to scan as well as overrides the default. Individual port numbers are OK, equally are ranges separated past times a hyphen (e.g. 1-1023). The initiative off and/or halt values of a make may live omitted, causing Nmap to occupation 1 as well as 65535, respectively. So yous tin specify -p- to scan ports from 1 through 65535. Scanning port null is allowed if yous specify it explicitly.
Nmap –p 1-1023 target
When scanning a combination of protocols (e.g. TCP as well as UDP), yous tin specify a exceptional protocol past times preceding the port numbers past times T: for TCP, U: for UDP, S: for SCTP, or P: for IP Protocol.
nmap -p U:53,111,137,T:21-25,80,139,8080 target
-F (Fast (limited port) scan)
Specifies that yous want to scan fewer ports than the default. Normally Nmap scans the most mutual 1,000 ports for each scanned protocol. With -F, this is reduced to 100.
nmap –F target
-r (Don’t randomize ports)
By default, Nmap randomizes the scanned port social club (except that sure commonly accessible ports are moved close the initiative off for efficiency reasons). This randomization is usually desirable, but yous tin specify -r for sequential (sorted from lowest to highest) port scanning instead.
nmap –r target
So this is the halt of this part of the series. In the next part, I volition become through advanced firewall evasion as well as custom creation of exploits amongst Nmap.
Warning: The higher upward mentioned malicious laid on conducted on the lab has been given prior permission past times the possessor of website or admin. The higher upward is meant for exclusively educational purposes. So exercise non occupation for whatsoever personal intent, equally it is prone to cyber attack.
References:
http://www.kyuzz.org/antirez/papers/dumbscan.html
http://www.kyuzz.org/antirez/papers/moreipid.html
http://en.wikipedia.org/wiki/Idle_scan
Blogger
Disqus
Pilih Sistem Komentar

No comments

Advertiser