Loading...
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 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 | /* * Copyright (c) 2013-2022, 2024, 2025 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * THEORY OF OPERATION * * The socket content filter subsystem provides a way for user space agents to * make filtering decisions based on the content of the data being sent and * received by INET/INET6 sockets. * * A content filter user space agents gets a copy of the data and the data is * also kept in kernel buffer until the user space agents makes a pass or drop * decision. This unidirectional flow of content avoids unnecessary data copies * back to the kernel. * * A user space filter agent opens a kernel control socket with the name * CONTENT_FILTER_CONTROL_NAME to attach to the socket content filter subsystem. * When connected, a "struct content_filter" is created and set as the * "unitinfo" of the corresponding kernel control socket instance. * * The socket content filter subsystem exchanges messages with the user space * filter agent until an ultimate pass or drop decision is made by the * user space filter agent. * * It should be noted that messages about many INET/INET6 sockets can be multiplexed * over a single kernel control socket. * * Notes: * - The current implementation supports all INET/INET6 sockets (i.e. TCP, * UDP, ICMP, etc). * - The current implementation supports up to two simultaneous content filters * for iOS devices and eight simultaneous content filters for OSX. * * * NECP FILTER CONTROL UNIT * * A user space filter agent uses the Network Extension Control Policy (NECP) * database to specify which INET/INET6 sockets need to be filtered. The NECP * criteria may be based on a variety of properties like user ID or proc UUID. * * The NECP "filter control unit" is used by the socket content filter subsystem * to deliver the relevant INET/INET6 content information to the appropriate * user space filter agent via its kernel control socket instance. * This works as follows: * * 1) The user space filter agent specifies an NECP filter control unit when * in adds its filtering rules to the NECP database. * * 2) The user space filter agent also sets its NECP filter control unit on the * content filter kernel control socket via the socket option * CFIL_OPT_NECP_CONTROL_UNIT. * * 3) The NECP database is consulted to find out if a given INET/INET6 socket * needs to be subjected to content filtering and returns the corresponding * NECP filter control unit -- the NECP filter control unit is actually * stored in the INET/INET6 socket structure so the NECP lookup is really simple. * * 4) The NECP filter control unit is then used to find the corresponding * kernel control socket instance. * * Note: NECP currently supports a single filter control unit per INET/INET6 socket * but this restriction may be soon lifted. * * * THE MESSAGING PROTOCOL * * The socket content filter subsystem and a user space filter agent * communicate over the kernel control socket via an asynchronous * messaging protocol (this is not a request-response protocol). * The socket content filter subsystem sends event messages to the user * space filter agent about the INET/INET6 sockets it is interested to filter. * The user space filter agent sends action messages to either allow * data to pass or to disallow the data flow (and drop the connection). * * All messages over a content filter kernel control socket share the same * common header of type "struct cfil_msg_hdr". The message type tells if * it's a event message "CFM_TYPE_EVENT" or a action message "CFM_TYPE_ACTION". * The message header field "cfm_sock_id" identifies a given INET/INET6 flow. * For TCP, flows are per-socket. For UDP and other datagrame protocols, there * could be multiple flows per socket. * * Note the message header length field may be padded for alignment and can * be larger than the actual content of the message. * The field "cfm_op" describe the kind of event or action. * * Here are the kinds of content filter events: * - CFM_OP_SOCKET_ATTACHED: a new INET/INET6 socket is being filtered * - CFM_OP_SOCKET_CLOSED: A INET/INET6 socket is closed * - CFM_OP_DATA_OUT: A span of data is being sent on a INET/INET6 socket * - CFM_OP_DATA_IN: A span of data is being or received on a INET/INET6 socket * * * EVENT MESSAGES * * The CFM_OP_DATA_OUT and CFM_OP_DATA_IN event messages contains a span of * data that is being sent or received. The position of this span of data * in the data flow is described by a set of start and end offsets. These * are absolute 64 bits offsets. The first byte sent (or received) starts * at offset 0 and ends at offset 1. The length of the content data * is given by the difference between the end offset and the start offset. * * After a CFM_OP_SOCKET_ATTACHED is delivered, CFM_OP_DATA_OUT and * CFM_OP_DATA_OUT events are not delivered until a CFM_OP_DATA_UPDATE * action message is sent by the user space filter agent. * * Note: absolute 64 bits offsets should be large enough for the foreseeable * future. A 64-bits counter will wrap after 468 years at 10 Gbit/sec: * 2E64 / ((10E9 / 8) * 60 * 60 * 24 * 365.25) = 467.63 * * They are two kinds of primary content filter actions: * - CFM_OP_DATA_UPDATE: to update pass or peek offsets for each direction. * - CFM_OP_DROP: to shutdown socket and disallow further data flow * * There is also an action to mark a given client flow as already filtered * at a higher level, CFM_OP_BLESS_CLIENT. * * * ACTION MESSAGES * * The CFM_OP_DATA_UPDATE action messages let the user space filter * agent allow data to flow up to the specified pass offset -- there * is a pass offset for outgoing data and a pass offset for incoming data. * When a new INET/INET6 socket is attached to the content filter and a flow is * created, each pass offset is initially set to 0 so no data is allowed to pass by * default. When the pass offset is set to CFM_MAX_OFFSET via a CFM_OP_DATA_UPDATE * then the data flow becomes unrestricted. * * Note that pass offsets can only be incremented. A CFM_OP_DATA_UPDATE message * with a pass offset smaller than the pass offset of a previous * CFM_OP_DATA_UPDATE message is silently ignored. * * A user space filter agent also uses CFM_OP_DATA_UPDATE action messages * to tell the kernel how much data it wants to see by using the peek offsets. * Just like pass offsets, there is a peek offset for each direction. * When a new INET/INET6 flow is created, each peek offset is initially set to 0 * so no CFM_OP_DATA_OUT and CFM_OP_DATA_IN event messages are dispatched by default * until a CFM_OP_DATA_UPDATE action message with a greater than 0 peek offset is sent * by the user space filter agent. When the peek offset is set to CFM_MAX_OFFSET via * a CFM_OP_DATA_UPDATE then the flow of update data events becomes unrestricted. * * Note that peek offsets cannot be smaller than the corresponding pass offset. * Also a peek offsets cannot be smaller than the corresponding end offset * of the last CFM_OP_DATA_OUT/CFM_OP_DATA_IN message dispatched. Trying * to set a too small peek value is silently ignored. * * * PER FLOW "struct cfil_info" * * As soon as a INET/INET6 socket gets attached to a content filter, a * "struct cfil_info" is created to hold the content filtering state for this * socket. For UDP and other datagram protocols, as soon as traffic is seen for * each new flow identified by its 4-tuple of source address/port and destination * address/port, a "struct cfil_info" is created. Each datagram socket may * have multiple flows maintained in a hash table of "struct cfil_info" entries. * * The content filtering state is made of the following information * for each direction: * - The current pass offset; * - The first and last offsets of the data pending, waiting for a filtering * decision; * - The inject queue for data that passed the filters and that needs * to be re-injected; * - A content filter specific state in a set of "struct cfil_entry" * * * CONTENT FILTER STATE "struct cfil_entry" * * The "struct cfil_entry" maintains the information most relevant to the * message handling over a kernel control socket with a user space filter agent. * * The "struct cfil_entry" holds the NECP filter control unit that corresponds * to the kernel control socket unit it corresponds to and also has a pointer * to the corresponding "struct content_filter". * * For each direction, "struct cfil_entry" maintains the following information: * - The pass offset * - The peek offset * - The offset of the last data peeked at by the filter * - A queue of data that's waiting to be delivered to the user space filter * agent on the kernel control socket * - A queue of data for which event messages have been sent on the kernel * control socket and are pending for a filtering decision. * * * CONTENT FILTER QUEUES * * Data that is being filtered is steered away from the INET/INET6 socket buffer * and instead will sit in one of three content filter queues until the data * can be re-injected into the INET/INET6 socket buffer. * * A content filter queue is represented by "struct cfil_queue" that contains * a list of mbufs and the start and end offset of the data span of * the list of mbufs. * * The data moves into the three content filter queues according to this * sequence: * a) The "cfe_ctl_q" of "struct cfil_entry" * b) The "cfe_pending_q" of "struct cfil_entry" * c) The "cfi_inject_q" of "struct cfil_info" * * Note: The sequence (a),(b) may be repeated several times if there is more * than one content filter attached to the INET/INET6 socket. * * The "cfe_ctl_q" queue holds data than cannot be delivered to the * kernel conntrol socket for two reasons: * - The peek offset is less that the end offset of the mbuf data * - The kernel control socket is flow controlled * * The "cfe_pending_q" queue holds data for which CFM_OP_DATA_OUT or * CFM_OP_DATA_IN have been successfully dispatched to the kernel control * socket and are waiting for a pass action message fromn the user space * filter agent. An mbuf length must be fully allowed to pass to be removed * from the cfe_pending_q. * * The "cfi_inject_q" queue holds data that has been fully allowed to pass * by the user space filter agent and that needs to be re-injected into the * INET/INET6 socket. * * * IMPACT ON FLOW CONTROL * * An essential aspect of the content filer subsystem is to minimize the * impact on flow control of the INET/INET6 sockets being filtered. * * The processing overhead of the content filtering may have an effect on * flow control by adding noticeable delays and cannot be eliminated -- * care must be taken by the user space filter agent to minimize the * processing delays. * * The amount of data being filtered is kept in buffers while waiting for * a decision by the user space filter agent. This amount of data pending * needs to be subtracted from the amount of data available in the * corresponding INET/INET6 socket buffer. This is done by modifying * sbspace() and tcp_sbspace() to account for amount of data pending * in the content filter. * * * LOCKING STRATEGY * * The global state of content filter subsystem is protected by a single * read-write lock "cfil_lck_rw". The data flow can be done with the * cfil read-write lock held as shared so it can be re-entered from multiple * threads. * * The per INET/INET6 socket content filterstate -- "struct cfil_info" -- is * protected by the socket lock. * * A INET/INET6 socket lock cannot be taken while the cfil read-write lock * is held. That's why we have some sequences where we drop the cfil read-write * lock before taking the INET/INET6 lock. * * It is also important to lock the INET/INET6 socket buffer while the content * filter is modifying the amount of pending data. Otherwise the calculations * in sbspace() and tcp_sbspace() could be wrong. * * The "cfil_lck_rw" protects "struct content_filter" and also the fields * "cfe_link" and "cfe_filter" of "struct cfil_entry". * * Actually "cfe_link" and "cfe_filter" are protected by both by * "cfil_lck_rw" and the socket lock: they may be modified only when * "cfil_lck_rw" is exclusive and the socket is locked. * * To read the other fields of "struct content_filter" we have to take * "cfil_lck_rw" in shared mode. * * DATAGRAM SPECIFICS: * * The socket content filter supports all INET/INET6 protocols. However * the treatments for TCP sockets and for datagram (UDP, ICMP, etc) sockets * are slightly different. * * Each datagram socket may have multiple flows. Each flow is identified * by the flow's source address/port and destination address/port tuple * and is represented as a "struct cfil_info" entry. For each socket, * a hash table is used to maintain the collection of flows under that socket. * * Each datagram flow is uniquely identified by it's "struct cfil_info" cfi_sock_id. * The highest 32-bits of the cfi_sock_id contains the socket's so_gencnt. This portion * of the cfi_sock_id is used locate the socket during socket lookup. The lowest 32-bits * of the cfi_sock_id contains a hash of the flow's 4-tuple. This portion of the cfi_sock_id * is used as the hash value for the flow hash table lookup within the parent socket. * * Since datagram sockets may not be connected, flow states may not be maintained in the * socket structures and thus have to be saved for each packet. These saved states will be * used for both outgoing and incoming reinjections. For outgoing packets, destination * address/port as well as the current socket states will be saved. During reinjection, * these saved states will be used instead. For incoming packets, control and address * mbufs will be chained to the data. During reinjection, the whole chain will be queued * onto the incoming socket buffer. * * LIMITATIONS * * - Support all INET/INET6 sockets, such as TCP, UDP, ICMP, etc * * - Does not support TCP unordered messages */ /* * TO DO LIST * * Deal with OOB * */ #include <sys/types.h> #include <sys/kern_control.h> #include <sys/queue.h> #include <sys/domain.h> #include <sys/protosw.h> #include <sys/syslog.h> #include <sys/systm.h> #include <sys/param.h> #include <sys/mbuf.h> #include <kern/locks.h> #include <kern/zalloc.h> #include <kern/debug.h> #include <net/ntstat.h> #include <net/content_filter.h> #include <net/content_filter_crypto.h> #define _IP_VHL #include <netinet/ip.h> #include <netinet/in_pcb.h> #include <netinet/tcp.h> #include <netinet/tcp_var.h> #include <netinet/udp.h> #include <netinet/udp_var.h> #include <netinet6/in6_pcb.h> #include <kern/socket_flows.h> #include <string.h> #include <libkern/libkern.h> #include <kern/sched_prim.h> #include <kern/task.h> #include <mach/task_info.h> #include <net/sockaddr_utils.h> #define MAX_CONTENT_FILTER 8 extern int tcp_msl; extern struct inpcbinfo ripcbinfo; struct cfil_entry; /* * The structure content_filter represents a user space content filter * It's created and associated with a kernel control socket instance */ struct content_filter { kern_ctl_ref cf_kcref; u_int32_t cf_kcunit; u_int32_t cf_flags; uint32_t cf_necp_control_unit; uint32_t cf_sock_count; TAILQ_HEAD(, cfil_entry) cf_sock_entries; cfil_crypto_state_t cf_crypto_state; }; #define CFF_ACTIVE 0x01 #define CFF_DETACHING 0x02 #define CFF_FLOW_CONTROLLED 0x04 #define CFF_PRESERVE_CONNECTIONS 0x08 struct content_filter *content_filters[MAX_CONTENT_FILTER]; uint32_t cfil_active_count = 0; /* Number of active content filters */ uint32_t cfil_sock_attached_count = 0; /* Number of sockets attachements */ uint32_t cfil_sock_attached_stats_count = 0; /* Number of sockets requested periodic stats report */ uint32_t cfil_close_wait_timeout = 1000; /* in milliseconds */ static kern_ctl_ref cfil_kctlref = NULL; static LCK_GRP_DECLARE(cfil_lck_grp, "content filter"); static LCK_RW_DECLARE(cfil_lck_rw, &cfil_lck_grp); #define CFIL_RW_LCK_MAX 8 int cfil_rw_nxt_lck = 0; void* cfil_rw_lock_history[CFIL_RW_LCK_MAX]; int cfil_rw_nxt_unlck = 0; void* cfil_rw_unlock_history[CFIL_RW_LCK_MAX]; static KALLOC_TYPE_DEFINE(content_filter_zone, struct content_filter, NET_KT_DEFAULT); MBUFQ_HEAD(cfil_mqhead); struct cfil_queue { uint64_t q_start; /* offset of first byte in queue */ uint64_t q_end; /* offset of last byte in queue */ struct cfil_mqhead q_mq; }; /* * struct cfil_entry * * The is one entry per content filter */ struct cfil_entry { TAILQ_ENTRY(cfil_entry) cfe_link; SLIST_ENTRY(cfil_entry) cfe_order_link; struct content_filter *cfe_filter; struct cfil_info *cfe_cfil_info; uint32_t cfe_flags; uint32_t cfe_necp_control_unit; struct timeval cfe_last_event; /* To user space */ struct timeval cfe_last_action; /* From user space */ uint64_t cfe_byte_inbound_count_reported; /* stats already been reported */ uint64_t cfe_byte_outbound_count_reported; /* stats already been reported */ struct timeval cfe_stats_report_ts; /* Timestamp for last stats report */ uint32_t cfe_stats_report_frequency; /* Interval for stats report in msecs */ boolean_t cfe_laddr_sent; struct cfe_buf { /* * cfe_pending_q holds data that has been delivered to * the filter and for which we are waiting for an action */ struct cfil_queue cfe_pending_q; /* * This queue is for data that has not be delivered to * the content filter (new data, pass peek or flow control) */ struct cfil_queue cfe_ctl_q; uint64_t cfe_pass_offset; uint64_t cfe_peek_offset; uint64_t cfe_peeked; } cfe_snd, cfe_rcv; }; #define CFEF_CFIL_ATTACHED 0x0001 /* was attached to filter */ #define CFEF_SENT_SOCK_ATTACHED 0x0002 /* sock attach event was sent */ #define CFEF_DATA_START 0x0004 /* can send data event */ #define CFEF_FLOW_CONTROLLED 0x0008 /* wait for flow control lift */ #define CFEF_SENT_DISCONNECT_IN 0x0010 /* event was sent */ #define CFEF_SENT_DISCONNECT_OUT 0x0020 /* event was sent */ #define CFEF_SENT_SOCK_CLOSED 0x0040 /* closed event was sent */ #define CFEF_CFIL_DETACHED 0x0080 /* filter was detached */ #define CFI_ADD_TIME_LOG(cfil, t1, t0, op) \ struct timeval64 _tdiff; \ size_t offset = (cfil)->cfi_op_list_ctr; \ if (offset < CFI_MAX_TIME_LOG_ENTRY) { \ timersub(t1, t0, &_tdiff); \ (cfil)->cfi_op_time[offset] = (uint32_t)(_tdiff.tv_sec * 1000 + _tdiff.tv_usec / 1000); \ (cfil)->cfi_op_list[offset] = (unsigned char)op; \ (cfil)->cfi_op_list_ctr ++; \ } /* * struct cfil_info * * There is a struct cfil_info per socket */ struct cfil_info { TAILQ_ENTRY(cfil_info) cfi_link; TAILQ_ENTRY(cfil_info) cfi_link_stats; struct socket *cfi_so; uint64_t cfi_flags; uint64_t cfi_sock_id; struct timeval64 cfi_first_event; uint32_t cfi_op_list_ctr; uint32_t cfi_op_time[CFI_MAX_TIME_LOG_ENTRY]; /* time interval in microseconds since first event */ unsigned char cfi_op_list[CFI_MAX_TIME_LOG_ENTRY]; union sockaddr_in_4_6 cfi_so_attach_faddr; /* faddr at the time of attach */ union sockaddr_in_4_6 cfi_so_attach_laddr; /* laddr at the time of attach */ int cfi_dir; uint64_t cfi_byte_inbound_count; uint64_t cfi_byte_outbound_count; struct timeval cfi_timestamp; boolean_t cfi_isSignatureLatest; /* Indicates if signature covers latest flow attributes */ u_int32_t cfi_filter_control_unit; u_int32_t cfi_filter_policy_gencount; u_int32_t cfi_debug; struct cfi_buf { /* * cfi_pending_first and cfi_pending_last describe the total * amount of data outstanding for all the filters on * this socket and data in the flow queue * cfi_pending_mbcnt counts in sballoc() "chars of mbufs used" */ uint64_t cfi_pending_first; uint64_t cfi_pending_last; uint32_t cfi_pending_mbcnt; uint32_t cfi_pending_mbnum; uint32_t cfi_tail_drop_cnt; /* * cfi_pass_offset is the minimum of all the filters */ uint64_t cfi_pass_offset; /* * cfi_inject_q holds data that needs to be re-injected * into the socket after filtering and that can * be queued because of flow control */ struct cfil_queue cfi_inject_q; } cfi_snd, cfi_rcv; struct cfil_entry cfi_entries[MAX_CONTENT_FILTER]; struct soflow_hash_entry *cfi_hash_entry; SLIST_HEAD(, cfil_entry) cfi_ordered_entries; os_refcnt_t cfi_ref_count; } __attribute__((aligned(8))); #define CFIF_DROP 0x0001 /* drop action applied */ #define CFIF_CLOSE_WAIT 0x0002 /* waiting for filter to close */ #define CFIF_SOCK_CLOSED 0x0004 /* socket is closed */ #define CFIF_RETRY_INJECT_IN 0x0010 /* inject in failed */ #define CFIF_RETRY_INJECT_OUT 0x0020 /* inject out failed */ #define CFIF_SHUT_WR 0x0040 /* shutdown write */ #define CFIF_SHUT_RD 0x0080 /* shutdown read */ #define CFIF_SOCKET_CONNECTED 0x0100 /* socket is connected */ #define CFIF_INITIAL_VERDICT 0x0200 /* received initial verdict */ #define CFIF_NO_CLOSE_WAIT 0x0400 /* do not wait to close */ #define CFIF_SO_DELAYED_DEAD 0x0800 /* Delayed socket DEAD marking */ #define CFIF_SO_DELAYED_TCP_TIME_WAIT 0x1000 /* Delayed TCP FIN TIME WAIT */ #define CFI_MASK_GENCNT 0xFFFFFFFF00000000 /* upper 32 bits */ #define CFI_SHIFT_GENCNT 32 #define CFI_MASK_FLOWHASH 0x00000000FFFFFFFF /* lower 32 bits */ #define CFI_SHIFT_FLOWHASH 0 #define CFI_ENTRY_KCUNIT(i, e) ((uint32_t)(((e) - &((i)->cfi_entries[0])) + 1)) static KALLOC_TYPE_DEFINE(cfil_info_zone, struct cfil_info, NET_KT_DEFAULT); TAILQ_HEAD(cfil_sock_head, cfil_info) cfil_sock_head; TAILQ_HEAD(cfil_sock_head_stats, cfil_info) cfil_sock_head_stats; #define CFIL_QUEUE_VERIFY(x) if (cfil_debug) cfil_queue_verify(x) #define CFIL_INFO_VERIFY(x) if (cfil_debug) cfil_info_verify(x) /* * UDP Socket Support */ #define IS_ICMP(so) (so && (SOCK_CHECK_TYPE(so, SOCK_RAW) || SOCK_CHECK_TYPE(so, SOCK_DGRAM)) && \ (SOCK_CHECK_PROTO(so, IPPROTO_ICMP) || SOCK_CHECK_PROTO(so, IPPROTO_ICMPV6))) #define IS_RAW(so) (so && SOCK_CHECK_TYPE(so, SOCK_RAW) && SOCK_CHECK_PROTO(so, IPPROTO_RAW)) #define OPTIONAL_IP_HEADER(so) (!IS_TCP(so) && !IS_UDP(so)) #define GET_SO_PROTOCOL(so) (so ? SOCK_PROTO(so) : IPPROTO_IP) #define GET_SO_INP_PROTOCOL(so) ((so && sotoinpcb(so)) ? sotoinpcb(so)->inp_ip_p : IPPROTO_IP) #define GET_SO_PROTO(so) ((GET_SO_PROTOCOL(so) != IPPROTO_IP) ? GET_SO_PROTOCOL(so) : GET_SO_INP_PROTOCOL(so)) #define IS_INP_V6(inp) (inp && (inp->inp_vflag & INP_IPV6)) #define UNCONNECTED(inp) (inp && (((inp->inp_vflag & INP_IPV4) && (inp->inp_faddr.s_addr == INADDR_ANY)) || \ ((inp->inp_vflag & INP_IPV6) && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)))) #define IS_ENTRY_ATTACHED(cfil_info, kcunit) (cfil_info != NULL && (kcunit <= MAX_CONTENT_FILTER) && \ cfil_info->cfi_entries[kcunit - 1].cfe_filter != NULL) #define IS_DNS(local, remote) (check_port(local, 53) || check_port(remote, 53) || check_port(local, 5353) || check_port(remote, 5353)) #define IS_INITIAL_TFO_DATA(so) (so && (so->so_flags1 & SOF1_PRECONNECT_DATA) && (so->so_state & SS_ISCONNECTING)) #define NULLADDRESS(addr) ((addr.sa.sa_len == 0) || \ (addr.sa.sa_family == AF_INET && addr.sin.sin_addr.s_addr == 0) || \ (addr.sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr.sin6.sin6_addr))) #define SKIP_FILTER_FOR_TCP_SOCKET(so) \ (so == NULL || \ (!SOCK_CHECK_DOM(so, PF_INET) && !SOCK_CHECK_DOM(so, PF_INET6)) || \ !SOCK_CHECK_TYPE(so, SOCK_STREAM) || \ !SOCK_CHECK_PROTO(so, IPPROTO_TCP) || \ (so->so_flags & SOF_MP_SUBFLOW) != 0 || \ (so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) != 0) /* * Special handling for 0.0.0.0-faddr TCP flows. This flows will be changed to loopback addr by TCP and * may result in an immediate TCP RESET and socket close. This leads to CFIL blocking the owner thread for * 1 sec waiting for ack from user-space provider (ack recevied by CFIL but socket already removed from * global socket list). To avoid this, identify these flows and do not perform the close-wait blocking. * These flows are identified as destined to Loopback address and were disconnected shortly after connect * (before initial-verdict received). */ #define IS_LOOPBACK_FADDR(inp) \ (inp && ((IS_INP_V6(inp) && IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr)) || (ntohl(inp->inp_faddr.s_addr) == INADDR_LOOPBACK))) #define SET_NO_CLOSE_WAIT(inp, cfil_info) \ if (inp && cfil_info && !(cfil_info->cfi_flags & CFIF_INITIAL_VERDICT) && IS_LOOPBACK_FADDR(inp)) { \ cfil_info->cfi_flags |= CFIF_NO_CLOSE_WAIT; \ } #define IS_NO_CLOSE_WAIT(cfil_info) (cfil_info && (cfil_info->cfi_flags & CFIF_NO_CLOSE_WAIT)) os_refgrp_decl(static, cfil_refgrp, "CFILRefGroup", NULL); #define CFIL_INFO_FREE(cfil_info) \ if (cfil_info && (os_ref_release(&cfil_info->cfi_ref_count) == 0)) { \ cfil_info_free(cfil_info); \ } #define SOCKET_PID(so) ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid) #define MATCH_PID(so) (so && (cfil_log_pid == SOCKET_PID(so))) #define MATCH_PORT(inp, local, remote) \ ((inp && ntohs(inp->inp_lport) == cfil_log_port) || (inp && ntohs(inp->inp_fport) == cfil_log_port) || \ check_port(local, cfil_log_port) || check_port(remote, cfil_log_port)) #define MATCH_PROTO(so) (GET_SO_PROTO(so) == cfil_log_proto) #define DEBUG_FLOW(inp, so, local, remote) \ ((cfil_log_port && MATCH_PORT(inp, local, remote)) || (cfil_log_pid && MATCH_PID(so)) || (cfil_log_proto && MATCH_PROTO(so))) #define SO_DELAYED_DEAD_SET(so, set) do { \ if (so->so_cfil) { \ if (set) { \ so->so_cfil->cfi_flags |= CFIF_SO_DELAYED_DEAD; \ } else { \ so->so_cfil->cfi_flags &= ~CFIF_SO_DELAYED_DEAD; \ } \ } else if (so->so_flow_db) { \ if (set) { \ so->so_flow_db->soflow_db_flags |= SOFLOWF_SO_DELAYED_DEAD; \ } else { \ so->so_flow_db->soflow_db_flags &= ~SOFLOWF_SO_DELAYED_DEAD; \ } \ } \ } while (0) #define SO_DELAYED_DEAD_GET(so) \ (so->so_cfil ? (so->so_cfil->cfi_flags & CFIF_SO_DELAYED_DEAD) : \ (so->so_flow_db) ? (so->so_flow_db->soflow_db_flags & SOFLOWF_SO_DELAYED_DEAD) : false) #define SO_DELAYED_TCP_TIME_WAIT_SET(so, set) do { \ if (so->so_cfil) { \ if (set) { \ so->so_cfil->cfi_flags |= CFIF_SO_DELAYED_TCP_TIME_WAIT; \ } else { \ so->so_cfil->cfi_flags &= ~CFIF_SO_DELAYED_TCP_TIME_WAIT; \ } \ } \ } while (0) #define SO_DELAYED_TCP_TIME_WAIT_GET(so) \ (so->so_cfil ? (so->so_cfil->cfi_flags & CFIF_SO_DELAYED_TCP_TIME_WAIT) : false) /* * Periodic Statistics Report: */ static struct thread *cfil_stats_report_thread; #define CFIL_STATS_REPORT_INTERVAL_MIN_MSEC 500 // Highest report frequency #define CFIL_STATS_REPORT_RUN_INTERVAL_NSEC (CFIL_STATS_REPORT_INTERVAL_MIN_MSEC * NSEC_PER_MSEC) #define CFIL_STATS_REPORT_MAX_COUNT 50 // Max stats to be reported per run /* This buffer must have same layout as struct cfil_msg_stats_report */ struct cfil_stats_report_buffer { struct cfil_msg_hdr msghdr; uint32_t count; struct cfil_msg_sock_stats stats[CFIL_STATS_REPORT_MAX_COUNT]; }; static struct cfil_stats_report_buffer *global_cfil_stats_report_buffers[MAX_CONTENT_FILTER]; static uint32_t global_cfil_stats_counts[MAX_CONTENT_FILTER]; /* * UDP Garbage Collection: */ #define UDP_FLOW_GC_ACTION_TO 10 // Flow Action Timeout (no action from user space) in seconds #define UDP_FLOW_GC_MAX_COUNT 100 // Max UDP flows to be handled per run /* * UDP flow queue thresholds */ #define UDP_FLOW_GC_MBUF_CNT_MAX (2 << MBSHIFT) // Max mbuf byte count in flow queue (2MB) #define UDP_FLOW_GC_MBUF_NUM_MAX (UDP_FLOW_GC_MBUF_CNT_MAX >> MCLSHIFT) // Max mbuf count in flow queue (1K) #define UDP_FLOW_GC_MBUF_SHIFT 5 // Shift to get 1/32 of platform limits /* * UDP flow queue threshold globals: */ static unsigned int cfil_udp_gc_mbuf_num_max = UDP_FLOW_GC_MBUF_NUM_MAX; static unsigned int cfil_udp_gc_mbuf_cnt_max = UDP_FLOW_GC_MBUF_CNT_MAX; /* * CFIL specific mbuf tag: * Save state of socket at the point of data entry into cfil. * Use saved state for reinjection at protocol layer. */ struct cfil_tag { union sockaddr_in_4_6 cfil_faddr; uint32_t cfil_so_state_change_cnt; uint32_t cfil_so_options; int cfil_inp_flags; }; /* * Global behavior flags: */ #define CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS 0x00000001 static uint32_t cfil_behavior_flags = 0; #define DO_PRESERVE_CONNECTIONS (cfil_behavior_flags & CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS) /* * Statistics */ struct cfil_stats cfil_stats; /* * For troubleshooting */ int cfil_log_level = LOG_ERR; int cfil_log_port = 0; int cfil_log_pid = 0; int cfil_log_proto = 0; int cfil_log_data = 0; int cfil_log_stats = 0; int cfil_debug = 1; /* * Sysctls for logs and statistics */ static int sysctl_cfil_filter_list(struct sysctl_oid *, void *, int, struct sysctl_req *); static int sysctl_cfil_sock_list(struct sysctl_oid *, void *, int, struct sysctl_req *); SYSCTL_NODE(_net, OID_AUTO, cfil, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "cfil"); SYSCTL_INT(_net_cfil, OID_AUTO, log, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_level, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, log_port, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_port, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, log_pid, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_pid, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, log_proto, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_proto, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, log_data, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_data, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, log_stats, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_log_stats, 0, ""); SYSCTL_INT(_net_cfil, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_debug, 0, ""); SYSCTL_UINT(_net_cfil, OID_AUTO, sock_attached_count, CTLFLAG_RD | CTLFLAG_LOCKED, &cfil_sock_attached_count, 0, ""); SYSCTL_UINT(_net_cfil, OID_AUTO, active_count, CTLFLAG_RD | CTLFLAG_LOCKED, &cfil_active_count, 0, ""); SYSCTL_UINT(_net_cfil, OID_AUTO, close_wait_timeout, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_close_wait_timeout, 0, ""); SYSCTL_UINT(_net_cfil, OID_AUTO, behavior_flags, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_behavior_flags, 0, ""); static int cfil_sbtrim = 1; SYSCTL_UINT(_net_cfil, OID_AUTO, sbtrim, CTLFLAG_RW | CTLFLAG_LOCKED, &cfil_sbtrim, 0, ""); SYSCTL_PROC(_net_cfil, OID_AUTO, filter_list, CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, sysctl_cfil_filter_list, "S,cfil_filter_stat", ""); SYSCTL_PROC(_net_cfil, OID_AUTO, sock_list, CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, sysctl_cfil_sock_list, "S,cfil_sock_stat", ""); SYSCTL_STRUCT(_net_cfil, OID_AUTO, stats, CTLFLAG_RD | CTLFLAG_LOCKED, &cfil_stats, cfil_stats, ""); /* * Forward declaration to appease the compiler */ static int cfil_action_data_pass(struct socket *, struct cfil_info *, uint32_t, int, uint64_t, uint64_t); static int cfil_action_drop(struct socket *, struct cfil_info *, uint32_t); static int cfil_action_bless_client(uint32_t, struct cfil_msg_hdr *); static int cfil_action_set_crypto_key(uint32_t, struct cfil_msg_hdr *); static int cfil_dispatch_closed_event(struct socket *, struct cfil_info *, int); static int cfil_data_common(struct socket *, struct cfil_info *, int, struct sockaddr *, struct mbuf *, struct mbuf *, uint32_t); static int cfil_data_filter(struct socket *, struct cfil_info *, uint32_t, int, struct mbuf *, uint32_t); static void fill_ip_sockaddr_4_6(union sockaddr_in_4_6 *, struct in_addr, u_int16_t); static void fill_ip6_sockaddr_4_6(union sockaddr_in_4_6 *, struct in6_addr *, u_int16_t, uint32_t); static int cfil_dispatch_attach_event(struct socket *, struct cfil_info *, uint32_t, int); static void cfil_info_free(struct cfil_info *); static struct cfil_info * cfil_info_alloc(struct socket *, struct soflow_hash_entry *); static int cfil_info_attach_unit(struct socket *, uint32_t, struct cfil_info *); static struct socket * cfil_socket_from_sock_id(cfil_sock_id_t, bool); static struct socket * cfil_socket_from_client_uuid(uuid_t, bool *); static int cfil_service_pending_queue(struct socket *, struct cfil_info *, uint32_t, int); static int cfil_data_service_ctl_q(struct socket *, struct cfil_info *, uint32_t, int); static void cfil_info_verify(struct cfil_info *); static int cfil_update_data_offsets(struct socket *, struct cfil_info *, uint32_t, int, uint64_t, uint64_t); static int cfil_acquire_sockbuf(struct socket *, struct cfil_info *, int); static void cfil_release_sockbuf(struct socket *, int); static int cfil_filters_attached(struct socket *); static void cfil_rw_lock_exclusive(lck_rw_t *); static void cfil_rw_unlock_exclusive(lck_rw_t *); static void cfil_rw_lock_shared(lck_rw_t *); static void cfil_rw_unlock_shared(lck_rw_t *); static boolean_t cfil_rw_lock_shared_to_exclusive(lck_rw_t *); static void cfil_rw_lock_exclusive_to_shared(lck_rw_t *); static unsigned int cfil_data_length(struct mbuf *, int *, int *); static struct cfil_info *cfil_sock_udp_get_info(struct socket *, uint32_t, bool, struct soflow_hash_entry *, struct sockaddr *, struct sockaddr *); static errno_t cfil_sock_udp_handle_data(bool, struct socket *, struct sockaddr *, struct sockaddr *, struct mbuf *, struct mbuf *, uint32_t, struct soflow_hash_entry *); static int32_t cfil_sock_udp_data_pending(struct sockbuf *, bool); static void cfil_sock_udp_is_closed(struct socket *); static int cfil_sock_udp_notify_shutdown(struct socket *, int, int, int); static int cfil_sock_udp_shutdown(struct socket *, int *); static void cfil_sock_udp_close_wait(struct socket *); static void cfil_sock_udp_buf_update(struct sockbuf *); static int cfil_filters_udp_attached(struct socket *, bool); static void cfil_get_flow_address_v6(struct soflow_hash_entry *, struct inpcb *, struct in6_addr **, struct in6_addr **, u_int16_t *, u_int16_t *); static void cfil_get_flow_address(struct soflow_hash_entry *, struct inpcb *, struct in_addr *, struct in_addr *, u_int16_t *, u_int16_t *); static void cfil_info_log(int, struct cfil_info *, const char *); void cfil_filter_show(u_int32_t); void cfil_info_show(void); bool cfil_info_action_timed_out(struct cfil_info *, int); bool cfil_info_buffer_threshold_exceeded(struct cfil_info *); struct m_tag *cfil_dgram_save_socket_state(struct cfil_info *, struct mbuf *); boolean_t cfil_dgram_peek_socket_state(struct mbuf *m, int *inp_flags); static void cfil_sock_received_verdict(struct socket *so); static void cfil_fill_event_msg_addresses(struct soflow_hash_entry *, struct inpcb *, union sockaddr_in_4_6 *, union sockaddr_in_4_6 *, boolean_t, boolean_t); static void cfil_stats_report_thread_func(void *, wait_result_t); static void cfil_stats_report(void *v, wait_result_t w); static bool cfil_dgram_gc_needed(struct socket *, struct soflow_hash_entry *, u_int64_t); static bool cfil_dgram_gc_perform(struct socket *, struct soflow_hash_entry *); static bool cfil_dgram_detach_entry(struct socket *, struct soflow_hash_entry *); static bool cfil_dgram_detach_db(struct socket *, struct soflow_db *); bool check_port(struct sockaddr *, u_short); __printflike(3, 4) static void cfil_log_printf(struct socket *so, struct cfil_info *info, const char *format, ...); /* * Content filter global read write lock */ static void cfil_rw_lock_exclusive(lck_rw_t *lck) { void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); lck_rw_lock_exclusive(lck); cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved; cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX; } static void cfil_rw_unlock_exclusive(lck_rw_t *lck) { void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); lck_rw_unlock_exclusive(lck); cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved; cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX; } static void cfil_rw_lock_shared(lck_rw_t *lck) { void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); lck_rw_lock_shared(lck); cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved; cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX; } static void cfil_rw_unlock_shared(lck_rw_t *lck) { void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); lck_rw_unlock_shared(lck); cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved; cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX; } static boolean_t cfil_rw_lock_shared_to_exclusive(lck_rw_t *lck) { boolean_t upgraded; void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); upgraded = lck_rw_lock_shared_to_exclusive(lck); if (upgraded) { cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved; cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX; } return upgraded; } static void cfil_rw_lock_exclusive_to_shared(lck_rw_t *lck) { void * __single lr_saved; lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0)); lck_rw_lock_exclusive_to_shared(lck); cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved; cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX; } static void cfil_rw_lock_assert_held(lck_rw_t *lck, int exclusive) { #if !MACH_ASSERT #pragma unused(lck, exclusive) #endif LCK_RW_ASSERT(lck, exclusive ? LCK_RW_ASSERT_EXCLUSIVE : LCK_RW_ASSERT_HELD); } /* * Return the number of bytes in the mbuf chain using the same * method as m_length() or sballoc() * * Returns data len - starting from PKT start * - retmbcnt - optional param to get total mbuf bytes in chain * - retmbnum - optional param to get number of mbufs in chain */ static unsigned int cfil_data_length(struct mbuf *m, int *retmbcnt, int *retmbnum) { struct mbuf *m0; unsigned int pktlen = 0; int mbcnt; int mbnum; // Locate M_PKTHDR and mark as start of data if present for (m0 = m; m0 != NULL; m0 = m0->m_next) { if (m0->m_flags & M_PKTHDR) { m = m0; break; } } if (retmbcnt == NULL && retmbnum == NULL) { return m_length(m); } pktlen = 0; mbcnt = 0; mbnum = 0; for (m0 = m; m0 != NULL; m0 = m0->m_next) { pktlen += m0->m_len; mbnum++; mbcnt += _MSIZE; if (m0->m_flags & M_EXT) { mbcnt += m0->m_ext.ext_size; } } if (retmbcnt) { *retmbcnt = mbcnt; } if (retmbnum) { *retmbnum = mbnum; } return pktlen; } static struct mbuf * cfil_data_start(struct mbuf *m) { struct mbuf *m0; // Locate M_PKTHDR and use it as start of data if present for (m0 = m; m0 != NULL; m0 = m0->m_next) { if (m0->m_flags & M_PKTHDR) { return m0; } } return m; } /* * Common mbuf queue utilities */ static inline void cfil_queue_init(struct cfil_queue *cfq) { cfq->q_start = 0; cfq->q_end = 0; MBUFQ_INIT(&cfq->q_mq); } static inline uint64_t cfil_queue_drain(struct cfil_queue *cfq) { uint64_t drained = cfq->q_start - cfq->q_end; cfq->q_start = 0; cfq->q_end = 0; MBUFQ_DRAIN(&cfq->q_mq); return drained; } /* Return 1 when empty, 0 otherwise */ static inline int cfil_queue_empty(struct cfil_queue *cfq) { return MBUFQ_EMPTY(&cfq->q_mq); } static inline uint64_t cfil_queue_offset_first(struct cfil_queue *cfq) { return cfq->q_start; } static inline uint64_t cfil_queue_offset_last(struct cfil_queue *cfq) { return cfq->q_end; } static inline uint64_t cfil_queue_len(struct cfil_queue *cfq) { return cfq->q_end - cfq->q_start; } /* * Routines to verify some fundamental assumptions */ static void cfil_queue_verify(struct cfil_queue *cfq) { mbuf_t chain; mbuf_t m; mbuf_t n; uint64_t queuesize = 0; /* Verify offset are ordered */ VERIFY(cfq->q_start <= cfq->q_end); /* * When queue is empty, the offsets are equal otherwise the offsets * are different */ VERIFY((MBUFQ_EMPTY(&cfq->q_mq) && cfq->q_start == cfq->q_end) || (!MBUFQ_EMPTY(&cfq->q_mq) && cfq->q_start != cfq->q_end)); MBUFQ_FOREACH(chain, &cfq->q_mq) { size_t chainsize = 0; m = chain; unsigned int mlen = cfil_data_length(m, NULL, NULL); // skip the addr and control stuff if present m = cfil_data_start(m); if (m == NULL || m == (void *)M_TAG_FREE_PATTERN || m->m_next == (void *)M_TAG_FREE_PATTERN || m->m_nextpkt == (void *)M_TAG_FREE_PATTERN) { panic("%s - mq %p is free at %p", __func__, &cfq->q_mq, m); } for (n = m; n != NULL; n = n->m_next) { if (!m_has_mtype(n, MTF_DATA | MTF_HEADER | MTF_OOBDATA)) { panic("%s - %p unsupported type %u", __func__, n, n->m_type); } chainsize += n->m_len; } if (mlen != chainsize) { panic("%s - %p m_length() %u != chainsize %lu", __func__, m, mlen, chainsize); } queuesize += chainsize; } OS_ANALYZER_SUPPRESS("81031590") if (queuesize != cfq->q_end - cfq->q_start) { panic("%s - %p queuesize %llu != offsetdiffs %llu", __func__, m, queuesize, cfq->q_end - cfq->q_start); } } static void cfil_queue_enqueue(struct cfil_queue *cfq, mbuf_t m, size_t len) { CFIL_QUEUE_VERIFY(cfq); MBUFQ_ENQUEUE(&cfq->q_mq, m); cfq->q_end += len; CFIL_QUEUE_VERIFY(cfq); } static void cfil_queue_remove(struct cfil_queue *cfq, mbuf_t m, size_t len) { CFIL_QUEUE_VERIFY(cfq); VERIFY(cfil_data_length(m, NULL, NULL) == len); MBUFQ_REMOVE(&cfq->q_mq, m); MBUFQ_NEXT(m) = NULL; cfq->q_start += len; CFIL_QUEUE_VERIFY(cfq); } static mbuf_t cfil_queue_first(struct cfil_queue *cfq) { return MBUFQ_FIRST(&cfq->q_mq); } static mbuf_t cfil_queue_next(struct cfil_queue *cfq, mbuf_t m) { #pragma unused(cfq) return MBUFQ_NEXT(m); } static void cfil_entry_buf_verify(struct cfe_buf *cfe_buf) { CFIL_QUEUE_VERIFY(&cfe_buf->cfe_ctl_q); CFIL_QUEUE_VERIFY(&cfe_buf->cfe_pending_q); /* Verify the queues are ordered so that pending is before ctl */ VERIFY(cfe_buf->cfe_ctl_q.q_start >= cfe_buf->cfe_pending_q.q_end); /* The peek offset cannot be less than the pass offset */ VERIFY(cfe_buf->cfe_peek_offset >= cfe_buf->cfe_pass_offset); /* Make sure we've updated the offset we peeked at */ VERIFY(cfe_buf->cfe_ctl_q.q_start <= cfe_buf->cfe_peeked); } static void cfil_entry_verify(struct cfil_entry *entry) { cfil_entry_buf_verify(&entry->cfe_snd); cfil_entry_buf_verify(&entry->cfe_rcv); } static void cfil_info_buf_verify(struct cfi_buf *cfi_buf) { CFIL_QUEUE_VERIFY(&cfi_buf->cfi_inject_q); VERIFY(cfi_buf->cfi_pending_first <= cfi_buf->cfi_pending_last); } static void cfil_info_verify(struct cfil_info *cfil_info) { int i; if (cfil_info == NULL) { return; } cfil_info_buf_verify(&cfil_info->cfi_snd); cfil_info_buf_verify(&cfil_info->cfi_rcv); for (i = 0; i < MAX_CONTENT_FILTER; i++) { cfil_entry_verify(&cfil_info->cfi_entries[i]); } } static void verify_content_filter(struct content_filter *cfc) { struct cfil_entry *entry; uint32_t count = 0; VERIFY(cfc->cf_sock_count >= 0); TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) { count++; VERIFY(cfc == entry->cfe_filter); } VERIFY(count == cfc->cf_sock_count); } /* * Kernel control socket callbacks */ static errno_t cfil_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo) { errno_t error = 0; struct content_filter * __single cfc = NULL; CFIL_LOG(LOG_NOTICE, ""); cfc = zalloc_flags(content_filter_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL); cfil_rw_lock_exclusive(&cfil_lck_rw); if (sac->sc_unit == 0 || sac->sc_unit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "bad sc_unit %u", sac->sc_unit); error = EINVAL; } else if (content_filters[sac->sc_unit - 1] != NULL) { CFIL_LOG(LOG_ERR, "sc_unit %u in use", sac->sc_unit); error = EADDRINUSE; } else { /* * kernel control socket kcunit numbers start at 1 */ content_filters[sac->sc_unit - 1] = cfc; cfc->cf_kcref = kctlref; cfc->cf_kcunit = sac->sc_unit; TAILQ_INIT(&cfc->cf_sock_entries); *unitinfo = cfc; cfil_active_count++; if (cfil_active_count == 1) { soflow_feat_set_functions(cfil_dgram_gc_needed, cfil_dgram_gc_perform, cfil_dgram_detach_entry, cfil_dgram_detach_db); } // Allocate periodic stats buffer for this filter if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] == NULL) { cfil_rw_unlock_exclusive(&cfil_lck_rw); struct cfil_stats_report_buffer * __single buf; buf = kalloc_type(struct cfil_stats_report_buffer, Z_WAITOK | Z_ZERO | Z_NOFAIL); cfil_rw_lock_exclusive(&cfil_lck_rw); /* Another thread may have won the race */ if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] != NULL) { kfree_type(struct cfil_stats_report_buffer, buf); } else { global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] = buf; } } } cfil_rw_unlock_exclusive(&cfil_lck_rw); if (error != 0 && cfc != NULL) { zfree(content_filter_zone, cfc); } if (error == 0) { OSIncrementAtomic(&cfil_stats.cfs_ctl_connect_ok); } else { OSIncrementAtomic(&cfil_stats.cfs_ctl_connect_fail); } CFIL_LOG(LOG_INFO, "return %d cfil_active_count %u kcunit %u", error, cfil_active_count, sac->sc_unit); return error; } static void cfil_update_behavior_flags(void) { struct content_filter *cfc = NULL; // Update global flag bool preserve_connections = false; for (int i = 0; i < MAX_CONTENT_FILTER; i++) { cfc = content_filters[i]; if (cfc != NULL) { if (cfc->cf_flags & CFF_PRESERVE_CONNECTIONS) { preserve_connections = true; } else { preserve_connections = false; break; } } } if (preserve_connections == true) { cfil_behavior_flags |= CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS; } else { cfil_behavior_flags &= ~CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS; } CFIL_LOG(LOG_INFO, "CFIL Preserve Connections - %s", (cfil_behavior_flags & CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS) ? "On" : "Off"); } static errno_t cfil_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo) { #pragma unused(kctlref) errno_t error = 0; struct content_filter * __single cfc; struct cfil_entry *entry; uint64_t sock_flow_id = 0; CFIL_LOG(LOG_NOTICE, ""); if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); error = EINVAL; goto done; } cfc = (struct content_filter *)unitinfo; if (cfc == NULL) { goto done; } cfil_rw_lock_exclusive(&cfil_lck_rw); if (content_filters[kcunit - 1] != cfc || cfc->cf_kcunit != kcunit) { CFIL_LOG(LOG_ERR, "bad unit info %u)", kcunit); cfil_rw_unlock_exclusive(&cfil_lck_rw); goto done; } cfc->cf_flags |= CFF_DETACHING; /* * Remove all sockets from the filter */ while ((entry = TAILQ_FIRST(&cfc->cf_sock_entries)) != NULL) { cfil_rw_lock_assert_held(&cfil_lck_rw, 1); verify_content_filter(cfc); /* * Accept all outstanding data by pushing to next filter * or back to socket * * TBD: Actually we should make sure all data has been pushed * back to socket */ if (entry->cfe_cfil_info && entry->cfe_cfil_info->cfi_so) { struct cfil_info *cfil_info = entry->cfe_cfil_info; struct socket *so = cfil_info->cfi_so; sock_flow_id = cfil_info->cfi_sock_id; /* Need to let data flow immediately */ entry->cfe_flags |= CFEF_SENT_SOCK_ATTACHED | CFEF_DATA_START; // Before we release global lock, retain the cfil_info - // We attempt to retain a valid cfil_info to prevent any deallocation until // we are done. Abort retain if cfil_info has already entered the free code path. if (cfil_info == NULL || os_ref_retain_try(&cfil_info->cfi_ref_count) == false) { // Failing to retain cfil_info means detach is in progress already, // remove entry from filter list and move on. entry->cfe_filter = NULL; entry->cfe_necp_control_unit = 0; TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link); cfc->cf_sock_count--; continue; } /* * Respect locking hierarchy */ cfil_rw_unlock_exclusive(&cfil_lck_rw); // Search for socket from cfil_info sock_flow_id and lock so so = cfil_socket_from_sock_id(sock_flow_id, false); if (so == NULL || so != cfil_info->cfi_so) { cfil_rw_lock_exclusive(&cfil_lck_rw); // Socket has already been disconnected and removed from socket list. // Remove entry from filter list and move on. if (entry == TAILQ_FIRST(&cfc->cf_sock_entries)) { entry->cfe_filter = NULL; entry->cfe_necp_control_unit = 0; TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link); cfc->cf_sock_count--; } goto release_cfil_info; } /* * When cfe_filter is NULL the filter is detached * and the entry has been removed from cf_sock_entries */ if ((so->so_cfil == NULL && so->so_flow_db == NULL) || entry->cfe_filter == NULL) { cfil_rw_lock_exclusive(&cfil_lck_rw); goto release; } (void) cfil_action_data_pass(so, cfil_info, kcunit, 1, CFM_MAX_OFFSET, CFM_MAX_OFFSET); (void) cfil_action_data_pass(so, cfil_info, kcunit, 0, CFM_MAX_OFFSET, CFM_MAX_OFFSET); cfil_rw_lock_exclusive(&cfil_lck_rw); /* * Check again to make sure if the cfil_info is still valid * as the socket may have been unlocked when when calling * cfil_acquire_sockbuf() */ if (entry->cfe_filter == NULL || (so->so_cfil == NULL && soflow_db_get_feature_context(so->so_flow_db, sock_flow_id) == NULL)) { goto release; } /* The filter is now detached */ entry->cfe_flags |= CFEF_CFIL_DETACHED; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: FILTER DISCONNECTED"); } CFIL_LOG(LOG_NOTICE, "so %llx detached %u", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit); if ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) && cfil_filters_attached(so) == 0) { CFIL_LOG(LOG_NOTICE, "so %llx waking", (uint64_t)VM_KERNEL_ADDRPERM(so)); wakeup((caddr_t)cfil_info); } /* * Remove the filter entry from the content filter * but leave the rest of the state intact as the queues * may not be empty yet */ entry->cfe_filter = NULL; entry->cfe_necp_control_unit = 0; TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link); cfc->cf_sock_count--; // This is the last filter disconnecting, clear the cfil_info // saved policy state so we will be able to drop this flow if // a new filter get installed. if (cfil_active_count == 1) { cfil_info->cfi_filter_control_unit = 0; cfil_info->cfi_filter_policy_gencount = 0; } release: socket_unlock(so, 1); release_cfil_info: /* * Release reference on cfil_info. To avoid double locking, * temporarily unlock in case it has been detached and we * end up freeing it which will take the global lock again. */ cfil_rw_unlock_exclusive(&cfil_lck_rw); CFIL_INFO_FREE(cfil_info); cfil_rw_lock_exclusive(&cfil_lck_rw); } } verify_content_filter(cfc); /* Free the stats buffer for this filter */ if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] != NULL) { kfree_type(struct cfil_stats_report_buffer, global_cfil_stats_report_buffers[cfc->cf_kcunit - 1]); global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] = NULL; } VERIFY(cfc->cf_sock_count == 0); /* * Make filter inactive */ content_filters[kcunit - 1] = NULL; cfil_active_count--; cfil_update_behavior_flags(); cfil_rw_unlock_exclusive(&cfil_lck_rw); if (cfc->cf_crypto_state != NULL) { cfil_crypto_cleanup_state(cfc->cf_crypto_state); cfc->cf_crypto_state = NULL; } zfree(content_filter_zone, cfc); done: if (error == 0) { OSIncrementAtomic(&cfil_stats.cfs_ctl_disconnect_ok); } else { OSIncrementAtomic(&cfil_stats.cfs_ctl_disconnect_fail); } CFIL_LOG(LOG_INFO, "return %d cfil_active_count %u kcunit %u", error, cfil_active_count, kcunit); return error; } /* * cfil_acquire_sockbuf() * * Prevent any other thread from acquiring the sockbuf * We use sb_cfil_thread as a semaphore to prevent other threads from * messing with the sockbuf -- see sblock() * Note: We do not set SB_LOCK here because the thread may check or modify * SB_LOCK several times until it calls cfil_release_sockbuf() -- currently * sblock(), sbunlock() or sodefunct() */ static int cfil_acquire_sockbuf(struct socket *so, struct cfil_info *cfil_info, int outgoing) { thread_t __single tp = current_thread(); struct sockbuf *sb = outgoing ? &so->so_snd : &so->so_rcv; lck_mtx_t *mutex_held; int error = 0; /* * Wait until no thread is holding the sockbuf and other content * filter threads have released the sockbuf */ while ((sb->sb_flags & SB_LOCK) || (sb->sb_cfil_thread != NULL && sb->sb_cfil_thread != tp)) { if (so->so_proto->pr_getlock != NULL) { mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK); } else { mutex_held = so->so_proto->pr_domain->dom_mtx; } LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED); sb->sb_wantlock++; VERIFY(sb->sb_wantlock != 0); msleep(&sb->sb_flags, mutex_held, PSOCK, "cfil_acquire_sockbuf", NULL); VERIFY(sb->sb_wantlock != 0); sb->sb_wantlock--; } /* * Use reference count for repetitive calls on same thread */ if (sb->sb_cfil_refs == 0) { VERIFY(sb->sb_cfil_thread == NULL); VERIFY((sb->sb_flags & SB_LOCK) == 0); sb->sb_cfil_thread = tp; sb->sb_flags |= SB_LOCK; } sb->sb_cfil_refs++; /* We acquire the socket buffer when we need to cleanup */ if (cfil_info == NULL) { CFIL_LOG(LOG_ERR, "so %llx cfil detached", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = 0; } else if (cfil_info->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EPIPE; } return error; } static void cfil_release_sockbuf(struct socket *so, int outgoing) { struct sockbuf *sb = outgoing ? &so->so_snd : &so->so_rcv; thread_t __single tp = current_thread(); socket_lock_assert_owned(so); if (sb->sb_cfil_thread != NULL && sb->sb_cfil_thread != tp) { panic("%s sb_cfil_thread %p not current %p", __func__, sb->sb_cfil_thread, tp); } /* * Don't panic if we are defunct because SB_LOCK has * been cleared by sodefunct() */ if (!(so->so_flags & SOF_DEFUNCT) && !(sb->sb_flags & SB_LOCK)) { panic("%s SB_LOCK not set on %p", __func__, sb); } /* * We can unlock when the thread unwinds to the last reference */ sb->sb_cfil_refs--; if (sb->sb_cfil_refs == 0) { sb->sb_cfil_thread = NULL; sb->sb_flags &= ~SB_LOCK; if (sb->sb_wantlock > 0) { wakeup(&sb->sb_flags); } } } cfil_sock_id_t cfil_sock_id_from_socket(struct socket *so) { if ((so->so_flags & SOF_CONTENT_FILTER) && so->so_cfil) { return so->so_cfil->cfi_sock_id; } else { return CFIL_SOCK_ID_NONE; } } /* * cfil_socket_safe_lock - * This routine attempts to lock the socket safely. * * The passed in pcbinfo is assumed to be locked and must be unlocked once the * inp state is safeguarded and before we attempt to lock/unlock the socket. * This is to prevent getting blocked by socket_lock() while holding the pcbinfo * lock, avoiding potential deadlock with other processes contending for the same * resources. This is also to avoid double locking the pcbinfo for rip sockets * since rip_unlock() will lock ripcbinfo if it needs to dispose inpcb when * so_usecount is 0. */ static bool cfil_socket_safe_lock(struct inpcb *inp, struct inpcbinfo *pcbinfo) { struct socket *so = NULL; VERIFY(pcbinfo != NULL); if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) { // Safeguarded the inp state, unlock pcbinfo before locking socket. lck_rw_done(&pcbinfo->ipi_lock); so = inp->inp_socket; socket_lock(so, 1); if (in_pcb_checkstate(inp, WNT_RELEASE, 1) != WNT_STOPUSING) { return true; } } else { // Failed to safeguarded the inp state, unlock pcbinfo and abort. lck_rw_done(&pcbinfo->ipi_lock); } if (so) { socket_unlock(so, 1); } return false; } static struct socket * cfil_socket_from_sock_id(cfil_sock_id_t cfil_sock_id, bool udp_only) { struct socket *so = NULL; u_int64_t gencnt = cfil_sock_id >> 32; u_int32_t flowhash = (u_int32_t)(cfil_sock_id & 0x0ffffffff); struct inpcb *inp = NULL; struct inpcbinfo *pcbinfo = NULL; if (udp_only) { goto find_udp; } pcbinfo = &tcbinfo; lck_rw_lock_shared(&pcbinfo->ipi_lock); LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) { if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket != NULL && inp->inp_flowhash == flowhash && (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt && inp->inp_socket->so_cfil != NULL) { if (cfil_socket_safe_lock(inp, pcbinfo)) { so = inp->inp_socket; } /* pcbinfo is already unlocked, we are done. */ goto done; } } lck_rw_done(&pcbinfo->ipi_lock); if (so != NULL) { goto done; } find_udp: pcbinfo = &udbinfo; lck_rw_lock_shared(&pcbinfo->ipi_lock); LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) { if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket != NULL && inp->inp_socket->so_flow_db != NULL && (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt) { if (cfil_socket_safe_lock(inp, pcbinfo)) { so = inp->inp_socket; } /* pcbinfo is already unlocked, we are done. */ goto done; } } lck_rw_done(&pcbinfo->ipi_lock); if (so != NULL) { goto done; } pcbinfo = &ripcbinfo; lck_rw_lock_shared(&pcbinfo->ipi_lock); LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) { if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket != NULL && inp->inp_socket->so_flow_db != NULL && (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt) { if (cfil_socket_safe_lock(inp, pcbinfo)) { so = inp->inp_socket; } /* pcbinfo is already unlocked, we are done. */ goto done; } } lck_rw_done(&pcbinfo->ipi_lock); done: if (so == NULL) { OSIncrementAtomic(&cfil_stats.cfs_sock_id_not_found); CFIL_LOG(LOG_DEBUG, "no socket for sock_id %llx gencnt %llx flowhash %x", cfil_sock_id, gencnt, flowhash); } return so; } static struct socket * cfil_socket_from_client_uuid(uuid_t necp_client_uuid, bool *cfil_attached) { struct socket *so = NULL; struct inpcb *inp = NULL; struct inpcbinfo *pcbinfo = &tcbinfo; lck_rw_lock_shared(&pcbinfo->ipi_lock); LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) { if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket != NULL && uuid_compare(inp->necp_client_uuid, necp_client_uuid) == 0) { *cfil_attached = (inp->inp_socket->so_cfil != NULL); if (cfil_socket_safe_lock(inp, pcbinfo)) { so = inp->inp_socket; } /* pcbinfo is already unlocked, we are done. */ goto done; } } lck_rw_done(&pcbinfo->ipi_lock); if (so != NULL) { goto done; } pcbinfo = &udbinfo; lck_rw_lock_shared(&pcbinfo->ipi_lock); LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) { if (inp->inp_state != INPCB_STATE_DEAD && inp->inp_socket != NULL && uuid_compare(inp->necp_client_uuid, necp_client_uuid) == 0) { *cfil_attached = (inp->inp_socket->so_flow_db != NULL); if (cfil_socket_safe_lock(inp, pcbinfo)) { so = inp->inp_socket; } /* pcbinfo is already unlocked, we are done. */ goto done; } } lck_rw_done(&pcbinfo->ipi_lock); done: return so; } static void cfil_info_stats_toggle(struct cfil_info *cfil_info, struct cfil_entry *entry, uint32_t report_frequency) { struct cfil_info *cfil = NULL; Boolean found = FALSE; int kcunit; if (cfil_info == NULL) { return; } if (report_frequency) { if (entry == NULL) { return; } // Update stats reporting frequency. if (entry->cfe_stats_report_frequency != report_frequency) { entry->cfe_stats_report_frequency = report_frequency; if (entry->cfe_stats_report_frequency < CFIL_STATS_REPORT_INTERVAL_MIN_MSEC) { entry->cfe_stats_report_frequency = CFIL_STATS_REPORT_INTERVAL_MIN_MSEC; } microuptime(&entry->cfe_stats_report_ts); // Insert cfil_info into list only if it is not in yet. TAILQ_FOREACH(cfil, &cfil_sock_head_stats, cfi_link_stats) { if (cfil == cfil_info) { return; } } TAILQ_INSERT_TAIL(&cfil_sock_head_stats, cfil_info, cfi_link_stats); // Wake up stats thread if this is first flow added if (cfil_sock_attached_stats_count == 0) { thread_wakeup((caddr_t)&cfil_sock_attached_stats_count); } cfil_sock_attached_stats_count++; if (cfil_info->cfi_debug && cfil_log_stats) { CFIL_LOG(LOG_ERR, "CFIL: VERDICT RECEIVED - STATS FLOW INSERTED: <so %llx sockID %llu <%llx>> stats frequency %d msecs", cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0, cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, entry->cfe_stats_report_frequency); } } } else { // Turn off stats reporting for this filter. if (entry != NULL) { // Already off, no change. if (entry->cfe_stats_report_frequency == 0) { return; } entry->cfe_stats_report_frequency = 0; // If cfil_info still has filter(s) asking for stats, no need to remove from list. for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { if (cfil_info->cfi_entries[kcunit - 1].cfe_stats_report_frequency > 0) { return; } } } // No more filter asking for stats for this cfil_info, remove from list. if (!TAILQ_EMPTY(&cfil_sock_head_stats)) { found = FALSE; TAILQ_FOREACH(cfil, &cfil_sock_head_stats, cfi_link_stats) { if (cfil == cfil_info) { found = TRUE; break; } } if (found) { cfil_sock_attached_stats_count--; TAILQ_REMOVE(&cfil_sock_head_stats, cfil_info, cfi_link_stats); if (cfil_info->cfi_debug && cfil_log_stats) { CFIL_LOG(LOG_ERR, "CFIL: VERDICT RECEIVED - STATS FLOW DELETED: <so %llx sockID %llu <%llx>> stats frequency reset", cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0, cfil_info->cfi_sock_id, cfil_info->cfi_sock_id); } } } } } static errno_t cfil_ctl_send(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, mbuf_t m, int flags) { #pragma unused(kctlref, flags) errno_t error = 0; struct cfil_msg_hdr *msghdr; struct content_filter *cfc = (struct content_filter *)unitinfo; struct socket *so; struct cfil_msg_action * __single action_msg; struct cfil_entry *entry; struct cfil_info * __single cfil_info = NULL; unsigned int data_len = 0; CFIL_LOG(LOG_INFO, ""); if (cfc == NULL) { CFIL_LOG(LOG_ERR, "no unitinfo"); error = EINVAL; goto done; } if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); error = EINVAL; goto done; } if (m == NULL) { CFIL_LOG(LOG_ERR, "null mbuf"); error = EINVAL; goto done; } data_len = m_length(m); if (data_len < sizeof(struct cfil_msg_hdr)) { CFIL_LOG(LOG_ERR, "too short %u", data_len); error = EINVAL; goto done; } msghdr = mtod(m, struct cfil_msg_hdr *); if (msghdr->cfm_version != CFM_VERSION_CURRENT) { CFIL_LOG(LOG_ERR, "bad version %u", msghdr->cfm_version); error = EINVAL; goto done; } if (msghdr->cfm_type != CFM_TYPE_ACTION) { CFIL_LOG(LOG_ERR, "bad type %u", msghdr->cfm_type); error = EINVAL; goto done; } if (msghdr->cfm_len > data_len) { CFIL_LOG(LOG_ERR, "bad length %u", msghdr->cfm_len); error = EINVAL; goto done; } /* Validate action operation */ switch (msghdr->cfm_op) { case CFM_OP_DATA_UPDATE: OSIncrementAtomic( &cfil_stats.cfs_ctl_action_data_update); break; case CFM_OP_DROP: OSIncrementAtomic(&cfil_stats.cfs_ctl_action_drop); break; case CFM_OP_BLESS_CLIENT: if (msghdr->cfm_len != sizeof(struct cfil_msg_bless_client)) { OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len); error = EINVAL; CFIL_LOG(LOG_ERR, "bad len: %u for op %u", msghdr->cfm_len, msghdr->cfm_op); goto done; } error = cfil_action_bless_client(kcunit, msghdr); goto done; case CFM_OP_SET_CRYPTO_KEY: if (msghdr->cfm_len != sizeof(struct cfil_msg_set_crypto_key)) { OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len); error = EINVAL; CFIL_LOG(LOG_ERR, "bad len: %u for op %u", msghdr->cfm_len, msghdr->cfm_op); goto done; } error = cfil_action_set_crypto_key(kcunit, msghdr); goto done; default: OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_op); CFIL_LOG(LOG_ERR, "bad op %u", msghdr->cfm_op); error = EINVAL; goto done; } if (msghdr->cfm_len != sizeof(struct cfil_msg_action)) { OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len); error = EINVAL; CFIL_LOG(LOG_ERR, "bad len: %u for op %u", msghdr->cfm_len, msghdr->cfm_op); goto done; } cfil_rw_lock_shared(&cfil_lck_rw); if (cfc != (void *)content_filters[kcunit - 1]) { CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u", kcunit); error = EINVAL; cfil_rw_unlock_shared(&cfil_lck_rw); goto done; } cfil_rw_unlock_shared(&cfil_lck_rw); // Search for socket (TCP+UDP and lock so) so = cfil_socket_from_sock_id(msghdr->cfm_sock_id, false); if (so == NULL) { CFIL_LOG(LOG_NOTICE, "bad sock_id %llx", msghdr->cfm_sock_id); error = EINVAL; goto done; } cfil_info = so->so_flow_db != NULL ? soflow_db_get_feature_context(so->so_flow_db, msghdr->cfm_sock_id) : so->so_cfil; // We should not obtain global lock here in order to avoid deadlock down the path. // But we attempt to retain a valid cfil_info to prevent any deallocation until // we are done. Abort retain if cfil_info has already entered the free code path. if (cfil_info && os_ref_retain_try(&cfil_info->cfi_ref_count) == false) { socket_unlock(so, 1); goto done; } if (cfil_info == NULL) { CFIL_LOG(LOG_NOTICE, "so %llx <id %llu> not attached", (uint64_t)VM_KERNEL_ADDRPERM(so), msghdr->cfm_sock_id); error = EINVAL; goto unlock; } else if (cfil_info->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_NOTICE, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EINVAL; goto unlock; } if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: RECEIVED MSG FROM FILTER"); } entry = &cfil_info->cfi_entries[kcunit - 1]; if (entry->cfe_filter == NULL) { CFIL_LOG(LOG_NOTICE, "so %llx no filter", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EINVAL; goto unlock; } if (entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) { entry->cfe_flags |= CFEF_DATA_START; } else { CFIL_LOG(LOG_ERR, "so %llx attached not sent for %u", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit); error = EINVAL; goto unlock; } microuptime(&entry->cfe_last_action); CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_action, &cfil_info->cfi_first_event, msghdr->cfm_op); action_msg = (struct cfil_msg_action *)msghdr; switch (msghdr->cfm_op) { case CFM_OP_DATA_UPDATE: if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: RECEIVED CFM_OP_DATA_UPDATE"); CFIL_LOG(LOG_ERR, "CFIL: VERDICT RECEIVED: <so %llx sockID %llu <%llx>> <IN peek:%llu pass:%llu, OUT peek:%llu pass:%llu>", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, action_msg->cfa_in_peek_offset, action_msg->cfa_in_pass_offset, action_msg->cfa_out_peek_offset, action_msg->cfa_out_pass_offset); } /* * Received verdict, at this point we know this * socket connection is allowed. Unblock thread * immediately before proceeding to process the verdict. */ cfil_sock_received_verdict(so); if (action_msg->cfa_out_peek_offset != 0 || action_msg->cfa_out_pass_offset != 0) { error = cfil_action_data_pass(so, cfil_info, kcunit, 1, action_msg->cfa_out_pass_offset, action_msg->cfa_out_peek_offset); } if (error == EJUSTRETURN) { error = 0; } if (error != 0) { break; } if (action_msg->cfa_in_peek_offset != 0 || action_msg->cfa_in_pass_offset != 0) { error = cfil_action_data_pass(so, cfil_info, kcunit, 0, action_msg->cfa_in_pass_offset, action_msg->cfa_in_peek_offset); } if (error == EJUSTRETURN) { error = 0; } // Toggle stats reporting according to received verdict. cfil_rw_lock_exclusive(&cfil_lck_rw); cfil_info_stats_toggle(cfil_info, entry, action_msg->cfa_stats_frequency); cfil_rw_unlock_exclusive(&cfil_lck_rw); break; case CFM_OP_DROP: cfil_info_log(LOG_ERR, cfil_info, "CFIL: RECEIVED CFM_OP_DROP"); CFIL_LOG(LOG_ERR, "CFIL: VERDICT DROP RECEIVED: <so %llx sockID %llu <%llx>> <IN peek:%llu pass:%llu, OUT peek:%llu pass:%llu>", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, action_msg->cfa_in_peek_offset, action_msg->cfa_in_pass_offset, action_msg->cfa_out_peek_offset, action_msg->cfa_out_pass_offset); error = cfil_action_drop(so, cfil_info, kcunit); cfil_sock_received_verdict(so); break; default: error = EINVAL; break; } unlock: CFIL_INFO_FREE(cfil_info) socket_unlock(so, 1); done: mbuf_freem(m); if (error == 0) { OSIncrementAtomic(&cfil_stats.cfs_ctl_send_ok); } else { OSIncrementAtomic(&cfil_stats.cfs_ctl_send_bad); } return error; } static errno_t cfil_ctl_getopt(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, int opt, void *data, size_t *len) { #pragma unused(kctlref, opt) struct cfil_info * __single cfil_info = NULL; errno_t error = 0; struct content_filter *cfc = (struct content_filter *)unitinfo; CFIL_LOG(LOG_NOTICE, ""); if (cfc == NULL) { CFIL_LOG(LOG_ERR, "no unitinfo"); return EINVAL; } cfil_rw_lock_shared(&cfil_lck_rw); if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); error = EINVAL; goto done; } if (cfc != (void *)content_filters[kcunit - 1]) { CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u", kcunit); error = EINVAL; goto done; } switch (opt) { case CFIL_OPT_NECP_CONTROL_UNIT: if (*len < sizeof(uint32_t)) { CFIL_LOG(LOG_ERR, "len too small %lu", *len); error = EINVAL; goto done; } if (data != NULL) { *(uint32_t *)data = cfc->cf_necp_control_unit; } break; case CFIL_OPT_PRESERVE_CONNECTIONS: if (*len < sizeof(uint32_t)) { CFIL_LOG(LOG_ERR, "CFIL_OPT_PRESERVE_CONNECTIONS len too small %lu", *len); error = EINVAL; goto done; } if (data != NULL) { *(uint32_t *)data = (cfc->cf_flags & CFF_PRESERVE_CONNECTIONS) ? true : false; } break; case CFIL_OPT_GET_SOCKET_INFO: if (*len != sizeof(struct cfil_opt_sock_info)) { CFIL_LOG(LOG_ERR, "len does not match %lu", *len); error = EINVAL; goto done; } if (data == NULL) { CFIL_LOG(LOG_ERR, "data not passed"); error = EINVAL; goto done; } struct cfil_opt_sock_info *sock_info = (struct cfil_opt_sock_info *) data; // Unlock here so that we never hold both cfil_lck_rw and the // socket_lock at the same time. Otherwise, this can deadlock // because soclose() takes the socket_lock and then exclusive // cfil_lck_rw and we require the opposite order. // WARNING: Be sure to never use anything protected // by cfil_lck_rw beyond this point. // WARNING: Be sure to avoid fallthrough and // goto return_already_unlocked from this branch. cfil_rw_unlock_shared(&cfil_lck_rw); // Search (TCP+UDP) and lock socket struct socket *sock = cfil_socket_from_sock_id(sock_info->cfs_sock_id, false); if (sock == NULL) { CFIL_LOG(LOG_ERR, "CFIL: GET_SOCKET_INFO failed: bad sock_id %llu", sock_info->cfs_sock_id); error = ENOENT; goto return_already_unlocked; } cfil_info = (sock->so_flow_db != NULL) ? soflow_db_get_feature_context(sock->so_flow_db, sock_info->cfs_sock_id) : sock->so_cfil; if (cfil_info == NULL) { CFIL_LOG(LOG_INFO, "CFIL: GET_SOCKET_INFO failed: so %llx not attached, cannot fetch info", (uint64_t)VM_KERNEL_ADDRPERM(sock)); error = EINVAL; socket_unlock(sock, 1); goto return_already_unlocked; } if (sock->so_proto == NULL || sock->so_proto->pr_domain == NULL) { CFIL_LOG(LOG_INFO, "CFIL: GET_SOCKET_INFO failed: so %llx NULL so_proto / pr_domain", (uint64_t)VM_KERNEL_ADDRPERM(sock)); error = EINVAL; socket_unlock(sock, 1); goto return_already_unlocked; } // Fill out family, type, and protocol sock_info->cfs_sock_family = SOCK_DOM(sock); sock_info->cfs_sock_type = SOCK_TYPE(sock); sock_info->cfs_sock_protocol = GET_SO_PROTO(sock); // Source and destination addresses struct inpcb *inp = sotoinpcb(sock); if (inp->inp_vflag & INP_IPV6) { struct in6_addr * __single laddr = NULL, * __single faddr = NULL; u_int16_t lport = 0, fport = 0; cfil_get_flow_address_v6(cfil_info->cfi_hash_entry, inp, &laddr, &faddr, &lport, &fport); fill_ip6_sockaddr_4_6(&sock_info->cfs_local, laddr, lport, inp->inp_lifscope); fill_ip6_sockaddr_4_6(&sock_info->cfs_remote, faddr, fport, inp->inp_fifscope); } else if (inp->inp_vflag & INP_IPV4) { struct in_addr laddr = {.s_addr = 0}, faddr = {.s_addr = 0}; u_int16_t lport = 0, fport = 0; cfil_get_flow_address(cfil_info->cfi_hash_entry, inp, &laddr, &faddr, &lport, &fport); fill_ip_sockaddr_4_6(&sock_info->cfs_local, laddr, lport); fill_ip_sockaddr_4_6(&sock_info->cfs_remote, faddr, fport); } // Set the pid info sock_info->cfs_pid = sock->last_pid; memcpy(sock_info->cfs_uuid, sock->last_uuid, sizeof(uuid_t)); if (sock->so_flags & SOF_DELEGATED) { sock_info->cfs_e_pid = sock->e_pid; memcpy(sock_info->cfs_e_uuid, sock->e_uuid, sizeof(uuid_t)); } else { sock_info->cfs_e_pid = sock->last_pid; memcpy(sock_info->cfs_e_uuid, sock->last_uuid, sizeof(uuid_t)); } #if defined(XNU_TARGET_OS_OSX) if (!uuid_is_null(sock->so_ruuid)) { sock_info->cfs_r_pid = sock->so_rpid; memcpy(sock_info->cfs_r_uuid, sock->so_ruuid, sizeof(uuid_t)); } #endif socket_unlock(sock, 1); goto return_already_unlocked; default: error = ENOPROTOOPT; break; } done: cfil_rw_unlock_shared(&cfil_lck_rw); return error; return_already_unlocked: return error; } static errno_t cfil_ctl_setopt(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, int opt, void *data, size_t len) { #pragma unused(kctlref, opt) errno_t error = 0; struct content_filter *cfc = (struct content_filter *)unitinfo; CFIL_LOG(LOG_NOTICE, ""); if (cfc == NULL) { CFIL_LOG(LOG_ERR, "no unitinfo"); return EINVAL; } cfil_rw_lock_exclusive(&cfil_lck_rw); if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); error = EINVAL; goto done; } if (cfc != (void *)content_filters[kcunit - 1]) { CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u", kcunit); error = EINVAL; goto done; } switch (opt) { case CFIL_OPT_NECP_CONTROL_UNIT: if (len < sizeof(uint32_t)) { CFIL_LOG(LOG_ERR, "CFIL_OPT_NECP_CONTROL_UNIT " "len too small %lu", len); error = EINVAL; goto done; } if (cfc->cf_necp_control_unit != 0) { CFIL_LOG(LOG_ERR, "CFIL_OPT_NECP_CONTROL_UNIT " "already set %u", cfc->cf_necp_control_unit); error = EINVAL; goto done; } cfc->cf_necp_control_unit = *(uint32_t *)data; break; case CFIL_OPT_PRESERVE_CONNECTIONS: if (len < sizeof(uint32_t)) { CFIL_LOG(LOG_ERR, "CFIL_OPT_PRESERVE_CONNECTIONS " "len too small %lu", len); error = EINVAL; goto done; } uint32_t preserve_connections = *((uint32_t *)data); CFIL_LOG(LOG_INFO, "CFIL_OPT_PRESERVE_CONNECTIONS got %d (kcunit %d)", preserve_connections, kcunit); if (preserve_connections) { cfc->cf_flags |= CFF_PRESERVE_CONNECTIONS; } else { cfc->cf_flags &= ~CFF_PRESERVE_CONNECTIONS; } cfil_update_behavior_flags(); break; default: error = ENOPROTOOPT; break; } done: cfil_rw_unlock_exclusive(&cfil_lck_rw); return error; } static void cfil_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, int flags) { #pragma unused(kctlref, flags) struct content_filter *cfc = (struct content_filter *)unitinfo; struct socket *so = NULL; int error; struct cfil_entry *entry; struct cfil_info *cfil_info = NULL; CFIL_LOG(LOG_INFO, ""); if (cfc == NULL) { CFIL_LOG(LOG_ERR, "no unitinfo"); OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad); return; } if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad); return; } cfil_rw_lock_shared(&cfil_lck_rw); if (cfc != (void *)content_filters[kcunit - 1]) { CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u", kcunit); OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad); goto done; } /* Let's assume the flow control is lifted */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags &= ~CFF_FLOW_CONTROLLED; cfil_rw_lock_exclusive_to_shared(&cfil_lck_rw); LCK_RW_ASSERT(&cfil_lck_rw, LCK_RW_ASSERT_SHARED); } /* * Flow control will be raised again as soon as an entry cannot enqueue * to the kernel control socket */ while ((cfc->cf_flags & CFF_FLOW_CONTROLLED) == 0) { verify_content_filter(cfc); cfil_rw_lock_assert_held(&cfil_lck_rw, 0); /* Find an entry that is flow controlled */ TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) { if (entry->cfe_cfil_info == NULL || entry->cfe_cfil_info->cfi_so == NULL) { continue; } if ((entry->cfe_flags & CFEF_FLOW_CONTROLLED) == 0) { continue; } } if (entry == NULL) { break; } OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_flow_lift); cfil_info = entry->cfe_cfil_info; so = cfil_info->cfi_so; if (cfil_info == NULL || os_ref_retain_try(&cfil_info->cfi_ref_count) == false) { break; } cfil_rw_unlock_shared(&cfil_lck_rw); socket_lock(so, 1); do { error = cfil_acquire_sockbuf(so, cfil_info, 1); if (error == 0) { error = cfil_data_service_ctl_q(so, cfil_info, kcunit, 1); } cfil_release_sockbuf(so, 1); if (error != 0) { break; } error = cfil_acquire_sockbuf(so, cfil_info, 0); if (error == 0) { error = cfil_data_service_ctl_q(so, cfil_info, kcunit, 0); } cfil_release_sockbuf(so, 0); } while (0); CFIL_INFO_FREE(cfil_info); socket_lock_assert_owned(so); socket_unlock(so, 1); cfil_rw_lock_shared(&cfil_lck_rw); } done: cfil_rw_unlock_shared(&cfil_lck_rw); } struct cflil_tag_container { struct m_tag cfil_m_tag; struct cfil_tag cfil_tag; }; static struct m_tag * m_tag_kalloc_cfil_udp(u_int32_t id, u_int16_t type, uint16_t len, int wait) { struct cflil_tag_container *tag_container; struct m_tag *tag = NULL; assert3u(id, ==, KERNEL_MODULE_TAG_ID); assert3u(type, ==, KERNEL_TAG_TYPE_CFIL_UDP); assert3u(len, ==, sizeof(struct cfil_tag)); if (len != sizeof(struct cfil_tag)) { return NULL; } tag_container = kalloc_type(struct cflil_tag_container, wait | M_ZERO); if (tag_container != NULL) { tag = &tag_container->cfil_m_tag; assert3p(tag, ==, tag_container); M_TAG_INIT(tag, id, type, len, &tag_container->cfil_tag, NULL); } return tag; } static void m_tag_kfree_cfil_udp(struct m_tag *tag) { struct cflil_tag_container * __single tag_container = (struct cflil_tag_container *)tag; kfree_type(struct cflil_tag_container, tag_container); } void cfil_register_m_tag(void) { errno_t error = 0; error = m_register_internal_tag_type(KERNEL_TAG_TYPE_CFIL_UDP, sizeof(struct cfil_tag), m_tag_kalloc_cfil_udp, m_tag_kfree_cfil_udp); assert3u(error, ==, 0); } void cfil_init(void) { struct kern_ctl_reg kern_ctl; errno_t error = 0; unsigned int mbuf_limit = 0; CFIL_LOG(LOG_NOTICE, ""); /* * Compile time verifications */ _CASSERT(CFIL_MAX_FILTER_COUNT == MAX_CONTENT_FILTER); _CASSERT(sizeof(struct cfil_filter_stat) % sizeof(uint32_t) == 0); _CASSERT(sizeof(struct cfil_entry_stat) % sizeof(uint32_t) == 0); _CASSERT(sizeof(struct cfil_sock_stat) % sizeof(uint32_t) == 0); /* * Runtime time verifications */ VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_in_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_out_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_in_peeked, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_out_peeked, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_pending_q_in_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_pending_q_out_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_in_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_out_enqueued, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_in_passed, sizeof(uint32_t))); VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_out_passed, sizeof(uint32_t))); /* * Allocate locks */ TAILQ_INIT(&cfil_sock_head); TAILQ_INIT(&cfil_sock_head_stats); /* * Register kernel control */ bzero(&kern_ctl, sizeof(kern_ctl)); strlcpy(kern_ctl.ctl_name, CONTENT_FILTER_CONTROL_NAME, sizeof(kern_ctl.ctl_name)); kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED | CTL_FLAG_REG_EXTENDED; kern_ctl.ctl_sendsize = 512 * 1024; /* enough? */ kern_ctl.ctl_recvsize = 512 * 1024; /* enough? */ kern_ctl.ctl_connect = cfil_ctl_connect; kern_ctl.ctl_disconnect = cfil_ctl_disconnect; kern_ctl.ctl_send = cfil_ctl_send; kern_ctl.ctl_getopt = cfil_ctl_getopt; kern_ctl.ctl_setopt = cfil_ctl_setopt; kern_ctl.ctl_rcvd = cfil_ctl_rcvd; error = ctl_register(&kern_ctl, &cfil_kctlref); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_register failed: %d", error); return; } // Spawn thread for statistics reporting if (kernel_thread_start(cfil_stats_report_thread_func, NULL, &cfil_stats_report_thread) != KERN_SUCCESS) { panic_plain("%s: Can't create statistics report thread", __func__); /* NOTREACHED */ } /* this must not fail */ VERIFY(cfil_stats_report_thread != NULL); // Set UDP per-flow mbuf thresholds to 1/32 of platform max mbuf_limit = MAX(UDP_FLOW_GC_MBUF_CNT_MAX, (nmbclusters << MCLSHIFT) >> UDP_FLOW_GC_MBUF_SHIFT); cfil_udp_gc_mbuf_num_max = (mbuf_limit >> MCLSHIFT); cfil_udp_gc_mbuf_cnt_max = mbuf_limit; memset(&global_cfil_stats_report_buffers, 0, sizeof(global_cfil_stats_report_buffers)); } struct cfil_info * cfil_info_alloc(struct socket *so, struct soflow_hash_entry *hash_entry) { int kcunit; struct cfil_info *cfil_info = NULL; struct inpcb *inp = sotoinpcb(so); CFIL_LOG(LOG_INFO, ""); socket_lock_assert_owned(so); cfil_info = zalloc_flags(cfil_info_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL); os_ref_init(&cfil_info->cfi_ref_count, &cfil_refgrp); cfil_queue_init(&cfil_info->cfi_snd.cfi_inject_q); cfil_queue_init(&cfil_info->cfi_rcv.cfi_inject_q); microuptime(&cfil_info->cfi_timestamp); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { struct cfil_entry *entry; entry = &cfil_info->cfi_entries[kcunit - 1]; entry->cfe_cfil_info = cfil_info; /* Initialize the filter entry */ entry->cfe_filter = NULL; entry->cfe_flags = 0; entry->cfe_necp_control_unit = 0; entry->cfe_snd.cfe_pass_offset = 0; entry->cfe_snd.cfe_peek_offset = 0; entry->cfe_snd.cfe_peeked = 0; entry->cfe_rcv.cfe_pass_offset = 0; entry->cfe_rcv.cfe_peek_offset = 0; entry->cfe_rcv.cfe_peeked = 0; /* * Timestamp the last action to avoid pre-maturely * triggering garbage collection */ microuptime(&entry->cfe_last_action); cfil_queue_init(&entry->cfe_snd.cfe_pending_q); cfil_queue_init(&entry->cfe_rcv.cfe_pending_q); cfil_queue_init(&entry->cfe_snd.cfe_ctl_q); cfil_queue_init(&entry->cfe_rcv.cfe_ctl_q); } cfil_rw_lock_exclusive(&cfil_lck_rw); /* * Create a cfi_sock_id that's not the socket pointer! */ if (hash_entry == NULL) { // This is the TCP case, cfil_info is tracked per socket if (inp->inp_flowhash == 0) { inp_calc_flowhash(inp); ASSERT(inp->inp_flowhash != 0); } so->so_cfil = cfil_info; cfil_info->cfi_so = so; cfil_info->cfi_sock_id = ((so->so_gencnt << 32) | inp->inp_flowhash); } else { // This is the UDP case, cfil_info is tracked in per-socket hash cfil_info->cfi_so = so; cfil_info->cfi_hash_entry = hash_entry; cfil_info->cfi_sock_id = ((so->so_gencnt << 32) | (hash_entry->soflow_flowhash & 0xffffffff)); } TAILQ_INSERT_TAIL(&cfil_sock_head, cfil_info, cfi_link); SLIST_INIT(&cfil_info->cfi_ordered_entries); cfil_sock_attached_count++; cfil_rw_unlock_exclusive(&cfil_lck_rw); if (cfil_info != NULL) { OSIncrementAtomic(&cfil_stats.cfs_cfi_alloc_ok); } else { OSIncrementAtomic(&cfil_stats.cfs_cfi_alloc_fail); } return cfil_info; } int cfil_info_attach_unit(struct socket *so, uint32_t filter_control_unit, struct cfil_info *cfil_info) { int kcunit; int attached = 0; CFIL_LOG(LOG_INFO, ""); socket_lock_assert_owned(so); cfil_rw_lock_exclusive(&cfil_lck_rw); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { struct content_filter *cfc = content_filters[kcunit - 1]; struct cfil_entry *entry; struct cfil_entry *iter_entry; struct cfil_entry *iter_prev; if (cfc == NULL) { continue; } if (!(cfc->cf_necp_control_unit & filter_control_unit)) { continue; } entry = &cfil_info->cfi_entries[kcunit - 1]; entry->cfe_filter = cfc; entry->cfe_necp_control_unit = cfc->cf_necp_control_unit; TAILQ_INSERT_TAIL(&cfc->cf_sock_entries, entry, cfe_link); cfc->cf_sock_count++; /* Insert the entry into the list ordered by control unit */ iter_prev = NULL; SLIST_FOREACH(iter_entry, &cfil_info->cfi_ordered_entries, cfe_order_link) { if (entry->cfe_necp_control_unit < iter_entry->cfe_necp_control_unit) { break; } iter_prev = iter_entry; } if (iter_prev == NULL) { SLIST_INSERT_HEAD(&cfil_info->cfi_ordered_entries, entry, cfe_order_link); } else { SLIST_INSERT_AFTER(iter_prev, entry, cfe_order_link); } verify_content_filter(cfc); attached = 1; entry->cfe_flags |= CFEF_CFIL_ATTACHED; } cfil_rw_unlock_exclusive(&cfil_lck_rw); return attached; } static void cfil_info_free(struct cfil_info *cfil_info) { int kcunit; uint64_t in_drain = 0; uint64_t out_drained = 0; if (cfil_info == NULL) { return; } CFIL_LOG(LOG_INFO, ""); cfil_rw_lock_exclusive(&cfil_lck_rw); if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: FREEING CFIL_INFO"); } for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { struct cfil_entry *entry; struct content_filter *cfc; entry = &cfil_info->cfi_entries[kcunit - 1]; /* Don't be silly and try to detach twice */ if (entry->cfe_filter == NULL) { continue; } cfc = content_filters[kcunit - 1]; VERIFY(cfc == entry->cfe_filter); entry->cfe_filter = NULL; entry->cfe_necp_control_unit = 0; TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link); cfc->cf_sock_count--; verify_content_filter(cfc); } cfil_sock_attached_count--; TAILQ_REMOVE(&cfil_sock_head, cfil_info, cfi_link); // Turn off stats reporting for cfil_info. cfil_info_stats_toggle(cfil_info, NULL, 0); out_drained += cfil_queue_drain(&cfil_info->cfi_snd.cfi_inject_q); in_drain += cfil_queue_drain(&cfil_info->cfi_rcv.cfi_inject_q); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { struct cfil_entry *entry; entry = &cfil_info->cfi_entries[kcunit - 1]; out_drained += cfil_queue_drain(&entry->cfe_snd.cfe_pending_q); in_drain += cfil_queue_drain(&entry->cfe_rcv.cfe_pending_q); out_drained += cfil_queue_drain(&entry->cfe_snd.cfe_ctl_q); in_drain += cfil_queue_drain(&entry->cfe_rcv.cfe_ctl_q); } cfil_rw_unlock_exclusive(&cfil_lck_rw); if (out_drained) { OSIncrementAtomic(&cfil_stats.cfs_flush_out_free); } if (in_drain) { OSIncrementAtomic(&cfil_stats.cfs_flush_in_free); } zfree(cfil_info_zone, cfil_info); } /* * Received a verdict from userspace for a socket. * Perform any delayed operation if needed. */ static void cfil_sock_received_verdict(struct socket *so) { if (so == NULL || so->so_cfil == NULL) { return; } so->so_cfil->cfi_flags |= CFIF_INITIAL_VERDICT; /* * If socket has already been connected, trigger * soisconnected now. */ if (so->so_cfil->cfi_flags & CFIF_SOCKET_CONNECTED) { so->so_cfil->cfi_flags &= ~CFIF_SOCKET_CONNECTED; soisconnected(so); return; } } /* * Entry point from Sockets layer * The socket is locked. * * Checks if a connected socket is subject to filter and * pending the initial verdict. */ boolean_t cfil_sock_connected_pending_verdict(struct socket *so) { if (so == NULL || so->so_cfil == NULL) { return false; } if (so->so_cfil->cfi_flags & CFIF_INITIAL_VERDICT) { return false; } else { /* * Remember that this protocol is already connected, so * we will trigger soisconnected() upon receipt of * initial verdict later. */ so->so_cfil->cfi_flags |= CFIF_SOCKET_CONNECTED; return true; } } /* * Entry point from Flow Divert * The socket is locked. * * Mark socket as DEAD if all CFIL data has been processed by filter(s). * Otherwise, delay the marking until all data has been processed. */ boolean_t cfil_sock_is_dead(struct socket *so) { struct inpcb *inp = NULL; if (so == NULL) { return false; } socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0) { int32_t pending_snd = cfil_sock_data_pending(&so->so_snd); int32_t pending_rcv = cfil_sock_data_pending(&so->so_rcv); if (pending_snd || pending_rcv) { SO_DELAYED_DEAD_SET(so, true); return false; } } inp = sotoinpcb(so); if (inp != NULL) { SO_DELAYED_DEAD_SET(so, false); if (SOCK_CHECK_DOM(so, PF_INET6)) { in6_pcbdetach(inp); } else { in_pcbdetach(inp); } return true; } return false; } /* * Entry point from tcp_timer.c * The socket is locked. * * Perform TCP FIN time wait handling if all CFIL data has been processed by filter(s). * Otherwise, delay until all data has been processed. */ boolean_t cfil_sock_tcp_add_time_wait(struct socket *so) { struct inpcb *inp = NULL; struct tcpcb *tp = NULL; // Only handle TCP sockets if (so == NULL || !IS_TCP(so)) { return false; } socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0) { int32_t pending_snd = cfil_sock_data_pending(&so->so_snd); int32_t pending_rcv = cfil_sock_data_pending(&so->so_rcv); if (pending_snd || pending_rcv) { SO_DELAYED_TCP_TIME_WAIT_SET(so, true); return false; } } inp = sotoinpcb(so); tp = inp ? intotcpcb(inp) : NULL; if (tp != NULL) { add_to_time_wait_now(tp, 2 * tcp_msl); SO_DELAYED_TCP_TIME_WAIT_SET(so, false); return true; } return false; } boolean_t cfil_filter_present(void) { return cfil_active_count > 0; } /* * Entry point from Sockets layer * The socket is locked. */ errno_t cfil_sock_attach(struct socket *so, struct sockaddr *local, struct sockaddr *remote, int dir) { errno_t error = 0; uint32_t filter_control_unit; int debug = 0; socket_lock_assert_owned(so); if (so->so_flags1 & SOF1_FLOW_DIVERT_SKIP) { /* * This socket has already been evaluated (and ultimately skipped) by * flow divert, so it has also already been through content filter if there * is one. */ goto done; } /* Limit ourselves to TCP that are not MPTCP subflows */ if (SKIP_FILTER_FOR_TCP_SOCKET(so)) { goto done; } debug = DEBUG_FLOW(sotoinpcb(so), so, local, remote); if (debug) { CFIL_LOG(LOG_ERR, "CFIL: TCP (dir %d) - debug flow with port %d", dir, cfil_log_port); } filter_control_unit = necp_socket_get_content_filter_control_unit(so); if (filter_control_unit == 0) { goto done; } if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) { goto done; } if ((filter_control_unit & NECP_MASK_USERSPACE_ONLY) != 0) { OSIncrementAtomic(&cfil_stats.cfs_sock_userspace_only); goto done; } if (cfil_active_count == 0) { OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain); goto done; } if (so->so_cfil != NULL) { OSIncrementAtomic(&cfil_stats.cfs_sock_attach_already); CFIL_LOG(LOG_ERR, "already attached"); goto done; } else { cfil_info_alloc(so, NULL); if (so->so_cfil == NULL) { error = ENOMEM; OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem); goto done; } so->so_cfil->cfi_dir = dir; so->so_cfil->cfi_filter_control_unit = filter_control_unit; so->so_cfil->cfi_filter_policy_gencount = necp_socket_get_policy_gencount(so); so->so_cfil->cfi_debug = debug; } if (cfil_info_attach_unit(so, filter_control_unit, so->so_cfil) == 0) { CFIL_LOG(LOG_ERR, "cfil_info_attach_unit(%u) failed", filter_control_unit); OSIncrementAtomic(&cfil_stats.cfs_sock_attach_failed); goto done; } CFIL_LOG(LOG_INFO, "so %llx filter_control_unit %u sockID %llu <%llx>", (uint64_t)VM_KERNEL_ADDRPERM(so), filter_control_unit, so->so_cfil->cfi_sock_id, so->so_cfil->cfi_sock_id); so->so_flags |= SOF_CONTENT_FILTER; OSIncrementAtomic(&cfil_stats.cfs_sock_attached); /* Hold a reference on the socket */ so->so_usecount++; /* * Save passed addresses for attach event msg (in case resend * is needed. */ if (remote != NULL && (remote->sa_len <= sizeof(union sockaddr_in_4_6))) { SOCKADDR_COPY(remote, SA(&so->so_cfil->cfi_so_attach_faddr), remote->sa_len); } if (local != NULL && (local->sa_len <= sizeof(union sockaddr_in_4_6))) { SOCKADDR_COPY(local, SA(&so->so_cfil->cfi_so_attach_laddr), local->sa_len); } if (so->so_cfil->cfi_debug) { cfil_info_log(LOG_ERR, so->so_cfil, "CFIL: ADDED"); } error = cfil_dispatch_attach_event(so, so->so_cfil, 0, dir); /* We can recover from flow control or out of memory errors */ if (error == ENOBUFS || error == ENOMEM) { error = 0; } else if (error != 0) { goto done; } CFIL_INFO_VERIFY(so->so_cfil); done: return error; } /* * Entry point from Sockets layer * The socket is locked. */ errno_t cfil_sock_detach(struct socket *so) { if (NEED_DGRAM_FLOW_TRACKING(so)) { return 0; } if (so->so_cfil) { if (so->so_flags & SOF_CONTENT_FILTER) { so->so_flags &= ~SOF_CONTENT_FILTER; VERIFY(so->so_usecount > 0); so->so_usecount--; } CFIL_INFO_FREE(so->so_cfil); so->so_cfil = NULL; OSIncrementAtomic(&cfil_stats.cfs_sock_detached); } return 0; } /* * Fill in the address info of an event message from either * the socket or passed in address info. */ static void cfil_fill_event_msg_addresses(struct soflow_hash_entry *entry, struct inpcb *inp, union sockaddr_in_4_6 *sin_src, union sockaddr_in_4_6 *sin_dst, boolean_t isIPv4, boolean_t outgoing) { if (isIPv4) { struct in_addr laddr = {0}, faddr = {0}; u_int16_t lport = 0, fport = 0; cfil_get_flow_address(entry, inp, &laddr, &faddr, &lport, &fport); if (outgoing) { fill_ip_sockaddr_4_6(sin_src, laddr, lport); fill_ip_sockaddr_4_6(sin_dst, faddr, fport); } else { fill_ip_sockaddr_4_6(sin_src, faddr, fport); fill_ip_sockaddr_4_6(sin_dst, laddr, lport); } } else { struct in6_addr * __single laddr = NULL, * __single faddr = NULL; u_int16_t lport = 0, fport = 0; const u_int32_t lifscope = inp ? inp->inp_lifscope : IFSCOPE_UNKNOWN; const u_int32_t fifscope = inp ? inp->inp_fifscope : IFSCOPE_UNKNOWN; cfil_get_flow_address_v6(entry, inp, &laddr, &faddr, &lport, &fport); if (outgoing) { fill_ip6_sockaddr_4_6(sin_src, laddr, lport, lifscope); fill_ip6_sockaddr_4_6(sin_dst, faddr, fport, fifscope); } else { fill_ip6_sockaddr_4_6(sin_src, faddr, fport, fifscope); fill_ip6_sockaddr_4_6(sin_dst, laddr, lport, lifscope); } } } static boolean_t cfil_dispatch_attach_event_sign(cfil_crypto_state_t crypto_state, struct cfil_info *cfil_info, struct cfil_msg_sock_attached *msg) { struct cfil_crypto_data data = {}; struct iovec extra_data[1] = { { NULL, 0 } }; if (crypto_state == NULL || msg == NULL || cfil_info == NULL) { return false; } data.sock_id = msg->cfs_msghdr.cfm_sock_id; data.direction = msg->cfs_conn_dir; data.pid = msg->cfs_pid; data.effective_pid = msg->cfs_e_pid; data.responsible_pid = msg->cfs_r_pid; uuid_copy(data.uuid, msg->cfs_uuid); uuid_copy(data.effective_uuid, msg->cfs_e_uuid); uuid_copy(data.responsible_uuid, msg->cfs_r_uuid); data.socketProtocol = msg->cfs_sock_protocol; if (data.direction == CFS_CONNECTION_DIR_OUT) { data.remote.sin6 = msg->cfs_dst.sin6; data.local.sin6 = msg->cfs_src.sin6; } else { data.remote.sin6 = msg->cfs_src.sin6; data.local.sin6 = msg->cfs_dst.sin6; } size_t len = strbuflen(msg->cfs_remote_domain_name, sizeof(msg->cfs_remote_domain_name)); if (len > 0) { extra_data[0].iov_base = msg->cfs_remote_domain_name; extra_data[0].iov_len = len; } // At attach, if local address is already present, no need to re-sign subsequent data messages. if (!NULLADDRESS(data.local)) { cfil_info->cfi_isSignatureLatest = true; } msg->cfs_signature_length = sizeof(cfil_crypto_signature); if (cfil_crypto_sign_data(crypto_state, &data, extra_data, sizeof(extra_data) / sizeof(extra_data[0]), msg->cfs_signature, &msg->cfs_signature_length) != 0) { msg->cfs_signature_length = 0; CFIL_LOG(LOG_ERR, "CFIL: Failed to sign attached msg <sockID %llu <%llx>>", msg->cfs_msghdr.cfm_sock_id, msg->cfs_msghdr.cfm_sock_id); return false; } return true; } struct cfil_sign_parameters { cfil_crypto_state_t csp_state; struct cfil_crypto_data *csp_data; uint8_t * __indexable csp_signature; uint32_t *csp_signature_size; }; static void cfil_sign_with_domain_name(char *domain_name __null_terminated, void *ctx) { struct cfil_sign_parameters *parameters = (struct cfil_sign_parameters *)ctx; struct iovec extra_data[1] = { { NULL, 0 } }; if (parameters == NULL) { return; } if (domain_name != NULL) { extra_data[0].iov_base = __unsafe_null_terminated_to_indexable(domain_name); extra_data[0].iov_len = strlen(domain_name); } *(parameters->csp_signature_size) = sizeof(cfil_crypto_signature); if (cfil_crypto_sign_data(parameters->csp_state, parameters->csp_data, extra_data, sizeof(extra_data) / sizeof(extra_data[0]), parameters->csp_signature, parameters->csp_signature_size) != 0) { *(parameters->csp_signature_size) = 0; } } static boolean_t cfil_dispatch_data_event_sign(cfil_crypto_state_t crypto_state, struct socket *so, struct cfil_info *cfil_info, struct cfil_msg_data_event *msg) { struct cfil_crypto_data data = {}; if (crypto_state == NULL || msg == NULL || so == NULL || cfil_info == NULL) { return false; } data.sock_id = cfil_info->cfi_sock_id; data.direction = cfil_info->cfi_dir; data.pid = so->last_pid; memcpy(data.uuid, so->last_uuid, sizeof(uuid_t)); if (so->so_flags & SOF_DELEGATED) { data.effective_pid = so->e_pid; memcpy(data.effective_uuid, so->e_uuid, sizeof(uuid_t)); } else { data.effective_pid = so->last_pid; memcpy(data.effective_uuid, so->last_uuid, sizeof(uuid_t)); } #if defined(XNU_TARGET_OS_OSX) if (!uuid_is_null(so->so_ruuid)) { data.responsible_pid = so->so_rpid; memcpy(data.responsible_uuid, so->so_ruuid, sizeof(uuid_t)); } #endif data.socketProtocol = GET_SO_PROTO(so); if (data.direction == CFS_CONNECTION_DIR_OUT) { data.remote.sin6 = msg->cfc_dst.sin6; data.local.sin6 = msg->cfc_src.sin6; } else { data.remote.sin6 = msg->cfc_src.sin6; data.local.sin6 = msg->cfc_dst.sin6; } // At first data, local address may show up for the first time, update address cache and // no need to re-sign subsequent data messages anymore. if (!NULLADDRESS(data.local)) { memcpy(&cfil_info->cfi_so_attach_laddr, &data.local, data.local.sa.sa_len); cfil_info->cfi_isSignatureLatest = true; } struct cfil_sign_parameters parameters = { .csp_state = crypto_state, .csp_data = &data, .csp_signature = msg->cfd_signature, .csp_signature_size = &msg->cfd_signature_length, }; necp_with_inp_domain_name(so, ¶meters, cfil_sign_with_domain_name); if (msg->cfd_signature_length == 0) { CFIL_LOG(LOG_ERR, "CFIL: Failed to sign data msg <sockID %llu <%llx>>", msg->cfd_msghdr.cfm_sock_id, msg->cfd_msghdr.cfm_sock_id); return false; } return true; } static boolean_t cfil_dispatch_closed_event_sign(cfil_crypto_state_t crypto_state, struct socket *so, struct cfil_info *cfil_info, struct cfil_msg_sock_closed *msg) { struct cfil_crypto_data data = {}; struct soflow_hash_entry hash_entry = {}; struct soflow_hash_entry *hash_entry_ptr = NULL; struct inpcb *inp = (struct inpcb *)so->so_pcb; if (crypto_state == NULL || msg == NULL || so == NULL || inp == NULL || cfil_info == NULL) { return false; } data.sock_id = cfil_info->cfi_sock_id; data.direction = cfil_info->cfi_dir; data.pid = so->last_pid; memcpy(data.uuid, so->last_uuid, sizeof(uuid_t)); if (so->so_flags & SOF_DELEGATED) { data.effective_pid = so->e_pid; memcpy(data.effective_uuid, so->e_uuid, sizeof(uuid_t)); } else { data.effective_pid = so->last_pid; memcpy(data.effective_uuid, so->last_uuid, sizeof(uuid_t)); } #if defined(XNU_TARGET_OS_OSX) if (!uuid_is_null(so->so_ruuid)) { data.responsible_pid = so->so_rpid; memcpy(data.responsible_uuid, so->so_ruuid, sizeof(uuid_t)); } #endif data.socketProtocol = GET_SO_PROTO(so); /* * Fill in address info: * For UDP, use the cfil_info hash entry directly. * For TCP, compose an hash entry with the saved addresses. */ if (cfil_info->cfi_hash_entry != NULL) { hash_entry_ptr = cfil_info->cfi_hash_entry; } else if (cfil_info->cfi_so_attach_faddr.sa.sa_len > 0 || cfil_info->cfi_so_attach_laddr.sa.sa_len > 0) { soflow_fill_hash_entry_from_address(&hash_entry, TRUE, SA(&cfil_info->cfi_so_attach_laddr), FALSE); soflow_fill_hash_entry_from_address(&hash_entry, FALSE, SA(&cfil_info->cfi_so_attach_faddr), FALSE); hash_entry_ptr = &hash_entry; } if (hash_entry_ptr != NULL) { boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT); union sockaddr_in_4_6 *src = outgoing ? &data.local : &data.remote; union sockaddr_in_4_6 *dst = outgoing ? &data.remote : &data.local; cfil_fill_event_msg_addresses(hash_entry_ptr, inp, src, dst, !IS_INP_V6(inp), outgoing); } data.byte_count_in = cfil_info->cfi_byte_inbound_count; data.byte_count_out = cfil_info->cfi_byte_outbound_count; struct cfil_sign_parameters parameters = { .csp_state = crypto_state, .csp_data = &data, .csp_signature = msg->cfc_signature, .csp_signature_size = &msg->cfc_signature_length }; necp_with_inp_domain_name(so, ¶meters, cfil_sign_with_domain_name); if (msg->cfc_signature_length == 0) { CFIL_LOG(LOG_ERR, "CFIL: Failed to sign closed msg <sockID %llu <%llx>>", msg->cfc_msghdr.cfm_sock_id, msg->cfc_msghdr.cfm_sock_id); return false; } return true; } static void cfil_populate_attached_msg_domain_name(char *domain_name __null_terminated, void *ctx) { struct cfil_msg_sock_attached *msg_attached = (struct cfil_msg_sock_attached *)ctx; if (msg_attached == NULL) { return; } if (domain_name != NULL) { strlcpy(msg_attached->cfs_remote_domain_name, domain_name, sizeof(msg_attached->cfs_remote_domain_name)); } } static bool cfil_copy_audit_token(pid_t pid, audit_token_t *buffer) { bool success = false; proc_t p = proc_find(pid); if (p != PROC_NULL) { task_t __single t = proc_task(p); if (t != TASK_NULL) { audit_token_t audit_token = {}; mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT; if (task_info(t, TASK_AUDIT_TOKEN, (task_info_t)&audit_token, &count) == KERN_SUCCESS) { memcpy(buffer, &audit_token, sizeof(audit_token_t)); success = true; } } proc_rele(p); } return success; } static int cfil_dispatch_attach_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int conn_dir) { errno_t error = 0; struct cfil_entry *entry = NULL; struct cfil_msg_sock_attached * __single msg_attached; struct content_filter *cfc = NULL; struct inpcb *inp = (struct inpcb *)so->so_pcb; struct soflow_hash_entry *hash_entry_ptr = NULL; struct soflow_hash_entry hash_entry; memset(&hash_entry, 0, sizeof(struct soflow_hash_entry)); socket_lock_assert_owned(so); cfil_rw_lock_shared(&cfil_lck_rw); if (so->so_proto == NULL || so->so_proto->pr_domain == NULL) { error = EINVAL; goto done; } if (kcunit == 0) { entry = SLIST_FIRST(&cfil_info->cfi_ordered_entries); } else { entry = &cfil_info->cfi_entries[kcunit - 1]; } if (entry == NULL) { goto done; } cfc = entry->cfe_filter; if (cfc == NULL) { goto done; } if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED)) { goto done; } if (kcunit == 0) { kcunit = CFI_ENTRY_KCUNIT(cfil_info, entry); } CFIL_LOG(LOG_INFO, "so %llx filter_control_unit %u kcunit %u", (uint64_t)VM_KERNEL_ADDRPERM(so), entry->cfe_necp_control_unit, kcunit); /* Would be wasteful to try when flow controlled */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { error = ENOBUFS; goto done; } msg_attached = kalloc_data(sizeof(struct cfil_msg_sock_attached), Z_WAITOK); if (msg_attached == NULL) { error = ENOMEM; goto done; } bzero(msg_attached, sizeof(struct cfil_msg_sock_attached)); msg_attached->cfs_msghdr.cfm_len = sizeof(struct cfil_msg_sock_attached); msg_attached->cfs_msghdr.cfm_version = CFM_VERSION_CURRENT; msg_attached->cfs_msghdr.cfm_type = CFM_TYPE_EVENT; msg_attached->cfs_msghdr.cfm_op = CFM_OP_SOCKET_ATTACHED; msg_attached->cfs_msghdr.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id; msg_attached->cfs_sock_family = SOCK_DOM(so); msg_attached->cfs_sock_type = SOCK_TYPE(so); msg_attached->cfs_sock_protocol = GET_SO_PROTO(so); msg_attached->cfs_pid = so->last_pid; memcpy(msg_attached->cfs_uuid, so->last_uuid, sizeof(uuid_t)); if (so->so_flags & SOF_DELEGATED) { msg_attached->cfs_e_pid = so->e_pid; memcpy(msg_attached->cfs_e_uuid, so->e_uuid, sizeof(uuid_t)); } else { msg_attached->cfs_e_pid = so->last_pid; memcpy(msg_attached->cfs_e_uuid, so->last_uuid, sizeof(uuid_t)); } #if defined(XNU_TARGET_OS_OSX) if (!uuid_is_null(so->so_ruuid)) { msg_attached->cfs_r_pid = so->so_rpid; memcpy(msg_attached->cfs_r_uuid, so->so_ruuid, sizeof(uuid_t)); } #endif /* * Fill in address info: * For UDP, use the cfil_info hash entry directly. * For TCP, compose an hash entry with the saved addresses. */ if (cfil_info->cfi_hash_entry != NULL) { hash_entry_ptr = cfil_info->cfi_hash_entry; } else if (cfil_info->cfi_so_attach_faddr.sa.sa_len > 0 || cfil_info->cfi_so_attach_laddr.sa.sa_len > 0) { soflow_fill_hash_entry_from_address(&hash_entry, TRUE, SA(&cfil_info->cfi_so_attach_laddr), FALSE); soflow_fill_hash_entry_from_address(&hash_entry, FALSE, SA(&cfil_info->cfi_so_attach_faddr), FALSE); hash_entry_ptr = &hash_entry; } if (hash_entry_ptr != NULL) { cfil_fill_event_msg_addresses(hash_entry_ptr, inp, &msg_attached->cfs_src, &msg_attached->cfs_dst, !IS_INP_V6(inp), conn_dir == CFS_CONNECTION_DIR_OUT); } msg_attached->cfs_conn_dir = conn_dir; if (msg_attached->cfs_e_pid != 0) { if (!cfil_copy_audit_token(msg_attached->cfs_e_pid, (audit_token_t *)&msg_attached->cfs_audit_token)) { CFIL_LOG(LOG_ERR, "CFIL: Failed to get effective audit token for <sockID %llu <%llx>> ", entry->cfe_cfil_info->cfi_sock_id, entry->cfe_cfil_info->cfi_sock_id); } } if (msg_attached->cfs_pid != 0) { if (msg_attached->cfs_pid == msg_attached->cfs_e_pid) { memcpy(&msg_attached->cfs_real_audit_token, &msg_attached->cfs_audit_token, sizeof(msg_attached->cfs_real_audit_token)); } else if (!cfil_copy_audit_token(msg_attached->cfs_pid, (audit_token_t *)&msg_attached->cfs_real_audit_token)) { CFIL_LOG(LOG_ERR, "CFIL: Failed to get real audit token for <sockID %llu <%llx>> ", entry->cfe_cfil_info->cfi_sock_id, entry->cfe_cfil_info->cfi_sock_id); } } necp_with_inp_domain_name(so, msg_attached, cfil_populate_attached_msg_domain_name); if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: SENDING ATTACH UP"); } cfil_dispatch_attach_event_sign(entry->cfe_filter->cf_crypto_state, cfil_info, msg_attached); error = ctl_enqueuedata(entry->cfe_filter->cf_kcref, entry->cfe_filter->cf_kcunit, msg_attached, sizeof(struct cfil_msg_sock_attached), CTL_DATA_EOR); kfree_data(msg_attached, sizeof(struct cfil_msg_sock_attached)); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed: %d", error); goto done; } microuptime(&entry->cfe_last_event); cfil_info->cfi_first_event.tv_sec = entry->cfe_last_event.tv_sec; cfil_info->cfi_first_event.tv_usec = entry->cfe_last_event.tv_usec; entry->cfe_flags |= CFEF_SENT_SOCK_ATTACHED; OSIncrementAtomic(&cfil_stats.cfs_attach_event_ok); done: /* We can recover from flow control */ if (error == ENOBUFS) { entry->cfe_flags |= CFEF_FLOW_CONTROLLED; OSIncrementAtomic(&cfil_stats.cfs_attach_event_flow_control); if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags |= CFF_FLOW_CONTROLLED; cfil_rw_unlock_exclusive(&cfil_lck_rw); } else { if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_attach_event_fail); } cfil_rw_unlock_shared(&cfil_lck_rw); } return error; } static int cfil_dispatch_disconnect_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing) { errno_t error = 0; struct mbuf *msg = NULL; struct cfil_entry *entry; struct cfe_buf *entrybuf; struct cfil_msg_hdr msg_disconnected; struct content_filter *cfc; socket_lock_assert_owned(so); cfil_rw_lock_shared(&cfil_lck_rw); entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } cfc = entry->cfe_filter; if (cfc == NULL) { goto done; } // Mark if this flow qualifies for immediate close. SET_NO_CLOSE_WAIT(sotoinpcb(so), cfil_info); CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing); /* * Send the disconnection event once */ if ((outgoing && (entry->cfe_flags & CFEF_SENT_DISCONNECT_OUT)) || (!outgoing && (entry->cfe_flags & CFEF_SENT_DISCONNECT_IN))) { CFIL_LOG(LOG_INFO, "so %llx disconnect already sent", (uint64_t)VM_KERNEL_ADDRPERM(so)); goto done; } /* * We're not disconnected as long as some data is waiting * to be delivered to the filter */ if (outgoing && cfil_queue_empty(&entrybuf->cfe_ctl_q) == 0) { CFIL_LOG(LOG_INFO, "so %llx control queue not empty", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EBUSY; goto done; } /* Would be wasteful to try when flow controlled */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { error = ENOBUFS; goto done; } if (cfil_info->cfi_debug) { const char * __null_terminated out = "CFIL: OUT - SENDING DISCONNECT UP"; const char * __null_terminated in = "CFIL: IN - SENDING DISCONNECT UP"; cfil_info_log(LOG_ERR, cfil_info, outgoing ? out : in); } bzero(&msg_disconnected, sizeof(struct cfil_msg_hdr)); msg_disconnected.cfm_len = sizeof(struct cfil_msg_hdr); msg_disconnected.cfm_version = CFM_VERSION_CURRENT; msg_disconnected.cfm_type = CFM_TYPE_EVENT; msg_disconnected.cfm_op = outgoing ? CFM_OP_DISCONNECT_OUT : CFM_OP_DISCONNECT_IN; msg_disconnected.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id; error = ctl_enqueuedata(entry->cfe_filter->cf_kcref, entry->cfe_filter->cf_kcunit, &msg_disconnected, sizeof(struct cfil_msg_hdr), CTL_DATA_EOR); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_enqueuembuf() failed: %d", error); mbuf_freem(msg); goto done; } microuptime(&entry->cfe_last_event); CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_event, &cfil_info->cfi_first_event, msg_disconnected.cfm_op); /* Remember we have sent the disconnection message */ if (outgoing) { entry->cfe_flags |= CFEF_SENT_DISCONNECT_OUT; OSIncrementAtomic(&cfil_stats.cfs_disconnect_out_event_ok); } else { entry->cfe_flags |= CFEF_SENT_DISCONNECT_IN; OSIncrementAtomic(&cfil_stats.cfs_disconnect_in_event_ok); } done: if (error == ENOBUFS) { entry->cfe_flags |= CFEF_FLOW_CONTROLLED; OSIncrementAtomic( &cfil_stats.cfs_disconnect_event_flow_control); if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags |= CFF_FLOW_CONTROLLED; cfil_rw_unlock_exclusive(&cfil_lck_rw); } else { if (error != 0) { OSIncrementAtomic( &cfil_stats.cfs_disconnect_event_fail); } cfil_rw_unlock_shared(&cfil_lck_rw); } return error; } int cfil_dispatch_closed_event(struct socket *so, struct cfil_info *cfil_info, int kcunit) { struct cfil_entry *entry; struct cfil_msg_sock_closed msg_closed; errno_t error = 0; struct content_filter *cfc; struct inpcb *inp = NULL; socket_lock_assert_owned(so); cfil_rw_lock_shared(&cfil_lck_rw); entry = &cfil_info->cfi_entries[kcunit - 1]; cfc = entry->cfe_filter; if (cfc == NULL) { goto done; } CFIL_LOG(LOG_INFO, "so %llx kcunit %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit); /* Would be wasteful to try when flow controlled */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { error = ENOBUFS; goto done; } /* * Send a single closed message per filter */ if ((entry->cfe_flags & CFEF_SENT_SOCK_CLOSED) != 0) { goto done; } if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) { goto done; } microuptime(&entry->cfe_last_event); CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_event, &cfil_info->cfi_first_event, CFM_OP_SOCKET_CLOSED); bzero(&msg_closed, sizeof(struct cfil_msg_sock_closed)); msg_closed.cfc_msghdr.cfm_len = sizeof(struct cfil_msg_sock_closed); msg_closed.cfc_msghdr.cfm_version = CFM_VERSION_CURRENT; msg_closed.cfc_msghdr.cfm_type = CFM_TYPE_EVENT; msg_closed.cfc_msghdr.cfm_op = CFM_OP_SOCKET_CLOSED; msg_closed.cfc_msghdr.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id; msg_closed.cfc_first_event.tv_sec = cfil_info->cfi_first_event.tv_sec; msg_closed.cfc_first_event.tv_usec = cfil_info->cfi_first_event.tv_usec; memcpy(msg_closed.cfc_op_time, cfil_info->cfi_op_time, sizeof(uint32_t) * CFI_MAX_TIME_LOG_ENTRY); memcpy(msg_closed.cfc_op_list, cfil_info->cfi_op_list, sizeof(unsigned char) * CFI_MAX_TIME_LOG_ENTRY); msg_closed.cfc_op_list_ctr = cfil_info->cfi_op_list_ctr; msg_closed.cfc_byte_inbound_count = cfil_info->cfi_byte_inbound_count; msg_closed.cfc_byte_outbound_count = cfil_info->cfi_byte_outbound_count; if (entry->cfe_laddr_sent == false) { /* cache it if necessary */ if (cfil_info->cfi_so_attach_laddr.sa.sa_len == 0) { inp = cfil_info->cfi_so ? sotoinpcb(cfil_info->cfi_so) : NULL; if (inp != NULL) { boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT); union sockaddr_in_4_6 *src = outgoing ? &cfil_info->cfi_so_attach_laddr : NULL; union sockaddr_in_4_6 *dst = outgoing ? NULL : &cfil_info->cfi_so_attach_laddr; cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp, src, dst, !IS_INP_V6(inp), outgoing); } } if (cfil_info->cfi_so_attach_laddr.sa.sa_len != 0) { msg_closed.cfc_laddr.sin6 = cfil_info->cfi_so_attach_laddr.sin6; entry->cfe_laddr_sent = true; } } cfil_dispatch_closed_event_sign(entry->cfe_filter->cf_crypto_state, so, cfil_info, &msg_closed); if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: SENDING CLOSED UP"); } /* for debugging * if (msg_closed.cfc_op_list_ctr > CFI_MAX_TIME_LOG_ENTRY) { * msg_closed.cfc_op_list_ctr = CFI_MAX_TIME_LOG_ENTRY; // just in case * } * for (unsigned int i = 0; i < msg_closed.cfc_op_list_ctr ; i++) { * CFIL_LOG(LOG_ERR, "MD: socket %llu event %2u, time + %u msec", msg_closed.cfc_msghdr.cfm_sock_id, (unsigned short)msg_closed.cfc_op_list[i], msg_closed.cfc_op_time[i]); * } */ error = ctl_enqueuedata(entry->cfe_filter->cf_kcref, entry->cfe_filter->cf_kcunit, &msg_closed, sizeof(struct cfil_msg_sock_closed), CTL_DATA_EOR); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed: %d", error); goto done; } entry->cfe_flags |= CFEF_SENT_SOCK_CLOSED; OSIncrementAtomic(&cfil_stats.cfs_closed_event_ok); done: /* We can recover from flow control */ if (error == ENOBUFS) { entry->cfe_flags |= CFEF_FLOW_CONTROLLED; OSIncrementAtomic(&cfil_stats.cfs_closed_event_flow_control); if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags |= CFF_FLOW_CONTROLLED; cfil_rw_unlock_exclusive(&cfil_lck_rw); } else { if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_closed_event_fail); } cfil_rw_unlock_shared(&cfil_lck_rw); } return error; } static void fill_ip6_sockaddr_4_6(union sockaddr_in_4_6 *sin46, struct in6_addr *ip6, u_int16_t port, uint32_t ifscope) { if (sin46 == NULL) { return; } struct sockaddr_in6 *sin6 = &sin46->sin6; sin6->sin6_family = AF_INET6; sin6->sin6_len = sizeof(*sin6); sin6->sin6_port = port; sin6->sin6_addr = *ip6; if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr)) { sin6->sin6_scope_id = ifscope; if (in6_embedded_scope) { in6_verify_ifscope(&sin6->sin6_addr, sin6->sin6_scope_id); if (sin6->sin6_addr.s6_addr16[1] != 0) { sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]); sin6->sin6_addr.s6_addr16[1] = 0; } } } } static void fill_ip_sockaddr_4_6(union sockaddr_in_4_6 *sin46, struct in_addr ip, u_int16_t port) { if (sin46 == NULL) { return; } struct sockaddr_in *sin = &sin46->sin; sin->sin_family = AF_INET; sin->sin_len = sizeof(*sin); sin->sin_port = port; sin->sin_addr.s_addr = ip.s_addr; } static void cfil_get_flow_address_v6(struct soflow_hash_entry *entry, struct inpcb *inp, struct in6_addr **laddr, struct in6_addr **faddr, u_int16_t *lport, u_int16_t *fport) { if (entry != NULL) { *laddr = &entry->soflow_laddr.addr6; *faddr = &entry->soflow_faddr.addr6; *lport = entry->soflow_lport; *fport = entry->soflow_fport; } else { *laddr = &inp->in6p_laddr; *faddr = &inp->in6p_faddr; *lport = inp->inp_lport; *fport = inp->inp_fport; } } static void cfil_get_flow_address(struct soflow_hash_entry *entry, struct inpcb *inp, struct in_addr *laddr, struct in_addr *faddr, u_int16_t *lport, u_int16_t *fport) { if (entry != NULL) { *laddr = entry->soflow_laddr.addr46.ia46_addr4; *faddr = entry->soflow_faddr.addr46.ia46_addr4; *lport = entry->soflow_lport; *fport = entry->soflow_fport; } else { *laddr = inp->inp_laddr; *faddr = inp->inp_faddr; *lport = inp->inp_lport; *fport = inp->inp_fport; } } static int cfil_dispatch_data_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing, struct mbuf *data, unsigned int copyoffset, unsigned int copylen) { errno_t error = 0; struct mbuf *copy = NULL; struct mbuf * __single msg = NULL; unsigned int one = 1; struct cfil_msg_data_event *data_req; struct inpcb *inp = (struct inpcb *)so->so_pcb; struct cfil_entry *entry; struct cfe_buf *entrybuf; struct content_filter *cfc; struct timeval tv; int inp_flags = 0; cfil_rw_lock_shared(&cfil_lck_rw); entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } cfc = entry->cfe_filter; if (cfc == NULL) { goto done; } data = cfil_data_start(data); if (data == NULL) { CFIL_LOG(LOG_ERR, "No data start"); goto done; } CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing); socket_lock_assert_owned(so); /* Would be wasteful to try */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { error = ENOBUFS; goto done; } /* Make a copy of the data to pass to kernel control socket */ copy = m_copym_mode(data, copyoffset, copylen, M_DONTWAIT, NULL, NULL, M_COPYM_NOOP_HDR); if (copy == NULL) { CFIL_LOG(LOG_ERR, "m_copym_mode() failed"); error = ENOMEM; goto done; } /* We need an mbuf packet for the message header */ const size_t hdrsize = sizeof(struct cfil_msg_data_event); error = mbuf_allocpacket(MBUF_DONTWAIT, hdrsize, &one, &msg); if (error != 0) { CFIL_LOG(LOG_ERR, "mbuf_allocpacket() failed"); m_freem(copy); /* * ENOBUFS is to indicate flow control */ error = ENOMEM; goto done; } mbuf_setlen(msg, hdrsize); mbuf_pkthdr_setlen(msg, hdrsize + copylen); msg->m_next = copy; data_req = mtod(msg, struct cfil_msg_data_event *); bzero(data_req, hdrsize); data_req->cfd_msghdr.cfm_len = (uint32_t)hdrsize + copylen; data_req->cfd_msghdr.cfm_version = 1; data_req->cfd_msghdr.cfm_type = CFM_TYPE_EVENT; data_req->cfd_msghdr.cfm_op = outgoing ? CFM_OP_DATA_OUT : CFM_OP_DATA_IN; data_req->cfd_msghdr.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id; data_req->cfd_start_offset = entrybuf->cfe_peeked; data_req->cfd_end_offset = entrybuf->cfe_peeked + copylen; // The last_pid or e_pid is set here because a socket could have been // accepted by launchd and a new process spawned (with a new pid). // So the last pid associated with the socket is appended to the data event. // for a provider that is peeking bytes. if (so->so_flags & SOF_DELEGATED) { data_req->cfd_delegated_pid = so->e_pid; } else { data_req->cfd_delegated_pid = so->last_pid; } if (data_req->cfd_delegated_pid != 0) { if (!cfil_copy_audit_token(data_req->cfd_delegated_pid, (audit_token_t *)&data_req->cfd_delegated_audit_token)) { CFIL_LOG(LOG_ERR, "CFIL: Failed to get audit token for <sockID %llu <%llx>> ", entry->cfe_cfil_info->cfi_sock_id, entry->cfe_cfil_info->cfi_sock_id); } } data_req->cfd_flags = 0; if (OPTIONAL_IP_HEADER(so)) { /* * For non-UDP/TCP traffic, indicate to filters if optional * IP header is present: * outgoing - indicate according to INP_HDRINCL flag * incoming - For IPv4 only, stripping of IP header is * optional. But for CFIL, we delay stripping * at rip_input. So CFIL always expects IP * frames. IP header will be stripped according * to INP_STRIPHDR flag later at reinjection. */ if ((!outgoing && !IS_INP_V6(inp)) || (outgoing && cfil_dgram_peek_socket_state(data, &inp_flags) && (inp_flags & INP_HDRINCL))) { data_req->cfd_flags |= CFD_DATA_FLAG_IP_HEADER; } } /* * Copy address/port into event msg. * For non connected sockets need to copy addresses from passed * parameters */ cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp, &data_req->cfc_src, &data_req->cfc_dst, !IS_INP_V6(inp), outgoing); if (cfil_info->cfi_debug && cfil_log_data) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: SENDING DATA UP"); } if (cfil_info->cfi_isSignatureLatest == false) { cfil_dispatch_data_event_sign(entry->cfe_filter->cf_crypto_state, so, cfil_info, data_req); } microuptime(&tv); CFI_ADD_TIME_LOG(cfil_info, &tv, &cfil_info->cfi_first_event, data_req->cfd_msghdr.cfm_op); /* Pass the message to the content filter */ error = ctl_enqueuembuf(entry->cfe_filter->cf_kcref, entry->cfe_filter->cf_kcunit, msg, CTL_DATA_EOR); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_enqueuembuf() failed: %d", error); mbuf_freem(msg); goto done; } entry->cfe_flags &= ~CFEF_FLOW_CONTROLLED; OSIncrementAtomic(&cfil_stats.cfs_data_event_ok); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: VERDICT ACTION: so %llx sockID %llu <%llx> outgoing %d: mbuf %llx copyoffset %u copylen %u (%s)", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, outgoing, (uint64_t)VM_KERNEL_ADDRPERM(data), copyoffset, copylen, data_req->cfd_flags & CFD_DATA_FLAG_IP_HEADER ? "IP HDR" : "NO IP HDR"); } done: if (error == ENOBUFS) { entry->cfe_flags |= CFEF_FLOW_CONTROLLED; OSIncrementAtomic( &cfil_stats.cfs_data_event_flow_control); if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags |= CFF_FLOW_CONTROLLED; cfil_rw_unlock_exclusive(&cfil_lck_rw); } else { if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_data_event_fail); } cfil_rw_unlock_shared(&cfil_lck_rw); } return error; } /* * Process the queue of data waiting to be delivered to content filter */ static int cfil_data_service_ctl_q(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing) { errno_t error = 0; struct mbuf *data, *tmp = NULL; unsigned int datalen = 0, copylen = 0, copyoffset = 0; struct cfil_entry *entry; struct cfe_buf *entrybuf; uint64_t currentoffset = 0; if (cfil_info == NULL) { return 0; } CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing); socket_lock_assert_owned(so); entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } /* Send attached message if not yet done */ if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) { error = cfil_dispatch_attach_event(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, entry), cfil_info->cfi_dir); if (error != 0) { /* We can recover from flow control */ if (error == ENOBUFS || error == ENOMEM) { error = 0; } goto done; } } else if ((entry->cfe_flags & CFEF_DATA_START) == 0) { OSIncrementAtomic(&cfil_stats.cfs_ctl_q_not_started); goto done; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE CTL-Q: pass_offset %llu peeked %llu peek_offset %llu", entrybuf->cfe_pass_offset, entrybuf->cfe_peeked, entrybuf->cfe_peek_offset); } /* Move all data that can pass */ while ((data = cfil_queue_first(&entrybuf->cfe_ctl_q)) != NULL && entrybuf->cfe_ctl_q.q_start < entrybuf->cfe_pass_offset) { datalen = cfil_data_length(data, NULL, NULL); tmp = data; if (entrybuf->cfe_ctl_q.q_start + datalen <= entrybuf->cfe_pass_offset) { /* * The first mbuf can fully pass */ copylen = datalen; } else { /* * The first mbuf can partially pass */ copylen = (unsigned int)(entrybuf->cfe_pass_offset - entrybuf->cfe_ctl_q.q_start); } VERIFY(copylen <= datalen); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE CTL-Q PASSING: %llx first %llu peeked %llu pass %llu peek %llu" "datalen %u copylen %u", (uint64_t)VM_KERNEL_ADDRPERM(tmp), entrybuf->cfe_ctl_q.q_start, entrybuf->cfe_peeked, entrybuf->cfe_pass_offset, entrybuf->cfe_peek_offset, datalen, copylen); } /* * Data that passes has been peeked at explicitly or * implicitly */ if (entrybuf->cfe_ctl_q.q_start + copylen > entrybuf->cfe_peeked) { entrybuf->cfe_peeked = entrybuf->cfe_ctl_q.q_start + copylen; } /* * Stop on partial pass */ if (copylen < datalen) { break; } /* All good, move full data from ctl queue to pending queue */ cfil_queue_remove(&entrybuf->cfe_ctl_q, data, datalen); cfil_queue_enqueue(&entrybuf->cfe_pending_q, data, datalen); if (outgoing) { OSAddAtomic64(datalen, &cfil_stats.cfs_pending_q_out_enqueued); } else { OSAddAtomic64(datalen, &cfil_stats.cfs_pending_q_in_enqueued); } } CFIL_INFO_VERIFY(cfil_info); if (tmp != NULL) { CFIL_LOG(LOG_DEBUG, "%llx first %llu peeked %llu pass %llu peek %llu" "datalen %u copylen %u", (uint64_t)VM_KERNEL_ADDRPERM(tmp), entrybuf->cfe_ctl_q.q_start, entrybuf->cfe_peeked, entrybuf->cfe_pass_offset, entrybuf->cfe_peek_offset, datalen, copylen); } tmp = NULL; /* Now deal with remaining data the filter wants to peek at */ for (data = cfil_queue_first(&entrybuf->cfe_ctl_q), currentoffset = entrybuf->cfe_ctl_q.q_start; data != NULL && currentoffset < entrybuf->cfe_peek_offset; data = cfil_queue_next(&entrybuf->cfe_ctl_q, data), currentoffset += datalen) { datalen = cfil_data_length(data, NULL, NULL); tmp = data; /* We've already peeked at this mbuf */ if (currentoffset + datalen <= entrybuf->cfe_peeked) { continue; } /* * The data in the first mbuf may have been * partially peeked at */ copyoffset = (unsigned int)(entrybuf->cfe_peeked - currentoffset); VERIFY(copyoffset < datalen); copylen = datalen - copyoffset; VERIFY(copylen <= datalen); /* * Do not copy more than needed */ if (currentoffset + copyoffset + copylen > entrybuf->cfe_peek_offset) { copylen = (unsigned int)(entrybuf->cfe_peek_offset - (currentoffset + copyoffset)); } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE CTL-Q PEEKING: %llx current %llu peeked %llu pass %llu peek %llu " "datalen %u copylen %u copyoffset %u", (uint64_t)VM_KERNEL_ADDRPERM(tmp), currentoffset, entrybuf->cfe_peeked, entrybuf->cfe_pass_offset, entrybuf->cfe_peek_offset, datalen, copylen, copyoffset); } /* * Stop if there is nothing more to peek at */ if (copylen == 0) { break; } /* * Let the filter get a peek at this span of data */ error = cfil_dispatch_data_event(so, cfil_info, kcunit, outgoing, data, copyoffset, copylen); if (error != 0) { /* On error, leave data in ctl_q */ break; } entrybuf->cfe_peeked += copylen; if (outgoing) { OSAddAtomic64(copylen, &cfil_stats.cfs_ctl_q_out_peeked); } else { OSAddAtomic64(copylen, &cfil_stats.cfs_ctl_q_in_peeked); } /* Stop when data could not be fully peeked at */ if (copylen + copyoffset < datalen) { break; } } CFIL_INFO_VERIFY(cfil_info); if (tmp != NULL) { CFIL_LOG(LOG_DEBUG, "%llx first %llu peeked %llu pass %llu peek %llu" "datalen %u copylen %u copyoffset %u", (uint64_t)VM_KERNEL_ADDRPERM(tmp), currentoffset, entrybuf->cfe_peeked, entrybuf->cfe_pass_offset, entrybuf->cfe_peek_offset, datalen, copylen, copyoffset); } /* * Process data that has passed the filter */ error = cfil_service_pending_queue(so, cfil_info, kcunit, outgoing); if (error != 0) { if (error != EJUSTRETURN) { CFIL_LOG(LOG_ERR, "cfil_service_pending_queue() error %d", error); } goto done; } /* * Dispatch disconnect events that could not be sent */ if (cfil_info == NULL) { goto done; } else if (outgoing) { if ((cfil_info->cfi_flags & CFIF_SHUT_WR) && !(entry->cfe_flags & CFEF_SENT_DISCONNECT_OUT)) { cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1); } } else { if ((cfil_info->cfi_flags & CFIF_SHUT_RD) && !(entry->cfe_flags & CFEF_SENT_DISCONNECT_IN)) { cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0); } } done: CFIL_LOG(LOG_DEBUG, "first %llu peeked %llu pass %llu peek %llu", entrybuf->cfe_ctl_q.q_start, entrybuf->cfe_peeked, entrybuf->cfe_pass_offset, entrybuf->cfe_peek_offset); CFIL_INFO_VERIFY(cfil_info); return error; } /* * cfil_data_filter() * * Process data for a content filter installed on a socket */ int cfil_data_filter(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing, struct mbuf *data, uint32_t datalen) { errno_t error = 0; struct cfil_entry *entry; struct cfe_buf *entrybuf; CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing); socket_lock_assert_owned(so); entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } /* Are we attached to the filter? */ if (entry->cfe_filter == NULL) { error = 0; goto done; } /* Dispatch to filters */ cfil_queue_enqueue(&entrybuf->cfe_ctl_q, data, datalen); if (outgoing) { OSAddAtomic64(datalen, &cfil_stats.cfs_ctl_q_out_enqueued); } else { OSAddAtomic64(datalen, &cfil_stats.cfs_ctl_q_in_enqueued); } error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing); if (error != 0) { if (error != EJUSTRETURN) { CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d", error); } } /* * We have to return EJUSTRETURN in all cases to avoid double free * by socket layer */ error = EJUSTRETURN; done: CFIL_INFO_VERIFY(cfil_info); CFIL_LOG(LOG_INFO, "return %d", error); return error; } static void cfil_strip_ip_header(struct cfil_info *cfil_info, mbuf_t data, struct socket *so) { struct ip *ip = NULL; unsigned int hlen = 0; mbuf_t data_start = NULL; struct inpcb *inp = so ? sotoinpcb(so) : NULL; if (inp && (inp->inp_flags & INP_STRIPHDR)) { data_start = cfil_data_start(data); if (data_start != NULL && (data_start->m_flags & M_PKTHDR)) { ip = mtod(data_start, struct ip *); hlen = IP_VHL_HL(ip->ip_vhl) << 2; if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: IPHDR STRIPPING: <so %llx>: <hlen %d m_len %d>", (uint64_t)VM_KERNEL_ADDRPERM(so), hlen, data_start->m_len); } VERIFY(hlen <= data_start->m_len); data_start->m_len -= hlen; data_start->m_pkthdr.len -= hlen; data_start->m_data += hlen; } } } /* * cfil_service_inject_queue() re-inject data that passed the * content filters */ static int cfil_service_inject_queue(struct socket *so, struct cfil_info *cfil_info, int outgoing) { mbuf_t data; unsigned int datalen; int mbcnt = 0; int mbnum = 0; errno_t error = 0; struct cfi_buf *cfi_buf; struct cfil_queue *inject_q; int need_rwakeup = 0; int count = 0; if (cfil_info == NULL) { return 0; } socket_lock_assert_owned(so); if (so->so_state & SS_DEFUNCT) { return 0; } if (outgoing) { cfi_buf = &cfil_info->cfi_snd; cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_OUT; } else { cfi_buf = &cfil_info->cfi_rcv; cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_IN; } inject_q = &cfi_buf->cfi_inject_q; if (cfil_queue_empty(inject_q)) { return 0; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE INJECT-Q: <so %llx> outgoing %d queue len %llu", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, cfil_queue_len(inject_q)); } while ((data = cfil_queue_first(inject_q)) != NULL) { datalen = cfil_data_length(data, &mbcnt, &mbnum); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE INJECT-Q: <so %llx> data %llx datalen %u (mbcnt %u)", (uint64_t)VM_KERNEL_ADDRPERM(so), (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, mbcnt); } /* Remove data from queue and adjust stats */ cfil_queue_remove(inject_q, data, datalen); cfi_buf->cfi_pending_first += datalen; cfi_buf->cfi_pending_mbcnt -= mbcnt; cfi_buf->cfi_pending_mbnum -= mbnum; cfil_info_buf_verify(cfi_buf); if (outgoing) { error = sosend_reinject(so, NULL, data, NULL, 0); if (error != 0) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: Error: sosend_reinject() failed"); CFIL_LOG(LOG_ERR, "CFIL: sosend() failed %d", error); break; } // At least one injection succeeded, need to wake up pending threads. need_rwakeup = 1; } else { data->m_flags |= M_SKIPCFIL; /* * NOTE: We currently only support TCP, UDP, ICMP, * ICMPv6 and RAWIP. For MPTCP and message TCP we'll * need to call the appropriate sbappendxxx() * of fix sock_inject_data_in() */ if (NEED_DGRAM_FLOW_TRACKING(so)) { if (OPTIONAL_IP_HEADER(so)) { cfil_strip_ip_header(cfil_info, data, so); } if (sbappendchain(&so->so_rcv, data)) { need_rwakeup = 1; } } else { if (sbappendstream(&so->so_rcv, data)) { need_rwakeup = 1; } } } if (outgoing) { OSAddAtomic64(datalen, &cfil_stats.cfs_inject_q_out_passed); } else { OSAddAtomic64(datalen, &cfil_stats.cfs_inject_q_in_passed); } count++; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE INJECT-Q: <so %llx> injected %d", (uint64_t)VM_KERNEL_ADDRPERM(so), count); } /* A single wakeup is for several packets is more efficient */ if (need_rwakeup) { if (outgoing == TRUE) { sowwakeup(so); } else { sorwakeup(so); } } if (error != 0 && cfil_info) { if (error == ENOBUFS) { OSIncrementAtomic(&cfil_stats.cfs_inject_q_nobufs); } if (error == ENOMEM) { OSIncrementAtomic(&cfil_stats.cfs_inject_q_nomem); } if (outgoing) { cfil_info->cfi_flags |= CFIF_RETRY_INJECT_OUT; OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_fail); } else { cfil_info->cfi_flags |= CFIF_RETRY_INJECT_IN; OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_fail); } } /* * Notify */ if (cfil_info && (cfil_info->cfi_flags & CFIF_SHUT_WR)) { cfil_sock_notify_shutdown(so, SHUT_WR); if (cfil_sock_data_pending(&so->so_snd) == 0) { soshutdownlock_final(so, SHUT_WR); } } if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) { if (cfil_filters_attached(so) == 0) { CFIL_LOG(LOG_INFO, "so %llx waking", (uint64_t)VM_KERNEL_ADDRPERM(so)); wakeup((caddr_t)cfil_info); } } if (SO_DELAYED_DEAD_GET(so)) { // Check to see if all data processed for this socket, if so mark it DEAD now. const bool is_dead = cfil_sock_is_dead(so); if (is_dead && cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: Marked previoulsy delayed socket as DEAD"); } } if (SO_DELAYED_TCP_TIME_WAIT_GET(so)) { // Check to see if all data processed for this socket, if so handle the TCP time wait now const bool is_added = cfil_sock_tcp_add_time_wait(so); if (is_added && cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: Handled previously delayed socket for TCP time wait"); } } CFIL_INFO_VERIFY(cfil_info); return error; } static int cfil_service_pending_queue(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing) { uint64_t passlen, curlen; mbuf_t data; unsigned int datalen; errno_t error = 0; struct cfil_entry *entry; struct cfe_buf *entrybuf; struct cfil_queue *pending_q; struct cfil_entry *iter_entry = NULL; CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing); socket_lock_assert_owned(so); entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } pending_q = &entrybuf->cfe_pending_q; passlen = entrybuf->cfe_pass_offset - pending_q->q_start; if (cfil_queue_empty(pending_q)) { for (iter_entry = SLIST_NEXT(entry, cfe_order_link); iter_entry != NULL; iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) { error = cfil_data_service_ctl_q(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing); /* 0 means passed so we can continue */ if (error != 0) { break; } } goto done; } /* * Locate the chunks of data that we can pass to the next filter * A data chunk must be on mbuf boundaries */ curlen = 0; while ((data = cfil_queue_first(pending_q)) != NULL) { datalen = cfil_data_length(data, NULL, NULL); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: SERVICE PENDING-Q: data %llx datalen %u passlen %llu curlen %llu", (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, passlen, curlen); } if (curlen + datalen > passlen) { break; } cfil_queue_remove(pending_q, data, datalen); curlen += datalen; for (iter_entry = SLIST_NEXT(entry, cfe_order_link); iter_entry != NULL; iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) { error = cfil_data_filter(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing, data, datalen); /* 0 means passed so we can continue */ if (error != 0) { break; } } /* When data has passed all filters, re-inject */ if (error == 0) { if (outgoing) { cfil_queue_enqueue( &cfil_info->cfi_snd.cfi_inject_q, data, datalen); OSAddAtomic64(datalen, &cfil_stats.cfs_inject_q_out_enqueued); } else { cfil_queue_enqueue( &cfil_info->cfi_rcv.cfi_inject_q, data, datalen); OSAddAtomic64(datalen, &cfil_stats.cfs_inject_q_in_enqueued); } } } done: CFIL_INFO_VERIFY(cfil_info); return error; } int cfil_update_data_offsets(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing, uint64_t pass_offset, uint64_t peek_offset) { errno_t error = 0; struct cfil_entry *entry = NULL; struct cfe_buf *entrybuf; int updated = 0; CFIL_LOG(LOG_INFO, "pass %llu peek %llu", pass_offset, peek_offset); socket_lock_assert_owned(so); if (cfil_info == NULL) { CFIL_LOG(LOG_ERR, "so %llx cfil detached", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = 0; goto done; } else if (cfil_info->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EPIPE; goto done; } entry = &cfil_info->cfi_entries[kcunit - 1]; if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } /* Record updated offsets for this content filter */ if (pass_offset > entrybuf->cfe_pass_offset) { entrybuf->cfe_pass_offset = pass_offset; if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) { entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset; } updated = 1; } else { CFIL_LOG(LOG_INFO, "pass_offset %llu <= cfe_pass_offset %llu", pass_offset, entrybuf->cfe_pass_offset); } /* Filter does not want or need to see data that's allowed to pass */ if (peek_offset > entrybuf->cfe_pass_offset && peek_offset > entrybuf->cfe_peek_offset) { entrybuf->cfe_peek_offset = peek_offset; updated = 1; } /* Nothing to do */ if (updated == 0) { goto done; } /* Move data held in control queue to pending queue if needed */ error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing); if (error != 0) { if (error != EJUSTRETURN) { CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d", error); } goto done; } error = EJUSTRETURN; done: /* * The filter is effectively detached when pass all from both sides * or when the socket is closed and no more data is waiting * to be delivered to the filter */ if (entry != NULL && ((entry->cfe_snd.cfe_pass_offset == CFM_MAX_OFFSET && entry->cfe_rcv.cfe_pass_offset == CFM_MAX_OFFSET) || ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) && cfil_queue_empty(&entry->cfe_snd.cfe_ctl_q) && cfil_queue_empty(&entry->cfe_rcv.cfe_ctl_q)))) { entry->cfe_flags |= CFEF_CFIL_DETACHED; if (cfil_info->cfi_debug) { const char * __null_terminated out = "CFIL: OUT - PASSED ALL - DETACH"; const char * __null_terminated in = "CFIL: IN - PASSED ALL - DETACH"; cfil_info_log(LOG_ERR, cfil_info, outgoing ? out : in); } CFIL_LOG(LOG_INFO, "so %llx detached %u", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit); if ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) && cfil_filters_attached(so) == 0) { if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: WAKING"); } CFIL_LOG(LOG_INFO, "so %llx waking", (uint64_t)VM_KERNEL_ADDRPERM(so)); wakeup((caddr_t)cfil_info); } } CFIL_INFO_VERIFY(cfil_info); CFIL_LOG(LOG_INFO, "return %d", error); return error; } /* * Update pass offset for socket when no data is pending */ static int cfil_set_socket_pass_offset(struct socket *so, struct cfil_info *cfil_info, int outgoing) { struct cfi_buf *cfi_buf; struct cfil_entry *entry; struct cfe_buf *entrybuf; uint32_t kcunit; uint64_t pass_offset = 0; boolean_t first = true; if (cfil_info == NULL) { return 0; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "so %llx outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing); } socket_lock_assert_owned(so); if (outgoing) { cfi_buf = &cfil_info->cfi_snd; } else { cfi_buf = &cfil_info->cfi_rcv; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx, sockID %llu <%llx>> outgoing %d cfi_pending_first %llu cfi_pending_last %llu", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, outgoing, cfi_buf->cfi_pending_first, cfi_buf->cfi_pending_last); } if (cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first == 0) { for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; /* Are we attached to a filter? */ if (entry->cfe_filter == NULL) { continue; } if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } // Keep track of the smallest pass_offset among filters. if (first == true || entrybuf->cfe_pass_offset < pass_offset) { pass_offset = entrybuf->cfe_pass_offset; first = false; } } cfi_buf->cfi_pass_offset = pass_offset; } if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx, sockID %llu <%llx>>, cfi_pass_offset %llu", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id, cfi_buf->cfi_pass_offset); } return 0; } int cfil_action_data_pass(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing, uint64_t pass_offset, uint64_t peek_offset) { errno_t error = 0; CFIL_LOG(LOG_INFO, ""); socket_lock_assert_owned(so); error = cfil_acquire_sockbuf(so, cfil_info, outgoing); if (error != 0) { CFIL_LOG(LOG_INFO, "so %llx %s dropped", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing ? "out" : "in"); goto release; } error = cfil_update_data_offsets(so, cfil_info, kcunit, outgoing, pass_offset, peek_offset); cfil_service_inject_queue(so, cfil_info, outgoing); cfil_set_socket_pass_offset(so, cfil_info, outgoing); release: CFIL_INFO_VERIFY(cfil_info); cfil_release_sockbuf(so, outgoing); return error; } static void cfil_flush_queues(struct socket *so, struct cfil_info *cfil_info) { struct cfil_entry *entry; int kcunit; uint64_t drained; if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) { goto done; } socket_lock_assert_owned(so); /* * Flush the output queues and ignore errors as long as * we are attached */ (void) cfil_acquire_sockbuf(so, cfil_info, 1); if (cfil_info != NULL) { drained = 0; for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; drained += cfil_queue_drain(&entry->cfe_snd.cfe_ctl_q); drained += cfil_queue_drain(&entry->cfe_snd.cfe_pending_q); } drained += cfil_queue_drain(&cfil_info->cfi_snd.cfi_inject_q); if (drained) { if (cfil_info->cfi_flags & CFIF_DROP) { OSIncrementAtomic( &cfil_stats.cfs_flush_out_drop); } else { OSIncrementAtomic( &cfil_stats.cfs_flush_out_close); } } } cfil_release_sockbuf(so, 1); /* * Flush the input queues */ (void) cfil_acquire_sockbuf(so, cfil_info, 0); if (cfil_info != NULL) { drained = 0; for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; drained += cfil_queue_drain( &entry->cfe_rcv.cfe_ctl_q); drained += cfil_queue_drain( &entry->cfe_rcv.cfe_pending_q); } drained += cfil_queue_drain(&cfil_info->cfi_rcv.cfi_inject_q); if (drained) { if (cfil_info->cfi_flags & CFIF_DROP) { OSIncrementAtomic( &cfil_stats.cfs_flush_in_drop); } else { OSIncrementAtomic( &cfil_stats.cfs_flush_in_close); } } } cfil_release_sockbuf(so, 0); done: CFIL_INFO_VERIFY(cfil_info); } int cfil_action_drop(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit) { errno_t error = 0; struct cfil_entry *entry; struct proc *p; if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) { goto done; } socket_lock_assert_owned(so); entry = &cfil_info->cfi_entries[kcunit - 1]; /* Are we attached to the filter? */ if (entry->cfe_filter == NULL) { goto done; } cfil_info->cfi_flags |= CFIF_DROP; p = current_proc(); /* * Force the socket to be marked defunct * (forcing fixed along with rdar://19391339) */ if (so->so_flow_db == NULL) { error = sosetdefunct(p, so, SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL, FALSE); /* Flush the socket buffer and disconnect */ if (error == 0) { error = sodefunct(p, so, SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL); } } /* The filter is done, mark as detached */ entry->cfe_flags |= CFEF_CFIL_DETACHED; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: DROP - DETACH"); } CFIL_LOG(LOG_INFO, "so %llx detached %u", (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit); /* Pending data needs to go */ cfil_flush_queues(so, cfil_info); if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) { if (cfil_filters_attached(so) == 0) { CFIL_LOG(LOG_INFO, "so %llx waking", (uint64_t)VM_KERNEL_ADDRPERM(so)); wakeup((caddr_t)cfil_info); } } done: return error; } int cfil_action_bless_client(uint32_t kcunit, struct cfil_msg_hdr *msghdr) { errno_t error = 0; struct cfil_info * __single cfil_info = NULL; bool cfil_attached = false; struct cfil_msg_bless_client *blessmsg = (struct cfil_msg_bless_client *)msghdr; // Search and lock socket struct socket *so = cfil_socket_from_client_uuid(blessmsg->cfb_client_uuid, &cfil_attached); if (so == NULL) { error = ENOENT; } else { // The client gets a pass automatically cfil_info = (so->so_flow_db != NULL) ? soflow_db_get_feature_context(so->so_flow_db, msghdr->cfm_sock_id) : so->so_cfil; if (cfil_attached) { if (cfil_info != NULL && cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: VERDICT RECEIVED: BLESS"); } cfil_sock_received_verdict(so); (void)cfil_action_data_pass(so, cfil_info, kcunit, 1, CFM_MAX_OFFSET, CFM_MAX_OFFSET); (void)cfil_action_data_pass(so, cfil_info, kcunit, 0, CFM_MAX_OFFSET, CFM_MAX_OFFSET); } else { so->so_flags1 |= SOF1_CONTENT_FILTER_SKIP; } socket_unlock(so, 1); } return error; } int cfil_action_set_crypto_key(uint32_t kcunit, struct cfil_msg_hdr *msghdr) { struct content_filter *cfc = NULL; cfil_crypto_state_t crypto_state = NULL; struct cfil_msg_set_crypto_key *keymsg = (struct cfil_msg_set_crypto_key *)msghdr; CFIL_LOG(LOG_NOTICE, ""); if (kcunit > MAX_CONTENT_FILTER) { CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)", kcunit, MAX_CONTENT_FILTER); return EINVAL; } crypto_state = cfil_crypto_init_client((uint8_t *)keymsg->crypto_key); if (crypto_state == NULL) { CFIL_LOG(LOG_ERR, "failed to initialize crypto state for unit %u)", kcunit); return EINVAL; } cfil_rw_lock_exclusive(&cfil_lck_rw); cfc = content_filters[kcunit - 1]; if (cfc->cf_kcunit != kcunit) { CFIL_LOG(LOG_ERR, "bad unit info %u)", kcunit); cfil_rw_unlock_exclusive(&cfil_lck_rw); cfil_crypto_cleanup_state(crypto_state); return EINVAL; } if (cfc->cf_crypto_state != NULL) { cfil_crypto_cleanup_state(cfc->cf_crypto_state); cfc->cf_crypto_state = NULL; } cfc->cf_crypto_state = crypto_state; cfil_rw_unlock_exclusive(&cfil_lck_rw); return 0; } static int cfil_update_entry_offsets(struct socket *so, struct cfil_info *cfil_info, int outgoing, unsigned int datalen) { struct cfil_entry *entry; struct cfe_buf *entrybuf; uint32_t kcunit; CFIL_LOG(LOG_INFO, "so %llx outgoing %d datalen %u", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, datalen); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; /* Are we attached to the filter? */ if (entry->cfe_filter == NULL) { continue; } if (outgoing) { entrybuf = &entry->cfe_snd; } else { entrybuf = &entry->cfe_rcv; } entrybuf->cfe_ctl_q.q_start += datalen; if (entrybuf->cfe_pass_offset < entrybuf->cfe_ctl_q.q_start) { entrybuf->cfe_pass_offset = entrybuf->cfe_ctl_q.q_start; } entrybuf->cfe_peeked = entrybuf->cfe_ctl_q.q_start; if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) { entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset; } entrybuf->cfe_ctl_q.q_end += datalen; entrybuf->cfe_pending_q.q_start += datalen; entrybuf->cfe_pending_q.q_end += datalen; } CFIL_INFO_VERIFY(cfil_info); return 0; } int cfil_data_common(struct socket *so, struct cfil_info *cfil_info, int outgoing, struct sockaddr *to, struct mbuf *data, struct mbuf *control, uint32_t flags) { #pragma unused(to, control, flags) errno_t error = 0; unsigned int datalen; int mbcnt = 0; int mbnum = 0; int kcunit; struct cfi_buf *cfi_buf; struct mbuf *chain = NULL; if (cfil_info == NULL) { CFIL_LOG(LOG_ERR, "so %llx cfil detached", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = 0; goto done; } else if (cfil_info->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); error = EPIPE; goto done; } datalen = cfil_data_length(data, &mbcnt, &mbnum); if (datalen == 0) { error = 0; goto done; } if (outgoing) { cfi_buf = &cfil_info->cfi_snd; cfil_info->cfi_byte_outbound_count += datalen; } else { cfi_buf = &cfil_info->cfi_rcv; cfil_info->cfi_byte_inbound_count += datalen; } cfi_buf->cfi_pending_last += datalen; cfi_buf->cfi_pending_mbcnt += mbcnt; cfi_buf->cfi_pending_mbnum += mbnum; if (NEED_DGRAM_FLOW_TRACKING(so)) { if (cfi_buf->cfi_pending_mbnum > cfil_udp_gc_mbuf_num_max || cfi_buf->cfi_pending_mbcnt > cfil_udp_gc_mbuf_cnt_max) { cfi_buf->cfi_tail_drop_cnt++; cfi_buf->cfi_pending_mbcnt -= mbcnt; cfi_buf->cfi_pending_mbnum -= mbnum; return EPIPE; } } cfil_info_buf_verify(cfi_buf); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: QUEUEING DATA: <so %llx> %s: data %llx len %u flags 0x%x nextpkt %llx - cfi_pending_last %llu cfi_pending_mbcnt %u cfi_pass_offset %llu", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing ? "OUT" : "IN", (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, data->m_flags, (uint64_t)VM_KERNEL_ADDRPERM(data->m_nextpkt), cfi_buf->cfi_pending_last, cfi_buf->cfi_pending_mbcnt, cfi_buf->cfi_pass_offset); } /* Fast path when below pass offset */ if (cfi_buf->cfi_pending_last <= cfi_buf->cfi_pass_offset) { cfil_update_entry_offsets(so, cfil_info, outgoing, datalen); if (cfil_info->cfi_debug && cfil_log_data) { CFIL_LOG(LOG_ERR, "CFIL: QUEUEING DATA: <so %llx> %s: FAST PATH", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing ? "OUT" : "IN"); } // For incoming packets, see if we need to strip off ip header if (!outgoing && NEED_DGRAM_FLOW_TRACKING(so) && OPTIONAL_IP_HEADER(so)) { cfil_strip_ip_header(cfil_info, data, so); } } else { struct cfil_entry *iter_entry; SLIST_FOREACH(iter_entry, &cfil_info->cfi_ordered_entries, cfe_order_link) { // Is cfil attached to this filter? kcunit = CFI_ENTRY_KCUNIT(cfil_info, iter_entry); if (IS_ENTRY_ATTACHED(cfil_info, kcunit)) { if (NEED_DGRAM_FLOW_TRACKING(so) && chain == NULL) { /* Datagrams only: * Chain addr (incoming only TDB), control (optional) and data into one chain. * This full chain will be reinjected into socket after recieving verdict. */ (void) cfil_dgram_save_socket_state(cfil_info, data); chain = sbconcat_mbufs(NULL, outgoing ? NULL : to, data, control); if (chain == NULL) { return ENOBUFS; } data = chain; } error = cfil_data_filter(so, cfil_info, kcunit, outgoing, data, datalen); } /* 0 means passed so continue with next filter */ if (error != 0) { break; } } } /* Move cursor if no filter claimed the data */ if (error == 0) { cfi_buf->cfi_pending_first += datalen; cfi_buf->cfi_pending_mbcnt -= mbcnt; cfi_buf->cfi_pending_mbnum -= mbnum; cfil_info_buf_verify(cfi_buf); } done: CFIL_INFO_VERIFY(cfil_info); return error; } /* * Callback from socket layer sosendxxx() */ int cfil_sock_data_out(struct socket *so, struct sockaddr *to, struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry) { int error = 0; int new_filter_control_unit = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_sock_udp_handle_data(TRUE, so, NULL, to, data, control, flags, flow_entry); } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { /* Drop pre-existing TCP sockets if filter is enabled now */ if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) { new_filter_control_unit = necp_socket_get_content_filter_control_unit(so); if (new_filter_control_unit > 0) { cfil_log_printf(so, NULL, "CFIL: outbound TCP data dropped for pre-existing un-filtered flow"); return EPIPE; } } return 0; } /* Drop pre-existing TCP sockets when filter state changed */ new_filter_control_unit = necp_socket_get_content_filter_control_unit(so); if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) { if (DO_PRESERVE_CONNECTIONS || (so->so_cfil->cfi_filter_policy_gencount == necp_socket_get_policy_gencount(so))) { // CFIL state has changed, but preserve the flow intentionally or if this is not a result of NECP policy change so->so_cfil->cfi_filter_control_unit = new_filter_control_unit; } else { cfil_log_printf(so, so->so_cfil, "CFIL: outbound TCP data dropped (0x%x -> 0x%x)", so->so_cfil->cfi_filter_control_unit, new_filter_control_unit); return EPIPE; } } /* * Pass initial data for TFO. */ if (IS_INITIAL_TFO_DATA(so)) { return 0; } socket_lock_assert_owned(so); if (so->so_cfil->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); return EPIPE; } if (control != NULL) { CFIL_LOG(LOG_ERR, "so %llx control", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_data_out_control); } if ((flags & MSG_OOB)) { CFIL_LOG(LOG_ERR, "so %llx MSG_OOB", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_data_out_oob); } /* * Abort if socket is defunct. */ if (so->so_flags & SOF_DEFUNCT) { return EPIPE; } if ((so->so_snd.sb_flags & SB_LOCK) == 0) { panic("so %p SB_LOCK not set", so); } if (so->so_snd.sb_cfil_thread != NULL) { panic("%s sb_cfil_thread %p not NULL", __func__, so->so_snd.sb_cfil_thread); } error = cfil_data_common(so, so->so_cfil, 1, to, data, control, flags); return error; } /* * Callback from socket layer sbappendxxx() */ int cfil_sock_data_in(struct socket *so, struct sockaddr *from, struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry) { int error = 0; int new_filter_control_unit = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_sock_udp_handle_data(FALSE, so, NULL, from, data, control, flags, flow_entry); } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { /* Drop pre-existing TCP sockets if filter is enabled now */ if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) { new_filter_control_unit = necp_socket_get_content_filter_control_unit(so); if (new_filter_control_unit > 0) { cfil_log_printf(so, NULL, "CFIL: inbound TCP data dropped for pre-existing un-filtered flow"); return EPIPE; } } return 0; } /* Drop pre-existing TCP sockets when filter state changed */ new_filter_control_unit = necp_socket_get_content_filter_control_unit(so); if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) { if (DO_PRESERVE_CONNECTIONS || (so->so_cfil->cfi_filter_policy_gencount == necp_socket_get_policy_gencount(so))) { // CFIL state has changed, but preserve the flow intentionally or if this is not a result of NECP policy change so->so_cfil->cfi_filter_control_unit = new_filter_control_unit; } else { cfil_log_printf(so, so->so_cfil, "CFIL: inbound TCP data dropped (0x%x -> 0x%x)", so->so_cfil->cfi_filter_control_unit, new_filter_control_unit); return EPIPE; } } /* * Pass initial data for TFO. */ if (IS_INITIAL_TFO_DATA(so)) { return 0; } socket_lock_assert_owned(so); if (so->so_cfil->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); return EPIPE; } if (control != NULL) { CFIL_LOG(LOG_ERR, "so %llx control", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_data_in_control); } if (data->m_type == MT_OOBDATA) { CFIL_LOG(LOG_ERR, "so %llx MSG_OOB", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_data_in_oob); } error = cfil_data_common(so, so->so_cfil, 0, from, data, control, flags); return error; } /* * Callback from socket layer soshutdownxxx() * * We may delay the shutdown write if there's outgoing data in process. * * There is no point in delaying the shutdown read because the process * indicated that it does not want to read anymore data. */ int cfil_sock_shutdown(struct socket *so, int *how) { int error = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_sock_udp_shutdown(so, how); } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { goto done; } socket_lock_assert_owned(so); CFIL_LOG(LOG_INFO, "so %llx how %d", (uint64_t)VM_KERNEL_ADDRPERM(so), *how); /* * Check the state of the socket before the content filter */ if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) { /* read already shut down */ error = ENOTCONN; goto done; } if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) { /* write already shut down */ error = ENOTCONN; goto done; } if ((so->so_cfil->cfi_flags & CFIF_DROP) != 0) { CFIL_LOG(LOG_ERR, "so %llx drop set", (uint64_t)VM_KERNEL_ADDRPERM(so)); goto done; } /* * shutdown read: SHUT_RD or SHUT_RDWR */ if (*how != SHUT_WR) { if (so->so_cfil->cfi_flags & CFIF_SHUT_RD) { error = ENOTCONN; goto done; } so->so_cfil->cfi_flags |= CFIF_SHUT_RD; cfil_sock_notify_shutdown(so, SHUT_RD); } /* * shutdown write: SHUT_WR or SHUT_RDWR */ if (*how != SHUT_RD) { if (so->so_cfil->cfi_flags & CFIF_SHUT_WR) { error = ENOTCONN; goto done; } so->so_cfil->cfi_flags |= CFIF_SHUT_WR; cfil_sock_notify_shutdown(so, SHUT_WR); /* * When outgoing data is pending, we delay the shutdown at the * protocol level until the content filters give the final * verdict on the pending data. */ if (cfil_sock_data_pending(&so->so_snd) != 0) { /* * When shutting down the read and write sides at once * we can proceed to the final shutdown of the read * side. Otherwise, we just return. */ if (*how == SHUT_WR) { error = EJUSTRETURN; } else if (*how == SHUT_RDWR) { *how = SHUT_RD; } } } done: return error; } /* * This is called when the socket is closed and there is no more * opportunity for filtering */ void cfil_sock_is_closed(struct socket *so) { errno_t error = 0; int kcunit; if (NEED_DGRAM_FLOW_TRACKING(so)) { cfil_sock_udp_is_closed(so); return; } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { return; } CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so)); socket_lock_assert_owned(so); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { /* Let the filters know of the closing */ error = cfil_dispatch_closed_event(so, so->so_cfil, kcunit); } /* Last chance to push passed data out */ error = cfil_acquire_sockbuf(so, so->so_cfil, 1); if (error == 0) { cfil_service_inject_queue(so, so->so_cfil, 1); } cfil_release_sockbuf(so, 1); if (so->so_cfil != NULL) { so->so_cfil->cfi_flags |= CFIF_SOCK_CLOSED; } /* Pending data needs to go */ cfil_flush_queues(so, so->so_cfil); CFIL_INFO_VERIFY(so->so_cfil); } /* * This is called when the socket is disconnected so let the filters * know about the disconnection and that no more data will come * * The how parameter has the same values as soshutown() */ void cfil_sock_notify_shutdown(struct socket *so, int how) { errno_t error = 0; int kcunit; if (NEED_DGRAM_FLOW_TRACKING(so)) { cfil_sock_udp_notify_shutdown(so, how, 0, 0); return; } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { return; } CFIL_LOG(LOG_INFO, "so %llx how %d", (uint64_t)VM_KERNEL_ADDRPERM(so), how); socket_lock_assert_owned(so); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { /* Disconnect incoming side */ if (how != SHUT_WR) { error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 0); } /* Disconnect outgoing side */ if (how != SHUT_RD) { error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 1); } } } static int cfil_filters_attached(struct socket *so) { struct cfil_entry *entry; uint32_t kcunit; int attached = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_filters_udp_attached(so, FALSE); } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { return 0; } socket_lock_assert_owned(so); for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &so->so_cfil->cfi_entries[kcunit - 1]; /* Are we attached to the filter? */ if (entry->cfe_filter == NULL) { continue; } if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) { continue; } if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) { continue; } attached = 1; break; } return attached; } /* * This is called when the socket is closed and we are waiting for * the filters to gives the final pass or drop */ void cfil_sock_close_wait(struct socket *so) { lck_mtx_t *mutex_held; struct timespec ts; int error; if (NEED_DGRAM_FLOW_TRACKING(so)) { cfil_sock_udp_close_wait(so); return; } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { return; } // This flow does not need to wait for close ack from user-space if (IS_NO_CLOSE_WAIT(so->so_cfil)) { if (so->so_cfil->cfi_debug) { cfil_info_log(LOG_ERR, so->so_cfil, "CFIL: SKIP CLOSE WAIT"); } return; } CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so)); if (so->so_proto->pr_getlock != NULL) { mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK); } else { mutex_held = so->so_proto->pr_domain->dom_mtx; } LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED); while (cfil_filters_attached(so)) { /* * Notify the filters we are going away so they can detach */ cfil_sock_notify_shutdown(so, SHUT_RDWR); /* * Make sure we need to wait after the filter are notified * of the disconnection */ if (cfil_filters_attached(so) == 0) { break; } CFIL_LOG(LOG_INFO, "so %llx waiting", (uint64_t)VM_KERNEL_ADDRPERM(so)); ts.tv_sec = cfil_close_wait_timeout / 1000; ts.tv_nsec = (cfil_close_wait_timeout % 1000) * NSEC_PER_USEC * 1000; OSIncrementAtomic(&cfil_stats.cfs_close_wait); so->so_cfil->cfi_flags |= CFIF_CLOSE_WAIT; error = msleep((caddr_t)so->so_cfil, mutex_held, PSOCK | PCATCH, "cfil_sock_close_wait", &ts); // Woke up from sleep, validate if cfil_info is still valid if (so->so_cfil == NULL) { // cfil_info is not valid, do not continue return; } so->so_cfil->cfi_flags &= ~CFIF_CLOSE_WAIT; CFIL_LOG(LOG_NOTICE, "so %llx timed out %d", (uint64_t)VM_KERNEL_ADDRPERM(so), (error != 0)); /* * Force close in case of timeout */ if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout); break; } } } /* * Returns the size of the data held by the content filter by using */ int32_t cfil_sock_data_pending(struct sockbuf *sb) { struct socket *so = sb->sb_so; uint64_t pending = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_sock_udp_data_pending(sb, FALSE); } if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL) { struct cfi_buf *cfi_buf; socket_lock_assert_owned(so); if ((sb->sb_flags & SB_RECV) == 0) { cfi_buf = &so->so_cfil->cfi_snd; } else { cfi_buf = &so->so_cfil->cfi_rcv; } pending = cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first; /* * If we are limited by the "chars of mbufs used" roughly * adjust so we won't overcommit */ if (pending > (uint64_t)cfi_buf->cfi_pending_mbcnt) { pending = cfi_buf->cfi_pending_mbcnt; } } VERIFY(pending < INT32_MAX); return (int32_t)(pending); } /* * Return the socket buffer space used by data being held by content filters * so processes won't clog the socket buffer */ int32_t cfil_sock_data_space(struct sockbuf *sb) { struct socket *so = sb->sb_so; uint64_t pending = 0; if (NEED_DGRAM_FLOW_TRACKING(so)) { return cfil_sock_udp_data_pending(sb, TRUE); } if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL && so->so_snd.sb_cfil_thread != current_thread()) { struct cfi_buf *cfi_buf; socket_lock_assert_owned(so); if ((sb->sb_flags & SB_RECV) == 0) { cfi_buf = &so->so_cfil->cfi_snd; } else { cfi_buf = &so->so_cfil->cfi_rcv; } pending = cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first; /* * If we are limited by the "chars of mbufs used" roughly * adjust so we won't overcommit */ if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) { pending = cfi_buf->cfi_pending_mbcnt; } VERIFY(pending < INT32_MAX); } return (int32_t)(pending); } /* * A callback from the socket and protocol layer when data becomes * available in the socket buffer to give a chance for the content filter * to re-inject data that was held back */ void cfil_sock_buf_update(struct sockbuf *sb) { int outgoing; int error; struct socket *so = sb->sb_so; if (NEED_DGRAM_FLOW_TRACKING(so)) { cfil_sock_udp_buf_update(sb); return; } if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) { return; } if (!cfil_sbtrim) { return; } socket_lock_assert_owned(so); if ((sb->sb_flags & SB_RECV) == 0) { if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) { return; } outgoing = 1; OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry); } else { if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) { return; } outgoing = 0; OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry); } CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing); error = cfil_acquire_sockbuf(so, so->so_cfil, outgoing); if (error == 0) { cfil_service_inject_queue(so, so->so_cfil, outgoing); } cfil_release_sockbuf(so, outgoing); } int sysctl_cfil_filter_list(struct sysctl_oid *oidp, void *arg1, int arg2, struct sysctl_req *req) { #pragma unused(oidp, arg1, arg2) int error = 0; size_t len = 0; u_int32_t i; /* Read only */ if (req->newptr != USER_ADDR_NULL) { return EPERM; } cfil_rw_lock_shared(&cfil_lck_rw); for (i = 0; i < MAX_CONTENT_FILTER; i++) { struct cfil_filter_stat filter_stat; struct content_filter *cfc = content_filters[i]; if (cfc == NULL) { continue; } /* If just asking for the size */ if (req->oldptr == USER_ADDR_NULL) { len += sizeof(struct cfil_filter_stat); continue; } bzero(&filter_stat, sizeof(struct cfil_filter_stat)); filter_stat.cfs_len = sizeof(struct cfil_filter_stat); filter_stat.cfs_filter_id = cfc->cf_kcunit; filter_stat.cfs_flags = cfc->cf_flags; filter_stat.cfs_sock_count = cfc->cf_sock_count; filter_stat.cfs_necp_control_unit = cfc->cf_necp_control_unit; error = SYSCTL_OUT(req, &filter_stat, sizeof(struct cfil_filter_stat)); if (error != 0) { break; } } /* If just asking for the size */ if (req->oldptr == USER_ADDR_NULL) { req->oldidx = len; } cfil_rw_unlock_shared(&cfil_lck_rw); if (cfil_log_level >= LOG_DEBUG) { if (req->oldptr != USER_ADDR_NULL) { for (i = 1; i <= MAX_CONTENT_FILTER; i++) { cfil_filter_show(i); } } } return error; } static int sysctl_cfil_sock_list(struct sysctl_oid *oidp, void *arg1, int arg2, struct sysctl_req *req) { #pragma unused(oidp, arg1, arg2) int error = 0; u_int32_t i; struct cfil_info *cfi; /* Read only */ if (req->newptr != USER_ADDR_NULL) { return EPERM; } cfil_rw_lock_shared(&cfil_lck_rw); /* * If just asking for the size, */ if (req->oldptr == USER_ADDR_NULL) { req->oldidx = cfil_sock_attached_count * sizeof(struct cfil_sock_stat); /* Bump the length in case new sockets gets attached */ req->oldidx += req->oldidx >> 3; goto done; } TAILQ_FOREACH(cfi, &cfil_sock_head, cfi_link) { struct cfil_entry *entry; struct cfil_sock_stat stat; struct socket *so = cfi->cfi_so; bzero(&stat, sizeof(struct cfil_sock_stat)); stat.cfs_len = sizeof(struct cfil_sock_stat); stat.cfs_sock_id = cfi->cfi_sock_id; stat.cfs_flags = cfi->cfi_flags; if (so != NULL && so->so_proto != NULL && so->so_proto->pr_domain != NULL) { stat.cfs_pid = so->last_pid; memcpy(stat.cfs_uuid, so->last_uuid, sizeof(uuid_t)); if (so->so_flags & SOF_DELEGATED) { stat.cfs_e_pid = so->e_pid; memcpy(stat.cfs_e_uuid, so->e_uuid, sizeof(uuid_t)); } else { stat.cfs_e_pid = so->last_pid; memcpy(stat.cfs_e_uuid, so->last_uuid, sizeof(uuid_t)); } stat.cfs_sock_family = SOCK_DOM(so); stat.cfs_sock_type = SOCK_TYPE(so); stat.cfs_sock_protocol = GET_SO_PROTO(so); } stat.cfs_snd.cbs_pending_first = cfi->cfi_snd.cfi_pending_first; stat.cfs_snd.cbs_pending_last = cfi->cfi_snd.cfi_pending_last; stat.cfs_snd.cbs_inject_q_len = cfil_queue_len(&cfi->cfi_snd.cfi_inject_q); stat.cfs_snd.cbs_pass_offset = cfi->cfi_snd.cfi_pass_offset; stat.cfs_rcv.cbs_pending_first = cfi->cfi_rcv.cfi_pending_first; stat.cfs_rcv.cbs_pending_last = cfi->cfi_rcv.cfi_pending_last; stat.cfs_rcv.cbs_inject_q_len = cfil_queue_len(&cfi->cfi_rcv.cfi_inject_q); stat.cfs_rcv.cbs_pass_offset = cfi->cfi_rcv.cfi_pass_offset; for (i = 0; i < MAX_CONTENT_FILTER; i++) { struct cfil_entry_stat *estat; struct cfe_buf *ebuf; struct cfe_buf_stat *sbuf; entry = &cfi->cfi_entries[i]; estat = &stat.ces_entries[i]; estat->ces_len = sizeof(struct cfil_entry_stat); estat->ces_filter_id = entry->cfe_filter ? entry->cfe_filter->cf_kcunit : 0; estat->ces_flags = entry->cfe_flags; estat->ces_necp_control_unit = entry->cfe_necp_control_unit; estat->ces_last_event.tv_sec = (int64_t)entry->cfe_last_event.tv_sec; estat->ces_last_event.tv_usec = (int64_t)entry->cfe_last_event.tv_usec; estat->ces_last_action.tv_sec = (int64_t)entry->cfe_last_action.tv_sec; estat->ces_last_action.tv_usec = (int64_t)entry->cfe_last_action.tv_usec; ebuf = &entry->cfe_snd; sbuf = &estat->ces_snd; sbuf->cbs_pending_first = cfil_queue_offset_first(&ebuf->cfe_pending_q); sbuf->cbs_pending_last = cfil_queue_offset_last(&ebuf->cfe_pending_q); sbuf->cbs_ctl_first = cfil_queue_offset_first(&ebuf->cfe_ctl_q); sbuf->cbs_ctl_last = cfil_queue_offset_last(&ebuf->cfe_ctl_q); sbuf->cbs_pass_offset = ebuf->cfe_pass_offset; sbuf->cbs_peek_offset = ebuf->cfe_peek_offset; sbuf->cbs_peeked = ebuf->cfe_peeked; ebuf = &entry->cfe_rcv; sbuf = &estat->ces_rcv; sbuf->cbs_pending_first = cfil_queue_offset_first(&ebuf->cfe_pending_q); sbuf->cbs_pending_last = cfil_queue_offset_last(&ebuf->cfe_pending_q); sbuf->cbs_ctl_first = cfil_queue_offset_first(&ebuf->cfe_ctl_q); sbuf->cbs_ctl_last = cfil_queue_offset_last(&ebuf->cfe_ctl_q); sbuf->cbs_pass_offset = ebuf->cfe_pass_offset; sbuf->cbs_peek_offset = ebuf->cfe_peek_offset; sbuf->cbs_peeked = ebuf->cfe_peeked; } error = SYSCTL_OUT(req, &stat, sizeof(struct cfil_sock_stat)); if (error != 0) { break; } } done: cfil_rw_unlock_shared(&cfil_lck_rw); if (cfil_log_level >= LOG_DEBUG) { if (req->oldptr != USER_ADDR_NULL) { cfil_info_show(); } } return error; } /* * UDP Socket Support */ static void cfil_hash_entry_log(int level, struct socket *so, struct soflow_hash_entry *entry, uint64_t sockId, const char* msg) { char local[MAX_IPv6_STR_LEN + 6] = {}; char remote[MAX_IPv6_STR_LEN + 6] = {}; const void *addr; proc_t sock_proc = NULL; pid_t sock_pid = 0; struct timeval current_ts = {}; struct timeval diff_time = {}; // No sock or not UDP, no-op if (so == NULL || entry == NULL) { return; } local[0] = remote[0] = 0x0; switch (entry->soflow_family) { case AF_INET6: addr = &entry->soflow_laddr.addr6; inet_ntop(AF_INET6, addr, local, sizeof(local)); addr = &entry->soflow_faddr.addr6; inet_ntop(AF_INET6, addr, remote, sizeof(local)); break; case AF_INET: addr = &entry->soflow_laddr.addr46.ia46_addr4.s_addr; inet_ntop(AF_INET, addr, local, sizeof(local)); addr = &entry->soflow_faddr.addr46.ia46_addr4.s_addr; inet_ntop(AF_INET, addr, remote, sizeof(local)); break; default: return; } sock_pid = SOCKET_PID(so); sock_proc = proc_find(sock_pid); microuptime(¤t_ts); timersub(¤t_ts, &entry->soflow_timestamp, &diff_time); CFIL_LOG(level, "<%s>: [%d %s] <%s(%d) %s so %llx %llu %llu age %ld> lport %d fport %d laddr %s faddr %s hash %X", msg, sock_pid, (sock_proc != NULL ? proc_best_name(sock_proc) : ""), IS_UDP(so) ? "UDP" : "proto", GET_SO_PROTO(so), (entry->soflow_outgoing ? "out" : "in"), (uint64_t)VM_KERNEL_ADDRPERM(so), sockId, entry->soflow_feat_ctxt_id, diff_time.tv_sec, ntohs(entry->soflow_lport), ntohs(entry->soflow_fport), local, remote, entry->soflow_flowhash); if (sock_proc != NULL) { proc_rele(sock_proc); } } static void cfil_inp_log(int level, struct socket *so, const char* msg) { struct inpcb *inp = NULL; struct sockaddr_in *sin = NULL; struct sockaddr_in6 *sin6 = NULL; char local[MAX_IPv6_STR_LEN + 6]; char remote[MAX_IPv6_STR_LEN + 6]; ushort lport = 0; ushort fport = 0; const void *addr; proc_t sock_proc = NULL; pid_t sock_pid = 0; if (so == NULL) { return; } inp = sotoinpcb(so); if (inp == NULL) { return; } local[0] = remote[0] = 0x0; if (inp->inp_vflag & INP_IPV6) { addr = &inp->in6p_laddr.s6_addr32; inet_ntop(AF_INET6, addr, local, sizeof(local)); addr = &inp->in6p_faddr.s6_addr32; inet_ntop(AF_INET6, addr, remote, sizeof(remote)); } else { addr = &inp->inp_laddr.s_addr; inet_ntop(AF_INET, addr, local, sizeof(local)); addr = &inp->inp_faddr.s_addr; inet_ntop(AF_INET, addr, remote, sizeof(remote)); } lport = inp->inp_lport; fport = inp->inp_fport; if (so->so_cfil && so->so_cfil->cfi_so_attach_faddr.sa.sa_len > 0) { if (so->so_cfil->cfi_so_attach_faddr.sa.sa_family == AF_INET6) { sin6 = SIN6(&so->so_cfil->cfi_so_attach_faddr.sa); addr = &sin6->sin6_addr; inet_ntop(AF_INET6, addr, remote, sizeof(remote)); fport = sin6->sin6_port; } else if (so->so_cfil->cfi_so_attach_faddr.sa.sa_family == AF_INET) { sin = SIN(&so->so_cfil->cfi_so_attach_faddr.sa); addr = &sin->sin_addr.s_addr; inet_ntop(AF_INET, addr, remote, sizeof(remote)); fport = sin->sin_port; } } if (so->so_cfil && so->so_cfil->cfi_so_attach_laddr.sa.sa_len > 0) { if (so->so_cfil->cfi_so_attach_laddr.sa.sa_family == AF_INET6) { sin6 = SIN6(&so->so_cfil->cfi_so_attach_laddr.sa); addr = &sin6->sin6_addr; inet_ntop(AF_INET6, addr, local, sizeof(remote)); fport = sin6->sin6_port; } else if (so->so_cfil->cfi_so_attach_laddr.sa.sa_family == AF_INET) { sin = SIN(&so->so_cfil->cfi_so_attach_laddr.sa); addr = &sin->sin_addr.s_addr; inet_ntop(AF_INET, addr, local, sizeof(remote)); fport = sin->sin_port; } } sock_pid = SOCKET_PID(so); sock_proc = proc_find(sock_pid); if (so->so_cfil != NULL) { struct timeval current_ts = {}; struct timeval diff_time = {}; microuptime(¤t_ts); timersub(¤t_ts, &(so->so_cfil->cfi_timestamp), &diff_time); CFIL_LOG(level, "<%s>: [%d %s] <%s %s so %llx flags 0x%x 0x%x %llu age %ld> lport %d fport %d laddr %s faddr %s", msg, sock_pid, (sock_proc != NULL ? proc_best_name(sock_proc) : ""), IS_UDP(so) ? "UDP" : "TCP", (so->so_cfil->cfi_dir == CFS_CONNECTION_DIR_IN ? "in" : "out"), (uint64_t)VM_KERNEL_ADDRPERM(so), inp->inp_flags, inp->inp_socket->so_flags, so->so_cfil->cfi_sock_id, diff_time.tv_sec, ntohs(lport), ntohs(fport), local, remote); } else { CFIL_LOG(level, "<%s>: [%d %s] <%s %s so %llx - flags 0x%x 0x%x> lport %d fport %d laddr %s faddr %s", msg, sock_pid, (sock_proc != NULL ? proc_best_name(sock_proc) : ""), IS_UDP(so) ? "UDP" : "TCP", (so->so_flags1 & SOF1_INBOUND) ? "in" : "out", (uint64_t)VM_KERNEL_ADDRPERM(so), inp->inp_flags, inp->inp_socket->so_flags, ntohs(lport), ntohs(fport), local, remote); } if (sock_proc != NULL) { proc_rele(sock_proc); } } static void cfil_info_log(int level, struct cfil_info *cfil_info, const char* msg) { if (cfil_info == NULL) { return; } if (cfil_info->cfi_hash_entry != NULL) { cfil_hash_entry_log(level, cfil_info->cfi_so, cfil_info->cfi_hash_entry, cfil_info->cfi_sock_id, msg); } else { cfil_inp_log(level, cfil_info->cfi_so, msg); } } void cfil_log_printf(struct socket *so, struct cfil_info *info, const char *format, ...) { va_list args; char buffer[256] = {}; va_start(args, format); vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); if (info != NULL) { cfil_info_log(LOG_ERR, info, __unsafe_null_terminated_from_indexable(buffer)); } else if (so != NULL) { cfil_inp_log(LOG_ERR, so, __unsafe_null_terminated_from_indexable(buffer)); } } static void cfil_sock_udp_unlink_flow(struct socket *so, struct soflow_hash_entry *hash_entry, struct cfil_info *cfil_info) { if (so == NULL || hash_entry == NULL || cfil_info == NULL) { return; } if (so->so_flags & SOF_CONTENT_FILTER) { VERIFY(so->so_usecount > 0); so->so_usecount--; } // Hold exclusive lock before clearing cfil_info hash entry link cfil_rw_lock_exclusive(&cfil_lck_rw); cfil_info->cfi_hash_entry = NULL; if (cfil_info->cfi_debug) { CFIL_LOG(LOG_ERR, "CFIL <%s>: <so %llx> - use count %d", IS_UDP(so) ? "UDP" : "TCP", (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_usecount); } cfil_rw_unlock_exclusive(&cfil_lck_rw); } bool check_port(struct sockaddr *addr, u_short port) { struct sockaddr_in *sin = NULL; struct sockaddr_in6 *sin6 = NULL; if (addr == NULL || port == 0) { return FALSE; } switch (addr->sa_family) { case AF_INET: sin = SIN(addr); if (sin->sin_len < sizeof(*sin)) { return FALSE; } if (port == ntohs(sin->sin_port)) { return TRUE; } break; case AF_INET6: sin6 = SIN6(addr); if (sin6->sin6_len < sizeof(*sin6)) { return FALSE; } if (port == ntohs(sin6->sin6_port)) { return TRUE; } break; default: break; } return FALSE; } cfil_sock_id_t cfil_sock_id_from_datagram_socket(struct socket *so, struct sockaddr *local, struct sockaddr *remote) { socket_lock_assert_owned(so); if (so->so_flow_db == NULL) { return CFIL_SOCK_ID_NONE; } return (cfil_sock_id_t)soflow_db_get_feature_context_id(so->so_flow_db, local, remote); } static struct cfil_info * cfil_sock_udp_get_info(struct socket *so, uint32_t filter_control_unit, bool outgoing, struct soflow_hash_entry *hash_entry, struct sockaddr *local, struct sockaddr *remote) { int new_filter_control_unit = 0; struct cfil_info *cfil_info = NULL; errno_t error = 0; socket_lock_assert_owned(so); if (hash_entry == NULL || hash_entry->soflow_db == NULL) { return NULL; } if (hash_entry->soflow_feat_ctxt != NULL && hash_entry->soflow_feat_ctxt_id != 0) { /* Drop pre-existing UDP flow if filter state changed */ cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt; new_filter_control_unit = filter_control_unit; if (new_filter_control_unit > 0 && new_filter_control_unit != cfil_info->cfi_filter_control_unit) { if (cfil_info->cfi_filter_policy_gencount == hash_entry->soflow_policies_gencount) { CFIL_LOG(LOG_NOTICE, "CFIL: UDP(%s) <so %llx> - filter state changed to 0x%x, but policies did not. Keeping existing filter state 0x%x", outgoing ? "OUT" : "IN", (uint64_t)VM_KERNEL_ADDRPERM(so), new_filter_control_unit, cfil_info->cfi_filter_control_unit); } else if (DO_PRESERVE_CONNECTIONS) { CFIL_LOG(LOG_NOTICE, "CFIL: UDP(%s) <so %llx> - filter state changed from 0x%x to 0x%x, but existing connections are to be preserved", outgoing ? "OUT" : "IN", (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_filter_control_unit, new_filter_control_unit); // CFIL state has changed, but preserve the flow intentionally because preserve existing connections is in effect. cfil_info->cfi_filter_control_unit = new_filter_control_unit; } else { cfil_log_printf(so, cfil_info, "CFIL: %sbound UDP data dropped (0x%x -> 0x%x)", (outgoing ? "out" : "in"), cfil_info->cfi_filter_control_unit, new_filter_control_unit); return NULL; } } return cfil_info; } cfil_info = cfil_info_alloc(so, hash_entry); if (cfil_info == NULL) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP failed to alloc cfil_info", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem); return NULL; } cfil_info->cfi_filter_control_unit = filter_control_unit; cfil_info->cfi_filter_policy_gencount = hash_entry->soflow_policies_gencount; cfil_info->cfi_dir = outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN; cfil_info->cfi_debug = DEBUG_FLOW(sotoinpcb(so), so, local, remote); if (cfil_info->cfi_debug) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP (outgoing %d) - debug flow with port %d", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, cfil_log_port); CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP so_gencnt %llx entry flowhash %x cfil %p sockID %llu <%llx>", (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_gencnt, hash_entry->soflow_flowhash, cfil_info, cfil_info->cfi_sock_id, cfil_info->cfi_sock_id); } if (cfil_info_attach_unit(so, filter_control_unit, cfil_info) == 0) { CFIL_INFO_FREE(cfil_info); CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP cfil_info_attach_unit(%u) failed", (uint64_t)VM_KERNEL_ADDRPERM(so), filter_control_unit); OSIncrementAtomic(&cfil_stats.cfs_sock_attach_failed); return NULL; } if (cfil_info->cfi_debug) { CFIL_LOG(LOG_ERR, "CFIL: UDP <so %llx> filter_control_unit %u sockID %llu <%llx> attached", (uint64_t)VM_KERNEL_ADDRPERM(so), filter_control_unit, cfil_info->cfi_sock_id, cfil_info->cfi_sock_id); } so->so_flags |= SOF_CONTENT_FILTER; OSIncrementAtomic(&cfil_stats.cfs_sock_attached); /* Hold a reference on the socket for each flow */ so->so_usecount++; /* link cfil_info to flow */ hash_entry->soflow_feat_ctxt = cfil_info; hash_entry->soflow_feat_ctxt_id = cfil_info->cfi_sock_id; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: ADDED"); } error = cfil_dispatch_attach_event(so, cfil_info, 0, outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN); /* We can recover from flow control or out of memory errors */ if (error != 0 && error != ENOBUFS && error != ENOMEM) { CFIL_LOG(LOG_ERR, "CFIL: UDP <so %llx> cfil_dispatch_attach_event failed <error %d>", (uint64_t)VM_KERNEL_ADDRPERM(so), error); return NULL; } CFIL_INFO_VERIFY(cfil_info); return cfil_info; } errno_t cfil_sock_udp_handle_data(bool outgoing, struct socket *so, struct sockaddr *local, struct sockaddr *remote, struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *hash_entry) { #pragma unused(outgoing, so, local, remote, data, control, flags) errno_t error = 0; uint32_t filter_control_unit = 0; struct cfil_info *cfil_info = NULL; socket_lock_assert_owned(so); if (cfil_active_count == 0) { CFIL_LOG(LOG_DEBUG, "CFIL: UDP no active filter"); OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain); return error; } // Socket has been blessed if ((so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) != 0) { return error; } if (hash_entry == NULL) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx> NULL soflow_hash_entry", (uint64_t)VM_KERNEL_ADDRPERM(so)); return EPIPE; } if (hash_entry->soflow_db == NULL) { CFIL_LOG(LOG_ERR, "CFIL: <so %llx> NULL soflow_hash_entry db", (uint64_t)VM_KERNEL_ADDRPERM(so)); return EPIPE; } filter_control_unit = hash_entry->soflow_filter_control_unit; if (filter_control_unit == 0) { CFIL_LOG(LOG_DEBUG, "CFIL: UDP failed to get control unit"); return error; } if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) { return error; } if ((filter_control_unit & NECP_MASK_USERSPACE_ONLY) != 0) { CFIL_LOG(LOG_DEBUG, "CFIL: UDP user space only"); OSIncrementAtomic(&cfil_stats.cfs_sock_userspace_only); return error; } cfil_info = cfil_sock_udp_get_info(so, filter_control_unit, outgoing, hash_entry, local, remote); if (cfil_info == NULL) { return EPIPE; } // Update last used timestamp, this is for flow Idle TO if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: Got flow"); } if (cfil_info->cfi_flags & CFIF_DROP) { if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP DROP"); } return EPIPE; } if (control != NULL) { OSIncrementAtomic(&cfil_stats.cfs_data_in_control); } if (data->m_type == MT_OOBDATA) { CFIL_LOG(LOG_ERR, "so %llx MSG_OOB", (uint64_t)VM_KERNEL_ADDRPERM(so)); OSIncrementAtomic(&cfil_stats.cfs_data_in_oob); } error = cfil_data_common(so, cfil_info, outgoing, remote, data, control, flags); return error; } struct cfil_udp_attached_context { bool need_wait; lck_mtx_t *mutex_held; int attached; }; static bool cfil_filters_udp_attached_per_flow(struct socket *so, struct soflow_hash_entry *hash_entry, void *context) { struct cfil_udp_attached_context *apply_context = NULL; struct cfil_info * __single cfil_info = NULL; struct cfil_entry *entry = NULL; uint64_t sock_flow_id = 0; struct timespec ts; errno_t error = 0; int kcunit; if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) { return true; } cfil_info = hash_entry->soflow_feat_ctxt; apply_context = (struct cfil_udp_attached_context *)context; for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; /* Are we attached to the filter? */ if (entry->cfe_filter == NULL) { continue; } if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) { continue; } if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) { continue; } if (apply_context->need_wait == TRUE) { if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TO FINISH"); } ts.tv_sec = cfil_close_wait_timeout / 1000; ts.tv_nsec = (cfil_close_wait_timeout % 1000) * NSEC_PER_USEC * 1000; OSIncrementAtomic(&cfil_stats.cfs_close_wait); cfil_info->cfi_flags |= CFIF_CLOSE_WAIT; sock_flow_id = cfil_info->cfi_sock_id; error = msleep((caddr_t)cfil_info, apply_context->mutex_held, PSOCK | PCATCH, "cfil_filters_udp_attached_per_flow", &ts); // Woke up from sleep, validate if cfil_info is still valid if (so->so_flow_db == NULL || (cfil_info != soflow_db_get_feature_context(so->so_flow_db, sock_flow_id))) { // cfil_info is not valid, do not continue return false; } cfil_info->cfi_flags &= ~CFIF_CLOSE_WAIT; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW DONE"); } /* * Force close in case of timeout */ if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout); if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TIMED OUT, FORCE DETACH"); } entry->cfe_flags |= CFEF_CFIL_DETACHED; return false; } } apply_context->attached = 1; return false; } return true; } /* * Go through all UDP flows for specified socket and returns TRUE if * any flow is still attached. If need_wait is TRUE, wait on first * attached flow. */ static int cfil_filters_udp_attached(struct socket *so, bool need_wait) { struct cfil_udp_attached_context apply_context = { 0 }; lck_mtx_t *mutex_held; socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) { if (so->so_proto->pr_getlock != NULL) { mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK); } else { mutex_held = so->so_proto->pr_domain->dom_mtx; } LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED); apply_context.need_wait = need_wait; apply_context.mutex_held = mutex_held; soflow_db_apply(so->so_flow_db, cfil_filters_udp_attached_per_flow, (void *)&apply_context); } return apply_context.attached; } struct cfil_udp_data_pending_context { struct sockbuf *sb; uint64_t total_pending; }; static bool cfil_sock_udp_data_pending_per_flow(struct socket *so, struct soflow_hash_entry *hash_entry, void *context) { #pragma unused(so) struct cfil_udp_data_pending_context *apply_context = NULL; struct cfil_info * __single cfil_info = NULL; struct cfi_buf *cfi_buf; uint64_t pending = 0; if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) { return true; } cfil_info = hash_entry->soflow_feat_ctxt; apply_context = (struct cfil_udp_data_pending_context *)context; if (apply_context->sb == NULL) { return true; } if ((apply_context->sb->sb_flags & SB_RECV) == 0) { cfi_buf = &cfil_info->cfi_snd; } else { cfi_buf = &cfil_info->cfi_rcv; } pending = cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first; /* * If we are limited by the "chars of mbufs used" roughly * adjust so we won't overcommit */ if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) { pending = cfi_buf->cfi_pending_mbcnt; } apply_context->total_pending += pending; return true; } int32_t cfil_sock_udp_data_pending(struct sockbuf *sb, bool check_thread) { struct cfil_udp_data_pending_context apply_context = { 0 }; struct socket *so = sb->sb_so; socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL && (check_thread == FALSE || so->so_snd.sb_cfil_thread != current_thread())) { apply_context.sb = sb; soflow_db_apply(so->so_flow_db, cfil_sock_udp_data_pending_per_flow, (void *)&apply_context); VERIFY(apply_context.total_pending < INT32_MAX); } return (int32_t)(apply_context.total_pending); } struct cfil_udp_notify_shutdown_context { int how; int drop_flag; int shut_flag; int done_count; }; static bool cfil_sock_udp_notify_shutdown_per_flow(struct socket *so, struct soflow_hash_entry *hash_entry, void *context) { struct cfil_udp_notify_shutdown_context *apply_context = NULL; struct cfil_info * __single cfil_info = NULL; errno_t error = 0; int kcunit; if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) { return true; } cfil_info = hash_entry->soflow_feat_ctxt; apply_context = (struct cfil_udp_notify_shutdown_context *)context; // This flow is marked as DROP if (cfil_info->cfi_flags & apply_context->drop_flag) { apply_context->done_count++; return true; } // This flow has been shut already, skip if (cfil_info->cfi_flags & apply_context->shut_flag) { return true; } // Mark flow as shut cfil_info->cfi_flags |= apply_context->shut_flag; apply_context->done_count++; for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { /* Disconnect incoming side */ if (apply_context->how != SHUT_WR) { error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0); } /* Disconnect outgoing side */ if (apply_context->how != SHUT_RD) { error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1); } } if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW NOTIFY_SHUTDOWN"); } return true; } int cfil_sock_udp_notify_shutdown(struct socket *so, int how, int drop_flag, int shut_flag) { struct cfil_udp_notify_shutdown_context apply_context = { 0 }; errno_t error = 0; socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) { apply_context.how = how; apply_context.drop_flag = drop_flag; apply_context.shut_flag = shut_flag; soflow_db_apply(so->so_flow_db, cfil_sock_udp_notify_shutdown_per_flow, (void *)&apply_context); } if (apply_context.done_count == 0) { error = ENOTCONN; } return error; } int cfil_sock_udp_shutdown(struct socket *so, int *how) { int error = 0; if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || (so->so_flow_db == NULL)) { goto done; } socket_lock_assert_owned(so); CFIL_LOG(LOG_INFO, "so %llx how %d", (uint64_t)VM_KERNEL_ADDRPERM(so), *how); /* * Check the state of the socket before the content filter */ if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) { /* read already shut down */ error = ENOTCONN; goto done; } if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) { /* write already shut down */ error = ENOTCONN; goto done; } /* * shutdown read: SHUT_RD or SHUT_RDWR */ if (*how != SHUT_WR) { error = cfil_sock_udp_notify_shutdown(so, SHUT_RD, CFIF_DROP, CFIF_SHUT_RD); if (error != 0) { goto done; } } /* * shutdown write: SHUT_WR or SHUT_RDWR */ if (*how != SHUT_RD) { error = cfil_sock_udp_notify_shutdown(so, SHUT_WR, CFIF_DROP, CFIF_SHUT_WR); if (error != 0) { goto done; } /* * When outgoing data is pending, we delay the shutdown at the * protocol level until the content filters give the final * verdict on the pending data. */ if (cfil_sock_data_pending(&so->so_snd) != 0) { /* * When shutting down the read and write sides at once * we can proceed to the final shutdown of the read * side. Otherwise, we just return. */ if (*how == SHUT_WR) { error = EJUSTRETURN; } else if (*how == SHUT_RDWR) { *how = SHUT_RD; } } } done: return error; } void cfil_sock_udp_close_wait(struct socket *so) { socket_lock_assert_owned(so); while (cfil_filters_udp_attached(so, FALSE)) { /* * Notify the filters we are going away so they can detach */ cfil_sock_udp_notify_shutdown(so, SHUT_RDWR, 0, 0); /* * Make sure we need to wait after the filter are notified * of the disconnection */ if (cfil_filters_udp_attached(so, TRUE) == 0) { break; } } } static bool cfil_sock_udp_is_closed_per_flow(struct socket *so, struct soflow_hash_entry *hash_entry, void *context) { #pragma unused(context) struct cfil_info * __single cfil_info = NULL; errno_t error = 0; int kcunit; if (hash_entry->soflow_feat_ctxt == NULL) { return true; } cfil_info = hash_entry->soflow_feat_ctxt; for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { /* Let the filters know of the closing */ error = cfil_dispatch_closed_event(so, cfil_info, kcunit); } /* Last chance to push passed data out */ error = cfil_acquire_sockbuf(so, cfil_info, 1); if (error == 0) { cfil_service_inject_queue(so, cfil_info, 1); } cfil_release_sockbuf(so, 1); cfil_info->cfi_flags |= CFIF_SOCK_CLOSED; /* Pending data needs to go */ cfil_flush_queues(so, cfil_info); CFIL_INFO_VERIFY(cfil_info); if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW IS_CLOSED"); } return true; } void cfil_sock_udp_is_closed(struct socket *so) { socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) { soflow_db_apply(so->so_flow_db, cfil_sock_udp_is_closed_per_flow, NULL); } } static bool cfil_sock_udp_buf_update_per_flow(struct socket *so, struct soflow_hash_entry *hash_entry, void *context) { struct cfil_info * __single cfil_info = NULL; struct sockbuf *sb = NULL; errno_t error = 0; int outgoing; if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) { return true; } cfil_info = hash_entry->soflow_feat_ctxt; sb = (struct sockbuf *) context; if ((sb->sb_flags & SB_RECV) == 0) { if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) { return true; } outgoing = 1; OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry); } else { if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) { return true; } outgoing = 0; OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry); } CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing); error = cfil_acquire_sockbuf(so, cfil_info, outgoing); if (error == 0) { cfil_service_inject_queue(so, cfil_info, outgoing); } cfil_release_sockbuf(so, outgoing); return true; } void cfil_sock_udp_buf_update(struct sockbuf *sb) { struct socket *so = sb->sb_so; socket_lock_assert_owned(so); if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) { if (!cfil_sbtrim) { return; } soflow_db_apply(so->so_flow_db, cfil_sock_udp_buf_update_per_flow, (void *)sb); } } void cfil_filter_show(u_int32_t kcunit) { struct content_filter *cfc = NULL; struct cfil_entry *entry; int count = 0; if (kcunit > MAX_CONTENT_FILTER) { return; } cfil_rw_lock_shared(&cfil_lck_rw); if (content_filters[kcunit - 1] == NULL) { cfil_rw_unlock_shared(&cfil_lck_rw); return; } cfc = content_filters[kcunit - 1]; CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW: Filter <unit %d, entry count %d> flags <%lx>:", kcunit, cfc->cf_sock_count, (unsigned long)cfc->cf_flags); if (cfc->cf_flags & CFF_DETACHING) { CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-DETACHING"); } if (cfc->cf_flags & CFF_ACTIVE) { CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-ACTIVE"); } if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-FLOW CONTROLLED"); } TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) { if (entry->cfe_cfil_info && entry->cfe_cfil_info->cfi_so) { struct cfil_info *cfil_info = entry->cfe_cfil_info; count++; if (entry->cfe_flags & CFEF_CFIL_DETACHED) { cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-DETACHED"); } else { cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-ATTACHED"); } } } CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:Filter - total entries shown: %d", count); cfil_rw_unlock_shared(&cfil_lck_rw); } void cfil_info_show(void) { struct cfil_info *cfil_info; int count = 0; cfil_rw_lock_shared(&cfil_lck_rw); CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:count %d", cfil_sock_attached_count); TAILQ_FOREACH(cfil_info, &cfil_sock_head, cfi_link) { count++; cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: INFO SHOW"); if (cfil_info->cfi_flags & CFIF_DROP) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - DROP"); } if (cfil_info->cfi_flags & CFIF_CLOSE_WAIT) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - CLOSE_WAIT"); } if (cfil_info->cfi_flags & CFIF_SOCK_CLOSED) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SOCK_CLOSED"); } if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_IN"); } if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_OUT"); } if (cfil_info->cfi_flags & CFIF_SHUT_WR) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_WR"); } if (cfil_info->cfi_flags & CFIF_SHUT_RD) { CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_RD"); } } CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:total cfil_info shown: %d", count); cfil_rw_unlock_shared(&cfil_lck_rw); } bool cfil_info_action_timed_out(struct cfil_info *cfil_info, int timeout) { struct cfil_entry *entry; struct timeval current_tv; struct timeval diff_time; if (cfil_info == NULL) { return false; } /* * If we have queued up more data than passed offset and we haven't received * an action from user space for a while (the user space filter might have crashed), * return action timed out. */ if (cfil_info->cfi_snd.cfi_pending_last > cfil_info->cfi_snd.cfi_pass_offset || cfil_info->cfi_rcv.cfi_pending_last > cfil_info->cfi_rcv.cfi_pass_offset) { microuptime(¤t_tv); for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; if (entry->cfe_filter == NULL) { continue; } if (cfil_info->cfi_snd.cfi_pending_last > entry->cfe_snd.cfe_pass_offset || cfil_info->cfi_rcv.cfi_pending_last > entry->cfe_rcv.cfe_pass_offset) { // haven't gotten an action from this filter, check timeout timersub(¤t_tv, &entry->cfe_last_action, &diff_time); if (diff_time.tv_sec >= timeout) { if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: flow ACTION timeout expired"); } return true; } } } } return false; } bool cfil_info_buffer_threshold_exceeded(struct cfil_info *cfil_info) { if (cfil_info == NULL) { return false; } /* * Clean up flow if it exceeded queue thresholds */ if (cfil_info->cfi_snd.cfi_tail_drop_cnt || cfil_info->cfi_rcv.cfi_tail_drop_cnt) { if (cfil_info->cfi_debug) { CFIL_LOG(LOG_ERR, "CFIL: queue threshold exceeded:mbuf max < count: %d bytes: %d > tail drop count < OUT: %d IN: %d > ", cfil_udp_gc_mbuf_num_max, cfil_udp_gc_mbuf_cnt_max, cfil_info->cfi_snd.cfi_tail_drop_cnt, cfil_info->cfi_rcv.cfi_tail_drop_cnt); cfil_info_log(LOG_ERR, cfil_info, "CFIL: queue threshold exceeded"); } return true; } return false; } static bool cfil_dgram_gc_needed(struct socket *so, struct soflow_hash_entry *hash_entry, u_int64_t current_time) { #pragma unused(current_time) struct cfil_info *cfil_info = NULL; if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) { return false; } cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt; cfil_rw_lock_shared(&cfil_lck_rw); if (cfil_info_action_timed_out(cfil_info, UDP_FLOW_GC_ACTION_TO) || cfil_info_buffer_threshold_exceeded(cfil_info)) { if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW GC NEEDED"); } cfil_rw_unlock_shared(&cfil_lck_rw); return true; } cfil_rw_unlock_shared(&cfil_lck_rw); return false; } static bool cfil_dgram_gc_perform(struct socket *so, struct soflow_hash_entry *hash_entry) { struct cfil_info *cfil_info = NULL; if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) { return false; } cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: UDP PER-FLOW GC PERFORM"); } for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { /* Let the filters know of the closing */ cfil_dispatch_closed_event(so, cfil_info, kcunit); } cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info); CFIL_INFO_FREE(cfil_info); OSIncrementAtomic(&cfil_stats.cfs_sock_detached); return true; } static bool cfil_dgram_detach_entry(struct socket *so, struct soflow_hash_entry *hash_entry) { struct cfil_info *cfil_info = NULL; if (hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) { return true; } cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt; if (cfil_info->cfi_debug) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: DGRAM DETACH ENTRY"); } cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info); CFIL_INFO_FREE(cfil_info); OSIncrementAtomic(&cfil_stats.cfs_sock_detached); return true; } static bool cfil_dgram_detach_db(struct socket *so, struct soflow_db *db) { #pragma unused(db) if (so && so->so_flags & SOF_CONTENT_FILTER) { so->so_flags &= ~SOF_CONTENT_FILTER; CFIL_LOG(LOG_DEBUG, "CFIL: DGRAM DETACH DB <so %llx>", (uint64_t)VM_KERNEL_ADDRPERM(so)); } return true; } struct m_tag * cfil_dgram_save_socket_state(struct cfil_info *cfil_info, struct mbuf *m) { struct m_tag *tag = NULL; struct cfil_tag *ctag = NULL; struct soflow_hash_entry *hash_entry = NULL; struct inpcb *inp = NULL; if (cfil_info == NULL || cfil_info->cfi_so == NULL || cfil_info->cfi_hash_entry == NULL || m == NULL || !(m->m_flags & M_PKTHDR)) { return NULL; } inp = sotoinpcb(cfil_info->cfi_so); /* Allocate a tag */ tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP, sizeof(struct cfil_tag), M_DONTWAIT, m); if (tag) { ctag = (struct cfil_tag *)(tag->m_tag_data); ctag->cfil_so_state_change_cnt = cfil_info->cfi_so->so_state_change_cnt; ctag->cfil_so_options = cfil_info->cfi_so->so_options; ctag->cfil_inp_flags = inp ? inp->inp_flags : 0; hash_entry = cfil_info->cfi_hash_entry; if (hash_entry->soflow_family == AF_INET6) { fill_ip6_sockaddr_4_6(&ctag->cfil_faddr, &hash_entry->soflow_faddr.addr6, hash_entry->soflow_fport, hash_entry->soflow_faddr6_ifscope); } else if (hash_entry->soflow_family == AF_INET) { fill_ip_sockaddr_4_6(&ctag->cfil_faddr, hash_entry->soflow_faddr.addr46.ia46_addr4, hash_entry->soflow_fport); } m_tag_prepend(m, tag); return tag; } return NULL; } struct m_tag * cfil_dgram_get_socket_state(struct mbuf *m, uint32_t *state_change_cnt, uint32_t *options, struct sockaddr **faddr, int *inp_flags) { struct m_tag *tag = NULL; struct cfil_tag *ctag = NULL; tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP); if (tag) { ctag = (struct cfil_tag *)(tag->m_tag_data); if (state_change_cnt) { *state_change_cnt = ctag->cfil_so_state_change_cnt; } if (options) { *options = ctag->cfil_so_options; } if (faddr) { *faddr = SA(&ctag->cfil_faddr); } if (inp_flags) { *inp_flags = ctag->cfil_inp_flags; } /* * Unlink tag and hand it over to caller. * Note that caller will be responsible to free it. */ m_tag_unlink(m, tag); return tag; } return NULL; } boolean_t cfil_dgram_peek_socket_state(struct mbuf *m, int *inp_flags) { struct m_tag *tag = NULL; struct cfil_tag *ctag = NULL; tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP); if (tag) { ctag = (struct cfil_tag *)(tag->m_tag_data); if (inp_flags) { *inp_flags = ctag->cfil_inp_flags; } return true; } return false; } static int cfil_dispatch_stats_event_locked(int kcunit, struct cfil_stats_report_buffer *buffer, uint32_t stats_count) { struct content_filter *cfc = NULL; errno_t error = 0; size_t msgsize = 0; if (buffer == NULL || stats_count == 0) { return error; } if (kcunit > MAX_CONTENT_FILTER) { return error; } cfc = content_filters[kcunit - 1]; if (cfc == NULL) { return error; } /* Would be wasteful to try */ if (cfc->cf_flags & CFF_FLOW_CONTROLLED) { error = ENOBUFS; goto done; } msgsize = sizeof(struct cfil_msg_stats_report) + (sizeof(struct cfil_msg_sock_stats) * stats_count); buffer->msghdr.cfm_len = (uint32_t)msgsize; buffer->msghdr.cfm_version = 1; buffer->msghdr.cfm_type = CFM_TYPE_EVENT; buffer->msghdr.cfm_op = CFM_OP_STATS; buffer->msghdr.cfm_sock_id = 0; buffer->count = stats_count; if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "STATS (kcunit %d): msg size %lu - %lu %lu %lu", kcunit, (unsigned long)msgsize, (unsigned long)sizeof(struct cfil_msg_stats_report), (unsigned long)sizeof(struct cfil_msg_sock_stats), (unsigned long)stats_count); } error = ctl_enqueuedata(cfc->cf_kcref, cfc->cf_kcunit, buffer, sizeof(struct cfil_stats_report_buffer), CTL_DATA_EOR); if (error != 0) { CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed:%d", error); goto done; } OSIncrementAtomic(&cfil_stats.cfs_stats_event_ok); if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT:send msg to %d", kcunit); } done: if (error == ENOBUFS) { OSIncrementAtomic( &cfil_stats.cfs_stats_event_flow_control); if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) { cfil_rw_lock_exclusive(&cfil_lck_rw); } cfc->cf_flags |= CFF_FLOW_CONTROLLED; cfil_rw_lock_exclusive_to_shared(&cfil_lck_rw); } else if (error != 0) { OSIncrementAtomic(&cfil_stats.cfs_stats_event_fail); } return error; } static void cfil_stats_report_thread_sleep(bool forever) { if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION SLEEP"); } if (forever) { (void) assert_wait((event_t) &cfil_sock_attached_stats_count, THREAD_INTERRUPTIBLE); } else { uint64_t deadline = 0; nanoseconds_to_absolutetime(CFIL_STATS_REPORT_RUN_INTERVAL_NSEC, &deadline); clock_absolutetime_interval_to_deadline(deadline, &deadline); (void) assert_wait_deadline(&cfil_sock_attached_stats_count, THREAD_INTERRUPTIBLE, deadline); } } static void cfil_stats_report_thread_func(void *v, wait_result_t w) { #pragma unused(v, w) ASSERT(cfil_stats_report_thread == current_thread()); thread_set_thread_name(current_thread(), "CFIL_STATS_REPORT"); // Kick off gc shortly cfil_stats_report_thread_sleep(false); thread_block_parameter((thread_continue_t) cfil_stats_report, NULL); /* NOTREACHED */ } static bool cfil_stats_collect_flow_stats_for_filter(int kcunit, struct cfil_info *cfil_info, struct cfil_entry *entry, struct timeval current_tv) { struct cfil_stats_report_buffer *buffer = NULL; struct cfil_msg_sock_stats *flow_array = NULL; struct cfil_msg_sock_stats *stats = NULL; struct inpcb *inp = NULL; struct timeval diff_time; uint64_t diff_time_usecs; int index = 0; if (entry->cfe_stats_report_frequency == 0) { return false; } buffer = global_cfil_stats_report_buffers[kcunit - 1]; if (buffer == NULL) { CFIL_LOG(LOG_ERR, "CFIL: STATS: no buffer"); return false; } timersub(¤t_tv, &entry->cfe_stats_report_ts, &diff_time); diff_time_usecs = (diff_time.tv_sec * USEC_PER_SEC) + diff_time.tv_usec; if (cfil_info->cfi_debug && cfil_log_stats) { CFIL_LOG(LOG_ERR, "CFIL: STATS REPORT - elapsed time - ts %llu %llu cur ts %llu %llu diff %llu %llu(usecs %llu) @freq %llu usecs sockID %llu <%llx>", (unsigned long long)entry->cfe_stats_report_ts.tv_sec, (unsigned long long)entry->cfe_stats_report_ts.tv_usec, (unsigned long long)current_tv.tv_sec, (unsigned long long)current_tv.tv_usec, (unsigned long long)diff_time.tv_sec, (unsigned long long)diff_time.tv_usec, (unsigned long long)diff_time_usecs, (unsigned long long)((entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC), cfil_info->cfi_sock_id, cfil_info->cfi_sock_id); } // Compare elapsed time in usecs if (diff_time_usecs >= (entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC) { if (cfil_info->cfi_debug && cfil_log_stats) { CFIL_LOG(LOG_ERR, "CFIL: STATS REPORT - in %llu reported %llu", cfil_info->cfi_byte_inbound_count, entry->cfe_byte_inbound_count_reported); CFIL_LOG(LOG_ERR, "CFIL: STATS REPORT - out %llu reported %llu", cfil_info->cfi_byte_outbound_count, entry->cfe_byte_outbound_count_reported); } // Check if flow has new bytes that have not been reported if (entry->cfe_byte_inbound_count_reported < cfil_info->cfi_byte_inbound_count || entry->cfe_byte_outbound_count_reported < cfil_info->cfi_byte_outbound_count) { flow_array = (struct cfil_msg_sock_stats *)&buffer->stats; index = global_cfil_stats_counts[kcunit - 1]; stats = &flow_array[index]; stats->cfs_sock_id = cfil_info->cfi_sock_id; stats->cfs_byte_inbound_count = cfil_info->cfi_byte_inbound_count; stats->cfs_byte_outbound_count = cfil_info->cfi_byte_outbound_count; if (entry->cfe_laddr_sent == false) { /* cache it if necessary */ if (cfil_info->cfi_so_attach_laddr.sa.sa_len == 0) { inp = cfil_info->cfi_so ? sotoinpcb(cfil_info->cfi_so) : NULL; if (inp != NULL) { boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT); union sockaddr_in_4_6 *src = outgoing ? &cfil_info->cfi_so_attach_laddr : NULL; union sockaddr_in_4_6 *dst = outgoing ? NULL : &cfil_info->cfi_so_attach_laddr; cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp, src, dst, !IS_INP_V6(inp), outgoing); } } if (cfil_info->cfi_so_attach_laddr.sa.sa_len != 0) { stats->cfs_laddr.sin6 = cfil_info->cfi_so_attach_laddr.sin6; entry->cfe_laddr_sent = true; } } global_cfil_stats_counts[kcunit - 1]++; entry->cfe_stats_report_ts = current_tv; entry->cfe_byte_inbound_count_reported = cfil_info->cfi_byte_inbound_count; entry->cfe_byte_outbound_count_reported = cfil_info->cfi_byte_outbound_count; if (cfil_info->cfi_debug && cfil_log_stats) { cfil_info_log(LOG_ERR, cfil_info, "CFIL: STATS COLLECTED"); } CFI_ADD_TIME_LOG(cfil_info, ¤t_tv, &cfil_info->cfi_first_event, CFM_OP_STATS); return true; } } return false; } static void cfil_stats_report(void *v, wait_result_t w) { #pragma unused(v, w) struct cfil_info *cfil_info = NULL; struct cfil_entry *entry = NULL; struct timeval current_tv; uint32_t flow_count = 0; uint64_t saved_next_sock_id = 0; // Next sock id to be reported for next loop bool flow_reported = false; if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION RUNNING"); } do { // Collect all sock ids of flows that has new stats cfil_rw_lock_shared(&cfil_lck_rw); if (cfil_sock_attached_stats_count == 0) { if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "CFIL: STATS: no flow"); } cfil_rw_unlock_shared(&cfil_lck_rw); goto go_sleep; } for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { if (global_cfil_stats_report_buffers[kcunit - 1] != NULL) { memset(global_cfil_stats_report_buffers[kcunit - 1], 0, sizeof(struct cfil_stats_report_buffer)); } global_cfil_stats_counts[kcunit - 1] = 0; } microuptime(¤t_tv); flow_count = 0; TAILQ_FOREACH(cfil_info, &cfil_sock_head_stats, cfi_link_stats) { if (saved_next_sock_id != 0 && saved_next_sock_id == cfil_info->cfi_sock_id) { // Here is where we left off previously, start accumulating saved_next_sock_id = 0; } if (saved_next_sock_id == 0) { if (flow_count >= CFIL_STATS_REPORT_MAX_COUNT) { // Examine a fixed number of flows each round. Remember the current flow // so we can start from here for next loop saved_next_sock_id = cfil_info->cfi_sock_id; break; } flow_reported = false; for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { entry = &cfil_info->cfi_entries[kcunit - 1]; if (entry->cfe_filter == NULL) { if (cfil_info->cfi_debug && cfil_log_stats) { CFIL_LOG(LOG_ERR, "CFIL: STATS REPORT - so %llx no filter", cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0); } continue; } if ((entry->cfe_stats_report_frequency > 0) && cfil_stats_collect_flow_stats_for_filter(kcunit, cfil_info, entry, current_tv) == true) { flow_reported = true; } } if (flow_reported == true) { flow_count++; } } } if (flow_count > 0) { if (cfil_log_stats) { CFIL_LOG(LOG_DEBUG, "CFIL: STATS reporting for %d flows", flow_count); } for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) { if (global_cfil_stats_report_buffers[kcunit - 1] != NULL && global_cfil_stats_counts[kcunit - 1] > 0) { cfil_dispatch_stats_event_locked(kcunit, global_cfil_stats_report_buffers[kcunit - 1], global_cfil_stats_counts[kcunit - 1]); } } } else { cfil_rw_unlock_shared(&cfil_lck_rw); goto go_sleep; } cfil_rw_unlock_shared(&cfil_lck_rw); // Loop again if we haven't finished the whole cfil_info list } while (saved_next_sock_id != 0); go_sleep: // Sleep forever (until waken up) if no more flow to report cfil_rw_lock_shared(&cfil_lck_rw); cfil_stats_report_thread_sleep(cfil_sock_attached_stats_count == 0 ? true : false); cfil_rw_unlock_shared(&cfil_lck_rw); thread_block_parameter((thread_continue_t) cfil_stats_report, NULL); /* NOTREACHED */ } |