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 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
|
#include "nmap.h"
/* global options */
extern char *optarg;
extern int optind;
struct ops o; /* option structure */
int main(int argc, char *argv[]) {
int i, j, arg, argvlen;
short fastscan=0, tcpscan=0, randomize=1, resolve_all=0;
short quashargv = 0, pingscan = 0;
int lookahead = LOOKAHEAD;
short bouncescan = 0;
unsigned short *ports = NULL;
char myname[MAXHOSTNAMELEN + 1];
#if (defined(IN_ADDR_DEEPSTRUCT) || defined( SOLARIS))
/* Note that struct in_addr in solaris is 3 levels deep just to store an
* unsigned int! */
struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { { { 0 } } } , 21, 0};
#else
struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { 0 }, 21, 0};
#endif
struct hostent *target = NULL;
struct in_addr *source=NULL;
char **fakeargv = (char **) safe_malloc(sizeof(char *) * (argc + 1));
struct hoststruct *currenths;
char emptystring[1];
int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
source addresses? */
/* argv faking silliness */
for(i=0; i < argc; i++) {
fakeargv[i] = safe_malloc(strlen(argv[i]) + 1);
strncpy(fakeargv[i], argv[i], strlen(argv[i]) + 1);
}
fakeargv[argc] = NULL;
/* initialize our options */
options_init();
emptystring[0] = '\0'; /* It wouldn't be an emptystring w/o this ;) */
/* Trap these sigs for cleanup */
signal(SIGINT, sigdie);
signal(SIGTERM, sigdie);
signal(SIGHUP, sigdie);
if (argc < 2 ) printusage(argv[0]);
/* OK, lets parse these args! */
while((arg = getopt(argc,fakeargv,"Ab:DdFfhiL:lM:Nno:Pp:qrRS:sT:tUuw:Vv")) != EOF) {
switch(arg) {
case 'A': o.allowall++; break;
case 'b':
bouncescan++;
if (parse_bounce(&ftp, optarg) < 0 ) {
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");
}
break;
case 'D': o.dontping++; break;
case 'd': o.debugging++; break;
case 'F': fastscan++; break;
case 'f': o.fragscan++; break;
case 'h':
case '?': printusage(argv[0]);
case 'i': o.identscan++; break;
case 'L': lookahead = atoi(optarg); break;
case 'l': o.lamerscan++; o.udpscan++; break;
case 'M':
o.max_sockets = atoi(optarg);
if (o.max_sockets > MAX_SOCKETS_ALLOWED) {
printf("Warning: You are limited to MAX_SOCKETS_ALLOWD (%d) paralell sockets. If you really need more, change the #define and recompile.\n", MAX_SOCKETS_ALLOWED);
o.max_sockets = MAX_SOCKETS_ALLOWED;
}
break;
case 'n': o.noresolve++; break;
case 'N': o.force++; break;
case 'o':
if (o.logfd) fatal("Only one log filename allowed");
o.logfd = fopen(optarg, "w");
if (!o.logfd)
fatal("Failed to open output file %s for writing", optarg);
break;
case 'P': pingscan++; break;
case 'p':
if (ports)
fatal("Only 1 -p option allowed, seperate multiple ranges with commas.");
ports = getpts(optarg); break;
case 'R': resolve_all++; break;
case 'r':
randomize = 0;
printf("Warning: Randomize syntax has been changed, -r now requests that ports NOT be randomized\n");
break;
case 's': o.synscan++; break;
case 'S':
if (o.spoofsource)
fatal("You can only use the source option once!\n");
source = safe_malloc(sizeof(struct in_addr));
o.spoofsource = 1;
if (!resolve(optarg, source))
fatal("Failed to resolve source address, try dotted decimal of check for type\n");
break;
case 'T': o.ptime = atoi(optarg); break;
case 't': tcpscan++; break;
case 'U': o.finscan++; break;
case 'u': o.udpscan++; break;
case 'q': quashargv++; break;
case 'w': o.wait = atoi(optarg); break;
case 'V':
printf("\nnmap V. %s by Fyodor (fyodor@dhp.com, www.dhp.com/~fyodor/nmap/)\n", VERSION);
exit(0);
break;
case 'v': o.verbose++; break;
}
}
/* Take care of user wierdness */
o.isr00t = !(geteuid()|geteuid());
if (!o.isr00t && pingscan) fatal("You can't do a ping scan if you aren't root");
if (pingscan && o.dontping) fatal("ICMP ping scan -P and don't ping -D are incompatible options, Duh.");
if (!o.isr00t) o.dontping++;
if (bouncescan && !o.dontping) printf("Hint: if your bounce scan target hosts aren't reachable from here, remember to use -D\n");
if (tcpscan && (o.synscan || o.finscan))
fatal("Pick one of -t, -s, and -U. They all do a TCP portscan.\
If you are trying to do TCP SYN scanning, just use -s, for FIN use -U, and \
for normal connect() style scanning, use -t");
if ((o.fragscan && !o.synscan && !o.finscan)) {
printf("Specified -f but don't know whether to fragment SYN (-s) scan or FIN (-U) scan. Doing fragmented SYN scan\n");
}
if (o.udpscan || o.lamerscan)
printf("Warning: udp scan is not always 100%c accurate, I will be rewriting it\n", '%'); /* Due to gcc -Wall stupidity */
if ((o.synscan || o.finscan || o.fragscan || pingscan) && !o.isr00t)
fatal("Options specified require r00t privileges. You don't have them!");
if (!tcpscan && !o.udpscan && !o.synscan && !o.finscan && !bouncescan && !pingscan) {
tcpscan++;
if (o.verbose) error("No scantype specified, assuming vanilla tcp connect()\
scan. Use -P if you really don't want to portscan (and just want to ping).");
if (fastscan && ports)
fatal("You can use -F (fastscan) OR -p for explicit port specification.\
Not both!\n");
}
if (o.max_sockets > MAX_SOCKETS_ALLOWED) {
printf("Warning: You are limited to MAX_SOCKETS_ALLOWD (%d) paralell sockets. If you really need more, change the #define and recompile.\n", MAX_SOCKETS_ALLOWED);
o.max_sockets = MAX_SOCKETS_ALLOWED;
}
/* If he wants to bounce off of an ftp site, that site better damn well be reachable! */
if (bouncescan) {
if (!inet_aton(ftp.server_name, &ftp.server)) {
if ((target = gethostbyname(ftp.server_name)))
memcpy(&ftp.server, target->h_addr_list[0], 4);
else {
fprintf(stderr, "Failed to resolve ftp bounce proxy hostname/IP: %s\n",
ftp.server_name);
exit(1);
}
} else if (o.verbose)
printf("Resolved ftp bounce attack proxy to %s (%s).\n",
ftp.server_name, inet_ntoa(ftp.server));
}
fflush(stdout);
if (o.logfd) {
/* Brief info incase they forget what was scanned */
fprintf(o.logfd, "# Log of: ");
for(i=0; i < argc; i++)
fprintf(o.logfd, "%s ", fakeargv[i]);
fprintf(o.logfd, "\n");
}
printf("\nStarting nmap V. %s by Fyodor (fyodor@dhp.com, www.dhp.com/~fyodor/nmap/)\n", VERSION);
/* I seriously doubt anyone likes this "feature"
if (!o.verbose)
error("Hint: The -v option notifies you of open ports as they are found.\n");
*/
if (fastscan)
ports = getfastports(o.synscan|tcpscan|o.fragscan|o.finscan|bouncescan,
o.udpscan|o.lamerscan);
if (!ports && !pingscan) ports = getpts("1-1024");
/* more fakeargv junk, BTW malloc'ing extra space in argv[0] doesn't work */
if (quashargv) {
argvlen = strlen(argv[0]);
if (argvlen < strlen(FAKE_ARGV))
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");
strncpy(argv[0], FAKE_ARGV, strlen(FAKE_ARGV));
for(i = strlen(FAKE_ARGV); i < argvlen; i++) argv[0][i] = '\0';
for(i=1; i < argc; i++) {
argvlen = strlen(argv[i]);
for(j=0; j <= argvlen; j++)
argv[i][j] = '\0';
}
}
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
of it, but we really shouldn't get an unsuspected
SIGPIPE */
if ((i = max_sd()) && i < o.max_sockets) {
printf("Your specified max_parallel_sockets of %d, but your system says it might only give us %d. Trying anyway\n", o.max_sockets, i);
}
if (o.debugging > 1) printf("The max # of sockets on your system is: %d\n", i);
srand(time(NULL));
if (randomize)
shortfry(ports);
while(optind < argc) {
while((currenths = nexthost(fakeargv[optind], lookahead, o.ptime)) && currenths->host.s_addr) {
/* printf("Nexthost() returned: %s\n", inet_ntoa(currenths->host));*/
target = NULL;
if (((currenths->flags & HOST_UP) || resolve_all) && !o.noresolve)
target = gethostbyaddr((char *) ¤ths->host, 4, AF_INET);
if (target) {
currenths->name = strdup(target->h_name);
}
else {
currenths->name = emptystring;
}
if (o.wait && currenths->rtt) currenths->rtt += o.wait;
if (source) memcpy(¤ths->source_ip, source, sizeof(struct in_addr));
if (!pingscan) {
if (!o.dontping && (currenths->flags & HOST_UP) && (o.verbose || o.debugging))
printf("Host %s (%s) appears to be up ... good.\n", currenths->name, inet_ntoa(currenths->host));
else if (o.verbose && !o.dontping && !(currenths->flags & HOST_UP)) {
if (resolve_all)
nmap_log("Host %s (%s) appears to be down, skipping it.\n", currenths->name, inet_ntoa(currenths->host));
else printf("Host %s (%s) appears to be down, skipping it.\n", currenths->name, inet_ntoa(currenths->host));
}
}
else {
if (currenths->flags & HOST_UP)
nmap_log("Host %s (%s) appears to be up.\n", currenths->name, inet_ntoa(currenths->host));
else
if (o.verbose || o.debugging || resolve_all) {
if (resolve_all)
nmap_log("Host %s (%s) appears to be down.\n", currenths->name, inet_ntoa(currenths->host));
else printf("Host %s (%s) appears to be down.\n", currenths->name, inet_ntoa(currenths->host));
}
if (currenths->wierd_responses)
nmap_log("Host %s (%s) seems to be a subnet broadcast address (returned %d extra pings)\n", currenths->name, inet_ntoa(currenths->host), currenths->wierd_responses);
}
if (currenths->flags & HOST_UP && !currenths->source_ip.s_addr && ( o.synscan || o.finscan)) {
if (gethostname(myname, MAXHOSTNAMELEN) ||
!(target = gethostbyname(myname)))
fatal("Your system is fucked up. Cannot get hostname!\n");
memcpy(¤ths->source_ip, target->h_addr_list[0], sizeof(struct in_addr));
if (! sourceaddrwarning) {
printf("We could not determine for sure which interface to use, so we are guessing %s . If this is wrong, use -S\n", inet_ntoa(currenths->source_ip));
sourceaddrwarning = 1;
}
}
if (currenths->flags & HOST_UP && (o.finscan || o.synscan) && !ipaddr2devname( currenths->device, ¤ths->source_ip))
fatal("Could not figure out what device to send the packet out on! You might possibly want to try -S (but this is probably a bigger problem)\n");
/* Time for some actual scanning! */
if (currenths->flags & HOST_UP) {
if (tcpscan) tcp_scan(currenths, ports, o.ptime);
if (o.synscan) syn_scan(currenths, ports);
if (o.finscan) fin_scan(currenths, ports);
if (bouncescan) {
if (ftp.sd <= 0) ftp_anon_connect(&ftp);
if (ftp.sd > 0) bounce_scan(currenths, ports, &ftp);
}
if (o.udpscan) {
if (!o.isr00t || o.lamerscan)
lamer_udp_scan(currenths, ports);
else udp_scan(currenths, ports);
}
if (!currenths->ports && !pingscan) {
nmap_log("No ports open for host %s (%s)\n", currenths->name,
inet_ntoa(currenths->host));
if (currenths->wierd_responses)
nmap_log("Host %s (%s) seems to be a subnet broadcast address (returned %d extra pings)\n", currenths->name, inet_ntoa(currenths->host), currenths->wierd_responses);
}
if (currenths->ports) {
nmap_log("Open ports on %s (%s):\n", currenths->name,
inet_ntoa(currenths->host));
printandfreeports(currenths->ports);
if (currenths->wierd_responses)
nmap_log("Host %s (%s) seems to be a subnet broadcast address (returned %d extra pings)\n", currenths->name, inet_ntoa(currenths->host), currenths->wierd_responses);
}
}
fflush(stdout);
}
optind++;
}
return 0;
}
void options_init() {
bzero( (char *) &o, sizeof(struct ops));
o.debugging = DEBUGGING;
o.verbose = DEBUGGING;
o.max_sockets = MAX_SOCKETS;
#ifdef IGNORE_ZERO_AND_255_HOSTS
o.allowall = !(IGNORE_ZERO_AND_255_HOSTS);
#endif
o.ptime = PING_TIMEOUT;
}
__inline__ void max_rcvbuf(int sd) {
int optval = 524288 /*2^19*/, optlen = sizeof(int);
if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &optval, optlen))
if (o.debugging) perror("Problem setting large socket recieve buffer");
if (o.debugging) {
getsockopt(sd, SOL_SOCKET, SO_RCVBUF,(void *) &optval, &optlen);
printf("Our buffer size is now %d\n", optval);
}
}
/* Maximize the open file descriptor limit for this process go up to the
max allowed */
int max_sd() {
struct rlimit r;
#if(defined(RLIMIT_NOFILE))
if (!getrlimit(RLIMIT_NOFILE, &r)) {
r.rlim_cur = r.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &r))
if (o.debugging) perror("setrlimit RLIMIT_NOFILE failed");
if (!getrlimit(RLIMIT_NOFILE, &r))
return r.rlim_cur;
else return 0;
}
#endif
#if(defined(RLIMIT_OFILE) && !defined(RLIMIT_NOFILE))
if (!getrlimit(RLIMIT_OFILE, &r)) {
r.rlim_cur = r.rlim_max;
if (setrlimit(RLIMIT_OFILE, &r))
if (o.debugging) perror("setrlimit RLIMIT_OFILE failed");
if (!getrlimit(RLIMIT_OFILE, &r))
return r.rlim_cur;
else return 0;
}
#endif
return 0;
}
__inline__ int block_socket(int sd) {
int options;
options = (~O_NONBLOCK) & fcntl(sd, F_GETFL);
fcntl(sd, F_SETFL, options);
return 1;
}
__inline__ void broadcast_socket(int sd) {
int one = 1;
if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, (void *)&one, sizeof(int)) != 0) {
printf("Failed to secure socket broadcasting permission\n");
perror("setsockopt");
}
}
/* We set the socket lingering so we will RST connection instead of wasting
bandwidth with the four step close */
__inline__ void init_socket(int sd) {
struct linger l;
l.l_onoff = 1;
l.l_linger = 0;
if (setsockopt(sd, SOL_SOCKET, SO_LINGER, (void *) &l, sizeof(struct linger)))
{
fprintf(stderr, "Problem setting socket SO_LINGER, errno: %d\n", errno);
perror("setsockopt");
}
}
/* Convert a string like "-100,200-1024,3000-4000,60000-" into an array
of port numbers*/
unsigned short *getpts(char *origexpr) {
int exlen = strlen(origexpr);
char *p,*q;
unsigned short *tmp, *ports;
int i=0, j=0,start,end;
char *expr = strdup(origexpr);
char *mem = expr;
ports = safe_malloc(65536 * sizeof(short));
for(;j < exlen; j++)
if (expr[j] != ' ') expr[i++] = expr[j];
expr[i] = '\0';
exlen = i;
i=0;
while((p = strchr(expr,','))) {
*p = '\0';
if (*expr == '-') {start = 1; end = atoi(expr+ 1);}
else {
start = end = atoi(expr);
if ((q = strchr(expr,'-')) && *(q+1) ) end = atoi(q + 1);
else if (q && !*(q+1)) end = 65535;
}
if (o.debugging)
printf("The first port is %d, and the last one is %d\n", start, end);
if (start < 1 || start > end) fatal("Your port specifications are illegal!");
for(j=start; j <= end; j++)
ports[i++] = j;
expr = p + 1;
}
if (*expr == '-') {
start = 1;
end = atoi(expr+ 1);
}
else {
start = end = atoi(expr);
if ((q = strchr(expr,'-')) && *(q+1) ) end = atoi(q+1);
else if (q && !*(q+1)) end = 65535;
}
if (o.debugging)
printf("The first port is %d, and the last one is %d\n", start, end);
if (start < 1 || start > end) fatal("Your port specifications are illegal!");
for(j=start; j <= end; j++)
ports[i++] = j;
o.numports = i;
ports[i++] = 0;
tmp = realloc(ports, i * sizeof(short));
free(mem);
return tmp;
}
unsigned short *getfastports(int tcpscan, int udpscan) {
int portindex = 0, res, lastport = 0;
unsigned int portno = 0;
unsigned short *ports;
char proto[10];
char line[81];
FILE *fp;
ports = safe_malloc(65535 * sizeof(unsigned short));
proto[0] = '\0';
if (!(fp = fopen("/etc/services", "r"))) {
printf("We can't open /etc/services for reading! Fix your system or don't use -f\n");
perror("fopen");
exit(1);
}
while(fgets(line, 80, fp)) {
res = sscanf(line, "%*s %u/%s", &portno, proto);
if (res == 2 && portno != 0 && portno != lastport) {
lastport = portno;
if (tcpscan && proto[0] == 't')
ports[portindex++] = portno;
else if (udpscan && proto[0] == 'u')
ports[portindex++] = portno;
}
}
o.numports = portindex;
ports[portindex++] = 0;
return realloc(ports, portindex * sizeof(unsigned short));
}
void printusage(char *name) {
printf("nmap V. %s usage: %s [options] [hostname[/mask] . . .]\n\
options (none are required, most can be combined):\n\
-t tcp connect() port scan\n\
-s tcp SYN stealth port scan (must be root)\n\
-U Uriel Maimon (P49-15) style FIN stealth scan.\n\
-P ping \"scan\". Find which hosts on specified network(s) are up.\n\
-b <ftp_relay_host> ftp \"bounce attack\" port scan\n\
-u UDP port scan, will use MUCH better version if you are root\n\
-l Do the lamer UDP scan even if root. Less accurate.\n\
-f use tiny fragmented packets for SYN or FIN scan.\n\
-D Don't ping hosts (needed to scan www.microsoft.com and others)\n\
-i Get identd (rfc 1413) info on listening TCP processes.\n\
-p <range> ports: ex: \'-p 23\' will only try port 23 of the host(s)\n\
\'-p 20-30,63000-\' scans 20-30 and 63000-65535 default: 1-1024\n\
-F fast scan. Only scans ports in /etc/services, a la strobe(1).\n\
-n Don't DNS resolve anything unless we have to (makes ping scans faster)\n\
-L <num> Number of pings to perform in parallel. Your default is: %d\n\
-o <logfile> Output scan logs to <logfile>.\n\
-R Try to resolve all hosts, even down ones (can take a lot of time)\n\
-r do NOT randomize target port scanning order.\n\
-S If you want to specify the source address of SYN or FYN scan.\n", VERSION, name, LOOKAHEAD);
if (!o.allowall) printf("-A Allow scanning .0 and .255 addresses" );
printf(" -T <seconds> Set the ping and tcp connect() timeout.\n\
-v Verbose. Its use is recommended. Use twice for greater effect.\n\
-h help, print this junk. Also see http://www.dhp.com/~fyodor/nmap/\n\
-V Print version number and exit.\n\
-w <n> delay. n microsecond delay. Not recommended unless needed.\n\
-M <n> maximum number of parallel sockets. Larger isn't always better.\n");
printf(" -q quash argv to something benign, currently set to \"%s\". (deprecated)\n", FAKE_ARGV);
printf("Hostnames specified as internet hostname or IP address. Optional '/mask' \
specifies subnet. cert.org/24 or 192.88.209.5/24 or 192.88.209.0-255 scan CERT's Class C.\n");
exit(0);
}
portlist tcp_scan(struct hoststruct *target, unsigned short *portarray, int timeout) {
int connecterror = 0; /* Have we given the "strange connect error" message yet? */
int starttime, current_out = 0, res , deadindex = 0, i=0, j=0, k=0, max=0;
struct sockaddr_in sock, stranger, mysock;
int sockaddr_in_len = sizeof(struct sockaddr_in);
int seconds, seconds2; /* Store time temporarily for timeout purposes */
int sockets[MAX_SOCKETS_ALLOWED]; /* All socket descriptors */
int deadstack[MAX_SOCKETS_ALLOWED]; /* Stack of dead descriptors (indexes to sockets[] */
unsigned short portno[MAX_SOCKETS_ALLOWED]; /* port numbers of sd's, parallel to sockets[] */
int times[MAX_SOCKETS_ALLOWED]; /* initial connect() times of sd's, parallel to sockets[]. For timeout information. */
int retrystack[MAX_SOCKETS_ALLOWED]; /* sd's that need to be retried */
static int retries[65535]; /* nr. or retries for this port */
int retryindex = -1;
int numretries = 2; /* How many retries before we give up on a connection */
char owner[513], buf[65536];
int tryident = o.identscan, current_socket /*actually it is a socket INDEX*/;
fd_set fds_read, fds_write;
struct timeval nowait = {0,0}, longwait = {7,0};
int timeouts=0;
static int threshold_warning = 0; /* Have we given the threshold warning yet?*/
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our 'write 0 bytes' test
doesn't crash our program!*/
owner[0] = '\0';
starttime = time(NULL);
bzero((char *)&sock,sizeof(struct sockaddr_in));
sock.sin_addr.s_addr = target->host.s_addr;
if (o.verbose || o.debugging)
printf("Initiating TCP connect() scan against %s (%s)\n",
target->name, inet_ntoa(sock.sin_addr));
sock.sin_family=AF_INET;
FD_ZERO(&fds_read);
FD_ZERO(&fds_write);
if (tryident)
tryident = check_ident_port(target->host);
/* Initially, all of our sockets are "dead" */
for(i = 0 ; i < o.max_sockets; i++) {
deadstack[deadindex++] = i;
portno[i] = 0;
}
deadindex--;
/* deadindex always points to the most recently added dead socket index */
while(portarray[j] || retryindex >= 0 || current_out != 0) {
longwait.tv_sec = timeout;
longwait.tv_usec = nowait.tv_sec = nowait.tv_usec = 0;
seconds = time(NULL);
for(i=current_out; i < o.max_sockets && (portarray[j] || retryindex >= 0); i++) {
current_socket = deadstack[deadindex--];
if ((sockets[current_socket] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{perror("Socket troubles"); exit(1);}
if (sockets[current_socket] > max) max = sockets[current_socket];
current_out++;
unblock_socket(sockets[current_socket]);
init_socket(sockets[current_socket]);
if (retryindex < 0) {
portno[current_socket] = portarray[j++];
}
else { /* we have retries to do ...*/
portno[current_socket] = retrystack[retryindex--];
}
sock.sin_port = htons(portno[current_socket]);
times[current_socket] = seconds;
if ((res = connect(sockets[current_socket],(struct sockaddr *)&sock,sizeof(struct sockaddr)))!=-1) {
/* This can happen on localhost, successful connection immediately
in non-blocking mode */
if (o.debugging || o.verbose)
printf("Adding TCP port %hi due to successful connection.\n",
portno[current_socket]);
if (tryident) {
if (getsockname(sockets[current_socket], (SA *) &mysock,
&sockaddr_in_len )) {
perror("getsockname");
exit(1);
}
if (getidentinfoz(target->host, ntohs(mysock.sin_port), portno[current_socket],
owner) == -1)
tryident = 0;
}
addport(&target->ports, portno[current_socket], IPPROTO_TCP, owner);
if (max == sockets[current_socket])
max--;
FD_CLR(sockets[current_socket], &fds_read);
FD_CLR(sockets[current_socket], &fds_write);
deadstack[++deadindex] = current_socket;
current_out--;
portno[current_socket] = 0;
close(sockets[current_socket]);
}
else { /* Connect() failed, normal case */
switch(errno) {
case EINPROGRESS: /* The one I always see */
case EAGAIN:
block_socket(sockets[current_socket]);
FD_SET(sockets[current_socket], &fds_write);
FD_SET(sockets[current_socket], &fds_read);
break;
default:
if (!connecterror) {
printf("Strange error from connect (%d):", errno);
fflush(stdout);
perror(""); /*falling through intentionally*/
connecterror++;
}
case ECONNREFUSED:
if (max == sockets[current_socket]) max--;
deadstack[++deadindex] = current_socket;
current_out--;
portno[current_socket] = 0;
close(sockets[current_socket]);
timeouts = 0; /* We may not want to give up on this host */
break;
}
}
}
/* if (!portarray[j] && retryindex < 0) sleep(2); *//*If we are done,
wait a second for any last packets*/
/* Use nowait if we have more to send, but if we already have max_sockets
out or if we are out of ports & retries, might as well wait awhile */
while((res = select(max + 1, &fds_read, &fds_write, NULL,
((current_out < o.max_sockets) &&
(current_out == 0 || portarray[j] || retryindex >= 0) )?
&nowait : &longwait)) > 0) {
fflush(stdout);
for(k=0; k < o.max_sockets; k++)
if (portno[k]) {
if (FD_ISSET(sockets[k], &fds_write)
&& FD_ISSET(sockets[k], &fds_read)) {
/*printf("Socket at port %hi is selectable for r & w.", portno[k]);*/
res = recvfrom(sockets[k], buf, 65536, 0, (struct sockaddr *)
& stranger, &sockaddr_in_len);
if (res >= 0) {
if (o.debugging || o.verbose)
printf("Adding TCP port %hi due to successful read.\n",
portno[k]);
if (tryident) {
if ( getsockname(sockets[k], (struct sockaddr *) &mysock,
&sockaddr_in_len ) ) {
perror("getsockname");
exit(1);
}
if (getidentinfoz(target->host, ntohs(mysock.sin_port), portno[k],
owner) == -1)
tryident = 0;
}
addport(&target->ports, portno[k], IPPROTO_TCP, owner);
}
if (max == sockets[k])
max--;
FD_CLR(sockets[k], &fds_read);
FD_CLR(sockets[k], &fds_write);
deadstack[++deadindex] = k;
current_out--;
portno[k] = 0;
close(sockets[k]);
}
else if(FD_ISSET(sockets[k], &fds_write)) {
/*printf("Socket at port %hi is selectable for w only.VERIFYING\n",
portno[k]);*/
res = send(sockets[k], buf, 0, 0);
if (res < 0 ) {
signal(SIGPIPE, SIG_IGN);
if (o.debugging > 1)
printf("Bad port %hi caught by 0-byte write!\n", portno[k]);
}
else {
if (o.debugging || o.verbose)
printf("Adding TCP port %hi due to successful 0-byte write!\n",
portno[k]);
if (tryident) {
if ( getsockname(sockets[k], (struct sockaddr *) &mysock ,
&sockaddr_in_len ) ) {
perror("getsockname");
exit(1);
}
if (getidentinfoz(target->host, ntohs(mysock.sin_port),portno[k],
owner) == -1)
tryident = 0;
}
addport(&target->ports, portno[k], IPPROTO_TCP, owner);
}
if (max == sockets[k]) max--;
FD_CLR(sockets[k], &fds_write);
deadstack[++deadindex] = k;
current_out--;
portno[k] = 0;
close(sockets[k]);
}
else if ( FD_ISSET(sockets[k], &fds_read) ) {
printf("Socket at port %hi is selectable for r only. This is very wierd.\n", portno[k]);
if (max == sockets[k]) max--;
FD_CLR(sockets[k], &fds_read);
deadstack[++deadindex] = k;
current_out--;
portno[k] = 0;
close(sockets[k]);
}
else { /* neither read nor write selected */
if (time(NULL) - times[k] < o.ptime) {
/*printf("Socket at port %hi not selecting, readding.\n",portno[k]);*/
FD_SET(sockets[k], &fds_write);
FD_SET(sockets[k], &fds_read);
}
else { /* time elapsed */
if (retries[portno[k]] < numretries &&
(portarray[j] || retryindex >= 0)) {
/* don't readd if we are done with all other ports */
if (o.debugging) printf("Initial timeout.\n");
retries[portno[k]]++;
retrystack[++retryindex] = portno[k];
}
else {
if (o.verbose || o.debugging)
printf("Port %d timed out\n", portno[k]);
timeouts++;
if (timeouts > MAX_TIMEOUTS && !target->ports && !o.force) {
if (!o.verbose && !o.debugging && !threshold_warning)
nmap_log("MAX_TIMEOUT threshold (%d) reached, giving up on host %s (%s). Use -N to skip this check. This warning won't be repeated during this session\n", MAX_TIMEOUTS, target->name, inet_ntoa(target->host));
else if (o.verbose || o.debugging)
nmap_log("MAX_TIMEOUT threshold (%d) reached, giving up on host %s (%s). Use -N to skip this check.\n", MAX_TIMEOUTS, target->name, inet_ntoa(target->host));
threshold_warning++;
for(k=0; k < o.max_sockets; k++)
if (portno[k])
close(sockets[k]);
return NULL;
}
}
if (max == sockets[k]) max--;
FD_CLR(sockets[k], &fds_write);
FD_CLR(sockets[k], &fds_read);
deadstack[++deadindex] = k;
current_out--;
portno[k] = 0;
close(sockets[k]);
}
}
}
longwait.tv_sec = timeout;
longwait.tv_usec = 0;
}
/* If we can't send anymore packets (because full or out of ports) */
if (current_out == o.max_sockets || (!portarray[j] && retryindex < 0)) {
int z;
seconds2 = time(NULL);
for(z=0; z < o.max_sockets; z++) {
if (portno[z] && seconds2 - times[z] >= o.ptime) { /* Timed out, dr0p it */
if (retries[portno[z]] < numretries &&
(portarray[j] || retryindex >= 0)) { /* don't re-add if we
are done with all other
ports */
if (o.debugging) printf("Initial timeout.\n");
retries[portno[z]]++;
retrystack[++retryindex] = portno[z];
}
else {
if (o.debugging)
printf("Port %d timed out\n", portno[z]);
timeouts++;
if (timeouts > MAX_TIMEOUTS && !target->ports && !o.force) {
if (!o.verbose && !o.debugging && !threshold_warning)
nmap_log("MAX_TIMEOUT threshold (%d) reached, giving up on host %s (%s). Use -N to skip this check. This warning won't be repeated during this session\n", MAX_TIMEOUTS, target->name, inet_ntoa(target->host));
else if (o.verbose || o.debugging)
nmap_log("MAX_TIMEOUT threshold (%d) reached, giving up on host %s (%s). Use -N to skip this check.\n", MAX_TIMEOUTS, target->name, inet_ntoa(target->host));
threshold_warning++;
for(k=0; k < o.max_sockets; k++)
if (portno[k])
close(sockets[k]);
return NULL;
}
if (max == sockets[z]) max--;
FD_CLR(sockets[z], &fds_write);
FD_CLR(sockets[z], &fds_read);
deadstack[++deadindex] = z;
current_out--;
portno[z] = 0;
close(sockets[z]);
}
}
}
}
}
for(k=0; k < o.max_sockets; k++) {
if (portno[k]) {
printf("Almost missed port %d\n", portno[k]);
close(sockets[k]);
}
}
if (o.debugging || o.verbose)
printf("Scanned %d ports in %ld seconds with %d parallel sockets.\n",
o.numports, (long) time(NULL) - starttime, o.max_sockets);
return target->ports;
}
/* gawd, my next project will be in c++ so I don't have to deal with
this crap ... simple linked list implementation */
int addport(portlist *ports, unsigned short portno, unsigned short protocol,
char *owner) {
struct port *current, *tmp;
int len;
if (*ports) {
current = *ports;
/* case 1: we add to the front of the list */
if (portno <= current->portno) {
if (current->portno == portno && current->proto == protocol) {
if (o.debugging || o.verbose)
printf("Duplicate port (%hi/%s)\n", portno ,
(protocol == IPPROTO_TCP)? "tcp": "udp");
return -1;
}
tmp = current;
*ports = safe_malloc(sizeof(struct port));
(*ports)->next = tmp;
current = *ports;
current->portno = portno;
current->proto = protocol;
if (owner && *owner) {
len = strlen(owner);
current->owner = malloc(sizeof(char) * (len + 1));
strncpy(current->owner, owner, len + 1);
}
else current->owner = NULL;
}
else { /* case 2: we add somewhere in the middle or end of the list */
while( current->next && current->next->portno < portno)
current = current->next;
if (current->next && current->next->portno == portno
&& current->next->proto == protocol) {
if (o.debugging || o.verbose)
printf("Duplicate port (%hi/%s)\n", portno ,
(protocol == IPPROTO_TCP)? "tcp": "udp");
return -1;
}
tmp = current->next;
current->next = safe_malloc(sizeof(struct port));
current->next->next = tmp;
tmp = current->next;
tmp->portno = portno;
tmp->proto = protocol;
if (owner && *owner) {
len = strlen(owner);
tmp->owner = malloc(sizeof(char) * (len + 1));
strncpy(tmp->owner, owner, len + 1);
}
else tmp->owner = NULL;
}
}
else { /* Case 3, list is null */
*ports = safe_malloc(sizeof(struct port));
tmp = *ports;
tmp->portno = portno;
tmp->proto = protocol;
if (owner && *owner) {
len = strlen(owner);
tmp->owner = safe_malloc(sizeof(char) * (len + 1));
strncpy(tmp->owner, owner, len + 1);
}
else tmp->owner = NULL;
tmp->next = NULL;
}
return 0; /*success */
}
int deleteport(portlist *ports, unsigned short portno,
unsigned short protocol) {
portlist current, tmp;
if (!*ports) {
if (o.debugging > 1) error("Tried to delete from empty port list!");
return -1;
}
/* Case 1, deletion from front of list*/
if ((*ports)->portno == portno && (*ports)->proto == protocol) {
tmp = (*ports)->next;
if ((*ports)->owner) free((*ports)->owner);
free(*ports);
*ports = tmp;
}
else {
current = *ports;
for(;current->next && (current->next->portno != portno || current->next->proto != protocol); current = current->next);
if (!current->next)
return -1;
tmp = current->next;
current->next = tmp->next;
if (tmp->owner) free(tmp->owner);
free(tmp);
}
return 0; /* success */
}
void printandfreeports(portlist ports) {
char protocol[4];
struct servent *service;
port *current = ports, *tmp;
nmap_log("Port Number Protocol Service");
nmap_log("%s", (o.identscan)?" Owner\n":"\n");
while(current != NULL) {
strcpy(protocol,(current->proto == IPPROTO_TCP)? "tcp": "udp");
service = getservbyport(htons(current->portno), protocol);
nmap_log("%-13d%-11s%-16s%s\n", current->portno, protocol,
(service)? service->s_name: "unknown",
(current->owner)? current->owner : "");
tmp = current;
current = current->next;
if (tmp->owner) free(tmp->owner);
free(tmp);
}
nmap_log("\n");
}
/* This is the version of udp_scan that uses raw ICMP sockets and requires
root priviliges.*/
portlist udp_scan(struct hoststruct *target, unsigned short *portarray) {
int icmpsock, udpsock, tmp, done=0, retries, bytes = 0, res, num_out = 0;
int i=0,j=0, k=0, icmperrlimittime, max_tries = UDP_MAX_PORT_RETRIES;
unsigned short outports[MAX_SOCKETS_ALLOWED];
unsigned short numtries[MAX_SOCKETS_ALLOWED];
struct sockaddr_in her;
char senddata[] = "blah\n";
unsigned long starttime, sleeptime;
struct timeval shortwait = {1, 0 };
fd_set fds_read, fds_write;
bzero( (char *) outports, o.max_sockets * sizeof(unsigned short));
bzero( (char *) numtries, o.max_sockets * sizeof(unsigned short));
/* Some systems (like linux) follow the advice of rfc1812 and limit
* the rate at which they will respons with icmp error messages
* (like port unreachable). icmperrlimittime is to compensate for that.
*/
icmperrlimittime = 60000;
sleeptime = (target->rtt)? ( target->rtt) + 30000 : 1e5;
if (o.wait) icmperrlimittime = o.wait;
starttime = time(NULL);
FD_ZERO(&fds_read);
FD_ZERO(&fds_write);
if (o.verbose || o.debugging)
printf("Initiating UDP (raw ICMP version) scan against %s (%s) using wait delay of %li usecs.\n", target->name, inet_ntoa(target->host), sleeptime);
if ((icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
perror("Opening ICMP RAW socket");
if ((udpsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
perror("Opening datagram socket");
unblock_socket(icmpsock);
her.sin_addr = target->host;
her.sin_family = AF_INET;
while(!done) {
tmp = num_out;
for(i=0; (i < o.max_sockets && portarray[j]) || i < tmp; i++) {
close(udpsock);
if ((udpsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
perror("Opening datagram socket");
if ((i > tmp && portarray[j]) || numtries[i] > 1) {
if (i > tmp) her.sin_port = htons(portarray[j++]);
else her.sin_port = htons(outports[i]);
FD_SET(udpsock, &fds_write);
FD_SET(icmpsock, &fds_read);
shortwait.tv_sec = 1; shortwait.tv_usec = 0;
usleep(icmperrlimittime);
res = select(udpsock + 1, NULL, &fds_write, NULL, &shortwait);
if (FD_ISSET(udpsock, &fds_write))
bytes = sendto(udpsock, senddata, sizeof(senddata), 0,
(struct sockaddr *) &her, sizeof(struct sockaddr_in));
else {
printf("udpsock not set for writing port %d!", ntohs(her.sin_port));
return target->ports;
}
if (bytes <= 0) {
if (errno == ECONNREFUSED) {
retries = 10;
do {
/* This is from when I was using the same socket and would
* (rather often) get strange connection refused errors, it
* shouldn't happen now that I create a new udp socket for each
* port. At some point I will probably go back to 1 socket again.
*/
printf("sendto said connection refused on port %d but trying again anyway.\n", ntohs(her.sin_port));
usleep(icmperrlimittime);
bytes = sendto(udpsock, senddata, sizeof(senddata), 0,
(struct sockaddr *) &her, sizeof(struct sockaddr_in));
printf("This time it returned %d\n", bytes);
} while(bytes <= 0 && retries-- > 0);
}
if (bytes <= 0) {
printf("sendto returned %d.", bytes);
fflush(stdout);
perror("sendto");
}
}
if (bytes > 0 && i > tmp) {
num_out++;
outports[i] = portarray[j-1];
}
}
}
usleep(sleeptime);
tmp = listen_icmp(icmpsock, outports, numtries, &num_out, target->host, &target->ports);
if (o.debugging) printf("listen_icmp caught %d bad ports.\n", tmp);
done = !portarray[j];
for (i=0,k=0; i < o.max_sockets; i++)
if (outports[i]) {
if (++numtries[i] > max_tries - 1) {
if (o.debugging || o.verbose)
printf("Adding port %d for 0 unreachable port generations\n",
outports[i]);
addport(&target->ports, outports[i], IPPROTO_UDP, NULL);
num_out--;
outports[i] = numtries[i] = 0;
}
else {
done = 0;
outports[k] = outports[i];
numtries[k] = numtries[i];
if (k != i)
outports[i] = numtries[i] = 0;
k++;
}
}
if (num_out == o.max_sockets) {
printf("Numout is max sockets, that is a problem!\n");
sleep(1); /* Give some time for responses to trickle back,
and possibly to reset the hosts ICMP error limit */
}
}
if (o.debugging || o.verbose)
printf("The UDP raw ICMP scanned %d ports in %ld seconds with %d parallel sockets.\n", o.numports, time(NULL) - starttime, o.max_sockets);
close(icmpsock);
close(udpsock);
return target->ports;
}
int listen_icmp(int icmpsock, unsigned short outports[],
unsigned short numtries[], int *num_out, struct in_addr target,
portlist *ports) {
char response[1024];
struct sockaddr_in stranger;
int sockaddr_in_size = sizeof(struct sockaddr_in);
struct in_addr bs;
struct ip *ip = (struct ip *)response;
struct ip *ip2;
struct icmp *icmp = (struct icmp *) (response + sizeof(struct ip));
unsigned short *data;
int badport, numcaught=0, bytes, i, tmptry=0, found=0;
while ((bytes = recvfrom(icmpsock, response, 1024, 0,
(struct sockaddr *) &stranger,
&sockaddr_in_size)) > 0) {
numcaught++;
bs.s_addr = ip->ip_src.s_addr;
if (ip->ip_src.s_addr == target.s_addr && ip->ip_p == IPPROTO_ICMP
&& icmp->icmp_type == 3 && icmp->icmp_code == 3) {
ip2 = (struct ip *) (response + 4 * ip->ip_hl + sizeof(struct icmp));
data = (unsigned short *) ((char *)ip2 + 4 * ip2->ip_hl);
badport = ntohs(data[1]);
/*delete it from our outports array */
found = 0;
for(i=0; i < o.max_sockets; i++)
if (outports[i] == badport) {
found = 1;
tmptry = numtries[i];
outports[i] = numtries[i] = 0;
(*num_out)--;
break;
}
if (o.debugging && found && tmptry > 0)
printf("Badport: %d on try number %d\n", badport, tmptry);
if (!found) {
if (o.debugging)
printf("Badport %d came in late, deleting from portlist.\n", badport);
if (deleteport(ports, badport, IPPROTO_UDP) < 0)
if (o.debugging) printf("Port deletion failed.\n");
}
}
else {
if (o.debugging) printf("Caught icmp type %d code %d\n", icmp->icmp_type, icmp->icmp_code);
}
}
return numcaught;
}
/* This fucntion is nonsens. I wrote it all, really optimized etc. Then
found out that many hosts limit the rate at which they send icmp errors :(
I will probably totally rewrite it to be much simpler at some point. For
now I won't worry about it since it isn't a very important functions (UDP
is lame, plus there is already a much better function for people who
are r00t */
portlist lamer_udp_scan(struct hoststruct *target, unsigned short *portarray) {
int sockaddr_in_size = sizeof(struct sockaddr_in),i=0,j=0,k=0, bytes;
int sockets[MAX_SOCKETS_ALLOWED];
int trynum[MAX_SOCKETS_ALLOWED];
unsigned short portno[MAX_SOCKETS_ALLOWED];
int last_open = 0;
char response[1024];
struct sockaddr_in her, stranger;
char data[] = "\nhelp\nquit\n";
unsigned long sleeptime;
unsigned int starttime;
/* Initialize our target sockaddr_in */
bzero((char *) &her, sizeof(struct sockaddr_in));
her.sin_family = AF_INET;
her.sin_addr = target->host;
if (o.wait) sleeptime = o.wait;
else sleeptime = calculate_sleep(target->host) + 60000; /*large to be on the
safe side */
if (o.verbose || o.debugging)
printf("Initiating UDP scan against %s (%s), sleeptime: %li\n", target->name,
inet_ntoa(target->host), sleeptime);
starttime = time(NULL);
for(i = 0 ; i < o.max_sockets; i++)
trynum[i] = portno[i] = 0;
while(portarray[j]) {
for(i=0; i < o.max_sockets && portarray[j]; i++, j++) {
if (i >= last_open) {
if ((sockets[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{perror("datagram socket troubles"); exit(1);}
block_socket(sockets[i]);
portno[i] = portarray[j];
}
her.sin_port = htons(portarray[j]);
bytes = sendto(sockets[i], data, sizeof(data), 0, (struct sockaddr *) &her,
sizeof(struct sockaddr_in));
usleep(5000);
if (o.debugging > 1)
printf("Sent %d bytes on socket %d to port %hi, try number %d.\n",
bytes, sockets[i], portno[i], trynum[i]);
if (bytes < 0 ) {
printf("Sendto returned %d the FIRST TIME!@#$!, errno %d\n", bytes,
errno);
perror("");
trynum[i] = portno[i] = 0;
close(sockets[i]);
}
}
last_open = i;
/* Might need to change this to 1e6 if you are having problems*/
usleep(sleeptime + 5e5);
for(i=0; i < last_open ; i++) {
if (portno[i]) {
unblock_socket(sockets[i]);
if ((bytes = recvfrom(sockets[i], response, 1024, 0,
(struct sockaddr *) &stranger,
&sockaddr_in_size)) == -1)
{
if (o.debugging > 1)
printf("2nd recvfrom on port %d returned %d with errno %d.\n",
portno[i], bytes, errno);
if (errno == EAGAIN /*11*/)
{
if (trynum[i] < 2) trynum[i]++;
else {
if (RISKY_UDP_SCAN) {
printf("Adding port %d after 3 EAGAIN errors.\n", portno[i]);
addport(&target->ports, portno[i], IPPROTO_UDP, NULL);
}
else if (o.debugging)
printf("Skipping possible false positive, port %d\n",
portno[i]);
trynum[i] = portno[i] = 0;
close(sockets[i]);
}
}
else if (errno == ECONNREFUSED /*111*/) {
if (o.debugging > 1)
printf("Closing socket for port %d, ECONNREFUSED received.\n",
portno[i]);
trynum[i] = portno[i] = 0;
close(sockets[i]);
}
else {
printf("Curious recvfrom error (%d) on port %hi: ",
errno, portno[i]);
perror("");
trynum[i] = portno[i] = 0;
close(sockets[i]);
}
}
else /*bytes is positive*/ {
if (o.debugging || o.verbose)
printf("Adding UDP port %d due to positive read!\n", portno[i]);
addport(&target->ports,portno[i], IPPROTO_UDP, NULL);
trynum[i] = portno[i] = 0;
close(sockets[i]);
}
}
}
/* Update last_open, we need to create new sockets.*/
for(i=0, k=0; i < last_open; i++)
if (portno[i]) {
close(sockets[i]);
sockets[k] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* unblock_socket(sockets[k]);*/
portno[k] = portno[i];
trynum[k] = trynum[i];
k++;
}
last_open = k;
for(i=k; i < o.max_sockets; i++)
trynum[i] = sockets[i] = portno[i] = 0;
}
if (o.debugging)
printf("UDP scanned %d ports in %ld seconds with %d parallel sockets\n",
o.numports, (long) time(NULL) - starttime, o.max_sockets);
return target->ports;
}
/* This attempts to calculate the round trip time (rtt) to a host by timing a
connect() to a port which isn't listening. A better approach is to time a
ping (since it is more likely to get through firewalls. This is now
implemented in isup() for users who are root. */
unsigned long calculate_sleep(struct in_addr target) {
struct timeval begin, end;
int sd;
struct sockaddr_in sock;
int res;
if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{perror("Socket troubles"); exit(1);}
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = target.s_addr;
sock.sin_port = htons(MAGIC_PORT);
gettimeofday(&begin, NULL);
if ((res = connect(sd, (struct sockaddr *) &sock,
sizeof(struct sockaddr_in))) != -1)
printf("You might want to change MAGIC_PORT in the include file, it seems to be listening on the target host!\n");
close(sd);
gettimeofday(&end, NULL);
if (end.tv_sec - begin.tv_sec > 5 ) /*uh-oh!*/
return 0;
return (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec);
}
/* Checks whether the identd port (113) is open on the target machine. No
sense wasting time trying it for each good port if it is down! */
int check_ident_port(struct in_addr target) {
int sd;
char buf[4096];
struct sockaddr_in sock;
int res;
struct sockaddr_in stranger;
int sockaddr_in_len = sizeof(struct sockaddr_in);
fd_set fds_read, fds_write;
struct timeval tv;
tv.tv_sec = o.ptime;
tv.tv_usec = 0;
if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{perror("Socket troubles"); exit(1);}
unblock_socket(sd);
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = target.s_addr;
sock.sin_port = htons(113); /*should use getservbyname(3), yeah, yeah */
FD_SET(sd, &fds_read);
FD_SET(sd, &fds_write);
res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
if (res != -1) /* must be scanning localhost, this socket is non-blocking */
goto success;
if (errno == ECONNREFUSED) /* Unlikely in non-blocking, but could happen */
goto failure;
if ((res = select(sd+1, &fds_read, &fds_write, NULL, &tv)) > 0) {
/* Yay, it may be up ... */
if (FD_ISSET(sd, &fds_read) && FD_ISSET(sd, &fds_write)) {
res = recvfrom(sd, buf,4096, 0, (struct sockaddr *) & stranger, &sockaddr_in_len);
if (res >= 0) goto success;
goto failure;
}
else if (FD_ISSET(sd, &fds_write)) {
res = send(sd, buf, 0, 0);
if (res < 0) goto failure;
goto success;
} else if (FD_ISSET(sd, &fds_read)) {
printf("I have never seen this type of socket selectable for read only. Please let me know how you did it and what OS you are running (fyodor@dhp.com).\n");
goto success;
}
else {
printf("Wow, select blatantly lied to us! Please let fyodor know what OS you are running (fyodor@dhp.com).\n");
goto failure;
}
}
failure:
close(sd);
if (o.debugging || o.verbose) printf("identd port not active\n");
return 0;
success:
close(sd);
if (o.debugging || o.verbose) printf("identd port is active\n");
return 1;
}
/* returns 0 for possibly temporary error, -1 means we shouldn't attempt
inetd again on this host */
int getidentinfoz(struct in_addr target, int localport, int remoteport,
char *owner) {
int sd;
struct sockaddr_in sock;
int res;
char request[15];
char response[1024];
char *p,*q;
char *os;
owner[0] = '\0';
if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{perror("Socket troubles"); exit(1);}
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = target.s_addr;
sock.sin_port = htons(113);
usleep(50000); /* If we aren't careful, we really MIGHT take out inetd,
some are very fragile */
res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
if (res < 0 ) {
if (o.debugging || o.verbose)
printf("identd port not active now for some reason ... hope we didn't break it!\n");
close(sd);
return 0;
}
sprintf(request,"%hi,%hi\r\n", remoteport, localport);
if (o.debugging > 1) printf("Connected to identd, sending request: %s", request);
if (write(sd, request, strlen(request) + 1) == -1) {
perror("identd write");
close(sd);
return 0;
}
else if ((res = read(sd, response, 1024)) == -1) {
perror("reading from identd");
close(sd);
return 0;
}
else {
close(sd);
if (o.debugging > 1) printf("Read %d bytes from identd: %s\n", res, response);
if ((p = strchr(response, ':'))) {
p++;
if ((q = strtok(p, " :"))) {
if (!strcasecmp( q, "error")) {
if (strstr(response, "HIDDEN-USER") || strstr(response, "hidden-user")) {
printf("identd returning HIDDEN-USER, giving up on it\n");
return -1;
}
if (o.debugging) printf("ERROR returned from identd for port %d\n", remoteport);
return 0;
}
if ((os = strtok(NULL, " :"))) {
if ((p = strtok(NULL, " :"))) {
if ((q = strchr(p, '\r'))) *q = '\0';
if ((q = strchr(p, '\n'))) *q = '\0';
strncpy(owner, p, 512);
owner[512] = '\0';
}
}
}
}
}
return 1;
}
/* SYN scan, we now use libpcap instead of the non-portable Linux technique
of using recvfrom() to read TCP packets from a RAW socket */
portlist syn_scan(struct hoststruct *target, unsigned short *portarray) {
int i=0, j=0, starttime;
unsigned int bytes;
int sockets[MAX_SOCKETS_ALLOWED];
struct timeval tv,start,end;
unsigned int elapsed_time;
/*char packet[65535];*/
struct ip *ip = NULL; /* = (struct ip *) packet;*/
struct tcphdr *tcp = NULL; /*(struct tcphdr *) (packet + sizeof(struct ip));*/
fd_set fd_read, fd_write;
struct hostent *myhostent = NULL;
char myname[MAXHOSTNAMELEN + 1];
unsigned short magic_port_NBO;
int packets_out;
pcap_t *pd;
struct bpf_program fcode;
char filter[512];
unsigned int localnet, netmask;
char *p = NULL;
char err0r[PCAP_ERRBUF_SIZE];
magic_port_NBO = htons(MAGIC_PORT);
FD_ZERO(&fd_read);
FD_ZERO(&fd_write);
/*if ((received = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) < 0 )
perror("socket troubles in syn_scan");*/
/*if ((received = socket(AF_INET, SOCK_PACKET, htons(ETH_P_IP))) < 0 )
perror("socket troubles in syn_scan");*/
/*unblock_socket(received);*/
/*(max_rcvbuf(received);*/ /* does nothing for linux */
/*FD_SET(received, &fd_read);*/
if (!target->source_ip.s_addr) {
if (gethostname(myname, MAXHOSTNAMELEN) ||
!(myhostent = gethostbyname(myname)))
fatal("Your system is fucked up.\n");
memcpy(&target->source_ip, myhostent->h_addr_list[0], sizeof(struct in_addr));
if (o.debugging || o.verbose)
printf("We skillfully deduced that your address is %s\n",
inet_ntoa(target->source_ip));
}
/* Now for the pcap opening nonsense ... */
/* Note that the snaplen is 92 = 64 byte max IPhdr + 24 byte max link_layer
* header + 4 bytes of TCP port info.
* Also note that we are going into promiscuous mode because Solaris
* apparently requires that for some unknown reason(!). I'd like to
* get out of promisc. if we can figure out the problem.
*/
if (!(pd = pcap_open_live(target->device, 92, (o.spoofsource)? 1 : 0, 1500, err0r)))
fatal("pcap_open_live: %s", err0r);
if (pcap_lookupnet(target->device, &localnet, &netmask, err0r) < 0)
fatal("Failed to lookup device subnet/netmask: %s", err0r);
p = strdup(inet_ntoa(target->host));
#ifdef HAVE_SNPRINTF
snprintf(filter, sizeof(filter), "tcp and src host %s and dst host %s and dst port %d", p, inet_ntoa(target->source_ip), MAGIC_PORT );
#else
sprintf(filter, "tcp and src host %s and dst host %s and dst port %d", p, inet_ntoa(target->source_ip), MAGIC_PORT );
#endif
free(p);
if (o.debugging)
printf("Packet capture filter: %s\n", filter);
if (pcap_compile(pd, &fcode, filter, 0, netmask) < 0)
fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
if (pcap_setfilter(pd, &fcode) < 0 )
fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
starttime = time(NULL);
do {
for(i=0; i < o.max_sockets && portarray[j]; i++) {
if ((sockets[i] = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
perror("socket trobles in syn_scan");
else {
if (o.fragscan)
send_small_fragz(sockets[i], &target->source_ip, &target->host, MAGIC_PORT,
portarray[j++], TH_SYN);
else send_tcp_raw(sockets[i], &target->source_ip , &target->host, MAGIC_PORT,
portarray[j++],0,0,TH_SYN,0,0,0);
usleep(10000);
}
}
gettimeofday(&start, NULL);
packets_out = i;
do {
tv.tv_sec = o.ptime;
tv.tv_usec = 0;
/* FD_SET(received, &fd_read);*/
/* if ((res = select(received + 1, &fd_read, NULL, NULL, &tv)) < 0)
perror("select problems in syn_scan");
else*/ /*if (res > 0)*//* {*/
/* Linux-Specific ... LAME
while ((bytes = recvfrom(received, packet, 65535, 0,
(struct sockaddr *)&from, &fromsize)) > 0 ) {
*/
#ifndef PCAP_TIMEOUT_IGNORED
while (( ip = (struct ip*) readip_pcap(pd, &bytes)))
#else
while(( ip = (struct ip*) readip_pcap_timed(pd, &bytes, 1)))
#endif
{
if (bytes < (4 * ip->ip_hl) + 4)
continue;
tcp = (struct tcphdr *) (((char *)ip) + (4 * ip->ip_hl));
if (ip->ip_src.s_addr == target->host.s_addr && tcp->th_sport != magic_port_NBO
&& tcp->th_dport == magic_port_NBO) {
packets_out--;
if (tcp->th_flags & TH_RST) {
if (o.debugging > 1) printf("Nothing open on port %d\n",
ntohs(tcp->th_sport));
}
else /*if (tcp->th_flags & TH_SYN && tcp->th_flags & TH_ACK)*/ {
if (o.debugging || o.verbose) {
printf("Possible catch on port %d! Here it is:\n",
ntohs(tcp->th_sport));
readtcppacket((char *)ip,1);
}
addport(&target->ports, ntohs(tcp->th_sport), IPPROTO_TCP, NULL);
}
}
}
gettimeofday(&end, NULL);
elapsed_time = (end.tv_sec - start.tv_sec) * 1e6 + end.tv_usec - start.tv_usec;
} while ( packets_out && elapsed_time < 1e6 * (double) o.ptime / 3 );
/*for(i=0; i < o.max_sockets && portarray[j]; i++) close(sockets[i]);*/
for(; i >= 0; i--) close(sockets[i]);
} while (portarray[j]);
if (o.debugging || o.verbose)
printf("The TCP SYN scan took %ld seconds to scan %d ports.\n",
(long) time(NULL) - starttime, o.numports);
/*close(received);*/
pcap_close(pd);
return target->ports;
}
/* We don't exactly need real crypto here (thank god!)\n"*/
int shortfry(unsigned short *ports) {
int num;
unsigned short tmp;
int i;
for(i=0; i < o.numports; i++) {
num = rand() % (o.numports);
tmp = ports[i];
ports[i] = ports[num];
ports[num] = tmp;
}
return 1;
}
/* Much of this is swiped from my send_tcp_raw function above, which
doesn't support fragmentation */
int send_small_fragz(int sd, struct in_addr *source, struct in_addr *victim,
int sport, int dport, int flags) {
struct pseudo_header {
/*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
unsigned long s_addy;
unsigned long d_addr;
char zer0;
unsigned char protocol;
unsigned short length;
};
/*In this placement we get data and some field alignment so we aren't wasting
too much to compute the TCP checksum.*/
char packet[sizeof(struct ip) + sizeof(struct tcphdr) + 100];
struct ip *ip = (struct ip *) packet;
struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
struct pseudo_header *pseudo = (struct pseudo_header *) (packet + sizeof(struct ip) - sizeof(struct pseudo_header));
char *frag2 = packet + sizeof(struct ip) + 16;
struct ip *ip2 = (struct ip *) (frag2 - sizeof(struct ip));
int res;
struct sockaddr_in sock;
int id;
/* It was a tough decision whether to do this here for every packet
or let the calling function deal with it. In the end I grudgingly decided
to do it here and potentially waste a couple microseconds... */
sethdrinclude(sd);
/*Why do we have to fill out this damn thing? This is a raw packet, after all */
sock.sin_family = AF_INET;
sock.sin_port = htons(dport);
sock.sin_addr.s_addr = victim->s_addr;
bzero((char *)packet, sizeof(struct ip) + sizeof(struct tcphdr));
pseudo->s_addy = source->s_addr;
pseudo->d_addr = victim->s_addr;
pseudo->protocol = IPPROTO_TCP;
pseudo->length = htons(sizeof(struct tcphdr));
tcp->th_sport = htons(sport);
tcp->th_dport = htons(dport);
tcp->th_seq = rand() + rand();
tcp->th_off = 5 /*words*/;
tcp->th_flags = flags;
tcp->th_win = htons(2048); /* Who cares */
tcp->th_sum = in_cksum((unsigned short *)pseudo,
sizeof(struct tcphdr) + sizeof(struct pseudo_header));
/* Now for the ip header of frag1 */
bzero((char *) packet, sizeof(struct ip));
ip->ip_v = 4;
ip->ip_hl = 5;
/*RFC 791 allows 8 octet frags, but I get "operation not permitted" (EPERM)
when I try that. */
ip->ip_len = BSDFIX(sizeof(struct ip) + 16);
id = ip->ip_id = rand();
ip->ip_off = BSDFIX(MORE_FRAGMENTS);
ip->ip_ttl = 255;
ip->ip_p = IPPROTO_TCP;
ip->ip_src.s_addr = source->s_addr;
ip->ip_dst.s_addr = victim->s_addr;
#if HAVE_IP_IP_SUM
ip->ip_sum= in_cksum((unsigned short *)ip, sizeof(struct ip));
#endif
if (o.debugging > 1) {
printf("Raw TCP packet fragment #1 creation completed! Here it is:\n");
hdump(packet,20);
}
if (o.debugging > 1)
printf("\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n",
sd, ntohs(ip->ip_len), inet_ntoa(*victim),
(int) sizeof(struct sockaddr_in));
/* Lets save this and send it AFTER we send the second one, just to be
cute ;) */
if ((res = sendto(sd, packet,sizeof(struct ip) + 16 , 0,
(struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)
{
perror("sendto in send_syn_fragz");
return -1;
}
if (o.debugging > 1) printf("successfully sent %d bytes of raw_tcp!\n", res);
/* Create the second fragment */
bzero((char *) ip2, sizeof(struct ip));
ip2->ip_v= 4;
ip2->ip_hl = 5;
ip2->ip_len = BSDFIX(sizeof(struct ip) + 4); /* the rest of our TCP packet */
ip2->ip_id = id;
ip2->ip_off = BSDFIX(2);
ip2->ip_ttl = 255;
ip2->ip_p = IPPROTO_TCP;
ip2->ip_src.s_addr = source->s_addr;
ip2->ip_dst.s_addr= victim->s_addr;
#if HAVE_IP_IP_SUM
ip2->ip_sum = in_cksum((unsigned short *)ip2, sizeof(struct ip));
#endif
if (o.debugging > 1) {
printf("Raw TCP packet fragment creation completed! Here it is:\n");
hdump(packet,20);
}
if (o.debugging > 1)
printf("\nTrying sendto(%d , ip2, %d, 0 , %s , %d)\n", sd,
ntohs(ip2->ip_len), inet_ntoa(*victim), (int) sizeof(struct sockaddr_in));
if ((res = sendto(sd, (void *)ip2,sizeof(struct ip) + 4 , 0,
(struct sockaddr *)&sock, (int) sizeof(struct sockaddr_in))) == -1)
{
perror("sendto in send_tcp_raw frag #2");
return -1;
}
return 1;
}
portlist fin_scan(struct hoststruct *target, unsigned short *portarray) {
int rawsd;
int done = 0, badport, starttime, someleft, i, j=0, retries=2;
int waiting_period = retries, sockaddr_in_size = sizeof(struct sockaddr_in);
int dupesinarow = 0;
unsigned bytes;
unsigned long timeout;
struct hostent *myhostent = NULL;
char response[65535], myname[513];
pcap_t *pd;
struct bpf_program fcode;
char filter[512];
unsigned int localnet, netmask;
char *p = NULL;
char err0r[PCAP_ERRBUF_SIZE];
struct ip *ip = NULL; /*(struct ip *) response;*/
struct tcphdr *tcp = NULL;
unsigned short portno[MAX_SOCKETS_ALLOWED];
unsigned short trynum[MAX_SOCKETS_ALLOWED];
struct sockaddr_in stranger;
timeout = (target->rtt)? target->rtt + 10000 : 1e5;
bzero(&stranger, sockaddr_in_size);
bzero(portno, o.max_sockets * sizeof(unsigned short));
bzero(trynum, o.max_sockets * sizeof(unsigned short));
starttime = time(NULL);
if (o.debugging || o.verbose)
printf("Initiating FIN stealth scan against %s (%s), sleep delay: %ld useconds\n", target->name, inet_ntoa(target->host), timeout);
if (!target->source_ip.s_addr) {
if (gethostname(myname, MAXHOSTNAMELEN) ||
!(myhostent = gethostbyname(myname)))
fatal("Your system is fucked up.\n");
memcpy(&target->source_ip, myhostent->h_addr_list[0], sizeof(struct in_addr));
if (o.debugging || o.verbose)
printf("We skillfully deduced that your address is %s\n",
inet_ntoa(target->source_ip));
}
/* Now for the pcap opening nonsense ... */
/* Note that the snaplen is 92 = 64 byte max IPhdr + 24 byte max link_layer
* header + 4 bytes of TCP port info.
* Also note that we are going into promiscuous mode because Solaris
* apparently requires that for some unknown reason(!). I'd like to
* get out of promisc. if we can figure out the problem.
*/
if (!(pd = pcap_open_live(target->device, 92, (o.spoofsource)? 1 : 0, 1500, err0r)))
fatal("pcap_open_live: %s", err0r);
if (pcap_lookupnet(target->device, &localnet, &netmask, err0r) < 0)
fatal("Failed to lookup device subnet/netmask: %s", err0r);
p = strdup(inet_ntoa(target->host));
#ifdef HAVE_SNPRINTF
snprintf(filter, sizeof(filter), "tcp and src host %s and dst host %s and dst port %d", p, inet_ntoa(target->source_ip), MAGIC_PORT );
#else
sprintf(filter, "tcp and src host %s and dst host %s and dst port %d", p, inet_ntoa(target->source_ip), MAGIC_PORT );
#endif
free(p);
if (o.debugging)
printf("Packet capture filter: %s\n", filter);
if (pcap_compile(pd, &fcode, filter, 0, netmask) < 0)
fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
if (pcap_setfilter(pd, &fcode) < 0 )
fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
perror("socket trobles in fin_scan");
/*if ((tcpsd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) < 0 )
perror("socket trobles in fin_scan");*/
/*unblock_socket(tcpsd);*/
while(!done) {
for(i=0; i < o.max_sockets; i++) {
if (!portno[i] && portarray[j]) {
portno[i] = portarray[j++];
}
if (portno[i]) {
if (o.fragscan)
send_small_fragz(rawsd, &target->source_ip, &target->host, MAGIC_PORT, portno[i], TH_FIN);
else send_tcp_raw(rawsd, &target->source_ip , &target->host, MAGIC_PORT,
portno[i], 0, 0, TH_FIN, 0, 0, 0);
usleep(10000); /* *WE* normally do not need this, but the target
lamer often does */
}
}
usleep(timeout);
dupesinarow = 0;
/* NOT PORTABLE, USING libpcap INSTEAD */
/*while ((bytes = recvfrom(tcpsd, response, 65535, 0, (struct sockaddr *)
&stranger, &sockaddr_in_size)) > 0) */
#ifndef PCAP_TIMEOUT_IGNORED
while(( ip = (struct ip*) readip_pcap(pd, &bytes)))
#else
while(( ip = (struct ip*) readip_pcap_timed(pd, &bytes, 1)))
#endif
{
if (bytes < (4 * ip->ip_hl) + 4)
continue;
if (ip->ip_src.s_addr == target->host.s_addr) {
tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
if (tcp->th_flags & TH_RST) {
badport = ntohs(tcp->th_sport);
if (o.debugging > 1) printf("Nothing open on port %d\n", badport);
/* delete the port from active scanning */
for(i=0; i < o.max_sockets; i++)
if (portno[i] == badport) {
if (o.debugging && trynum[i] > 0)
printf("Bad port %d caught on fin scan, try number %d\n",
badport, trynum[i] + 1);
trynum[i] = 0;
portno[i] = 0;
break;
}
if (i == o.max_sockets) {
if (o.debugging)
printf("Late packet or dupe, deleting port %d.\n", badport);
dupesinarow++;
if (target->ports) deleteport(&target->ports, badport, IPPROTO_TCP);
}
}
else
if (o.debugging > 1) {
printf("Strange packet from target%d! Here it is:\n",
ntohs(tcp->th_sport));
if (bytes >= 40) readtcppacket(response,1);
else hdump(response,bytes);
}
}
}
/* adjust waiting time if neccessary */
if (dupesinarow > 6) {
if (o.debugging || o.verbose)
printf("Slowing down send frequency due to multiple late packets.\n");
if (timeout < 10 * (target->rtt + 20000)) timeout *= 1.5;
else {
printf("Too many late packets despite send frequency decreases, skipping scan.\n");
return target->ports;
}
}
/* Ok, collect good ports (those that we haven't received responses too
after all our retries */
someleft = 0;
for(i=0; i < o.max_sockets; i++)
if (portno[i]) {
if (++trynum[i] >= retries) {
if (o.verbose || o.debugging)
printf("Good port %d detected by fin_scan!\n", portno[i]);
addport(&target->ports, portno[i], IPPROTO_TCP, NULL);
send_tcp_raw( rawsd, &target->source_ip, &target->host, MAGIC_PORT, portno[i], 0, 0,
TH_FIN, 0, 0, 0);
portno[i] = trynum[i] = 0;
}
else someleft = 1;
}
if (!portarray[j] && (!someleft || --waiting_period <= 0)) done++;
}
if (o.debugging || o.verbose)
printf("The TCP stealth FIN scan took %ld seconds to scan %d ports.\n",
(long) time(NULL) - starttime, o.numports);
/*close(tcpsd);*/
pcap_close(pd);
close(rawsd);
return target->ports;
}
int ftp_anon_connect(struct ftpinfo *ftp) {
int sd;
struct sockaddr_in sock;
int res;
char recvbuf[2048];
char command[512];
if (o.verbose || o.debugging)
printf("Attempting connection to ftp://%s:%s@%s:%i\n", ftp->user, ftp->pass,
ftp->server_name, ftp->port);
if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
perror("Couldn't create ftp_anon_connect socket");
return 0;
}
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = ftp->server.s_addr;
sock.sin_port = htons(ftp->port);
res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
if (res < 0 ) {
printf("Your ftp bounce proxy server won't talk to us!\n");
exit(1);
}
if (o.verbose || o.debugging) printf("Connected:");
while ((res = recvtime(sd, recvbuf, 2048,7)) > 0)
if (o.debugging || o.verbose) {
recvbuf[res] = '\0';
printf("%s", recvbuf);
}
if (res < 0) {
perror("recv problem from ftp bounce server");
exit(1);
}
#ifndef HAVE_SNPRINTF
sprintf(command, "USER %s\r\n", ftp->user);
#else
snprintf(command, 511, "USER %s\r\n", ftp->user);
#endif
send(sd, command, strlen(command), 0);
res = recvtime(sd, recvbuf, 2048,12);
if (res <= 0) {
perror("recv problem from ftp bounce server");
exit(1);
}
recvbuf[res] = '\0';
if (o.debugging) printf("sent username, received: %s", recvbuf);
if (recvbuf[0] == '5') {
printf("Your ftp bounce server doesn't like the username \"%s\"\n",
ftp->user);
exit(1);
}
#ifndef HAVE_SNPRINTF
sprintf(command, "PASS %s\r\n", ftp->pass);
#else
snprintf(command, 511, "PASS %s\r\n", ftp->pass);
#endif
send(sd, command, strlen(command), 0);
res = recvtime(sd, recvbuf, 2048,12);
if (res < 0) {
perror("recv problem from ftp bounce server\n");
exit(1);
}
if (!res) printf("Timeout from bounce server ...");
else {
recvbuf[res] = '\0';
if (o.debugging) printf("sent password, received: %s", recvbuf);
if (recvbuf[0] == '5') {
fprintf(stderr, "Your ftp bounce server refused login combo (%s/%s)\n",
ftp->user, ftp->pass);
exit(1);
}
}
while ((res = recvtime(sd, recvbuf, 2048,2)) > 0)
if (o.debugging) {
recvbuf[res] = '\0';
printf("%s", recvbuf);
}
if (res < 0) {
perror("recv problem from ftp bounce server");
exit(1);
}
if (o.verbose) printf("Login credentials accepted by ftp server!\n");
ftp->sd = sd;
return sd;
}
int recvtime(int sd, char *buf, int len, int seconds) {
int res;
struct timeval timeout;
fd_set readfd;
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
FD_ZERO(&readfd);
FD_SET(sd, &readfd);
res = select(sd + 1, &readfd, NULL, NULL, &timeout);
if (res > 0 ) {
res = recv(sd, buf, len, 0);
if (res >= 0) return res;
perror("recv in recvtime");
return 0;
}
else if (!res) return 0;
perror("select() in recvtime");
return -1;
}
portlist bounce_scan(struct hoststruct *target, unsigned short *portarray,
struct ftpinfo *ftp) {
int starttime, res , sd = ftp->sd, i=0;
char *t = (char *)&target->host;
int retriesleft = FTP_RETRIES;
char recvbuf[2048];
char targetstr[20];
char command[512];
unsigned short portno,p1,p2;
#ifndef HAVE_SNPRINTF
sprintf(targetstr, "%d,%d,%d,%d,", UC(t[0]), UC(t[1]), UC(t[2]), UC(t[3]));
#else
snprintf(targetstr, 20, "%d,%d,%d,%d,", UC(t[0]), UC(t[1]), UC(t[2]), UC(t[3]));
#endif
starttime = time(NULL);
if (o.verbose || o.debugging)
printf("Initiating TCP ftp bounce scan against %s (%s)\n",
target->name, inet_ntoa(target->host));
for(i=0; portarray[i]; i++) {
portno = htons(portarray[i]);
p1 = ((char *) &portno)[0];
p2 = ((char *) &portno)[1];
#ifndef HAVE_SNPRINTF
sprintf(command, "PORT %s%i,%i\r\n", targetstr, p1,p2);
#else
snprintf(command, 512, "PORT %s%i,%i\r\n", targetstr, p1,p2);
#endif
if (o.debugging) printf("Attempting command: %s", command);
if (send(sd, command, strlen(command), 0) < 0 ) {
perror("send in bounce_scan");
if (retriesleft) {
if (o.verbose || o.debugging)
printf("Our ftp proxy server hung up on us! retrying\n");
retriesleft--;
close(sd);
ftp->sd = ftp_anon_connect(ftp);
if (ftp->sd < 0) return target->ports;
sd = ftp->sd;
i--;
}
else {
fprintf(stderr, "Our socket descriptor is dead and we are out of retries. Giving up.\n");
close(sd);
ftp->sd = -1;
return target->ports;
}
} else { /* Our send is good */
res = recvtime(sd, recvbuf, 2048,15);
if (res <= 0) perror("recv problem from ftp bounce server\n");
else { /* our recv is good */
recvbuf[res] = '\0';
if (o.debugging) printf("result of port query on port %i: %s",
portarray[i], recvbuf);
if (recvbuf[0] == '5') {
if (portarray[i] > 1023) {
fprintf(stderr, "Your ftp bounce server sucks, it won't let us feed bogus ports!\n");
exit(1);
}
else {
fprintf(stderr, "Your ftp bounce server doesn't allow priviliged ports, skipping them.\n");
while(portarray[i] && portarray[i] < 1024) i++;
if (!portarray[i]) {
fprintf(stderr, "And you didn't want to scan any unpriviliged ports. Giving up.\n");
/* close(sd);
ftp->sd = -1;
return *ports;*/
/* screw this gentle return crap! This is an emergency! */
exit(1);
}
}
}
else /* Not an error message */
if (send(sd, "LIST\r\n", 6, 0) > 0 ) {
res = recvtime(sd, recvbuf, 2048,12);
if (res <= 0) perror("recv problem from ftp bounce server\n");
else {
recvbuf[res] = '\0';
if (o.debugging) printf("result of LIST: %s", recvbuf);
if (!strncmp(recvbuf, "500", 3)) {
/* fuck, we are not aligned properly */
if (o.verbose || o.debugging)
printf("misalignment detected ... correcting.\n");
res = recvtime(sd, recvbuf, 2048,10);
}
if (recvbuf[0] == '1' || recvbuf[0] == '2') {
if (o.verbose || o.debugging) printf("Port number %i appears good.\n",
portarray[i]);
addport(&target->ports, portarray[i], IPPROTO_TCP, NULL);
if (recvbuf[0] == '1') {
res = recvtime(sd, recvbuf, 2048,5);
recvbuf[res] = '\0';
if (res > 0) {
if (o.debugging) printf("nxt line: %s", recvbuf);
if (recvbuf[0] == '4' && recvbuf[1] == '2' &&
recvbuf[2] == '6') {
deleteport(&target->ports, portarray[i], IPPROTO_TCP);
if (o.debugging || o.verbose)
printf("Changed my mind about port %i\n", portarray[i]);
}
}
}
}
}
}
}
}
}
if (o.debugging || o.verbose)
printf("Scanned %d ports in %ld seconds via the Bounce scan.\n",
o.numports, (long) time(NULL) - starttime);
return target->ports;
}
/* parse a URL stype ftp string of the form user:pass@server:portno */
int parse_bounce(struct ftpinfo *ftp, char *url) {
char *p = url,*q, *s;
if ((q = strrchr(url, '@'))) /*we have username and/or pass */ {
*(q++) = '\0';
if ((s = strchr(q, ':')))
{ /* has portno */
*(s++) = '\0';
strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
ftp->port = atoi(s);
}
else strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
if ((s = strchr(p, ':'))) { /* User AND pass given */
*(s++) = '\0';
strncpy(ftp->user, p, 63);
strncpy(ftp->pass, s, 255);
}
else { /* Username ONLY given */
printf("Assuming %s is a username, and using the default password: %s\n",
p, ftp->pass);
strncpy(ftp->user, p, 63);
}
}
else /* no username or password given */
if ((s = strchr(url, ':'))) { /* portno is given */
*(s++) = '\0';
strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
ftp->port = atoi(s);
}
else /* default case, no username, password, or portnumber */
strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
ftp->user[63] = ftp->pass[255] = ftp->server_name[MAXHOSTNAMELEN] = 0;
return 1;
}
void nmap_log(char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
fflush(stdout);
if (o.logfd && o.logfd != stdout) {
vfprintf(o.logfd, fmt, ap);
}
va_end(ap);
return;
}
void sigdie(int signo) {
switch(signo) {
case SIGINT:
fprintf(stderr, "caught SIGINT signal, cleaning up\n");
break;
case SIGTERM:
fprintf(stderr, "caught SIGTERM signal, cleaning up\n");
break;
case SIGHUP:
fprintf(stderr, "caught SIGHUP signal, cleaning up\n");
break;
case SIGSEGV:
fprintf(stderr, "caught SIGSEGV signal, cleaning up\n");
break;
case SIGBUS:
fprintf(stderr, "caught SIGBUS signal, cleaning up\n");
break;
default:
fprintf(stderr, "caught signal %d, cleaning up\n", signo);
break;
}
fflush(stdout);
if (o.logfd && o.logfd != stdout) fclose(o.logfd);
exit(1);
}
|