if (o.randomize_ports) { if (ports.tcp_count) { shortfry(ports.tcp_ports, ports.tcp_count); // move a few more common ports closer to the beginning to speed scan random_port_cheat(ports.tcp_ports, ports.tcp_count); } if (ports.udp_count) shortfry(ports.udp_ports, ports.udp_count); if (ports.sctp_count) shortfry(ports.sctp_ports, ports.sctp_count); if (ports.prot_count) shortfry(ports.prots, ports.prot_count); }
而随机化算法如下,是简单的洗牌算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
voidshortfry(unsignedshort *arr, int num_elem) { int num; unsignedshort tmp; int i;
if (num_elem < 2) return;
for (i = num_elem - 1; i > 0 ; i--) { num = get_random_ushort() % (i + 1); if (i == num) continue; tmp = arr[i]; arr[i] = arr[num]; arr[num] = tmp; }
// Move some popular TCP ports to the beginning of the portlist, because // that can speed up certain scans. You should have already done any port // randomization, this should prevent the ports from always coming out in the // same order. voidrandom_port_cheat(u16 *ports, int portcount) { int allportidx = 0; int popportidx = 0; int earlyreplidx = 0; /* Updated 2008-12-19 from nmap-services-all. Top 25 open TCP ports plus 113, 554, and 256 */ u16 pop_ports[] = { 80, 23, 443, 21, 22, 25, 3389, 110, 445, 139, 143, 53, 135, 3306, 8080, 1723, 111, 995, 993, 5900, 1025, 587, 8888, 199, 1720, 113, 554, 256 }; int num_pop_ports = sizeof(pop_ports) / sizeof(u16);
for(allportidx = 0; allportidx < portcount; allportidx++) { // see if the currentport is a popular port for(popportidx = 0; popportidx < num_pop_ports; popportidx++) { if (ports[allportidx] == pop_ports[popportidx]) { // This one is popular! Swap it near to the beginning. if (allportidx != earlyreplidx) { ports[allportidx] = ports[earlyreplidx]; ports[earlyreplidx] = pop_ports[popportidx]; } earlyreplidx++; break; } } } }