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 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903
|
/****************************************************************************
*
* Copyright (C) 2005-2012 Sourcefire, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2 as
* published by the Free Software Foundation. You may not use, modify or
* distribute this program under any other version of the GNU General
* Public License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
****************************************************************************/
/*
sfportobject.c
author: marc norton
date: 11/05/2005
description:
Port objects provides support for generic ports lists comprised of
individual ports, port ranges, and negation of ports and port ranges.
Port lists require a somewhat more complex scheme to determine the proper
grouping of rules for each port while minimizing the number of rule groups
created. We can use a single group of rules in the multi-pattern detection phase,
however that can have a huge impact on performance. Instead we try to create
a smaller grouping of rules that might be applicable to each port.
As rules are defined using port ranges, and port lists there will be port
overlapps between rules. This requires us to determine whether we should
create one larger rule group to apply to all relevant ports, or to
create multiple rule groups and apply the smallest applicable one to
each port. In practice snort has some rules which span almost all 64K ports
which might cause all rules in all port-rule groups to be merged into one set
unless we apply a more complex logic than simply merging rule-port groups
with common ports. This is the problem addressed by the sfportobject
module.
port list examples of acceptable usage:
- var has been overloaded, if it includes _port we add as a port-object also.
var http_ports 80
var http_range_ports 80:81
var http_list_ports [80,8080,8138]
- portvar has been added to indicate portvariables, this form does not require _port
portvar http 80
portvar http_range 80:81
portvar http_list [80,8080,8138]
80
$http
!90
80:81
$http_range
!90:91
[80,8080,8138]
$http_list
[$http,$http_list]
[2001,2008,20022,8100:8150,!8121,!8123]
[!any] - uhhh, why do people ask about this ?
Rules are defined using a port, a port-range or a list of these, we call
these port objects.
As rules are loaded we generate some large rule counts on some ports, and
small rule counts on most ports. If for each port you build a list of
rules on that port, we may end up with some ports with a large rule set that
differs by the addition of a few rules on each port (relative to the group sizes)
we don't want to generate compeletely different rule groups for these as that
would than generate multiple large state machines for the multi-pattern matching
phase of the detection engine which in turn could use a lot of memory.
It turns out that one scheme, the one used herein, provides some blending
of rule groups to minimize memory, and tries to minimize large group sizes
to keep performance more optimal - although this is at the expense of memory.
--- Port variables
Var - has been overloaded. If it's name includes _port as part of the var name it is
added to the PortVarTable.
PortVar - has been added. These are always added to the PortVarTable.
--- Loading Port lists and rules
PortTables - we support src and dst tables for tcp/udp/icmp/ip/arp rules.
PortVar References - we dup the PortVar entries as needed into each table if referenced,
so HTTP_PORTS for tcp and udp contain different rules. If a rule references a PortVar
we look it up in the table, if its not present we dup it from the PortVarTable, otherwise
we just add the rule index to the PortVar HTTP_PORTS in the proper table. If a PortVar
is not used to specify a Port entry in a rule we create a temp port-object, and check if
it's port-list is already in the table. If it's not we make the temp port-object the
permanent entry in the table. If it is, we just add the rule index to the existing entry,
and delete the temp port-object. When the rules are done loading we should have a set of
port-objects with port-lists that differ by at least one port. The next step handles the
cases where we have multiple port-objects with at least one common port.
--- Merging Ports and Rules
We maintain for each port a list of port objects and their rules that apply
to it. This allows us to view combining the rules associated with each port
object using a few heuristics. A list of port objects applicable to each port
presents rules in one of four catagories:
1) a single port object, and all rules associated with it.
2) multiple port objects each with a small set of rules associated with it.
3) one port object with a large rule set, and one or more port objects
with a small set of rules associated with each.
4) multiple port objects with large rule sets, and zero or more port objects
each with a small set of rules associated with it.
We process these four categories as follows:
1) -a single port object (large or small)
do nothing, each port referencing this port object is complete.
2) -multiple small port objects
merge the rules for all port objects into one virtual object,
for each port in this category lookup it's combined port object
to see if it's already defined, if not create one. This way
all ports that have the same port groups point to the same virtual
port object.
3) -one large port object, and one or more small port objects
add the small rule groups into the large rule set, using the existing
port object.
4) -multiple large port objects and zero or more small port objects
merge the large port objects into a virtual port object and
add all rules from both large and small sets into it's rule set.
we use the combined large group ports to form a key, so any ports
referencing just these large rule groups, and some small ones
will be recognized as the same. This handles cases where we have
2,3,4.etc large rule groups combined. Any time we see a 'n' grouping
of the same large rule sets we'll look it up and point to it for that
port.
To determine when a port object has a large rule set or a small one we use
a simple threshold value. In theory the larger this value is the more
merging of rules in category 2 and 3 will occur. When this value is
small category 4 should become a more prevalent situation. However,
the behavior of groupings for a given threshold can change as more rules
are added to port groups. Therefore generous statistics are printed after
the rules and port objects are compiled into their final groupings.
Procedure for using PortLists
1) Process Var's as PortVar's and standard Var's (for now). This allows
existing snort features to work, with the Var's. Add in the PortVar support
to parse the Var input into PortObjects, and add these to the PortVartable.
2) Read Rules
a) Read port numbers and lists
1) Dereference PortVar/Var Names if any are referenced.
b) Create a Port Object
c) Test if this Port object exists already,
1) If so, add the sid to it.
2) If not add it ....
Notes:
All any-any port rules are managed separately, and added in to the final
rules lists of each port group after this analysis. Rules defined with
ranges are no longer considered any-any rules for the purpose of organizing
port-rule groupings. This should help prevent some cross fertilization of
rule groups with rules that are unneccessary, this causes rule group
sizes to bloat and performance to slow.
Hierarchy:
PortTable -> PortObject's
PortVar -> PortObject ( These are pure, and are dup'ed for use in the PortTables )
PortObject -> PortObjectItems (port or port range)
*/
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <ctype.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "sf_types.h"
#include "snort.h"
#include "snort_bounds.h"
#include "snort_debug.h"
#include "sfportobject.h"
#include "sfrim.h"
#include "util.h"
#define PO_EXTRA_RULE_CNT 25
#define PTBL_LRC_DEFAULT 10
#define PO_INIT_ID 1000000
#define PO_HASH_TBL_ROWS 10000
/*
Hash Key Comparisons for treating PortObjects as Keys
return values memcmp style
*/
static
int PortObject_keycmp( const void *a , const void *b, size_t n )
{
n = n;
return !PortObjectEqual( *(PortObject**)a, *(PortObject**)b );
}
/*
* plx_t is a variable sized array of pointers
*/
typedef struct {
int n;
void ** p;
}plx_t;
static
plx_t * plx_new( void * pv_array[], int n )
{
plx_t * p;
int i;
if(!pv_array || n < 0)
return NULL;
p = SnortAlloc(sizeof(plx_t));
p->p = SnortAlloc(n * sizeof(void*));
p->n = n;
for(i=0;i<n;i++)
{
p->p[i] = pv_array[i];
}
return p;
}
static void plx_free(void * p )
{
plx_t * plx=(plx_t*)p;
if( !plx ) return;
if( plx->p ) free(plx->p);
free( p );
}
#ifdef DEBUG_MSGS
static
void plx_print(plx_t * p)
{
DEBUG_WRAP(
int i;
DebugMessage(DEBUG_PORTLISTS, "plx-n=%d\n", p->n);
for(i=0;i<p->n;i++)
DebugMessage(DEBUG_PORTLISTS, "plx[%d]=%lu\n", i, p->p[i]);
);
}
#endif
/*
* hash function for plx_t types
*/
static
unsigned plx_hash( SFHASHFCN * p, unsigned char *d, int n )
{
unsigned k, hash = p->seed;
int i;
plx_t* plx;
n = n; /* To silence a Win32 warning */
plx = *(plx_t**)d;
for(i=0;i<plx->n;i++)
{
unsigned char * pc_ptr = (unsigned char*)&plx->p[i];
for(k=0;k<sizeof(void*);k++)
{
hash *= p->scale;
hash += pc_ptr[k];
}
}
return hash ^ p->hardener;
}
/* for sorting an array of pointers */
static inline
int p_keycmp( const void *a , const void *b )
{
if( *(unsigned long**)a < *(unsigned long**)b ) return -1;
if( *(unsigned long**)a > *(unsigned long**)b ) return 1;
return 0; /* they are equal */
}
/*
Hash Key Comparisons for treating plx_t types as Keys
return values memcmp style
this only needs to produce 0 => exact match, otherwise not.
-1, and +1 are not strictly needed, they could both return
a non zero value for the purposes of hashing and searching.
*/
static
int plx_keycmp( const void *a , const void *b, size_t n )
{
int i, cmp;
plx_t * pla = *(plx_t**)a;
plx_t * plb = *(plx_t**)b;
n = n; /* To silence a Win32 warning */
if( pla->n < plb->n ) return -1;
if( pla->n > plb->n ) return 1;
for(i=0;i<pla->n;i++)
{
if((cmp = p_keycmp(&pla->p[i], &plb->p[i])) != 0)
return cmp;
}
return 0; /* they are equal */
}
/* global for printing so we don't put so many bytes
* on the stack */
static char po_print_buf[MAXPORTS];
/*
PORT OBJECT FUNCTIONS
*/
/*
Create a new PortObject
*/
PortObject * PortObjectNew(void)
{
PortObject *po = (PortObject *)SnortAlloc(sizeof(PortObject));
po->item_list =(SF_LIST*) sflist_new();
if( !po->item_list )
{
free( po );
return 0;
}
po->rule_list =(SF_LIST*) sflist_new();
if( !po->rule_list )
{
sflist_free_all( po->item_list, free );
free( po );
return 0;
}
return po;
}
/* This is the opposite of ntohl/htonl defines, and does the
* swap on big endian hardware */
#ifdef WORDS_BIGENDIAN
#define SWAP_BYTES(a) \
((((uint32_t)(a) & 0xFF000000) >> 24) | \
(((uint32_t)(a) & 0x00FF0000) >> 8) | \
(((uint32_t)(a) & 0x0000FF00) << 8) | \
(((uint32_t)(a) & 0x000000FF) << 24))
#else
#define SWAP_BYTES(a) (a)
#endif
static unsigned po_rule_hash_func(SFHASHFCN *p, unsigned char *k, int n)
{
unsigned char *key;
int ikey = *(int*)k;
/* Since the input is really an int, put the bytes into a normalized
* order so that the hash function returns consistent results across
* on BE & LE hardware. */
ikey = SWAP_BYTES(ikey);
/* Set a pointer to the key to pass to the hashing function */
key = (unsigned char *)&ikey;
return sfhashfcn_hash(p, key, n);
}
/*
Create a new PortObject2
*/
PortObject2 * PortObject2New(int nrules)
{
PortObject2 *po = (PortObject2 *)SnortAlloc(sizeof(PortObject2));
po->item_list =(SF_LIST*) sflist_new();
if( !po->item_list )
{
free( po );
return 0;
}
po->rule_hash =(SFGHASH*) sfghash_new(nrules,sizeof(int),0,free /* frees data - should be rule id ptrs == (int*) */);
if( !po->rule_hash )
{
sflist_free_all( po->item_list, free );
free( po );
return 0;
}
/* Use hash function defined above for hashing the key as an int. */
sfghash_set_keyops(po->rule_hash, po_rule_hash_func, memcmp);
//sfhashfcn_static( po->rule_hash->sfhashfcn ); /* TODO: Leave this in, else we get different events */
return po;
}
/*
* Set the name of the Port Object
*/
int PortObjectSetName(PortObject * po, char * name)
{
if( !po )
return -1;
if( !name )
return -1;
/* free the old name */
if(po->name)
free(po->name);
/* alloc a new name */
po->name = SnortStrdup(name);
if( !po->name )
return -1;
return 0;
}
/*
* Free a PortObjectItem
*/
void PortObjectItemFree (PortObjectItem * poi)
{
if(poi) free(poi);
}
/*
* Free the PortObject
*/
void PortObjectFree( void * pvoid )
{
PortObject * po = (PortObject *)pvoid;
DEBUG_WRAP(static int pof_cnt = 0; pof_cnt++;);
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"PortObjectFree-Cnt: %d ptr=%p\n",pof_cnt,pvoid););
if( !po ) return ;
if( po->name ) free (po->name );
if( po->item_list) sflist_free_all( po->item_list, free );
if( po->rule_list) sflist_free_all( po->rule_list, free );
if (po->data && po->data_free)
{
po->data_free(po->data);
}
free( po );
}
/*
* Free the PortObject2
*/
void PortObject2Free( void * pvoid )
{
PortObject2 * po = (PortObject2 *)pvoid;
DEBUG_WRAP(static int pof2_cnt = 0; pof2_cnt++;);
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"PortObjectFree2-Cnt: %d ptr=%p\n",pof2_cnt,pvoid););
if( !po ) return;
if( po->name ) free (po->name );
if( po->item_list) sflist_free_all( po->item_list, free );
if( po->rule_hash) sfghash_delete( po->rule_hash );
if (po->bitop)
{
boFreeBITOP(po->bitop);
free(po->bitop);
}
if (po->data && po->data_free)
{
po->data_free(po->data);
}
free( po );
}
/*
* Create a new PortObjectItem
*/
PortObjectItem * PortObjectItemNew(void)
{
PortObjectItem *poi = (PortObjectItem *)SnortAlloc(sizeof(PortObjectItem));
return poi;
}
/*
* Add a PortObjectItem to a PortObject
*/
int PortObjectAddItem( PortObject * po, PortObjectItem * poi, int *errflag)
{
PortObjectItem *p;
SF_LNODE *pos = NULL;
if(!po || !poi) return 0;
if(errflag) *errflag = 0;
/* Make sure this is not a duplicate */
for(p=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
p != 0;
p=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
if((p->lport == poi->lport) && (p->hport == poi->hport))
{
if(errflag) *errflag = POPERR_DUPLICATE_ENTRY;
return -1; /* -1 chosen for consistency with sflist_add_tail */
}
}
return sflist_add_tail( po->item_list, poi );
}
/*
* Add a PortObjectItem to a PortObject
*/
int PortObjectAddPortObject(PortObject * podst, PortObject * posrc, int *errflag)
{
PortObjectItem *po;
SF_LNODE *pos = NULL;
int ret = 0;
if(errflag) *errflag = 0;
for(po=(PortObjectItem*)sflist_firstpos(posrc->item_list, &pos);
po != 0;
po=(PortObjectItem*)sflist_nextpos(posrc->item_list, &pos) )
{
PortObjectItem *poi = PortObjectItemDup(po);
if((ret = PortObjectAddItem(podst, poi, errflag)) != 0)
return ret;
}
return ret;
}
/*
Dup a PortObjectItem
*/
PortObjectItem * PortObjectItemDup( PortObjectItem * poi)
{
PortObjectItem * poinew;
if( !poi )
return 0;
poinew = PortObjectItemNew();
if( !poinew )
return 0;
memcpy(poinew,poi,sizeof(PortObjectItem));
return poinew;
}
/*
* Dup the PortObjects Item List, RuleList, and Name
*/
PortObject * PortObjectDup( PortObject * po )
{
PortObject * ponew = NULL;
PortObjectItem * poi = NULL;
PortObjectItem * poinew = NULL;
SF_LNODE * lpos = NULL;
int * prid = NULL;
int * prule = NULL;
ponew = PortObjectNew();
if( !ponew )
return 0;
/* Dup the Name */
if( po->name )
ponew->name = strdup(po->name);
else
ponew->name = strdup("dup");
if( !ponew->name )
{
free( ponew );
return NULL;
}
/* Dup the Item List */
if( po->item_list )
{
for(poi =(PortObjectItem*)sflist_firstpos(po->item_list,&lpos);
poi != NULL;
poi =(PortObjectItem*)sflist_nextpos(po->item_list,&lpos) )
{
poinew = PortObjectItemDup( poi );
if(!poinew)
{
free( ponew->name );
free( ponew );
return 0;
}
PortObjectAddItem( ponew, poinew, NULL );
}
}
/* Dup the input rule list */
if( po->rule_list )
{
for(prid = (int*)sflist_firstpos(po->rule_list,&lpos);
prid != 0;
prid = (int*)sflist_nextpos(po->rule_list,&lpos) )
{
prule = calloc(1,sizeof(int));
if(!prule)
{
free( poinew );
free( ponew->name );
free( ponew );
return NULL;
}
*prule = *prid;
sflist_add_tail(ponew->rule_list,prule);
}
}
return ponew;
}
/*
* Dup the PortObjects Item List, and Name
*/
PortObject * PortObjectDupPorts( PortObject * po )
{
PortObject * ponew = NULL;
PortObjectItem * poi = NULL;
PortObjectItem * poinew = NULL;
SF_LNODE * lpos = NULL;
ponew = PortObjectNew();
if( !ponew )
return 0;
/* Dup the Name */
if( po->name )
ponew->name = strdup(po->name);
else
ponew->name = strdup("dup");
if( !ponew->name )
{
free( ponew );
return NULL;
}
/* Dup the Item List */
if( po->item_list )
{
for(poi =(PortObjectItem*)sflist_firstpos(po->item_list,&lpos);
poi != NULL;
poi =(PortObjectItem*)sflist_nextpos(po->item_list,&lpos) )
{
poinew = PortObjectItemDup( poi );
if(!poinew)
return 0;
PortObjectAddItem( ponew, poinew, NULL );
}
}
return ponew;
}
/*
* Dup the PortObjects Item List, Name, and RuleList->RuleHash
*/
PortObject2 * PortObject2Dup( PortObject * po )
{
PortObject2 * ponew = NULL;
PortObjectItem * poi = NULL;
PortObjectItem * poinew = NULL;
SF_LNODE * lpos = NULL;
int * prid = NULL;
int * prule = NULL;
if( !po )
return NULL;
if( !po->rule_list )
return NULL;
ponew = PortObject2New(po->rule_list->count + PO_EXTRA_RULE_CNT);
if( !ponew )
return NULL;
/* Dup the Name */
if( po->name )
ponew->name = strdup(po->name);
else
ponew->name = strdup("dup");
if( !ponew->name )
{
free( ponew );
return NULL;
}
/* Dup the Item List */
if( po->item_list )
{
for(poi =(PortObjectItem*)sflist_firstpos(po->item_list,&lpos);
poi != NULL;
poi =(PortObjectItem*)sflist_nextpos(po->item_list,&lpos) )
{
poinew = PortObjectItemDup( poi );
if(!poinew)
return 0;
PortObjectAddItem( (PortObject*)ponew, poinew, NULL );
}
}
/* Dup the input rule list */
if( po->rule_list )
{
for(prid = (int*)sflist_firstpos(po->rule_list,&lpos);
prid != 0;
prid = (int*)sflist_nextpos(po->rule_list,&lpos) )
{
prule = calloc(1,sizeof(int));
if(!prule)
{
return NULL;
}
*prule = *prid;
if( sfghash_add( ponew->rule_hash, prule, prule ) != SFGHASH_OK )
{
free( prule );
}
}
}
return ponew;
}
/*
Add a Port to a PortObject
*/
int PortObjectAddPort( PortObject * po, int port, int not_flag )
{
PortObjectItem * poi;
poi = PortObjectItemNew();
if( !poi )
return -1;
poi->type = PORT_OBJECT_PORT;
if( not_flag )
poi->flags = PORT_OBJECT_NOT_FLAG;
poi->lport = (unsigned short)port;
poi->hport = (unsigned short)port;
return sflist_add_tail( po->item_list, poi );
}
/*
Add a Port Range to a PortObject
*/
int PortObjectAddRange( PortObject * po, int lport, int hport, int not_flag )
{
PortObjectItem * poi;
poi = PortObjectItemNew();
if( !poi )
return -1;
poi->type = PORT_OBJECT_RANGE;
if( not_flag )
poi->flags = PORT_OBJECT_NOT_FLAG;
poi->lport = (unsigned short)lport;
poi->hport = (unsigned short)hport;
return sflist_add_tail( po->item_list, poi );
}
/*
Add ANY port
*/
int PortObjectAddPortAny( PortObject * po )
{
PortObjectItem * poi;
if(!po)
return -1 ;
poi = PortObjectItemNew();
if( !poi )
return -1;
poi->type = PORT_OBJECT_ANY;
poi->lport = 0;
poi->hport = MAXPORTS-1;
if(!po->name)
po->name = strdup("any");
if(!po->name)
{
free(poi);
return -1;
}
return sflist_add_tail( po->item_list, poi );
}
/*
* Check if we have any ANY ports
*/
int PortObjectHasAny (PortObject * po )
{
PortObjectItem *poi;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
if( poi->type == PORT_OBJECT_ANY )
return 1;
}
return 0;
}
int PortObjectHasNot (PortObject * po )
{
PortObjectItem *poi;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
if ( poi->flags== PORT_OBJECT_NOT_FLAG) return 1;
}
return 0;
}
int PortObjectIsPureNot (PortObject * po )
{
PortObjectItem *poi;
int cnt=0;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
cnt++;
if ( poi->flags != PORT_OBJECT_NOT_FLAG)
return 0;
}
if( cnt == 0 ) return 0;
return 1;
}
/*
* This does NOT return true if the object is an ANY port
*/
int PortObjectHasPort (PortObject * po, int port )
{
PortObjectItem *poi;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
switch( poi->type )
{
case PORT_OBJECT_ANY:
return 0;
case PORT_OBJECT_PORT:
if( poi->lport == (uint16_t)(port&0xffff) )
return 1;
if( poi->flags & PORT_OBJECT_NOT_FLAG )
return 1;
break;
case PORT_OBJECT_RANGE:
if( (uint16_t)port >= poi->lport &&
(uint16_t)port <= poi->hport )
return 1;
if( poi->flags & PORT_OBJECT_NOT_FLAG )
return 1;
break;
}
}
return 0;
}
/*
* This returns true if the object is an ANY port
*/
int PortObjectIncludesPort (PortObject * po, int port )
{
PortObjectItem *poi;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
switch( poi->type )
{
case PORT_OBJECT_ANY:
return 1;
case PORT_OBJECT_PORT:
if( poi->lport == (uint16_t)port )
return 1;
if( poi->flags & PORT_OBJECT_NOT_FLAG )
return 1;
break;
case PORT_OBJECT_RANGE:
if( (uint16_t)port >= poi->lport &&
(uint16_t)port <= poi->hport )
return 1;
if( poi->flags & PORT_OBJECT_NOT_FLAG )
return 1;
break;
}
}
return 0;
}
/*
* Locate a PortObject by Port number , this only locates the 1st one
* This was a hack fro testing....
*/
PortObject * PortTableFindPortObjectByPort( PortTable * p , int port )
{
PortObject * po;
SF_LNODE * pos;
for(po =(PortObject*)sflist_firstpos(p->pt_polist,&pos);
po != NULL;
po =(PortObject*)sflist_nextpos(p->pt_polist,&pos) )
{
if( PortObjectHasPort ( po, port ) )
{
return po;
}
}
return 0;
}
/*
* Calcs number of ports in this object,
* object do not have to be normalized,
* but if the same ports are referenced
* twice, the count will be off.
*
* returns:
* any = -1
* 0 = none/empty
* >0 = number of ports
*/
int PortObjectPortCount (PortObject * po )
{
PortObjectItem *poi;
int cnt=0;
int nports;
if( !po )
return 0;
for(poi=(PortObjectItem*)sflist_first(po->item_list);
poi != 0;
poi=(PortObjectItem*)sflist_next(po->item_list) )
{
switch( poi->type )
{
case PORT_OBJECT_ANY:
return -1;
case PORT_OBJECT_PORT:
if( poi->flags & PORT_OBJECT_NOT_FLAG )
{
cnt--;
}
else
{
cnt++;
}
break;
case PORT_OBJECT_RANGE:
nports = poi->hport - poi->lport + 1;
if( poi->flags & PORT_OBJECT_NOT_FLAG )
{
cnt-=nports;
}
else
{
cnt+=nports;
}
}
}
if( cnt < 0 )
{
/* we have a pure not port or port range
*
* !80 = -1, add 64K (65535 -1 = 65534)
* !80:81 = -2, (65535 - 2 = 65533)
*
* [:1023,!80] = 1024 - 1 = 1023 ports
*
*/
cnt += SFPO_MAX_PORTS; /* add back in the acceptable ports */
}
return cnt;
}
/*
* Build a PortMap Char Array
* returns: 0 if an ANY port.
* n number of unique ports.
*/
char * PortObjectCharPortArray ( char * parray, PortObject * po, int * nports )
{
int cnt = 0;
unsigned not_cnt=0;
PortObjectItem * poi;
SF_LNODE * pos;
if( !po || PortObjectHasAny ( po ) )
{
return 0; /* ANY =64K */
}
if( !parray )
{
parray = (char*) calloc(1,SFPO_MAX_PORTS);
if( !parray )
return 0;
}
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
/* Add ports that are not NOT'd */
if( poi->flags & PORT_OBJECT_NOT_FLAG )
{
not_cnt++;
continue;
}
if( poi->type == PORT_OBJECT_PORT )
{
if( !parray[poi->lport] )
cnt++;
parray[poi->lport] = 1;
}
else if( poi->type == PORT_OBJECT_RANGE )
{
int i;
for(i=poi->lport;i<=poi->hport;i++)
{
if( !parray[i] )
cnt++;
parray[i] = 1;
}
}
}
/* Remove any NOT'd ports that may have been added above */
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
if( !( poi->flags & PORT_OBJECT_NOT_FLAG) )
continue;
if( poi->type == PORT_OBJECT_PORT )
{
if( parray[poi->lport] )
cnt--;
parray[poi->lport] =0;
}
else if( poi->type == PORT_OBJECT_RANGE )
{
int i;
for(i=poi->lport;i<=poi->hport;i++)
{
if( parray[i] )
cnt--;
parray[i] = 0;
}
}
}
/* A pure Not list */
if( po->item_list->count == not_cnt )
{
int i;
/* enable all of the ports */
for(i=0;i<SFPO_MAX_PORTS;i++)
{
parray[i] =1;
cnt++;
}
/* disable the NOT'd ports */
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
if( !( poi->flags & PORT_OBJECT_NOT_FLAG) )
continue; /* should not happen */
if( poi->type == PORT_OBJECT_PORT )
{
if( parray[poi->lport] )
cnt--;
parray[poi->lport] =0;
}
else if( poi->type == PORT_OBJECT_RANGE )
{
int k;
for(k=poi->lport;k<=poi->hport;k++)
{
if( parray[k] )
cnt--;
parray[k] = 0;
}
}
}
}
*nports = cnt;
return parray;
}
/*
* Make a list of ports form the char array, each char is either
* on or off.
*/
static
SF_LIST * PortObjectItemListFromCharPortArray( char * parray, int n )
{
int i, lport ,hport;
SF_LIST * plist;
PortObjectItem * poi;
plist = sflist_new();
if( !plist )
return 0;
for(i=0;i<n;i++)
{
if( parray[i] == 0 ) continue;
/* Either a port or the start of a range */
lport = hport = i;
for(i++;i<n;i++)
{
if( parray[i] )
{
hport = i;
continue;
}
break;
}
poi = PortObjectItemNew();
if( !poi )
{
sflist_free_all(plist,free);
return 0;
}
if( hport == lport )
{
poi->type = PORT_OBJECT_PORT;
poi->lport = (unsigned short)lport;
}
else
{
poi->type = PORT_OBJECT_RANGE;
poi->lport =(unsigned short)lport;
poi->hport =(unsigned short)hport;
}
if( sflist_add_tail( plist, poi ) )
{
sflist_free_all( plist, free );
return 0;
}
}
return plist;
}
/*
* Removes Ports in B from A ... A = A - B
*/
int PortObjectRemovePorts( PortObject * a, PortObject * b )
{
int i;
int nportsa;
int nportsb;
SF_LIST * plist;
static char pA[SFPO_MAX_PORTS];
static char pB[SFPO_MAX_PORTS];
memset(pA,0,SFPO_MAX_PORTS);
memset(pB,0,SFPO_MAX_PORTS);
/* Create a char array of ports */
PortObjectCharPortArray ( pA, a, &nportsa );
/* Create a char array of ports */
PortObjectCharPortArray ( pB, b, &nportsb );
for(i=0;i<SFPO_MAX_PORTS;i++)
{
if( pB[i] ) pA[i] = 0; /* remove portB from A */
}
/* Convert the array into a Port Object list */
plist = PortObjectItemListFromCharPortArray( pA, SFPO_MAX_PORTS );
/* Release the old port list */
sflist_free_all( a->item_list, free );
/* Replace the old PortObject list */
a->item_list = plist;
return 0;
}
/*
* Normalize a port object
*
* The reduces multiple references to a given port to a single unique reference
* This function should be used on each PortObject, once it's completed. After
* the normalized PortObject is created, the input PortObject may be deleted.
*/
int PortObjectNormalize (PortObject * po )
{
SF_LIST * plist;
int nports = 0;
static char parray[SFPO_MAX_PORTS];
if( PortObjectHasAny ( po ) )
{
return 0; /* ANY =65K */
}
memset(parray,0,SFPO_MAX_PORTS);
/* Create a char array of ports */
PortObjectCharPortArray ( parray, po, &nports );
/* Convert the array into a Port Object list */
plist = PortObjectItemListFromCharPortArray( parray, SFPO_MAX_PORTS );
if( !plist )
return -1;
/* Release the old port list */
sflist_free_all( po->item_list, free );
/* Replace the old PortObject list */
po->item_list = plist;
return nports;
}
/*
* Negate an entire PortObject
*/
int PortObjectNegate (PortObject * po )
{
int i;
SF_LIST * plist;
int nports = 0;
static char parray[SFPO_MAX_PORTS];
if( PortObjectHasAny ( po ) )
{
return 0; /* ANY =65K */
}
memset(parray,0,SFPO_MAX_PORTS);
/* Create a char array of ports */
PortObjectCharPortArray ( parray, po, &nports );
for(i=0;i<SFPO_MAX_PORTS;i++)
{
if( parray[i] ) /* negate */
parray[i] = 0;
else
parray[i] = 1;
}
/* Convert the array into a Port Object list */
plist = PortObjectItemListFromCharPortArray( parray, SFPO_MAX_PORTS );
/* Release the old port list */
sflist_free_all( po->item_list, free );
/* Replace the old PortObject list */
po->item_list = plist;
return nports;
}
/*
PortObjects should be normalized, prior to testing
*/
static
int PortObjectItemsEqual(PortObjectItem * a, PortObjectItem * b )
{
if( a->type != b->type )
return 0;
switch( a->type )
{
case PORT_OBJECT_ANY:
return 1;
case PORT_OBJECT_PORT:
if( a->lport == b->lport )
return 1;
break;
case PORT_OBJECT_RANGE:
if( a->lport == b->lport && a->hport == b->hport )
return 1;
break;
}
return 0;
}
/*
PortObjects should be normalized, prior to testing
*/
int PortObjectEqual( PortObject * a, PortObject *b )
{
PortObjectItem *pa;
PortObjectItem *pb;
SF_LNODE * posa;
SF_LNODE * posb;
if( a->item_list->count != b->item_list->count )
return 0;
pa = (PortObjectItem*)sflist_firstpos(a->item_list,&posa);
pb = (PortObjectItem*)sflist_firstpos(b->item_list,&posb);
while( pa && pb )
{
if( !PortObjectItemsEqual( pa, pb) )
return 0;
pa = (PortObjectItem*)sflist_nextpos(a->item_list,&posa);
pb = (PortObjectItem*)sflist_nextpos(b->item_list,&posb);
}
if( pa || pb ) /* both are not done - cannot match */
return 0;
return 1; /* match */
}
/*
Dup and Append PortObjectItems from pob to poa
*/
PortObject * PortObjectAppend(PortObject * poa, PortObject * pob )
{
PortObjectItem * poia;
PortObjectItem * poib;
for( poib = (PortObjectItem*) sflist_first(pob->item_list);
poib!= 0;
poib = (PortObjectItem*)sflist_next(pob->item_list) )
{
poia = PortObjectItemNew();
if(!poia)
return 0;
memcpy(poia,poib,sizeof(PortObjectItem));
sflist_add_tail(poa->item_list,poia);
}
return poa;
}
/* Dup and append rule list numbers from pob to poa */
PortObject * PortObjectAppendPortObject(PortObject * poa, PortObject * pob )
{
int * prid;
int * prid2;
SF_LNODE * lpos;
for( prid = (int*) sflist_firstpos(pob->rule_list,&lpos);
prid!= 0;
prid = (int*)sflist_nextpos(pob->rule_list,&lpos) )
{
prid2 = calloc( 1, sizeof(int));
if( !prid2 )
return 0;
*prid2 = *prid;
sflist_add_tail(poa->rule_list,prid2);
}
return poa;
}
/* Dup and append rule list numbers from pob to poa */
PortObject2 * PortObject2AppendPortObject(PortObject2 * poa, PortObject * pob )
{
int * prid;
int * prid2;
SF_LNODE * lpos;
for( prid = (int*) sflist_firstpos(pob->rule_list,&lpos);
prid!= 0;
prid = (int*)sflist_nextpos(pob->rule_list,&lpos) )
{
prid2 = calloc( 1, sizeof(int));
if( !prid2 )
return 0;
*prid2 = *prid;
if( sfghash_add(poa->rule_hash,prid2,prid2) != SFGHASH_OK )
{
free(prid2);
}
}
return poa;
}
/* Dup and append rule list numbers from pob to poa */
PortObject2 * PortObject2AppendPortObject2(PortObject2 * poa, PortObject2 * pob )
{
int * prid;
int * prid2;
SFGHASH_NODE * node;
for( node = sfghash_findfirst(pob->rule_hash);
node!= NULL;
node = sfghash_findnext(pob->rule_hash) )
{
prid = node->data;
if( !prid )
continue;
prid2 = calloc( 1, sizeof(int));
if( !prid2 )
return 0;
*prid2 = *prid;
if( sfghash_add(poa->rule_hash,prid2,prid2) != SFGHASH_OK )
{
free( prid2 );
}
}
return poa;
}
/*
* Append Ports and Rules from pob to poa
*/
PortObject * PortObjectAppendEx(PortObject * poa, PortObject * pob )
{
// LogMessage("PortObjectAppendEx: appending ports\n");
if( !PortObjectAppend( poa, pob ) ) return 0;
//LogMessage("PortObjectAppendEx: appending rules\n");
if( !PortObjectAppendPortObject( poa, pob ) ) return 0;
return poa;
}
/*
* Append Ports and Rules from pob to poa
*/
PortObject2 * PortObjectAppendEx2(PortObject2 * poa, PortObject * pob )
{
// LogMessage("PortObjectAppendEx: appending ports\n");
if( !PortObjectAppend((PortObject*) poa, pob ) ) return 0;
// LogMessage("PortObjectAppendEx: appending rules\n");
if( !PortObject2AppendPortObject( poa, pob ) ) return 0;
return poa;
}
/*
PORT TABLE FUNCTIONS
*/
/*
Create a new table
*/
PortTable * PortTableNew(void)
{
PortTable * p;
p = (PortTable*) calloc(1,sizeof(PortTable));
if(!p)
return 0;
p->pt_polist = sflist_new();
if(!p->pt_polist )
{
free(p);
return 0;
}
p->pt_lrc = PTBL_LRC_DEFAULT; /* 10 rules, user should really control these */
p->pt_optimize = 1; /* if disabled, only one merged rule group is used */
return p;
}
void PortTableFree(PortTable *p)
{
int i;
SFGHASH_NODE *node;
if (!p)
return;
if (p->pt_polist)
{
sflist_free_all(p->pt_polist, PortObjectFree );
}
if (p->pt_mpo_hash)
{
PortObject2 *po;
for (node = sfghash_findfirst(p->pt_mpo_hash);
node;
node = sfghash_findnext(p->pt_mpo_hash))
{
po = node->data;
/* Free the data from this entry */
PortObject2Free(po);
}
sfghash_delete(p->pt_mpo_hash);
}
if (p->pt_plx_list)
{
sflist_free_all(p->pt_plx_list, plx_free);
}
if (p->pt_mpxo_hash)
{
#if 0
PortObject2 *po;
for (node = sfghash_findfirst(p->pt_mpxo_hash);
node;
node = sfghash_findnext(p->pt_mpxo_hash))
{
po = node->data;
/* Free the data from this entry */
//PortObject2Free(po);
}
#endif
sfghash_delete(p->pt_mpxo_hash);
}
for (i=0;i<SFPO_MAX_PORTS;i++)
{
#if 0
if (p->pt_port_object[i])
{
PortObject2Free(p->pt_port_object[i]);
}
#endif
}
free(p);
}
PortObject * PortTableFindInputPortObjectName(PortTable * pt, char * po_name)
{
SF_LNODE * lpos;
PortObject * po;
if( !pt ) return NULL;
if( !po_name ) return NULL;
/* Normalize each of the input port objects */
for(po =(PortObject*)sflist_firstpos(pt->pt_polist,&lpos);
po!=0;
po =(PortObject*)sflist_nextpos(pt->pt_polist,&lpos) )
{
if( po->name )
{
if( strcmp(po->name,po_name)==0 )
{
return po;
}
}
}
return NULL;
}
/*
* Find PortObject by PortItem Info
*/
PortObject * PortTableFindInputPortObjectPorts( PortTable * pt, PortObject * pox )
{
SF_LNODE * lpos;
PortObject * po;
if( !pt ) return NULL;
if( !pox ) return NULL;
for(po =(PortObject*)sflist_firstpos(pt->pt_polist,&lpos);
po!=0;
po =(PortObject*)sflist_nextpos(pt->pt_polist,&lpos) )
{
if( PortObjectEqual( po, pox ) )
{
return po;
}
}
return NULL;
}
int PortTableNormalizeInputPortObjects( PortTable *p )
{
SF_LNODE * lpos;
PortObject * po;
/* Normalize each of the input port objects */
for(po =(PortObject*)sflist_firstpos(p->pt_polist,&lpos);
po!=0;
po =(PortObject*)sflist_nextpos(p->pt_polist,&lpos) )
{
PortObjectNormalize(po);
}
return 0;
}
int PortObjectAddRule( PortObject * po , int rule )
{
int * pruleid;
//LogMessage("Adding Rule %d to Port Object '%s'\n",rule,po->name);
if( !po )
return -1;
if( !po->rule_list )
return -1;
/* Add rule index to rule list */
pruleid = calloc(1,sizeof(int));
if( !pruleid )
{
return -1;
}
*pruleid = rule;
sflist_add_tail( po->rule_list, pruleid );
return 0;
}
/*
Add Users PortObjects to the Table
We save the users port object, so it's no longer the users.
*/
int PortTableAddObject( PortTable *p, PortObject * po )
{
SF_LNODE * lpos;
PortObject * pox;
/* Search for the Port Object in the input list, by address */
for(pox =(PortObject*)sflist_firstpos(p->pt_polist,&lpos);
pox!=0;
pox =(PortObject*)sflist_nextpos(p->pt_polist,&lpos) )
{
if( pox == po )
{
/* already in list - just return */
return 0;
}
}
/* Save the users port object, if not already in the list */
if( sflist_add_tail(p->pt_polist,po) )
return -1;
return 0;
}
/*
Hash routine for hashing PortObjects as Keys
p - SFHASHFCN *
d - PortObject *
n = 4 bytes (sizeof*) - not used
Don't use this for type=ANY port objects
*/
static
unsigned PortObject_hash( SFHASHFCN * p, unsigned char *d, int n )
{
unsigned hash = p->seed;
PortObjectItem * poi;
PortObject * po;
SF_LNODE * pos;
n = n; /* This quiets a Win32 warning */
po = *(PortObject**) d;
/* hash up each item */
for(poi =(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != NULL;
poi =(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
switch(poi->type)
{
case PORT_OBJECT_PORT:
hash *= p->scale;
hash += poi->lport & 0xff;
hash *= p->scale;
hash += (poi->lport >> 8) & 0xff;
break;
case PORT_OBJECT_RANGE:
hash *= p->scale;
hash += poi->lport & 0xff;
hash *= p->scale;
hash += (poi->lport >> 8) & 0xff;
hash *= p->scale;
hash += poi->hport & 0xff;
hash *= p->scale;
hash += (poi->hport >> 8) & 0xff;
break;
}
}
return hash ^ p->hardener;
}
/*
* Merge multiple PortObjects into a final PortObject2,
* this merges ports and rules.
*
* merge po's in pol, find a previous instance add it.
*
* This is done as follows:
* 1) check if it's in the plx table-mhashx, this uses the list of
* addresses of the Input PortObjects as it's key, not the ports.
* This is quick and does not require assembling/merging the port
* objects intoa PortObject2 1st.
* 2) if found were done, otherwise
* 3) make a merged PortObject2
* 4) Try adding the PortObject2 to it's table - mhash
* a) if it adds go on, else
* b) if it's already in the table
* 1) get the one in the table
* 2) add any ports in the just created one
* 3) free the one just created
* 5) Create a plx object
* 6) Add the plx object to the plx Table
* 1) if it's already in the object - fail this contradicts 1)
* 7) return the create PortObject2, or the one retrived from the
* PortObject table.
*
* pol - list of input PortObject pointers
* pol_cnt- count in 'pol'
* mhash - stores the merged ports, using the merged port objects port list as a key.
* mhashx - stores plx keys, and PortObject2 *'s as data for the final merged port objects,
* the plx keys provide a quicker way to compare port lists to ensure if two ports
* are using the same set of rules (port objects).
* mhash and mhashx reference the same port objects as data, but use different keys for lookup
* purposes. Once we perform a merge we store the results, using the 'plx' as the key for future lookup.
* plx - key to use to lookup and store the merged port object
*
*
*/
static
PortObject2 * _merge_N_pol( SFGHASH * mhash, SFGHASH * mhashx,
SF_LIST * plx_list, void ** pol,
int pol_cnt, plx_t * plx )
{
PortObject2 * ponew;
PortObject2 * pox;
plx_t * plx_tmp;
int stat;
int i;
/*
* Check for the merged port object in the plx table
*/
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"++++n=%d sfghash_find-mhashx\n",pol_cnt););
ponew = sfghash_find( mhashx, &plx );
if( ponew )
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"n=%d ponew found in mhashx\n",pol_cnt););
return ponew;
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"n=%d posnew not found in mhashx\n",pol_cnt););
/*
* Merge the port objects together - ports and rules
*/
/* Dup the 1st port objects rules and ports */
ponew = PortObject2Dup( (PortObject *)pol[0] );
if( !ponew )
{
FatalError("Could not Dup2\n");
}
/* Merge in all the other port object rules and ports */
if( pol_cnt > 1 )
{
for(i=1;i<pol_cnt;i++)
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** %d rules in object %d\n",
((PortObject *)pol[i])->rule_list->count,i););
PortObjectAppendEx2( ponew, (PortObject *)pol[i] );
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"*** merged port-object[%d], %d rules\n",
i,ponew->rule_hash->count););
}
PortObjectNormalize( (PortObject*)ponew );
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"*** merged %d port objects, %d rules\n",
pol_cnt,ponew->rule_hash->count););
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** merged ponew - follows: \n"););
// PortObjectPrint2(ponew);
/*
* Add the Merged PortObject2 to the PortObject2 hash table
* keyed by ports.
*/
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"n=%d sfghash_add-mhash\n",pol_cnt););
stat =sfghash_add( mhash, &ponew, ponew );
if( stat != SFGHASH_OK )
{
/* This is possible since PLX hash on a different key */
if( stat == SFGHASH_INTABLE )
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"n=%d sfghash_add-mhash ponew in table\n",pol_cnt););
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"n=%d sfghash_find-mhash ponew\n",pol_cnt););
pox = sfghash_find(mhash,&ponew);
if( pox )
{
PortObject2AppendPortObject2(pox,ponew);
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"sfportobject.c: merge_N_pol() line=%d SFGHASH_INTABLE\n",__LINE__););
PortObject2Free( ponew );
ponew = pox;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"n=%d sfghash_find-mhash ponew found, new rules merged\n",pol_cnt););
}
else
{
FatalError("mhash add/find error n=%d\n", pol_cnt);
}
}
else
{
FatalError("Could not add ponew to hash table- error\n");
}
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***%d ports merged object added to mhash table\n",pol_cnt););
/*
* Create a plx node and add it to plx table
* as the key with the merged port object as the data
*/
plx_tmp = plx_new( pol, pol_cnt);
if(!plx_tmp)
{
FatalError("plx_new: memory alloc error\n");
}
sflist_add_head(plx_list, (void *)plx_tmp);
/*
* Add the plx node to the PLX hash table
*/
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"n=%d sfghash_add-mhashx\n",pol_cnt););
stat = sfghash_add( mhashx, &plx_tmp, ponew );
if( stat != SFGHASH_OK )
{
if( stat == SFGHASH_INTABLE )
{
FatalError("Could not add merged plx to PLX HASH table-INTABLE\n");
}
else
{
FatalError("Could not add merged plx to PLX HASH table\n");
}
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"Added-%d Merged Rule Groups to PLX HASH\n",pol_cnt););
/*
* Validate hash table entry
*/
if( sfghash_find( mhashx, &plx_tmp ) != ponew )
{
FatalError("Find after add failed on PLX HASH table key\n");
}
return ponew;
}
/*
* Merge Input Port Objects into rule collections that are particular to
* each port. We store the results as objects and point to these in the
* pt_port_object[MAX_PORTS] array.
*
* We use plx_t types to manage tracking and testing for merged large
* rule groups, and merged small port groups.
*
* mhash - table of merged port objects ( built and used here )
* mhashx - table of plx_t objects ( built and used here )
* pol - list of input port objects touching the current port
* pol_cnt - number of port objects in port list
* lcnt - large rule count
*
*/
static
PortObject2 * PortTableCompileMergePortObjectList2(SFGHASH * mhash,
SFGHASH * mhashx,
SF_LIST * plx_list,
PortObject * pol[],
int pol_cnt,
unsigned int lcnt )
{
PortObject2 * ponew = NULL;
PortObject2 * posnew = NULL;
static void * polarge[SFPO_MAX_LPORTS];
static void * posmall[SFPO_MAX_LPORTS];
int nlarge = 0;
int nsmall = 0;
plx_t plx_small;
plx_t plx_large;
unsigned largest;
int i;
/*
* Find the largest rule count of all of the port objects
*/
largest = 0;
for(i=0;i<pol_cnt;i++)
{
if( pol[i]->rule_list->count >= (unsigned)lcnt )
{
if( pol[i]->rule_list->count > largest )
largest = pol[i]->rule_list->count;
}
}
/*
* Classify PortObjects as large or small based on rule set size
* and copy them into separate lists
*/
for(i=0;i<pol_cnt;i++)
{
if( pol[i]->rule_list->count >= (unsigned)lcnt )
{
if( nlarge < SFPO_MAX_LPORTS )
polarge[ nlarge++ ] = (void *)pol[i];
}
else
{
if( nsmall < SFPO_MAX_LPORTS )
posmall[ nsmall++ ] = (void *)pol[i];
}
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** %d small rule groups, %d large rule groups\n",nsmall,nlarge););
/*
* Sort the pointers to the input port objects so
* we always get them in the same order for key comparisons
*/
if( nlarge > 1 )
qsort( polarge, nlarge, sizeof(void*), p_keycmp );
if( nsmall > 1 )
qsort( posmall, nsmall, sizeof(void*), p_keycmp );
DEBUG_WRAP(
for(i=0;i<nsmall;i++) DebugMessage(DEBUG_PORTLISTS, "posmall[%d]=%lu\n",i,posmall[i]);
for(i=0;i<nlarge;i++) DebugMessage(DEBUG_PORTLISTS, "polarge[%d]=%lu\n",i,polarge[i]);
);
/*
* Setup plx_t representation of port list pointers
*/
plx_small.n = nsmall;
plx_small.p = (void**)&posmall[0];
plx_large.n = nlarge;
plx_large.p = (void**)&polarge[0];
#ifdef DEBUG_MSGS
if( nlarge )
{
DebugMessage(DEBUG_PORTLISTS, "large "); plx_print(&plx_large);
}
if( nsmall )
{
DebugMessage(DEBUG_PORTLISTS, "small "); plx_print(&plx_small);
}
#endif
/*
* Merge Large PortObjects
*/
if( nlarge )
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***nlarge=%d \n",nlarge););
ponew = _merge_N_pol( mhash, mhashx, plx_list, polarge, nlarge, &plx_large);
}
/*
* Merge Small PortObjects
*/
if( nsmall )
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***nsmall=%d \n",nsmall););
posnew = _merge_N_pol( mhash, mhashx, plx_list, posmall, nsmall, &plx_small);
}
/*
* Merge Large and Small (rule groups) PortObject2's together
* append small port object rule sets to the large port objects,
* remove the large port objects ports from the smaller port objects
*/
if( nlarge && nsmall )
{
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** appending small rules to larger rule group\n"););
if (ponew != posnew)
{
/* Append small port object, just the rules */
PortObject2AppendPortObject2( ponew, posnew );
/* Remove Ports in ponew from posnew */
PortObjectRemovePorts( (PortObject*)posnew, (PortObject*)ponew );
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** final - using small+large rule group \n"););
}
else if( nsmall )
{
/* Only a small port object */
ponew = posnew;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** final - using small rule group only \n"););
}
else if( nlarge )
{
/*
* The large rule group port object is already set to ponew
*/
}
return ponew;
}
/*
*
*
* mhash
* mhashx
data structure used: p->pt_polist
*/
int PortTableCompileMergePortObjects( PortTable * p )
{
SF_LNODE * lpos;
SFGHASH * mhash;
SFGHASH * mhashx;
SFGHASH_NODE * node;
SF_LIST * plx_list;
int id = PO_INIT_ID;
static PortObject * pol[SFPO_MAX_LPORTS]; // TODO: dynamically allocate
int pol_cnt;
char * parray = NULL;
int i;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***\n***Merging PortObjects->PortObjects2\n***\n"););
/* Create a Merged Port Object Table - hash by ports */
mhash = sfghash_new(PO_HASH_TBL_ROWS, sizeof(PortObject *), 0 /*userkeys-no*/, 0 /*free data-don't*/);
if( !mhash )
return -1;
/* Setup hashing function and key comparison function */
sfhashfcn_set_keyops( mhash->sfhashfcn, PortObject_hash, PortObject_keycmp );
/* remove randomness */
if (ScStaticHash())
sfhashfcn_static( mhash->sfhashfcn );
p->pt_mpo_hash = mhash;
/* Create a Merged Port Object Table - hash by ports */
mhashx = sfghash_new(PO_HASH_TBL_ROWS, sizeof(plx_t *), 0/*userkeys-no*/, 0/*freedata()-don't*/);
if( !mhashx )
return -1;
/* Setup hashing function and key comparison function */
sfhashfcn_set_keyops( mhashx->sfhashfcn,plx_hash,plx_keycmp );
/* remove randomness */
if (ScStaticHash())
sfhashfcn_static( mhashx->sfhashfcn );
p->pt_mpxo_hash = mhashx;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***\n*** PortList-Merging, Large Rule groups must have %d rules\n",p->pt_lrc););
plx_list = sflist_new();
sflist_init(plx_list);
p->pt_plx_list = plx_list;
/*
* For each port, merge rules from all port objects that touch the port
* into an optimal object, that may be shared with other ports.
*/
for(i=0;i<SFPO_MAX_PORTS;i++)
{
PortObject * po;
/* Build a list of port objects touching port 'i' */
pol_cnt = 0;
for(po=sflist_firstpos(p->pt_polist,&lpos);
po;
po=sflist_nextpos(p->pt_polist,&lpos) )
{
if( PortObjectHasPort ( po, i ) )
{
if( pol_cnt < SFPO_MAX_LPORTS )
{
pol[ pol_cnt++ ] = po;
}
}
}
p->pt_port_object[i] = 0;
if( !pol_cnt )
{
//port not contained in any PortObject
continue;
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"*** merging list for port[%d] \n",i);fflush(stdout););
/* merge the rules into an optimal port object */
p->pt_port_object[i] =
PortTableCompileMergePortObjectList2( mhash, mhashx, plx_list, pol, pol_cnt, p->pt_lrc );
if( !p->pt_port_object[i] )
{
FatalError(" Could not merge PorObjectList on port %d\n",i);
}
/* give the new compiled port object an id of its own */
p->pt_port_object[i]->id = id++;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"\n");fflush(stdout););
}
/*
* Normalize the Ports so they indicate only the ports that
* reference the composite port object
*/
/* 1st- Setup bitmasks for collecting ports */
for(node=sfghash_findfirst(mhashx);
node;
node=sfghash_findnext(mhashx) )
{
unsigned char * buf;
PortObject2 * poa;
poa = (PortObject2*)node->data;
if( !poa )
continue;
if (!poa->bitop)
{
poa->bitop = calloc(1,sizeof(BITOP));
if( !poa->bitop)
{
FatalError("Memory error in PortTableCompile\n");
}
buf = calloc(1,8192);
if( !buf )
{
FatalError("Memory alloc error in PortObjectCompile()\n");
}
if( boInitStaticBITOP(poa->bitop,8192,buf) )
{
FatalError("BitOp error in PortObjectCompile()\n");
}
}
}
/* Count how many ports each final port-object is used on */
for(i=0;i<SFPO_MAX_PORTS;i++)
{
PortObject2 * poa;
poa = p->pt_port_object[i];
if(poa)
{
poa->port_cnt++;
if( poa->bitop )
{
if( boSetBit(poa->bitop, (unsigned int) i ) )
{
FatalError("BitOp-Set error\n");
}
}
else
{
FatalError("NULL po->bitop in po on port %d\n",i);
}
}
}
/* get a port array 64K bytes */
parray = calloc(1,SFPO_MAX_PORTS);
if(!parray)
{
FatalError("Memory error in PortTableCompile()\n");
}
/* Process Port-Bitop map and print final port-object usage stats */
for(node=sfghash_findfirst(mhashx);
node;
node=sfghash_findnext(mhashx) )
{
SF_LIST * plist;
PortObject2 * po;
po = (PortObject2*)node->data;
if( !po )
{
FatalError("MergePortOBject-NormalizePorts -NULL po\n");
}
if( !po->port_cnt )/* port object is not used ignore it */
continue;
if( !po->bitop )
{
//FatalError("MergePortOBject-NormalizePorts -NULL po->bitop\n");
continue;
}
/* Convert the bitop bits to a char array */
memset(parray,0,SFPO_MAX_PORTS);
for(i=0;i<SFPO_MAX_PORTS;i++)
{
if( boIsBitSet(po->bitop, i ) )
{
parray[ i ] = 1;
}
}
/* Release bit buffer for each port object */
if( po->bitop )
{
//if( po->bitop->pucBitBuffer )
//{
// free( po->bitop->pucBitBuffer );
// po->bitop->pucBitBuffer = NULL;
//}
boFreeBITOP(po->bitop);
free( po->bitop );
po->bitop=NULL;
}
/* Build a PortObjectItem list from the char array */
plist = PortObjectItemListFromCharPortArray( parray, SFPO_MAX_PORTS );
if( !plist )
{
FatalError("MergePortObjects: No PortObjectItems in portobject\n");
}
/* free the original list */
sflist_free_all( po->item_list, free );
/* set the new list - this is a list of port itmes for this port object */
po->item_list = plist;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"port-object id = %d, port cnt = %d\n",po->id,po->port_cnt););
}
if(parray) free(parray);
return 0;
}
/*
*
* Verify all rules in 'po' list are in 'po2' hash
*
* return 0 - OK
* !0 - a rule in po is not in po2
*/
static
int _po2_include_po_rules( PortObject2 * po2, PortObject * po )
{
//SFGHASH_NODE * node;
int * pid;
int * id;
SF_LNODE * rpos;
/* get each rule in po */
for(pid=sflist_firstpos(po->rule_list,&rpos);
pid;
pid=sflist_nextpos(po->rule_list,&rpos) )
{
/* find it in po2 */
id =(int*) sfghash_find(po2->rule_hash,pid);
/* make sure it's in po2 */
if(!id )
{
return 1; /* error */
}
}
return 0;
}
/*
* Perform a consistency check on the final port+rule objects
*
* Walk the rules
*/
int PortTableConsistencyCheck( PortTable *p )
{
char * parray = 0;
SFGHASH_NODE * node;
int i;
SF_LNODE * pos;
SF_LNODE * ipos;
PortObject * ipo;
PortObject2 * lastpo = NULL;
PortObjectItem * poi;
parray = calloc(1,SFPO_MAX_PORTS);
if(!parray)
{
FatalError("Memory eror in PortTableComopile\n");
}
/* Make sure each port is only in one composite port object */
for(node=sfghash_findfirst(p->pt_mpo_hash);
node;
node=sfghash_findnext(p->pt_mpo_hash) )
{
PortObject2 * po;
po = (PortObject2*)node->data;
if( !po )
{
FatalError("PortObject consistency Check failed, hash table problem\n");
}
if( !po->port_cnt )/* port object is not used ignore it */
continue;
for(i=0;i<SFPO_MAX_PORTS;i++)
{
if( PortObjectHasPort( (PortObject*)po, i ) )
{
if( parray[i] )
{
FatalError("PortTableCompile: failed consistency check, multiple objects reference port %d\n",i);
}
parray[i]=1;
}
}
}
if( parray ) free(parray);
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"***\n***Port Table Compiler Consistency Check Phase-I Passed !\n"););
/*
* This phase checks the Input port object rules/ports against
* the composite port objects.
*
* For each input object
* check that each port it reference has all of the rules
* referenced to that port in the composit object
*/
for(ipo=sflist_firstpos(p->pt_polist,&pos);
ipo;
ipo=sflist_nextpos(p->pt_polist,&pos) )
{
/*
* for each port in this object get the composite port object
* assigned to that port and verify all of the input objects rules
* are in the composite object. This verifies all rules are applied
* to the originally intended port.
*/
for(poi=sflist_firstpos(ipo->item_list,&ipos);
poi;
poi=sflist_nextpos(ipo->item_list,&ipos) )
{
switch(poi->type)
{
case PORT_OBJECT_ANY: /* do nothing */
break;
case PORT_OBJECT_PORT:
if( _po2_include_po_rules( p->pt_port_object[ poi->lport ], ipo ) )
{
FatalError("InputPortObject<->CompositePortObject consistency Check II failed!\n");
}
break;
case PORT_OBJECT_RANGE:
{
for(i=poi->lport;i<=poi->hport;i++)
{
/* small optimization*/
if( lastpo != p->pt_port_object[ i ] )
{
if( _po2_include_po_rules( p->pt_port_object[ i ], ipo ) )
{
FatalError("InputPortObject<->CompositePortObject consistency Check II failed!\n");
}
lastpo = p->pt_port_object[ i ];
}
}
}
break;
}
}
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,
"***\n***Port Table Compiler Consistency Check Phase-II Passed !!! - Good to go Houston\n****\n"););
return 0;
}
/*
* Compile the PortTable
*
* This builds a set of Port+Rule objects that are in some way an optimal
* set of objects to indicate which rules to apply to which ports. Since
* these groups are calculated consistency checking is done witht he finished
* objects.
*/
int PortTableCompile( PortTable * p )
{
/*
* If not using an optimized Table use the rule_index_map in parser.c
*/
if( !p->pt_optimize )
{
return 0;
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"#PortTableCompile: Compiling Port Array Lists\n"););
if( PortTableCompileMergePortObjects( p ) )
{
FatalError("Could not create PortArryayLists\n");
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"Done\n");fflush(stdout););
PortTableConsistencyCheck(p);
return 0;
}
static
int integer_compare( const void *arg1, const void *arg2 )
{
if( *(int*)arg1 < *(int*)arg2 ) return -1;
if( *(int*)arg1 > *(int*)arg2 ) return 1;
return 0;
}
static
int * RuleListToSortedArray( SF_LIST * rl )
{
SF_LNODE * pos = NULL;
int * prid;
int * ra;
int k=0;
if( !rl )
return 0;
if(!rl->count)
return NULL;
ra = (int *)SnortAlloc(rl->count * sizeof(int));
for( prid = sflist_firstpos(rl,&pos);
prid!= 0 && k < (int)rl->count;
prid = sflist_nextpos(rl,&pos) )
{
ra[k++] = *prid;
}
/* sort the array */
qsort(ra,rl->count,sizeof(int),integer_compare);
return ra;
}
/**sort and uniq rule list.
*/
void RuleListSortUniq(
SF_LIST * rl
)
{
unsigned i;
int lastRuleIndex = -1;
SF_LNODE *pos = NULL;
int *currNode = NULL;
unsigned uniqElements = 0;
int *node = 0;
int * rlist = NULL;
rlist = RuleListToSortedArray(rl);
if(!rlist )
{
return ;
}
currNode = sflist_firstpos(rl,&pos);
for(i=0; i < rl->count; i++)
{
if (rlist[i] > lastRuleIndex)
{
*currNode = lastRuleIndex = rlist[i];
//replace the next element in place
currNode = sflist_nextpos(rl,&pos);
uniqElements++;
}
}
//free the remaining list nodes
while (uniqElements != rl->count)
{
node = sflist_remove_tail (rl);
free(node);
}
free(rlist);
}
/**Sort and make rule index in all port objects unique. Multiple policies may add
* the same rule which can lead to duplication.
*/
void PortTableSortUniqRules(
PortTable * p
)
{
PortObject * po;
SF_LNODE *pos = NULL;
for(po =(PortObject*)sflist_firstpos(p->pt_polist,&pos);
po != NULL;
po =(PortObject*)sflist_nextpos(p->pt_polist,&pos) )
{
RuleListSortUniq(po->rule_list);
}
}
static
int * RuleHashToSortedArray( SFGHASH * rh )
{
int * prid;
int * ra;
int k = 0;
SFGHASH_NODE * node;
if( !rh )
return 0;
if(!rh->count)
return NULL;
ra = (int *)SnortAlloc(rh->count * sizeof(int));
for( node = sfghash_findfirst(rh);
node != 0 && k < (int)rh->count;
node = sfghash_findnext(rh) )
{
prid = node->data;
if( prid )
{
ra[k++] = *prid;
}
}
/* sort the array */
qsort(ra,rh->count,sizeof(int),integer_compare);
return ra;
}
/*
* Print Input Port List
*/
void PortTablePrintInput( PortTable * p )
{
PortObject * po;
SF_LNODE * pos;
LogMessage("*** %d PortObjects in Table\n",p->pt_polist->count);
for(po =(PortObject*)sflist_firstpos(p->pt_polist,&pos);
po!=0;
po =(PortObject*)sflist_nextpos(p->pt_polist,&pos) )
{
PortObjectPrint( po );
}
}
void PortTablePrintInputEx( PortTable * p,
void (*print_index_map)(int index, char *buf, int bufsize) )
{
PortObject * po;
SF_LNODE * pos;
for(po =(PortObject*)sflist_firstpos(p->pt_polist,&pos);
po != NULL;
po =(PortObject*)sflist_nextpos(p->pt_polist,&pos) )
{
PortObjectPrintEx( po, print_index_map );
}
}
/*
Prints Compiled Ports/Rules Objects
*/
int PortTablePrintCompiledEx( PortTable * p ,
void (*print_index_map)(int index, char *buf, int bufsize) )
{
PortObject2 * po = NULL;
SFGHASH_NODE * node = NULL;
LogMessage(" *** PortTableCompiled [ %d compiled port groups ] \n\n",
p->pt_mpo_hash->count);
for(node = sfghash_findfirst(p->pt_mpo_hash);
node!= 0;
node = sfghash_findnext(p->pt_mpo_hash) )
{
po = node->data;
PortObject2PrintEx( po, print_index_map );
}
return 0;
}
/*
Print port items. Used internally by sfportobject.c.
Buffer assumed trusted.
*/
static void PortObjectItemPrint ( PortObjectItem * poi, char *dstbuf, int bufsize )
{
SnortSnprintfAppend(dstbuf, bufsize, " ");
if( poi->flags & PORT_OBJECT_NOT_FLAG )
SnortSnprintfAppend(dstbuf, bufsize, "!");
switch( poi->type )
{
case PORT_OBJECT_PORT :
SnortSnprintfAppend(dstbuf, bufsize, "%u", poi->lport);
break;
case PORT_OBJECT_RANGE :
SnortSnprintfAppend(dstbuf, bufsize, "%u:%u",poi->lport,poi->hport);
break;
case PORT_OBJECT_ANY:
SnortSnprintfAppend(dstbuf, bufsize, "any");
break;
default:
SnortSnprintfAppend(dstbuf, bufsize, " unknown port type @ %p", (void*)poi);
break;
}
}
void PortObjectPrintPortsRaw(PortObject * po )
{
PortObjectItem * poi = NULL;
SF_LNODE * pos = NULL;
char * buf;
int bufsize;
/* Need to buffer the string so we only do one LogMessage,
* due to syslog output. The largest string needed to represent
* each portobject is the length required to represent:
* " unknown port type @ 0x<8 max bytes>" (See PortObjectItemPrint), or:
* 30 bytes. For the entire list, need room for spaces and brackets and
* potential negations. Or:
* list_size * (30 + 1space_for_each_element, +
* 1potential_negation) + surrounding_whitespace + brackets + NULL */
bufsize = po->item_list->count * (30 + 1 + 1) + 5;
buf = (char*)SnortAlloc(bufsize);
SnortSnprintfAppend(buf, bufsize, " [");
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list, &pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list, &pos) )
{
PortObjectItemPrint(poi, buf, bufsize);
}
SnortSnprintfAppend(buf, bufsize, " ]");
LogMessage("%s", buf);
free(buf);
}
void PortObject2PrintPorts(PortObject2 * po )
{
PortObjectItem * poi = NULL;
SF_LNODE * pos = NULL;
int bufsize = sizeof(po_print_buf);
po_print_buf[0] = '\0';
SnortSnprintfAppend(po_print_buf, bufsize, " PortObject ");
if( po->name )
{
SnortSnprintfAppend(po_print_buf, bufsize, "%s ", po->name);
}
SnortSnprintfAppend(po_print_buf, bufsize,
" Id:%d Ports:%d Rules:%d\n {\n Ports [",
po->id, po->item_list->count, po->rule_hash->count);
if( PortObjectHasAny( (PortObject*)po ) )
{
SnortSnprintfAppend(po_print_buf, bufsize, "any");
}
else
{
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
PortObjectItemPrint(poi, po_print_buf, bufsize);
}
}
SnortSnprintfAppend(po_print_buf, bufsize, " ]\n }\n");
LogMessage("%s", po_print_buf);
}
/*
Print Port Object - Prints input ports and rules (uncompiled)
ports
rules (input by user)
*/
void PortObjectPrintEx(PortObject * po,
void (*print_index_map)(int index, char *buf, int bufsize) )
{
PortObjectItem * poi = NULL;
SF_LNODE * pos = NULL;
int k=0;
int * rlist = NULL;
unsigned i;
int bufsize = sizeof(po_print_buf);
po_print_buf[0] = '\0';
if( !po )
return ;
if( !po->rule_list )
return ;
if( !po->rule_list->count )
return ;
SnortSnprintfAppend(po_print_buf, bufsize, " PortObject ");
if( po->name )
{
SnortSnprintfAppend(po_print_buf, bufsize, "%s ", po->name);
}
SnortSnprintfAppend(po_print_buf, bufsize,
" Id:%d Ports:%d Rules:%d\n {\n",
po->id, po->item_list->count,po->rule_list->count );
SnortSnprintfAppend(po_print_buf, bufsize, " Ports [\n ");
if( PortObjectHasAny( po ) )
{
SnortSnprintfAppend(po_print_buf, bufsize, "any");
}
else
{
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
PortObjectItemPrint(poi, po_print_buf, bufsize);
}
}
SnortSnprintfAppend(po_print_buf, bufsize, " ]\n");
rlist = RuleListToSortedArray( po->rule_list );
if(!rlist )
{
return ;
}
SnortSnprintfAppend(po_print_buf, bufsize, " Rules [ \n ");
for(i=0;i<po->rule_list->count;i++)
{
if( print_index_map )
{
print_index_map( rlist[i], po_print_buf, bufsize );
}
else
{
SnortSnprintfAppend(po_print_buf, bufsize, " %d",rlist[i]);
}
k++;
if( k == 25 )
{
k=0;
SnortSnprintfAppend(po_print_buf, bufsize, " \n ");
}
}
SnortSnprintfAppend(po_print_buf, bufsize, " ]\n }\n");
LogMessage("%s", po_print_buf);
free(rlist);
}
// extern void rule_index_map_print_index( int index );
void PortObjectPrint (PortObject * po )
{
PortObjectPrintEx( po, rule_index_map_print_index );
}
void PortObject2PrintEx(PortObject2 * po,
void (*print_index_map)(int index, char *buf, int bufsize) )
{
PortObjectItem * poi = NULL;
SF_LNODE * pos = NULL;
int k=0;
int * rlist = NULL;
unsigned int i;
int bufsize = sizeof(po_print_buf);
po_print_buf[0] = '\0';
SnortSnprintfAppend(po_print_buf, bufsize, " PortObject2 ");
if( po->name ) SnortSnprintfAppend(po_print_buf, bufsize, "%s ",po->name);
SnortSnprintfAppend(po_print_buf, bufsize, " Id:%d Ports:%d Rules:%d PortUsageCnt=%d\n {\n",
po->id, po->item_list->count, po->rule_hash->count, po->port_cnt );
SnortSnprintfAppend(po_print_buf, bufsize, " Ports [\n ");
if( PortObjectHasAny( (PortObject*)po ) )
{
SnortSnprintfAppend(po_print_buf, bufsize, "any");
}
else
{
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
PortObjectItemPrint(poi, po_print_buf, bufsize);
}
}
SnortSnprintfAppend(po_print_buf, bufsize, " ]\n");
rlist = RuleHashToSortedArray( po->rule_hash );
if(!rlist )
return ;
SnortSnprintfAppend(po_print_buf, bufsize, " Rules [ \n ");
for(i=0;i<po->rule_hash->count;i++)
{
if( print_index_map )
{
print_index_map( rlist[i], po_print_buf, bufsize );
}
else
{
SnortSnprintfAppend(po_print_buf, bufsize, " %d", rlist[i]);
}
k++;
if( k == 25 )
{
k=0;
SnortSnprintfAppend(po_print_buf, bufsize, " \n ");
}
}
SnortSnprintfAppend(po_print_buf, bufsize, " ]\n }\n");
LogMessage("%s", po_print_buf);
free(rlist);
}
void PortObject2Print (PortObject2 * po )
{
// void rule_index_map_print_index( int index );
PortObject2PrintEx( po, rule_index_map_print_index );
}
/*
Prints the original (normalized) PortGroups and
as sepcified by the user
*/
void PortTablePrintUserRules( PortTable * p )
{
PortObject * po;
/* normalized user PortObjects and rule ids */
LogMessage(">>>PortTable - Rules\n");
for(po = (PortObject*)sflist_first(p->pt_polist);
po!= 0;
po = (PortObject*)sflist_next(p->pt_polist) )
{
PortObjectPrint( po );
}
/* port array of rule ids */
}
/*
Prints the Unique Port Groups and rules that reference them
*/
void PortTablePrintPortGroups( PortTable * p )
{
PortObject2 * po;
SFGHASH_NODE * ponode;
/* normalized user PortObjects and rule ids */
LogMessage(">>>PortTable - Compiled Port Groups\n");
LogMessage(" [ %d port groups ] \n\n",p->pt_mpo_hash->count);
for(ponode = sfghash_findfirst(p->pt_mpo_hash);
ponode!= 0;
ponode = sfghash_findnext(p->pt_mpo_hash) )
{
po = ponode->data;
PortObject2Print(po);
}
/* port array of rule ids */
}
/*
Print
*/
void PortTablePrintPortPortObjects( PortTable * p )
{
int i;
PortObject * po;
SF_LIST * last = NULL;
int bufsize = sizeof(po_print_buf);
po_print_buf[0] = '\0';
LogMessage(">>>Port PortObjects\n");
for(i=0;i<SFPO_MAX_PORTS;i++)
{
if( !p->pt_port_lists[i] ) continue;
if( p->pt_port_lists[i] == last )
continue;
SnortSnprintfAppend(po_print_buf, bufsize, "---Port[%d] PortObjects [ ",i);
for(po=(PortObject*)sflist_first(p->pt_port_lists[i]);
po != 0;
po=(PortObject*)sflist_next(p->pt_port_lists[i]) )
{
SnortSnprintfAppend(po_print_buf, bufsize, "%d ",po->id);
}
SnortSnprintfAppend(po_print_buf, bufsize, "]\n");
last = p->pt_port_lists[i] ;
}
LogMessage("%s", po_print_buf);
}
/*
*
* Port Object Parser
*
*/
static
int POParserInit( POParser * pop, char * s, PortVarTable * pvTable )
{
memset(pop,0,sizeof(POParser));
pop->pos = 0;
pop->s = s;
pop->slen = strlen(s);
pop->errflag = 0;
pop->pvTable = pvTable;
return 0;
}
/*
Get a Char
*/
static
int POPGetChar( POParser * pop )
{
int c;
if( pop->slen > 0 )
{
c = pop->s[0];
pop->slen--;
pop->s++;
pop->pos++;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"GetChar: %c, %d bytes left\n",c, pop->slen););
return c;
}
return 0;
}
/*
Skip whitespace till we find a non-whitespace char
*/
static
int POPGetChar2( POParser * pop )
{
int c;
for(;;)
{
c=POPGetChar( pop ) ;
if( !c )
return 0;
if( isspace(c) || c==',' )
continue;
break;
}
return c;
}
/*
Restore last char
*/
static
void POPUnGetChar( POParser * pop )
{
if( pop->pos > 0 )
{
pop->slen++;
pop->s--;
pop->pos--;
}
}
/*
Peek at next char
*/
static
int POPPeekChar( POParser * pop )
{
if( pop->slen > 0)
{
return pop->s[0];
}
return 0;
}
#ifdef XXXX
/* copy a simple alpha string */
static
void POPeekString(POParser * p, char * s, int smax)
{
int c;
int cnt = 0;
int k = p->slen;
smax--;
s[0] = 0;
while( k > 0 && cnt < smax )
{
c = p->s[ cnt ];
if( c == 0 ) break;
if( !isalpha(c) ) break;
s[ cnt++ ] = c;
s[ cnt ] = 0;
k--;
}
}
static
void POGetString(POParser * p, char * s, int smax)
{
int c;
int cnt = 0;
smax--;
s[0] = 0;
while( p->slen > 0 && cnt < smax )
{
c = p->s[ 0 ];
if( c == 0 ) break;
if( !isalpha(c) ) break;
s[ cnt++ ] = c;
s[ cnt ] = 0;
p->slen--;
p->s++;
}
}
#endif
/*
Skip whitespace : ' ', '\t', '\n'
*/
static
int POPSkipSpace( POParser * p )
{
int c;
for( c = POPPeekChar(p);
c != 0 ;
c = POPPeekChar(p) )
{
if( !isspace(c) && c != ',' )
return c;
POPGetChar(p);
}
return 0;
}
/*
Get the Port Object Name
*/
static
char * POParserName( POParser * pop )
{
int k = 0;
int c;
/* check if were done */
if( !pop || !pop->s || !*(pop->s) )
return 0;
/* Start the name - skip space */
c = POPGetChar2(pop) ;
if( !c )
return 0;
if( c== '$' )/* skip leading '$' - old Var indicator */
{
c = POPGetChar2(pop) ;
if( !c )
return 0;
}
if( isalnum(c) )
{
pop->token[k++] = (char)c;
pop->token[k] = (char)0;
}
else
{
POPUnGetChar( pop );
return 0; /* not a name */
}
for( c = POPGetChar(pop);
c != 0 && k < POP_MAX_BUFFER_SIZE;
c = POPGetChar(pop) )
{
if( isalnum(c) || c== '_' || c=='-' || c=='.' )
{
pop->token[k++] = (char)c;
pop->token[k] = (char)0;
}
else
{
POPUnGetChar( pop );
break;
}
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,">>> POParserName : %s\n",pop->token););
return strdup(pop->token);
}
/*
* Read an unsigned short (a port)
*/
static
uint16_t POParserGetShort(POParser * pop)
{
int c;
int k = 0;
char buffer[32];
char * pend;
POPSkipSpace(pop);
buffer[0] = 0;
while( (c = POPGetChar(pop)) != 0 )
{
if( isdigit(c) )
{
buffer[k++]=(char)c;
buffer[k] =0;
if( k == sizeof(buffer)-1 ) break; /* thats all that fits */
}
else
{
if( c && ( c!= ':' && c != ' ' && c != ']' && c != ',' && c != '\t' && c != '\n' ) )
{
pop->errflag = POPERR_NOT_A_NUMBER;
return 0;
}
POPUnGetChar(pop);
break;
}
}
c = (int)strtoul(buffer,&pend,10);
if(c > 65535 || c < 0)
{
pop->errflag = POPERR_BOUNDS;
return 0;
}
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"GetUNumber: %d\n",c););
return c;
}
static PortObject *_POParseVar(POParser *pop)
{
PortObject *pox;
char *name;
name = POParserName(pop);
if(!name)
{
pop->pos++;
pop->errflag = POPERR_NO_NAME;
return NULL;
}
pox = PortVarTableFind(pop->pvTable, name);
free(name);
if(!pox)
{
pop->errflag = POPERR_BAD_VARIABLE;
return NULL;
}
pox = PortObjectDup(pox);
if(!pox)
{
pop->errflag = POPERR_MALLOC_FAILED;
return NULL;
}
return pox;
}
/*
* Sets the PORT_OBJECT_NOT_FLAG flag on each port object item in the list
*/
static void _PONegateList(PortObject *po)
{
PortObjectItem *poi;
SF_LNODE * pos;
if(!po) return;
/* disable the NOT'd ports */
for(poi=(PortObjectItem*)sflist_firstpos(po->item_list,&pos);
poi != 0;
poi=(PortObjectItem*)sflist_nextpos(po->item_list,&pos) )
{
poi->flags ^= PORT_OBJECT_NOT_FLAG;
}
}
static PortObject *_POParsePort(POParser *pop)
{
uint16_t hport, lport;
char c;
PortObject *po = PortObjectNew();
if(!po)
{
pop->errflag = POPERR_MALLOC_FAILED;
return NULL;
}
hport = MAXPORTS-1;
pop->token[0]=0;
/* The string in pop should only be of the form <port> or <port>:<port> */
lport = POParserGetShort(pop);
if(pop->errflag)
{
PortObjectFree(po);
return NULL;
}
c = POPPeekChar(pop);
if( c == ':' ) /* half open range */
{
POPGetChar(pop);
c = POPPeekChar(pop);
if (((c == 0) && (pop->slen == 0)) ||
(c == ','))
{
/* Open ended range, highport is 65k */
hport = MAXPORTS-1;
PortObjectAddRange(po, lport, hport, 0);
return po;
}
if( !isdigit((int)c) ) /* not a number */
{
pop->errflag = POPERR_NOT_A_NUMBER;
PortObjectFree(po);
return NULL;
}
hport = POParserGetShort(pop);
if( pop->errflag )
{
PortObjectFree(po);
return NULL;
}
if(lport > hport)
{
pop->errflag = POPERR_INVALID_RANGE;
PortObjectFree(po);
return NULL;
}
PortObjectAddRange(po, lport, hport, 0);
}
else
{
PortObjectAddPort(po, lport, 0);
}
return po;
}
static PortObject* _POParseString(POParser *pop)
{
PortObject * po;
PortObject * potmp = NULL;
int local_neg = 0;
char c;
int list_count = 0;
po = PortObjectNew();
if(!po)
{
pop->errflag = POPERR_MALLOC_FAILED;
return NULL;
}
while( (c = POPGetChar2(pop)) != 0 )
{
if(c == '!')
{
local_neg = 1;
continue;
}
if(c == '$')
{
/* Don't dup this again - the returned PortObject has already
* been dup'ed */
potmp = _POParseVar(pop);
}
/* Start of a list. Tokenize list and recurse on it */
else if(c == '[')
{
POParser local_pop;
char *tok;
char *end;
list_count++;
if( (end = strrchr(pop->s, (int)']')) == NULL )
{
pop->errflag = POPERR_NO_ENDLIST_BRACKET;
PortObjectFree(po);
return NULL;
}
if( (tok = SnortStrndup(pop->s, end - pop->s)) == NULL)
{
pop->errflag = POPERR_MALLOC_FAILED;
PortObjectFree(po);
return NULL;
}
POParserInit(&local_pop, tok, pop->pvTable);
/* Recurse */
potmp = _POParseString(&local_pop);
free(tok);
if(!potmp)
{
pop->errflag = local_pop.errflag;
PortObjectFree(po);
return NULL;
}
/* Advance "cursor" to end of this list */
for(; c && pop->s != end; c = POPGetChar2(pop))
;
}
else if(c == ']')
{
list_count--;
if(list_count < 0)
{
pop->errflag = POPERR_EXTRA_BRACKET;
PortObjectFree(po);
return NULL;
}
continue;
}
else
{
POPUnGetChar(pop);
potmp = _POParsePort(pop);
}
if(!potmp)
{
PortObjectFree(po);
return NULL;
}
if(local_neg)
{
/* Note: this intentionally only sets the negation flag! */
/* The actual negation will take place when normalization is called */
_PONegateList(potmp);
local_neg = 0;
}
if(PortObjectAddPortObject(po, potmp, &pop->errflag))
{
PortObjectFree(po);
PortObjectFree(potmp);
return NULL;
}
if (potmp)
{
PortObjectFree(potmp);
potmp = NULL;
}
}
/* Check for mis-matched brackets */
if(list_count)
{
if(list_count > 0) pop->errflag = POPERR_NO_ENDLIST_BRACKET;
else pop->errflag = POPERR_EXTRA_BRACKET;
PortObjectFree(po);
return NULL;
}
return po;
}
/*
* PortObject : name value
* PortObject : name [!][ value value value ... ]
*
* value : [!]port
* [!]low-port[:high-port]
*
* inputs:
* pvTable - PortVarTable to search for PortVar references in the current PortVar
* pop - parsing structure
* s - string with port object text
*
* nameflag - indicates a name must be present, this allows usage for
* embedded rule or portvar declarations of portlists
* returns:
* (PortObject *) - a normalized version
*/
PortObject * PortObjectParseString ( PortVarTable * pvTable, POParser * pop,
char * name, char * s , int nameflag )
{
PortObject *po, *potmp;
DEBUG_WRAP(DebugMessage(DEBUG_PORTLISTS,"PortObjectParseString: %s\n",s););
POParserInit( pop, s, pvTable );
po = PortObjectNew();
if(!po)
{
pop->errflag=POPERR_MALLOC_FAILED;
return 0;
}
if( nameflag ) /* parse a name */
{
po->name = POParserName( pop );
if(!po->name )
{
pop->errflag=POPERR_NO_NAME;
PortObjectFree(po);
return 0;
}
}
else
{
if( name )
po->name = SnortStrdup(name);
else
po->name = SnortStrdup("noname");
}
// LogMessage("PortObjectParseString: po->name=%s\n",po->name);
potmp = _POParseString(pop);
if(!potmp)
{
PortObjectFree(po);
return NULL;
}
PortObjectNormalize(potmp);
if(PortObjectAddPortObject(po, potmp, &pop->errflag))
{
PortObjectFree(po);
PortObjectFree(potmp);
return NULL;
}
PortObjectFree(potmp);
return po;
}
char * PortObjectParseError( POParser * pop )
{
switch( pop->errflag )
{
case POPERR_NO_NAME: return "no name";
case POPERR_NO_ENDLIST_BRACKET: return "no end of list bracket."
" Elements must be comma seperated,"
" and no spaces may appear between"
" brackets.";
case POPERR_NOT_A_NUMBER: return "not a number";
case POPERR_EXTRA_BRACKET: return "extra list bracket";
case POPERR_NO_DATA: return "no data";
case POPERR_ADDITEM_FAILED: return "add item failed";
case POPERR_MALLOC_FAILED: return "mem alloc failed";
case POPERR_INVALID_RANGE: return "invalid port range";
case POPERR_DUPLICATE_ENTRY: return "duplicate ports in list";
case POPERR_BOUNDS: return "value out of bounds for a port";
case POPERR_BAD_VARIABLE: return "unrecognized variable";
default:
break;
}
return "unknown POParse error";
}
/*
*
* PORT VAR TABLE FUNCTIONS
*
*/
/*
* Create a PortVar Table
*
* The PortVar table used to store and lookup Named PortObjects
*/
PortVarTable * PortVarTableCreate(void)
{
PortObject * po;
SFGHASH * h;
/*
* This is used during parsing of config,
* so 1000 entries is ok, worst that happens is somewhat slower
* config/rule processing.
*/
h = sfghash_new(1000,0,0,PortObjectFree);
if( !h )
return 0;
/* Create default port objects */
po = PortObjectNew();
if( !po )
return 0;
/* Default has an ANY port */
PortObjectAddPortAny( po );
/* Add ANY to the table */
PortVarTableAdd( h, po );
return h;
}
/*
* PortVarTableAdd()
*
* returns
* -1 : error, no memory...
* 0 : added
* 1 : in table
*/
int PortVarTableAdd( PortVarTable * h, PortObject * po )
{
int stat;
stat = sfghash_add(h,po->name,po);
if( stat == SFGHASH_INTABLE )
return 1;
if( stat == SFGHASH_OK )
return 0;
return -1;
}
PortObject * PortVarTableFind( PortVarTable * h, char * name )
{
if (!h || !name)
return NULL;
return sfghash_find(h,name);
}
/*
This deletes the table, the PortObjects and PortObjectItems,
and rule list.
*/
int PortVarTableFree(PortVarTable * pvt)
{
if( pvt )
{
sfghash_delete( pvt );
}
return 0;
}
/*
TEST DRIVER
PorObjects use the follow creation strategy
po = PortObjectNew();
PortObjectAddPort( po, 80, 0 );
PortObjectAddPort( po, 8080, 0 );
PortObjectAddPort( po, 8138, 0 );
PortTableAddObject( p, po, k++ );
PortVarTable just stores PorObjects by Name
*/
//#define MAIN_PORTOBJECT
//char * sample1="http [ 80 8100:8200 !8150 ]";
//char * sample2="httpx [ !http 8120 ]";
#ifdef MAIN_PORTOBJECT
int main( int argc, char ** argv )
{
PortVarTable * pvTable;
PortTable * p;
PortObject * po;
POParser pop;
int i;
int k=1;
int debug=0;
int names=1;
int lrc =100;
int lrp =20;
char * portlist;
for(i=1;i<argc;i++)
{
if( strcmp(argv[i],"-debug")==0 ) debug=1;
if( strcmp(argv[i],"-lrc")==0 ) lrc=atoi(argv[++i]);
if( strcmp(argv[i],"-lrp")==0 ) lrp=atoi(argv[++i]);
}
/*
Create a PortVar table - this is automatic and not necessary
*/
pvTable=PortVarTableCreate();
if( !pvTable )
{
LogMessage("Cound not init port variables\n");
exit(1);
}
/*
Create a table for src and one for dst
we'll only add specific ports, no ANY ports,
but ranges are ok.
*/
p = PortTableNew();
if(!p)
{
LogMessage("no memory\n");
exit(0);
}
p->pt_lrc=lrc; // large rule count - primary
for(i=1;i<argc;i++)
{
if( argv[i][0] == '-' )
{
if( strcmp(argv[i],"-names")==0 ) names=0;/* disable names in var input*/
continue;
}
portlist = argv[i];
//if( i==1) portlist = sample1;
//if( i==2) portlist = sample2;
//LogMessage("PortObject : '%s' \n",portlist);
/*
This is seperate fom PortVar's since some rules may declare these inline
*/
po = PortObjectParseString ( pvTable, &pop, argv[i], PORTLISTS, names/* bool 0/1 - name required in parse */);
if( !po )
{
LogMessage(">>Bogus PortObject Definition (pos=%d,errflag=%d)\n>>%s\n>>%*s\n",
pop.pos,pop.errflag,PORTLISTS,pop.pos,"^");
continue; /* invalid parse - no port object to add */
}
PortObjectPrint ( po );
if( PortVarTableAdd( pvTable, po ) ) /* requires a name : portlist http [ portlist ]*/
{
LogMessage("error: named port var '%s' already in table \n",po->name);
}
// Lets test the lookup ...
if( !PortVarTableFind(pvTable,po->name) )
{
LogMessage("Could not find PortVar: %s\n",po->name);
exit(0);
}
/*
Assume each PortVar object has one rule and add it to the PortTable
PortObjects that are defined in rules have no names and are not
added to the PortVar table
*/
PortTableAddObject(p,po,k++/*rule id*/);
}
PortTableCompile( p );
//PortTablePrintRules( p );
//if(debug)
PortTablePrintPortGroups( p );
//PortTablePrintPortPortObjects( p );
PortTableDumpPortRules( p );
LogMessage("\n");
LogMessage("#rule and port groups compiled successfully\n");
return 0;
}
#endif
|