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 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 | /* * Copyright (c) 2000-2020 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_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. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * 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_OSREFERENCE_LICENSE_HEADER_END@ */ /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */ /* * Mach Operating System * Copyright (c) 1987 Carnegie-Mellon University * All rights reserved. The CMU software License Agreement specifies * the terms and conditions for use and redistribution. */ /*- * Copyright (c) 1982, 1986, 1991, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)kern_exec.c 8.1 (Berkeley) 6/10/93 */ /* * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce * support for mandatory and extensible security protections. This notice * is included in support of clause 2.2 (b) of the Apple Public License, * Version 2.0. */ #include <machine/reg.h> #include <machine/cpu_capabilities.h> #include <sys/cdefs.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/filedesc.h> #include <sys/kernel.h> #include <sys/proc_internal.h> #include <sys/kauth.h> #include <sys/user.h> #include <sys/socketvar.h> #include <sys/malloc.h> #include <sys/namei.h> #include <sys/mount_internal.h> #include <sys/vnode_internal.h> #include <sys/file_internal.h> #include <sys/stat.h> #include <sys/uio_internal.h> #include <sys/acct.h> #include <sys/exec.h> #include <sys/kdebug.h> #include <sys/signal.h> #include <sys/aio_kern.h> #include <sys/lockdown_mode.h> #include <sys/sysproto.h> #include <sys/sysctl.h> #include <sys/persona.h> #include <sys/reason.h> #if SYSV_SHM #include <sys/shm_internal.h> /* shmexec() */ #endif #include <sys/ubc_internal.h> /* ubc_map() */ #include <sys/spawn.h> #include <sys/spawn_internal.h> #include <sys/process_policy.h> #include <sys/codesign.h> #include <sys/random.h> #include <crypto/sha1.h> #include <libkern/libkern.h> #include <libkern/amfi/amfi.h> #include <libkern/crypto/sha2.h> #include <security/audit/audit.h> #include <ipc/ipc_types.h> #include <mach/mach_param.h> #include <mach/mach_types.h> #include <mach/port.h> #include <mach/task.h> #include <mach/task_access.h> #include <mach/thread_act.h> #include <mach/vm_map.h> #include <mach/mach_vm.h> #include <mach/vm_param.h> #include <mach_debug/mach_debug_types.h> #include <kern/sched_prim.h> /* thread_wakeup() */ #include <kern/affinity.h> #include <kern/assert.h> #include <kern/ipc_kobject.h> #include <kern/task.h> #include <kern/thread.h> #include <kern/coalition.h> #include <kern/policy_internal.h> #include <kern/kalloc.h> #include <kern/zalloc.h> /* zone_userspace_reboot_checks() */ #include <os/log.h> #if CONFIG_MACF #include <security/mac_framework.h> #include <security/mac_mach_internal.h> #endif #if CONFIG_AUDIT #include <bsm/audit_kevents.h> #endif #if CONFIG_ARCADE #include <kern/arcade.h> #endif #include <vm/vm_map_xnu.h> #include <vm/vm_kern_xnu.h> #include <vm/vm_protos.h> #include <vm/vm_fault.h> #include <vm/vm_pageout_xnu.h> #include <vm/pmap.h> #include <vm/vm_reclaim_xnu.h> #include <kdp/kdp_dyld.h> #include <machine/machine_routines.h> #include <machine/pal_routines.h> #include <pexpert/pexpert.h> #include <pexpert/device_tree.h> #if CONFIG_MEMORYSTATUS #include <sys/kern_memorystatus.h> #endif #include <IOKit/IOBSD.h> #include <IOKit/IOKitKeys.h> /* kIODriverKitEntitlementKey */ #include "kern_exec_internal.h" #include <CodeSignature/Entitlements.h> #include <mach/exclaves.h> #if HAS_MTE #include <arm64/mte_xnu.h> #endif /* HAS_MTE */ extern boolean_t vm_darkwake_mode; /* enable crash reports on various exec failures */ static TUNABLE(bool, bootarg_execfailurereports, "execfailurecrashes", false); #if XNU_TARGET_OS_OSX #if __has_feature(ptrauth_calls) static TUNABLE(bool, bootarg_arm64e_preview_abi, "-arm64e_preview_abi", false); #endif /* __has_feature(ptrauth_calls) */ #if DEBUG || DEVELOPMENT static TUNABLE(bool, unentitled_ios_sim_launch, "unentitled_ios_sim_launch", false); #endif /* DEBUG || DEVELOPMENT */ #endif /* XNU_TARGET_OS_OSX */ #if DEVELOPMENT || DEBUG os_log_t exec_log_handle = NULL; #define EXEC_LOG(fmt, ...) \ do { \ if (exec_log_handle) { \ os_log_with_type(exec_log_handle, OS_LOG_TYPE_INFO, "exec - %s:%d " fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ } \ } while (0) #else /* DEVELOPMENT || DEBUG */ #define EXEC_LOG(fmt, ...) do { } while (0) #endif /* DEVELOPMENT || DEBUG */ #if CONFIG_DTRACE /* Do not include dtrace.h, it redefines kmem_[alloc/free] */ extern void dtrace_proc_exec(proc_t); extern void (*dtrace_proc_waitfor_exec_ptr)(proc_t); /* * Since dtrace_proc_waitfor_exec_ptr can be added/removed in dtrace_subr.c, * we will store its value before actually calling it. */ static void (*dtrace_proc_waitfor_hook)(proc_t) = NULL; #include <sys/dtrace_ptss.h> #endif #if __has_feature(ptrauth_calls) static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_per_team_id, "vm_shared_region_per_team_id", 1); static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_by_entitlement, "vm_shared_region_by_entitlement", 1); /* Upon userland request, reslide the shared cache. */ static TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_aslr, "vm_shared_region_reslide_aslr", #if CONFIG_RESLIDE_SHARED_CACHE 1 #else 0 #endif /* CONFIG_RESLIDE_SHARED_CACHE */ ); /* * Flag to control what processes should get shared cache randomize resliding * after a fault in the shared cache region: * * 0 - all processes get a new randomized slide * 1 - only platform processes get a new randomized slide */ TUNABLE_DEV_WRITEABLE(int, vm_shared_region_reslide_restrict, "vm_shared_region_reslide_restrict", 1); #if DEVELOPMENT || DEBUG SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_per_team_id, CTLFLAG_RW, &vm_shared_region_per_team_id, 0, ""); SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_by_entitlement, CTLFLAG_RW, &vm_shared_region_by_entitlement, 0, ""); SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_restrict, CTLFLAG_RW, &vm_shared_region_reslide_restrict, 0, ""); SYSCTL_INT(_vm, OID_AUTO, vm_shared_region_reslide_aslr, CTLFLAG_RW, &vm_shared_region_reslide_aslr, 0, ""); #endif #endif /* __has_feature(ptrauth_calls) */ #if DEVELOPMENT || DEBUG static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", true); #else static TUNABLE(bool, enable_dext_coredumps_on_panic, "dext_panic_coredump", false); #endif extern kern_return_t kern_register_userspace_coredump(task_t task, const char * name, boolean_t emergency); #define USERSPACE_COREDUMP_PANIC_ENTITLEMENT "com.apple.private.enable-coredump-on-panic" #define USERSPACE_COREDUMP_PANIC_SEED_ENTITLEMENT \ "com.apple.private.enable-coredump-on-panic-seed-privacy-approved" extern void proc_apply_task_networkbg_internal(proc_t, thread_t); extern void task_set_did_exec_flag(task_t task); extern void task_clear_exec_copy_flag(task_t task); proc_t proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task, task_t new_task, struct image_params *imgp, void **inherit); boolean_t task_is_active(task_t); boolean_t thread_is_active(thread_t thread); void thread_copy_resource_info(thread_t dst_thread, thread_t src_thread); void *ipc_importance_exec_switch_task(task_t old_task, task_t new_task); extern void ipc_importance_release(void *elem); extern boolean_t task_has_watchports(task_t task); extern void task_set_no_smt(task_t task); #if defined(HAS_APPLE_PAC) char *task_get_vm_shared_region_id_and_jop_pid(task_t task, uint64_t *jop_pid); #endif task_t convert_port_to_task(ipc_port_t port); #if CONFIG_EXCLAVES int task_add_conclave(task_t task, void *vnode, int64_t off, const char *task_conclave_id); kern_return_t task_inherit_conclave(task_t old_task, task_t new_task, void *vnode, int64_t off); #endif /* CONFIG_EXCLAVES */ /* * Mach things for which prototypes are unavailable from Mach headers */ extern void ipc_task_enable(task_t task); extern void ipc_task_reset(task_t task); extern void ipc_thread_reset(thread_t thread); #if DEVELOPMENT || DEBUG void task_importance_update_owner_info(task_t); #endif extern struct savearea *get_user_regs(thread_t); __attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid); #include <kern/thread.h> #include <kern/task.h> #include <kern/ast.h> #include <kern/mach_loader.h> #include <kern/mach_fat.h> #include <mach-o/fat.h> #include <mach-o/loader.h> #include <machine/vmparam.h> #include <sys/imgact.h> #include <sys/sdt.h> /* * EAI_ITERLIMIT The maximum number of times to iterate an image * activator in exec_activate_image() before treating * it as malformed/corrupt. */ #define EAI_ITERLIMIT 3 /* * For #! interpreter parsing */ #define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t')) #define IS_EOL(ch) ((ch == '#') || (ch == '\n')) extern vm_map_t bsd_pageable_map; extern const struct fileops vnops; extern int nextpidversion; #define USER_ADDR_ALIGN(addr, val) \ ( ( (user_addr_t)(addr) + (val) - 1) \ & ~((val) - 1) ) /* * For subsystem root support */ #define SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT "com.apple.private.spawn-subsystem-root" /* * Allow setting p_crash_behavior to trigger panic on crash */ #define SPAWN_SET_PANIC_CRASH_BEHAVIOR "com.apple.private.spawn-panic-crash-behavior" /* Platform Code Exec Logging */ static int platform_exec_logging = 0; SYSCTL_DECL(_security_mac); SYSCTL_INT(_security_mac, OID_AUTO, platform_exec_logging, CTLFLAG_RW, &platform_exec_logging, 0, "log cdhashes for all platform binary executions"); static os_log_t peLog = OS_LOG_DEFAULT; struct exception_port_action_t { ipc_port_t port; _ps_port_action_t *port_action; }; struct exec_port_actions { uint32_t exception_port_count; uint32_t portwatch_count; uint32_t registered_count; struct exception_port_action_t *excport_array; ipc_port_t *portwatch_array; ipc_port_t registered_array[TASK_PORT_REGISTER_MAX]; }; struct image_params; /* Forward */ static int exec_activate_image(struct image_params *imgp); static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp); static int load_return_to_errno(load_return_t lrtn); static int execargs_alloc(struct image_params *imgp); static int execargs_free(struct image_params *imgp); static int exec_check_permissions(struct image_params *imgp); static int exec_extract_strings(struct image_params *imgp); static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result, task_t task); static int exec_handle_sugid(struct image_params *imgp); static int sugid_scripts = 0; SYSCTL_INT(_kern, OID_AUTO, sugid_scripts, CTLFLAG_RW | CTLFLAG_LOCKED, &sugid_scripts, 0, ""); static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p); static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size); static void exec_resettextvp(proc_t, struct image_params *); static int process_signature(proc_t, struct image_params *); static void exec_prefault_data(proc_t, struct image_params *, load_result_t *); static errno_t exec_handle_port_actions(struct image_params *imgp, struct exec_port_actions *port_actions); static errno_t exec_handle_exception_port_actions(const struct image_params *imgp, const struct exec_port_actions *port_actions); static errno_t exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp, task_role_t psa_darwin_role, struct exec_port_actions *port_actions); static void exec_port_actions_destroy(struct exec_port_actions *port_actions); /* * exec_add_user_string * * Add the requested string to the string space area. * * Parameters; struct image_params * image parameter block * user_addr_t string to add to strings area * int segment from which string comes * boolean_t TRUE if string contributes to NCARGS * * Returns: 0 Success * !0 Failure errno from copyinstr() * * Implicit returns: * (imgp->ip_strendp) updated location of next add, if any * (imgp->ip_strspace) updated byte count of space remaining * (imgp->ip_argspace) updated byte count of space in NCARGS */ __attribute__((noinline)) static int exec_add_user_string(struct image_params *imgp, user_addr_t str, int seg, boolean_t is_ncargs) { int error = 0; do { size_t len = 0; int space; if (is_ncargs) { space = imgp->ip_argspace; /* by definition smaller than ip_strspace */ } else { space = imgp->ip_strspace; } if (space <= 0) { error = E2BIG; break; } if (!UIO_SEG_IS_USER_SPACE(seg)) { char *kstr = CAST_DOWN(char *, str); /* SAFE */ error = copystr(kstr, imgp->ip_strendp, space, &len); } else { error = copyinstr(str, imgp->ip_strendp, space, &len); } imgp->ip_strendp += len; imgp->ip_strspace -= len; if (is_ncargs) { imgp->ip_argspace -= len; } } while (error == ENAMETOOLONG); return error; } /* * dyld is now passed the executable path as a getenv-like variable * in the same fashion as the stack_guard and malloc_entropy keys. */ #define EXECUTABLE_KEY "executable_path=" /* * exec_save_path * * To support new app package launching for Mac OS X, the dyld needs the * first argument to execve() stored on the user stack. * * Save the executable path name at the bottom of the strings area and set * the argument vector pointer to the location following that to indicate * the start of the argument and environment tuples, setting the remaining * string space count to the size of the string area minus the path length. * * Parameters; struct image_params * image parameter block * char * path used to invoke program * int segment from which path comes * * Returns: int 0 Success * EFAULT Bad address * copy[in]str:EFAULT Bad address * copy[in]str:ENAMETOOLONG Filename too long * * Implicit returns: * (imgp->ip_strings) saved path * (imgp->ip_strspace) space remaining in ip_strings * (imgp->ip_strendp) start of remaining copy area * (imgp->ip_argspace) space remaining of NCARGS * (imgp->ip_applec) Initial applev[0] * * Note: We have to do this before the initial namei() since in the * path contains symbolic links, namei() will overwrite the * original path buffer contents. If the last symbolic link * resolved was a relative pathname, we would lose the original * "path", which could be an absolute pathname. This might be * unacceptable for dyld. */ static int exec_save_path(struct image_params *imgp, user_addr_t path, int seg, const char **excpath) { int error; size_t len; char *kpath; // imgp->ip_strings can come out of a cache, so we need to obliterate the // old path. memset(imgp->ip_strings, '\0', strlen(EXECUTABLE_KEY) + MAXPATHLEN); len = MIN(MAXPATHLEN, imgp->ip_strspace); switch (seg) { case UIO_USERSPACE32: case UIO_USERSPACE64: /* Same for copyin()... */ error = copyinstr(path, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len); break; case UIO_SYSSPACE: kpath = CAST_DOWN(char *, path); /* SAFE */ error = copystr(kpath, imgp->ip_strings + strlen(EXECUTABLE_KEY), len, &len); break; default: error = EFAULT; break; } if (!error) { bcopy(EXECUTABLE_KEY, imgp->ip_strings, strlen(EXECUTABLE_KEY)); len += strlen(EXECUTABLE_KEY); imgp->ip_strendp += len; imgp->ip_strspace -= len; if (excpath) { *excpath = imgp->ip_strings + strlen(EXECUTABLE_KEY); } } return error; } /* * exec_reset_save_path * * If we detect a shell script, we need to reset the string area * state so that the interpreter can be saved onto the stack. * * Parameters; struct image_params * image parameter block * * Returns: int 0 Success * * Implicit returns: * (imgp->ip_strings) saved path * (imgp->ip_strspace) space remaining in ip_strings * (imgp->ip_strendp) start of remaining copy area * (imgp->ip_argspace) space remaining of NCARGS * */ static int exec_reset_save_path(struct image_params *imgp) { imgp->ip_strendp = imgp->ip_strings; imgp->ip_argspace = NCARGS; imgp->ip_strspace = (NCARGS + PAGE_SIZE); return 0; } /* * exec_shell_imgact * * Image activator for interpreter scripts. If the image begins with * the characters "#!", then it is an interpreter script. Verify the * length of the script line indicating the interpreter is not in * excess of the maximum allowed size. If this is the case, then * break out the arguments, if any, which are separated by white * space, and copy them into the argument save area as if they were * provided on the command line before all other arguments. The line * ends when we encounter a comment character ('#') or newline. * * Parameters; struct image_params * image parameter block * * Returns: -1 not an interpreter (keep looking) * -3 Success: interpreter: relookup * >0 Failure: interpreter: error number * * A return value other than -1 indicates subsequent image activators should * not be given the opportunity to attempt to activate the image. */ static int exec_shell_imgact(struct image_params *imgp) { char *vdata = imgp->ip_vdata; char *ihp; char *line_startp, *line_endp; char *interp; /* * Make sure it's a shell script. If we've already redirected * from an interpreted file once, don't do it again. */ if (vdata[0] != '#' || vdata[1] != '!' || (imgp->ip_flags & IMGPF_INTERPRET) != 0) { return -1; } if (imgp->ip_origcputype != 0) { /* Fat header previously matched, don't allow shell script inside */ return -1; } imgp->ip_flags |= IMGPF_INTERPRET; imgp->ip_interp_sugid_fd = -1; imgp->ip_interp_buffer[0] = '\0'; /* Check to see if SUGID scripts are permitted. If they aren't then * clear the SUGID bits. * imgp->ip_vattr is known to be valid. */ if (sugid_scripts == 0) { imgp->ip_origvattr->va_mode &= ~(VSUID | VSGID); } /* Try to find the first non-whitespace character */ for (ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++) { if (IS_EOL(*ihp)) { /* Did not find interpreter, "#!\n" */ return ENOEXEC; } else if (IS_WHITESPACE(*ihp)) { /* Whitespace, like "#! /bin/sh\n", keep going. */ } else { /* Found start of interpreter */ break; } } if (ihp == &vdata[IMG_SHSIZE]) { /* All whitespace, like "#! " */ return ENOEXEC; } line_startp = ihp; /* Try to find the end of the interpreter+args string */ for (; ihp < &vdata[IMG_SHSIZE]; ihp++) { if (IS_EOL(*ihp)) { /* Got it */ break; } else { /* Still part of interpreter or args */ } } if (ihp == &vdata[IMG_SHSIZE]) { /* A long line, like "#! blah blah blah" without end */ return ENOEXEC; } /* Backtrack until we find the last non-whitespace */ while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) { ihp--; } /* The character after the last non-whitespace is our logical end of line */ line_endp = ihp + 1; /* * Now we have pointers to the usable part of: * * "#! /usr/bin/int first second third \n" * ^ line_startp ^ line_endp */ /* copy the interpreter name */ interp = imgp->ip_interp_buffer; for (ihp = line_startp; (ihp < line_endp) && !IS_WHITESPACE(*ihp); ihp++) { *interp++ = *ihp; } *interp = '\0'; exec_reset_save_path(imgp); exec_save_path(imgp, CAST_USER_ADDR_T(imgp->ip_interp_buffer), UIO_SYSSPACE, NULL); /* Copy the entire interpreter + args for later processing into argv[] */ interp = imgp->ip_interp_buffer; for (ihp = line_startp; (ihp < line_endp); ihp++) { *interp++ = *ihp; } *interp = '\0'; #if CONFIG_SETUID /* * If we have an SUID or SGID script, create a file descriptor * from the vnode and pass /dev/fd/%d instead of the actual * path name so that the script does not get opened twice */ if (imgp->ip_origvattr->va_mode & (VSUID | VSGID)) { proc_t p; struct fileproc *fp; int fd; int error; p = vfs_context_proc(imgp->ip_vfs_context); error = falloc_exec(p, imgp->ip_vfs_context, &fp, &fd); if (error) { return error; } fp->fp_glob->fg_flag = FREAD; fp->fp_glob->fg_ops = &vnops; fp_set_data(fp, imgp->ip_vp); proc_fdlock(p); procfdtbl_releasefd(p, fd, NULL); fp_drop(p, fd, fp, 1); proc_fdunlock(p); vnode_ref(imgp->ip_vp); imgp->ip_interp_sugid_fd = fd; } #endif /* CONFIG_SETUID */ return -3; } /* * exec_fat_imgact * * Image activator for fat 1.0 binaries. If the binary is fat, then we * need to select an image from it internally, and make that the image * we are going to attempt to execute. At present, this consists of * reloading the first page for the image with a first page from the * offset location indicated by the fat header. * * Parameters; struct image_params * image parameter block * * Returns: -1 not a fat binary (keep looking) * -2 Success: encapsulated binary: reread * >0 Failure: error number * * Important: This image activator is byte order neutral. * * Note: A return value other than -1 indicates subsequent image * activators should not be given the opportunity to attempt * to activate the image. * * If we find an encapsulated binary, we make no assertions * about its validity; instead, we leave that up to a rescan * for an activator to claim it, and, if it is claimed by one, * that activator is responsible for determining validity. */ static int exec_fat_imgact(struct image_params *imgp) { proc_t p = vfs_context_proc(imgp->ip_vfs_context); kauth_cred_t cred = kauth_cred_proc_ref(p); struct fat_header *fat_header = (struct fat_header *)imgp->ip_vdata; struct _posix_spawnattr *psa = NULL; struct fat_arch fat_arch; int resid, error; load_return_t lret; if (imgp->ip_origcputype != 0) { /* Fat header previously matched, don't allow another fat file inside */ error = -1; /* not claimed */ goto bad; } /* Make sure it's a fat binary */ if (OSSwapBigToHostInt32(fat_header->magic) != FAT_MAGIC) { error = -1; /* not claimed */ goto bad; } /* imgp->ip_vdata has PAGE_SIZE, zerofilled if the file is smaller */ lret = fatfile_validate_fatarches((vm_offset_t)fat_header, PAGE_SIZE, (off_t)imgp->ip_vattr->va_data_size); if (lret != LOAD_SUCCESS) { error = load_return_to_errno(lret); goto bad; } /* If posix_spawn binprefs exist, respect those prefs. */ psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa != NULL && psa->psa_binprefs[0] != 0) { uint32_t pr = 0; /* Check each preference listed against all arches in header */ for (pr = 0; pr < NBINPREFS; pr++) { cpu_type_t pref = psa->psa_binprefs[pr]; cpu_type_t subpref = psa->psa_subcpuprefs[pr]; if (pref == 0) { /* No suitable arch in the pref list */ error = EBADARCH; goto bad; } if (pref == CPU_TYPE_ANY) { /* Fall through to regular grading */ goto regular_grading; } lret = fatfile_getbestarch_for_cputype(pref, subpref, (vm_offset_t)fat_header, PAGE_SIZE, imgp, &fat_arch); if (lret == LOAD_SUCCESS) { goto use_arch; } } /* Requested binary preference was not honored */ error = EBADEXEC; goto bad; } regular_grading: /* Look up our preferred architecture in the fat file. */ lret = fatfile_getbestarch((vm_offset_t)fat_header, PAGE_SIZE, imgp, &fat_arch, (p->p_flag & P_AFFINITY) != 0); if (lret != LOAD_SUCCESS) { error = load_return_to_errno(lret); goto bad; } use_arch: /* Read the Mach-O header out of fat_arch */ error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, fat_arch.offset, UIO_SYSSPACE, (IO_UNIT | IO_NODELOCKED), cred, &resid, p); if (error) { if (error == ERESTART) { error = EINTR; } goto bad; } if (resid) { memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid); } /* Success. Indicate we have identified an encapsulated binary */ error = -2; imgp->ip_arch_offset = (user_size_t)fat_arch.offset; imgp->ip_arch_size = (user_size_t)fat_arch.size; imgp->ip_origcputype = fat_arch.cputype; imgp->ip_origcpusubtype = fat_arch.cpusubtype; bad: kauth_cred_unref(&cred); return error; } static int activate_exec_state(task_t task, proc_t p, thread_t thread, load_result_t *result) { int ret; (void)task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0, false); task_set_64bit(task, result->is_64bit_addr, result->is_64bit_data); if (result->is_64bit_addr) { OSBitOrAtomic(P_LP64, &p->p_flag); get_bsdthread_info(thread)->uu_flag |= UT_LP64; } else { OSBitAndAtomic(~((uint32_t)P_LP64), &p->p_flag); get_bsdthread_info(thread)->uu_flag &= ~UT_LP64; } task_set_mach_header_address(task, result->mach_header); ret = thread_state_initialize(thread); if (ret != KERN_SUCCESS) { return ret; } if (result->threadstate) { uint32_t *ts = result->threadstate; uint32_t total_size = (uint32_t)result->threadstate_sz; while (total_size > 0) { uint32_t flavor = *ts++; uint32_t size = *ts++; ret = thread_setstatus(thread, flavor, (thread_state_t)ts, size); if (ret) { return ret; } ts += size; total_size -= (size + 2) * sizeof(uint32_t); } } thread_setentrypoint(thread, result->entry_point); return KERN_SUCCESS; } extern char panic_on_proc_crash[]; extern int use_panic_on_proc_crash; extern char panic_on_proc_exit[]; extern int use_panic_on_proc_exit; extern char panic_on_proc_spawn_fail[]; extern int use_panic_on_proc_spawn_fail; static inline void set_crash_behavior_from_bootarg(proc_t p) { if (use_panic_on_proc_crash && strcmp(p->p_comm, panic_on_proc_crash) == 0) { printf("will panic on proc crash: %s\n", p->p_comm); p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_CRASH; } if (use_panic_on_proc_exit && strcmp(p->p_comm, panic_on_proc_exit) == 0) { printf("will panic on proc exit: %s\n", p->p_comm); p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_EXIT; } if (use_panic_on_proc_spawn_fail && strcmp(p->p_comm, panic_on_proc_spawn_fail) == 0) { printf("will panic on proc spawn fail: %s\n", p->p_comm); p->p_crash_behavior |= POSIX_SPAWN_PANIC_ON_SPAWN_FAIL; } } void set_proc_name(struct image_params *imgp, proc_t p) { uint64_t buflen = imgp->ip_ndp->ni_cnd.cn_namelen; const int p_name_len = sizeof(p->p_name) - 1; const int p_comm_len = sizeof(p->p_comm) - 1; if (buflen > p_name_len) { buflen = p_name_len; } bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_name, buflen); p->p_name[buflen] = '\0'; if (buflen > p_comm_len) { static_assert(MAXCOMLEN + 1 == sizeof(p->p_comm)); buflen = p_comm_len; } bcopy((caddr_t)imgp->ip_ndp->ni_cnd.cn_nameptr, (caddr_t)p->p_comm, buflen); p->p_comm[buflen] = '\0'; /* * This happens during image activation, so the crash behavior flags from * posix_spawn will have already been set. So we don't have to worry about * this being overridden. */ set_crash_behavior_from_bootarg(p); } #if __has_feature(ptrauth_calls) /** * Returns a team ID string that may be used to assign a shared region. * * Platform binaries do not have team IDs and will return NULL. Non-platform * binaries without a team ID will be assigned an artificial team ID of "" * (empty string) so that they will not be assigned to the default shared * region. * * @param imgp image parameter block * @return NULL if this is a platform binary, or an appropriate team ID string * otherwise */ static inline const char * get_teamid_for_shared_region(struct image_params *imgp) { assert(imgp->ip_vp != NULL); const char *ret = csvnode_get_teamid(imgp->ip_vp, imgp->ip_arch_offset); if (ret) { return ret; } struct cs_blob *blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset); if (csblob_get_platform_binary(blob)) { return NULL; } else { static const char *NO_TEAM_ID = ""; return NO_TEAM_ID; } } /** * Determines whether ptrauth should be enabled for the provided arm64 CPU subtype. * * @param cpusubtype Mach-O style CPU subtype * @return whether the CPU subtype matches arm64e with the current ptrauth ABI */ static inline bool arm64_cpusubtype_uses_ptrauth(cpu_subtype_t cpusubtype) { int ptrauth_abi_version = (int)CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(cpusubtype); return (cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E && (ptrauth_abi_version >= CPU_SUBTYPE_ARM64_PTR_AUTHV0_VERSION && ptrauth_abi_version <= CPU_SUBTYPE_ARM64_PTR_AUTH_MAX_PREFERRED_VERSION); } #endif /* __has_feature(ptrauth_calls) */ /** * Returns whether a type/subtype slice matches the requested * type/subtype. * * @param mask Bits to mask from the requested/tested cpu type * @param req_cpu Requested cpu type * @param req_subcpu Requested cpu subtype * @param test_cpu Tested slice cpu type * @param test_subcpu Tested slice cpu subtype */ boolean_t binary_match(cpu_type_t mask, cpu_type_t req_cpu, cpu_subtype_t req_subcpu, cpu_type_t test_cpu, cpu_subtype_t test_subcpu) { if ((test_cpu & ~mask) != (req_cpu & ~mask)) { return FALSE; } test_subcpu &= ~CPU_SUBTYPE_MASK; req_subcpu &= ~CPU_SUBTYPE_MASK; if (test_subcpu != req_subcpu && req_subcpu != (CPU_SUBTYPE_ANY & ~CPU_SUBTYPE_MASK)) { return FALSE; } return TRUE; } /* * Check entitlements to see if this is a platform restrictions binary. * Save this in load_result until later for two purposes: * 1. We can mark the task at a certain security level once it's been created * 2. We can propagate which entitlements are present to the apple array */ static inline void encode_HR_entitlement(const char *entitlement, hardened_browser_flags_t mask, const struct image_params *imgp, load_result_t *load_result) { if (IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, entitlement)) { load_result->hardened_browser |= mask; } } /* * If the passed in executable's vnode should use the RSR * shared region, then this should return TRUE, otherwise, return FALSE. */ static uint32_t rsr_current_version = 0; boolean_t (*rsr_check_vnode)(void *vnode) = NULL; boolean_t vnode_is_rsr(vnode_t vp) { if (!(vnode_isreg(vp) && vnode_tag(vp) == VT_APFS)) { return FALSE; } if (rsr_check_vnode != NULL && rsr_check_vnode((void *)vp)) { return TRUE; } return FALSE; } static struct { char *legacy; char *security; } exec_security_mitigation_entitlement[] = { /* The following entries must match the enum declaration in kern_exec_internal.h */ [HARDENED_PROCESS] = { "com.apple.developer.hardened-process", "com.apple.security.hardened-process" }, [HARDENED_HEAP] = { "com.apple.developer.hardened-process.hardened-heap", "com.apple.security.hardened-process.hardened-heap" }, [TPRO] = { NULL, "com.apple.security.hardened-process.dyld-ro", }, #if HAS_MTE [CHECKED_ALLOCATIONS] = { "com.apple.developer.hardened-process.checked-allocations", "com.apple.security.hardened-process.checked-allocations" }, [CHECKED_ALLOCATIONS_DISABLE_PURE_DATA] = { NULL, "com.apple.security.hardened-process.checked-allocations.disable-pure-data" }, [CHECKED_ALLOCATIONS_NO_TAGGED_RECEIVE] = { NULL, "com.apple.security.hardened-process.checked-allocations.no-tagged-receive" }, [CHECKED_ALLOCATIONS_SOFT_MODE] = { NULL, "com.apple.security.hardened-process.checked-allocations.soft-mode" }, #endif /* HAS_MTE */ [SCRIPT_RESTRICTIONS] = { NULL, "com.apple.security.script-restrictions" }, [IPC_CONTAINMENT_VESSEL] = { NULL, "com.apple.security.hardened-process.containment.ipc" }, [NO_GUARD_OBJECTS] = { NULL, "com.apple.security.hardened-process.no-guard-objects" } }; /* * Platform Restrictions * * This mitigation opts you into the grab bag of various kernel mitigations * including IPC security restrictions * The presence of the entitlement opts the binary into the feature. * The entitlement is a <string> entitlement containing a version number * for the platform restrictions you are opting into. */ #define SPAWN_ENABLE_PLATFORM_RESTRICTIONS_ENT_STR "com.apple.security.hardened-process.platform-restrictions-string" /* * rdar://168452024: The platform restrictions entitlement was originally mapped * to an integer, but unfortunately some machinery doesn't support integer value ranges. * The original entitlement is preserved and parsed for compatibility. */ #define SPAWN_ENABLE_PLATFORM_RESTRICTIONS_ENT_INT "com.apple.security.hardened-process.platform-restrictions" /* See kern_exec_internal.h for the extensive documentation. */ exec_security_err_t exec_check_security_entitlement(struct image_params *imgp, exec_security_mitigation_entitlement_t entitlement) { bool has_legacy_entitlement = false, has_security_entitlement = false; assert(exec_security_mitigation_entitlement[entitlement].security != NULL); if (exec_security_mitigation_entitlement[entitlement].legacy != NULL) { has_legacy_entitlement = IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, exec_security_mitigation_entitlement[entitlement].legacy); } has_security_entitlement = IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, exec_security_mitigation_entitlement[entitlement].security); /* If both entitlements are present, this is an invalid configuration. */ if (has_legacy_entitlement && has_security_entitlement) { EXEC_LOG("Binary has both legacy (%s) and security (%s) entitlements\n", exec_security_mitigation_entitlement[entitlement].legacy, exec_security_mitigation_entitlement[entitlement].security); return EXEC_SECURITY_INVALID_CONFIG; } if (has_legacy_entitlement || has_security_entitlement) { return EXEC_SECURITY_ENTITLED; } return EXEC_SECURITY_NOT_ENTITLED; } /* * Entitled binaries get hardened_heap */ static inline errno_t imgact_setup_hardened_heap(struct image_params *imgp, task_t task) { exec_security_err_t ret = exec_check_security_entitlement(imgp, HARDENED_HEAP); if (ret == EXEC_SECURITY_ENTITLED) { task_set_hardened_heap(task); } else { task_clear_hardened_heap(task); } switch (ret) { case EXEC_SECURITY_INVALID_CONFIG: return EINVAL; case EXEC_SECURITY_ENTITLED: case EXEC_SECURITY_NOT_ENTITLED: return 0; } } static inline errno_t imgact_setup_script_restrictions(struct image_params *imgp, task_t task) { exec_security_err_t ret = exec_check_security_entitlement(imgp, SCRIPT_RESTRICTIONS); if (ret == EXEC_SECURITY_ENTITLED) { task_set_script_restrictions(task); } else { task_clear_script_restrictions(task); } switch (ret) { case EXEC_SECURITY_INVALID_CONFIG: return EINVAL; case EXEC_SECURITY_ENTITLED: case EXEC_SECURITY_NOT_ENTITLED: return 0; } } /* * Configure the platform restrictions security features on the task. * This must be done before `ipc_task_enable` so that the bits * can be propagated to the IPC space. * * Returns KERN_SUCCESS on success, or EINVAL if validation fails. */ static inline errno_t imgact_setup_platform_restrictions(struct image_params *imgp, load_result_t *load_result, task_t task) { char* endptr = NULL; char* maybe_platform_restrictions_level_str = NULL; uint64_t maybe_platform_restrictions_level_int = 0; /* Platform binaries always get the highest available restriction level */ if (load_result->platform_binary) { task_set_platform_restrictions_version(task, 3); return KERN_SUCCESS; } /* * Parse the platform restriction version via entitlement if present. * rdar://168452024: Prefer the new-style string version over the old-style int version. */ if (IOVnodeIsEntitlementPresentWithAnyValue(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, SPAWN_ENABLE_PLATFORM_RESTRICTIONS_ENT_STR)) { maybe_platform_restrictions_level_str = IOVnodeGetEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, SPAWN_ENABLE_PLATFORM_RESTRICTIONS_ENT_STR); /* * Note we're able to enforce stricter validation on the string-based * entitlement as we've never shipped this entitlement without validation. */ if (maybe_platform_restrictions_level_str == NULL) { /* The entitlement is present but we failed to parse it as a string */ EXEC_LOG("Invalid platform restrictions string specified"); return EINVAL; } else { maybe_platform_restrictions_level_int = (uint64_t)strtoul(maybe_platform_restrictions_level_str, &endptr, 10); if (maybe_platform_restrictions_level_str == endptr || *endptr != '\0' || maybe_platform_restrictions_level_int > UINT_MAX) { /* Failed to parse an int out of the string */ kfree_data(maybe_platform_restrictions_level_str, strlen(maybe_platform_restrictions_level_str) + 1); EXEC_LOG("Invalid platform restrictions string specified"); return EINVAL; } kfree_data(maybe_platform_restrictions_level_str, strlen(maybe_platform_restrictions_level_str) + 1); if (maybe_platform_restrictions_level_int < 2 || maybe_platform_restrictions_level_int >= 8) { /* Only levels 2 <= val < 8 are valid via this entitlement */ EXEC_LOG("Invalid platform restrictions level specified"); return EINVAL; } /* Parsed out a valid version from the string entitlement */ task_set_platform_restrictions_version(task, maybe_platform_restrictions_level_int); return KERN_SUCCESS; } } /* * Last resort: try the integer value entitlement. * To paper over compatibility concerns from when this entitlement was primary * and lacked some validation, all settings of this entitlement result in version==2 * (which was the only valid value in the extant timeframe of this entitlement). */ if (IOVnodeIsEntitlementPresentWithAnyValue(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, SPAWN_ENABLE_PLATFORM_RESTRICTIONS_ENT_INT)) { task_set_platform_restrictions_version(task, 2); return KERN_SUCCESS; } /* No entitlement, no problem */ return KERN_SUCCESS; } #if HAS_MTE || HAS_MTE_EMULATION_SHIMS #if DEVELOPMENT || DEBUG static inline void config_sec_inheritance(task_t, task_t); #endif /* DEVELOPMENT || DEBUG */ static inline void config_sec_spawnflags(load_result_t *load_result, struct _posix_spawnattr *, task_t); #if HAS_MTE static inline void config_sec_user_data(struct image_params *, load_result_t *, task_t, struct cs_blob *); static inline errno_t config_checked_allocations_entitlements(struct image_params *, load_result_t *, task_t, struct cs_blob *, proc_t); static inline exec_security_err_t imgact_setup_has_checked_allocations_entitlement(struct image_params *imgp, load_result_t *load_result, __unused task_t new_task, __unused struct cs_blob *cs_blob) { /* First-party DriverKit always gets MTE regardless of our normal entitlement knobs */ if (load_result->platform_binary && IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, kIODriverKitEntitlementKey)) { /* In soft mode, to mitigate risks on the build */ EXEC_LOG("Enabling MTE because we're launching a first-party dext"); return EXEC_SECURITY_ENTITLED; } /* If not a hardened-process, bail out. */ if (!load_result->hardened_process_version) { return EXEC_SECURITY_NOT_ENTITLED; } /* Check the entitlement. */ exec_security_err_t ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS); /* Bail out early on invalid configuration. These will fail execution. */ if (ret == EXEC_SECURITY_INVALID_CONFIG) { return ret; } /* * We need a couple of extra checks for first party binaries, mostly around * AMFI and reporting early (forbidden) usage of the entitlement. */ if (load_result->platform_binary) { #if KERN_AMFI_SUPPORTS_MTE >= 2 if (__improbable(amfi->has_mte_opt_out && amfi->has_mte_opt_out(cs_blob))) { EXEC_LOG("Binary checked-allocations enablement was denied by AMFI static list\n"); return EXEC_SECURITY_NOT_ENTITLED; } #endif /* KERN_AMFI_SUPPORTS_MTE */ /* * At this stage we are an hardened-process and AMFI hasn't said that we should * not enable MTE, therefore we just force enable even if the entitlement is not * present (until we can publicly require checked-allocations to be true). */ return EXEC_SECURITY_ENTITLED; } /* * The third-party flow is more linear: whatever the entitlement said it was the * setting, we'll run with it. */ return ret; } #endif /* HAS_MTE */ /* * Checked-allocations is a security feature that leverages MTE (Memory Tagging Extensions) * inside userspace allocators to protect dynamic memory allocations. * * MTE is a hardware security feature available in recent hardware devices. For legacy * devices, we support an internal-only readiness tool based on Rosetta that aims at * qualifying binaries for the new hardware, but that is not meant to be used in production. * * Checked-allocations enablement (generally referred to as MTE enabled here) and * configuration is controlled by: * - inheritance (debugging feature for bringup/readiness/performance evaluation) * - posix_spawn flags (no downgrade flags supported on RELEASE) * - entitlements (hardware only, no emulation. Main RELEASE configuration) * * The algorithm to decide whether checked-allocations should be enabled on the target * process is summarized here. * For Rosetta binaries, only posix_spawn flags are supported. * * ┌────────────────┐ ┌───────────────┐ * │ Inheritance │ ┌───────────────┐ │ Configure MTE │ * │ enabled? ├─YES──▶│ Enable MTE │──────▶│ mirroring │ * └──────────┬─────┘ └───────────────┘ │ parent state │ * │ └───────────────┘ * NO * │ * │ ┌─────────────────────────────┐ * └─────▶│posix_spawn explicit enable? │ * └──┬─────────────┬────────────┘ * │ │ * │ │ * YES NO * │ │ ┌──────────────────────────────────┐ * ┌───────────────┐ │ └──▶│ hardened-process entitlement or │ * │ Enable MTE │◀────┘ │ (1p && DriverKit entitlement)? │ * └───────┬───────┘ └───────────┬─────────────┬────────┘ * │ YES NO * ┌───────▼───────┐ │ │ * │ Configure MTE │ ┌──────────▼────┐ ┌────▼─────────┐ * │ through │ │ Enable MTE │ │ Disable MTE │ * │ posix_spawn │ └──────────┬────┘ └──────────────┘ * │ flags │ │ * └───────────────┘ ┌──────────▼────┐ * │ Configure MTE │ * │ through │ * │ entitlements │ * └───────────────┘ * * * The above algorithm covers the decision of enabling checked-allocations but doesn't * cover the configuration options which are described later. * * This function returns false only in case POSIX_SPAWN_SECFLAG_EXPLICIT_REQUIRE_ENABLE is passed * and the binary fails to satisfy the requirement. */ static inline errno_t imgact_setup_sec(struct image_params *imgp, __unused load_result_t *load_result, task_t old_task, task_t new_task, __unused vm_map_t new_map, __unused proc_t new_proc) { #if HAS_MTE /* Nothing to do if we have disabled MTE for userspace programs */ if (!mte_user_enabled()) { EXEC_LOG("MTE enablement is skipped due to system-wide disablement\n"); return 0; } #endif /* HAS_MTE */ #if HAS_MTE_EMULATION_SHIMS /* Ignore any emulation attempt if we are not running under Rosetta. */ if ((imgp->ip_flags & (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA)) == 0) { return 0; } #endif /* HAS_MTE_EMULATION_SHIMS */ /* Reset to a clear view on the target task - we'll decide the configuration here. */ task_clear_sec(new_task); task_clear_sec_policy(new_task); /* * If the parent has sec inherit, propagate the security settings. * Inheritance is currently aimed only at debug sessions and will trump * any existing configuration. Inheritance should be seen as the same posix_spawn * flags used to enable it (+ configure the feature) re-applied over and over on * every descendant. */ if (task_has_sec_inherit(old_task)) { EXEC_LOG("Task will be configured based on inheritance\n"); /* Inheritance propagates to the next task. */ task_set_sec_inherit(new_task); if (task_has_sec(old_task)) { task_set_sec(new_task); #if DEVELOPMENT || DEBUG config_sec_inheritance(old_task, new_task); #endif /* DEVELOPMENT || DEBUG */ } return 0; } #if HAS_MTE struct cs_blob* cs_blob = csvnode_get_blob(imgp->ip_vp, imgp->ip_arch_offset); #endif /* HAS_MTE */ /* Check posix_spawn flags now if any */ struct _posix_spawnattr *px_sa = imgp->ip_px_sa; if (px_sa != NULL) { #if DEVELOPMENT || DEBUG /* * Do we have a request to explicitly disable? */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_DISABLE) != 0) { EXEC_LOG("Task configured to disable the security feature due to posix_spawn\n"); /* For A/B testing, allow DISABLE to propagate through inheritance. */ config_sec_spawnflags(load_result, px_sa, new_task); /* Clear we were, clear we stay. */ return 0; } #endif /* DEVELOPMENT || DEBUG */ /* Do we have a request to explicitly enable? */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE) != 0) { EXEC_LOG("Task is explicitly enabled via posix_spawn flags\n"); task_set_sec(new_task); config_sec_spawnflags(load_result, px_sa, new_task); #if HAS_MTE /* Configure tagging of user data allocations */ config_sec_user_data(imgp, load_result, new_task, cs_blob); #endif /* HAS_MTE */ return 0; } #if HAS_MTE /* Do we have a request to enforce that the target is properly entitled? */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_REQUIRE_ENABLE) != 0) { if (!load_result->hardened_process_version) { EXEC_LOG("Caller requested the explicit presence of the hardened-process entitlement" " which the binary doesn't have\n"); return EINVAL; } /* FALLTHROUGH to entitlement evaluation */ } #endif /* HAS_MTE */ } #if HAS_MTE #if DEVELOPMENT || DEBUG /* Runtime options solely affect entitlement-driven choices. */ if (!mte_user_enabled()) { /* Clear we were, clear we stay. */ return 0; } #endif /* DEVELOPMENT || DEBUG */ switch (imgact_setup_has_checked_allocations_entitlement(imgp, load_result, new_task, cs_blob)) { case EXEC_SECURITY_INVALID_CONFIG: EXEC_LOG("Invalid configuration detected\n"); return EINVAL; case EXEC_SECURITY_ENTITLED: EXEC_LOG("Task is explicitly configured via entitlements\n"); task_set_sec(new_task); return config_checked_allocations_entitlements(imgp, load_result, new_task, cs_blob, new_proc); case EXEC_SECURITY_NOT_ENTITLED: #if DEVELOPMENT || DEBUG /* Last chance: everything 1p is force-enabled. */ if (mte_force_all_enabled() && load_result->platform_binary) { EXEC_LOG("Task is explicitly configured via enable-all boot-arg\n"); task_set_sec(new_task); } #endif /* DEVELOPMENT || DEBUG */ return 0; default: panic("Invalid return value from entitlement evaluation"); } #endif /* HAS_MTE */ return 0; } /* * MTE/Checked-allocation configuration. * * There are three configuration vectors: inheritance, posix_spawn flags and entitlements. * Each of the functions below covers one configuration vector. * * Configuration vectors are designed to be exclusive when it comes to define how the * feature will behave. This means that if configurations happens through inheritance, * it will trump any posix_spawn flag or entitlement and if it happens through * posix_spawn flag, it will trump entitlements. * * Inheritance is provided as a dev feature and needs to be explicitly "enabled" via posix_spawn. * Just like posix_spawn, it's not allowed to downgrade MTE state. * * While there are several posix_spawn flags, the majority of them is again only for * DEVELOPMENT || DEBUG. Only flags that do not _decrease_ the security posture of the * target are supported in production (essentially, only flags that _enable_ features). * posix_spawn flags are also the only way to control the emulation of MTE via the * readiness tool based on Rosetta. * * Entitlements are the expected and preferred way to configure MTE/checked-allocations * for the system. They are not supported for the Rosetta based emulation. */ #if DEVELOPMENT || DEBUG static inline void config_sec_inheritance(task_t current, task_t new_task) { /* Configure the target task based on current task */ if (task_has_sec_never_check(current)) { task_set_sec_never_check(new_task); vm_map_set_sec_disabled(get_task_map(new_task)); } if (task_has_sec_user_data(current)) { task_set_sec_user_data(new_task); } /* Allow soft-mode to propagate for internal testing */ if (task_has_sec_soft_mode(current)) { task_set_sec_soft_mode(new_task); } } #endif /* DEVELOPMENT || DEBUG */ static inline void config_sec_spawnflags(load_result_t *load_result, struct _posix_spawnattr *px_sa, task_t new_task) { /* We cannot be here if there were no posix_spawn attributes */ assert(px_sa); /* * Most configurations are not available on RELEASE, but we need to * allow inheritance for Xcode debugging workflows. */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE_INHERIT) != 0) { EXEC_LOG("Task explicitly enables inheritance via posix_spawn flags\n"); task_set_sec_inherit(new_task); } /* * On both RELEASE and DEVELOPMENT, we allow preflighting MTE through * posix spawn flags: unlike POSIX_SPAWN_SECFLAG_EXPLICIT_CHECK_BYPASS, * with POSIX_SPAWN_SECFLAG_EXPLICIT_PREFLIGHT we only allow turning * on soft mode if the process is not a hardened process. */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_PREFLIGHT) != 0) { if (!load_result->hardened_process_version) { EXEC_LOG("Task explicitly enables soft-mode preflight via posix_spawn flags\n"); task_set_sec_soft_mode(new_task); } } #if DEVELOPMENT || DEBUG if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_ENABLE_PURE_DATA) != 0) { EXEC_LOG("Task explicitly enables userspace coverage via posix_spawn flags\n"); task_set_sec_user_data(new_task); } /* Allow testing of soft-mode via posix_spawn */ if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_CHECK_BYPASS) != 0) { EXEC_LOG("Task explicitly enables soft-mode via posix_spawn flags\n"); task_set_sec_soft_mode(new_task); } if ((px_sa->psa_sec_flags & POSIX_SPAWN_SECFLAG_EXPLICIT_NEVER_CHECK_ENABLE) != 0) { task_set_sec_never_check(new_task); vm_map_set_sec_disabled(get_task_map(new_task)); } #endif /* DEVELOPMENT || DEBUG */ } #if HAS_MTE static inline void config_sec_user_data(struct image_params *imgp, load_result_t *load_result, task_t new_task, __unused struct cs_blob *cs_blob) { exec_security_err_t ret = EXEC_SECURITY_INVALID_CONFIG; bool enable_user_data = false; bool explicit_opt_out = false; uint8_t hardened_proc_vers = load_result->hardened_process_version; if (!mte_user_data_enabled()) { return; } if (load_result->platform_binary) { /* For platform binaries, check the negative entitlement */ ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS_DISABLE_PURE_DATA); assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED); if (ret == EXEC_SECURITY_ENTITLED) { EXEC_LOG("Disabling user data tagging via entitlement"); explicit_opt_out = true; } /* * If there are no explicit opt outs, we enable user data tagging * by default for platform binaries. */ enable_user_data = !explicit_opt_out; } else { /* * For non-platform binaries, we enable data tagging by default, if * they are hardened-process. */ if (hardened_proc_vers >= HARDENED_PROCESS_VERSION_ONE) { EXEC_LOG("Enabling user data tagging 3P binary"); enable_user_data = true; } } if (enable_user_data) { task_set_sec_user_data(new_task); } } static inline errno_t config_checked_allocations_entitlements(struct image_params *imgp, __unused load_result_t *load_result, task_t new_task, __unused struct cs_blob *cs_blob, __unused proc_t new_proc) { /* Configure tagging of user data allocations */ config_sec_user_data(imgp, load_result, new_task, cs_blob); /* * Check whether we need to restrict receiving aliases to MTE memory (which are, by policy, * untagged) from other actors. */ exec_security_err_t ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS_NO_TAGGED_RECEIVE); assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED); if (ret == EXEC_SECURITY_ENTITLED) { EXEC_LOG("Restricting receiving aliases to tagged memory due to entitlement\n"); task_set_sec_restrict_receiving_aliases_to_tagged_memory(new_task); } ret = exec_check_security_entitlement(imgp, CHECKED_ALLOCATIONS_SOFT_MODE); assert(ret == EXEC_SECURITY_ENTITLED || ret == EXEC_SECURITY_NOT_ENTITLED); /* * All 1p processes run in hard-mode in lockdown mode, regardless of their * entitlement configuration. */ if (load_result->platform_binary && get_lockdown_mode_state() != 0) { ret = EXEC_SECURITY_NOT_ENTITLED; } if (ret == EXEC_SECURITY_ENTITLED) { EXEC_LOG("Enabling soft-mode from entitlement\n"); task_set_sec_soft_mode(new_task); } return EXEC_SECURITY_NOT_ENTITLED; } #endif /* HAS_MTE */ #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */ static inline errno_t imgact_setup_guard_objects(struct image_params *imgp, load_result_t *load_result, task_t task) { exec_security_err_t ret = exec_check_security_entitlement(imgp, NO_GUARD_OBJECTS); if (ret == EXEC_SECURITY_NOT_ENTITLED) { /* apply guard objects entitlement if hardened-process and not disabled */ if (load_result->hardened_process_version >= HARDENED_PROCESS_VERSION_TWO) { task_set_guard_objects(task); return 0; } /* force-enroll 1p driverkit drivers */ if (load_result->platform_binary && IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, kIODriverKitEntitlementKey)) { task_set_guard_objects(task); return 0; } } task_clear_guard_objects(task); if (ret == EXEC_SECURITY_INVALID_CONFIG) { return EINVAL; } return 0; } /* * This routine configures the various runtime mitigations we can apply to a process * during image activation. This occurs before `imgact_setup_runtime_mitigations` * * Returns true on success, false on failure. Failure will be fatal in exec_mach_imgact(). */ static inline errno_t imgact_setup_runtime_mitigations(struct image_params *imgp, __unused load_result_t *load_result, __unused task_t old_task, task_t new_task, __unused vm_map_t map, __unused proc_t proc) { /* Set hardened process version */ task_set_hardened_process_version(new_task, load_result->hardened_process_version); /* * It's safe to check entitlements anytime after `load_machfile` if you check * based on the vnode in imgp. We must perform this entitlement check * before we start using load_result->hardened_browser further down */ load_result->hardened_browser = 0; encode_HR_entitlement(kCSWebBrowserHostEntitlement, BrowserHostEntitlementMask, imgp, load_result); encode_HR_entitlement(kCSWebBrowserGPUEntitlement, BrowserGPUEntitlementMask, imgp, load_result); encode_HR_entitlement(kCSWebBrowserNetworkEntitlement, BrowserNetworkEntitlementMask, imgp, load_result); encode_HR_entitlement(kCSWebBrowserWebContentEntitlement, BrowserWebContentEntitlementMask, imgp, load_result); if (load_result->hardened_browser) { task_set_platform_restrictions_version(new_task, 1); } errno_t retval = 0; /* * Hardened-heap enables a set of extra security features in our system memory allocator. */ if ((retval = imgact_setup_hardened_heap(imgp, new_task)) != 0) { EXEC_LOG("Invalid configuration detected for hardened-heap"); return retval; } /* * Script-Restrictions enables protections around script usage in the process. */ if ((retval = imgact_setup_script_restrictions(imgp, new_task)) != 0) { EXEC_LOG("Invalid configuration detected for script-restrictions"); return retval; } /* * Platform-Restrictions enables a grab bag of various kernel mitigations * including IPC security restrictions. */ if ((retval = imgact_setup_platform_restrictions(imgp, load_result, new_task)) != 0) { EXEC_LOG("Invalid configuration detected for platform-restrictions"); return retval; } #if HAS_MTE || HAS_MTE_EMULATION_SHIMS /* * Sec-shims a.k.a. checked-allocations a.k.a. MTE (due to several hoops around secrecy) * control whether the target process system allocators leverage MTE or not to provide * further security mitigations. */ if ((retval = imgact_setup_sec(imgp, load_result, old_task, new_task, map, proc)) != 0) { EXEC_LOG("Invalid configuration detected for the security shim"); return retval; } #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */ /* Pipe through the IPC containment vessel entitlement state from the load result */ if (load_result->is_ipc_containment_vessel) { EXEC_LOG("Enabling IPC-specific containment vessel restrictions as the load result carried the relevant flag.\n"); task_set_ipc_containment_vessel(new_task); } else { task_clear_ipc_containment_vessel(new_task); } /* * No-guard-objects disables guards for process deallocated allocations or VM. */ if ((retval = imgact_setup_guard_objects(imgp, load_result, new_task)) != 0) { EXEC_LOG("Invalid configuration detected for no-guard-objects"); return retval; } return retval; } uint32_t rsr_get_version(void) { return os_atomic_load(&rsr_current_version, relaxed); } void rsr_bump_version(void) { os_atomic_inc(&rsr_current_version, relaxed); } #if XNU_TARGET_OS_OSX static int rsr_version_sysctl SYSCTL_HANDLER_ARGS { #pragma unused(arg1, arg2, oidp) int value = rsr_get_version(); int error = SYSCTL_OUT(req, &value, sizeof(int)); if (error) { return error; } if (!req->newptr) { return 0; } error = SYSCTL_IN(req, &value, sizeof(int)); if (error) { return error; } if (value != 0) { rsr_bump_version(); } return 0; } SYSCTL_PROC(_vm, OID_AUTO, shared_region_control, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED, 0, 0, rsr_version_sysctl, "I", ""); #endif /* XNU_TARGET_OS_OSX */ /* * exec_mach_imgact * * Image activator for mach-o 1.0 binaries. * * Parameters; struct image_params * image parameter block * * Returns: -1 not a fat binary (keep looking) * -2 Success: encapsulated binary: reread * >0 Failure: error number * EBADARCH Mach-o binary, but with an unrecognized * architecture * ENOMEM No memory for child process after - * can only happen after vfork() * * Important: This image activator is NOT byte order neutral. * * Note: A return value other than -1 indicates subsequent image * activators should not be given the opportunity to attempt * to activate the image. */ static int exec_mach_imgact(struct image_params *imgp) { struct mach_header *mach_header = (struct mach_header *)imgp->ip_vdata; proc_t p = vfs_context_proc(imgp->ip_vfs_context); int error = 0; task_t task; task_t new_task = NULL; /* protected by vfexec */ thread_t thread; struct uthread *uthread; vm_map_switch_context_t switch_ctx; vm_map_t old_map = VM_MAP_NULL; vm_map_t map = VM_MAP_NULL; load_return_t lret; load_result_t load_result = {}; struct _posix_spawnattr *psa = NULL; int spawn = (imgp->ip_flags & IMGPF_SPAWN); const int vfexec = 0; int exec = (imgp->ip_flags & IMGPF_EXEC); os_reason_t exec_failure_reason = OS_REASON_NULL; boolean_t reslide = FALSE; char * userspace_coredump_name = NULL; /* * make sure it's a Mach-O 1.0 or Mach-O 2.0 binary; the difference * is a reserved field on the end, so for the most part, we can * treat them as if they were identical. Reverse-endian Mach-O * binaries are recognized but not compatible. */ if ((mach_header->magic == MH_CIGAM) || (mach_header->magic == MH_CIGAM_64)) { error = EBADARCH; goto bad; } if ((mach_header->magic != MH_MAGIC) && (mach_header->magic != MH_MAGIC_64)) { error = -1; goto bad; } if (mach_header->filetype != MH_EXECUTE) { error = -1; goto bad; } if (imgp->ip_origcputype != 0) { /* Fat header previously had an idea about this thin file */ if (imgp->ip_origcputype != mach_header->cputype || imgp->ip_origcpusubtype != mach_header->cpusubtype) { error = EBADARCH; goto bad; } } else { imgp->ip_origcputype = mach_header->cputype; imgp->ip_origcpusubtype = mach_header->cpusubtype; } task = current_task(); thread = current_thread(); uthread = get_bsdthread_info(thread); if ((mach_header->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64) { imgp->ip_flags |= IMGPF_IS_64BIT_ADDR | IMGPF_IS_64BIT_DATA; } /* If posix_spawn binprefs exist, respect those prefs. */ psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa != NULL && psa->psa_binprefs[0] != 0) { int pr = 0; for (pr = 0; pr < NBINPREFS; pr++) { cpu_type_t pref = psa->psa_binprefs[pr]; cpu_subtype_t subpref = psa->psa_subcpuprefs[pr]; if (pref == 0) { /* No suitable arch in the pref list */ error = EBADARCH; goto bad; } if (pref == CPU_TYPE_ANY) { /* Jump to regular grading */ goto grade; } if (binary_match(CPU_ARCH_MASK, pref, subpref, imgp->ip_origcputype, imgp->ip_origcpusubtype)) { goto grade; } } error = EBADARCH; goto bad; } grade: if (!grade_binary(imgp->ip_origcputype, imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK, imgp->ip_origcpusubtype & CPU_SUBTYPE_MASK, TRUE)) { error = EBADARCH; goto bad; } if (validate_potential_simulator_binary(imgp->ip_origcputype, imgp, imgp->ip_arch_offset, imgp->ip_arch_size) != LOAD_SUCCESS) { #if __x86_64__ const char *excpath; error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath); os_log_error(OS_LOG_DEFAULT, "Unsupported 32-bit executable: \"%s\"", (error) ? imgp->ip_vp->v_name : excpath); #endif error = EBADARCH; goto bad; } #if defined(HAS_APPLE_PAC) assert(mach_header->cputype == CPU_TYPE_ARM64 ); if ((mach_header->cputype == CPU_TYPE_ARM64 && arm64_cpusubtype_uses_ptrauth(mach_header->cpusubtype)) ) { imgp->ip_flags &= ~IMGPF_NOJOP; } else { imgp->ip_flags |= IMGPF_NOJOP; } #endif /* Copy in arguments/environment from the old process */ error = exec_extract_strings(imgp); if (error) { goto bad; } AUDIT_ARG(argv, imgp->ip_startargv, imgp->ip_argc, imgp->ip_endargv - imgp->ip_startargv); AUDIT_ARG(envv, imgp->ip_endargv, imgp->ip_envc, imgp->ip_endenvv - imgp->ip_endargv); /* reset local idea of thread, uthread, task */ thread = imgp->ip_new_thread; uthread = get_bsdthread_info(thread); task = new_task = get_threadtask(thread); /* * Load the Mach-O file. * * NOTE: An error after this point indicates we have potentially * destroyed or overwritten some process state while attempting an * execve() following a vfork(), which is an unrecoverable condition. * We send the new process an immediate SIGKILL to avoid it executing * any instructions in the mutated address space. For true spawns, * this is not the case, and "too late" is still not too late to * return an error code to the parent process. */ /* * Actually load the image file we previously decided to load. */ lret = load_machfile(imgp, mach_header, thread, &map, &load_result); if (lret != LOAD_SUCCESS) { error = load_return_to_errno(lret); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO, 0, 0); if (lret == LOAD_BADMACHO_UPX) { set_proc_name(imgp, p); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_UPX); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } else { exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } } exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE; goto badtoolate; } assert(imgp->ip_free_map == NULL); /* * ERROR RECOVERY * * load_machfile() returned the new VM map ("map") but we haven't * committed to it yet. * Any error path between here and the point where we commit to using * the new "map" (with swap_task_map()) should deallocate "map". */ #ifndef KASAN /* * Security: zone sanity checks on fresh boot or initproc re-exec. * launchd by design does not tear down its own service port on USR (rdar://72797967), * which means here is the earliest point we can assert on empty service port label zone, * after load_machfile() above terminates old launchd's IPC space. * * Disable on KASAN builds since zone_size_allocated() accounts for elements * under quarantine. */ if (task_pid(task) == 1) { zone_userspace_reboot_checks(); } #endif proc_lock(p); p->p_cputype = imgp->ip_origcputype; p->p_cpusubtype = imgp->ip_origcpusubtype; proc_setplatformdata(p, load_result.ip_platform, load_result.lr_min_sdk, load_result.lr_sdk); vm_map_set_size_limit(map, proc_limitgetcur(p, RLIMIT_AS)); vm_map_set_data_limit(map, proc_limitgetcur(p, RLIMIT_DATA)); vm_map_set_user_wire_limit(map, (vm_size_t)proc_limitgetcur(p, RLIMIT_MEMLOCK)); #if XNU_TARGET_OS_OSX if (proc_platform(p) == PLATFORM_IOS) { assert(vm_map_is_alien(map)); } else { assert(!vm_map_is_alien(map)); } #endif /* XNU_TARGET_OS_OSX */ proc_unlock(p); /* * Setup runtime mitigations. */ if ((error = imgact_setup_runtime_mitigations(imgp, &load_result, current_task(), new_task, map, p)) != 0) { set_proc_name(imgp, p); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO); if (bootarg_execfailurereports) { exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE; } /* release new address space since we won't use it */ imgp->ip_free_map = map; map = VM_MAP_NULL; goto badtoolate; } /* * Set code-signing flags if this binary is signed, or if parent has * requested them on exec. */ if (load_result.csflags & CS_VALID) { imgp->ip_csflags |= load_result.csflags & (CS_VALID | CS_SIGNED | CS_DEV_CODE | CS_LINKER_SIGNED | CS_HARD | CS_KILL | CS_RESTRICT | CS_ENFORCEMENT | CS_REQUIRE_LV | CS_FORCED_LV | CS_ENTITLEMENTS_VALIDATED | CS_NO_UNTRUSTED_HELPERS | CS_RUNTIME | CS_ENTITLEMENT_FLAGS | CS_EXEC_SET_HARD | CS_EXEC_SET_KILL | CS_EXEC_SET_ENFORCEMENT); } else { imgp->ip_csflags &= ~CS_VALID; } if (proc_getcsflags(p) & CS_EXEC_SET_HARD) { imgp->ip_csflags |= CS_HARD; } if (proc_getcsflags(p) & CS_EXEC_SET_KILL) { imgp->ip_csflags |= CS_KILL; } if (proc_getcsflags(p) & CS_EXEC_SET_ENFORCEMENT) { imgp->ip_csflags |= CS_ENFORCEMENT; } if (proc_getcsflags(p) & CS_EXEC_INHERIT_SIP) { if (proc_getcsflags(p) & CS_INSTALLER) { imgp->ip_csflags |= CS_INSTALLER; } if (proc_getcsflags(p) & CS_DATAVAULT_CONTROLLER) { imgp->ip_csflags |= CS_DATAVAULT_CONTROLLER; } if (proc_getcsflags(p) & CS_NVRAM_UNRESTRICTED) { imgp->ip_csflags |= CS_NVRAM_UNRESTRICTED; } } #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) /* * ptrauth version 0 is a preview ABI. Developers can opt into running * their own arm64e binaries for local testing, with the understanding * that future OSes may break ABI. */ if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E && CPU_SUBTYPE_ARM64_PTR_AUTH_VERSION(imgp->ip_origcpusubtype) == 0 && !load_result.platform_binary && !bootarg_arm64e_preview_abi) { static bool logged_once = false; set_proc_name(imgp, p); printf("%s: not running binary \"%s\" built against preview arm64e ABI\n", __func__, p->p_name); if (!os_atomic_xchg(&logged_once, true, relaxed)) { printf("%s: (to allow this, add \"-arm64e_preview_abi\" to boot-args)\n", __func__); } exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO); if (bootarg_execfailurereports) { exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE; } /* release new address space since we won't use it */ imgp->ip_free_map = map; map = VM_MAP_NULL; goto badtoolate; } if ((imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) != CPU_SUBTYPE_ARM64E && imgp->ip_origcputype == CPU_TYPE_ARM64 && load_result.platform_binary && (imgp->ip_flags & IMGPF_DRIVER) != 0) { set_proc_name(imgp, p); printf("%s: disallowing arm64 platform driverkit binary \"%s\", should be arm64e\n", __func__, p->p_name); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_MACHO); if (bootarg_execfailurereports) { exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE; } /* release new address space since we won't use it */ imgp->ip_free_map = map; map = VM_MAP_NULL; goto badtoolate; } #endif /* __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) */ /* * Set up the shared cache region in the new process. * * Normally there is a single shared region per architecture. * However on systems with Pointer Authentication, we can create * multiple shared caches with the amount of sharing determined * by team-id or entitlement. Inherited shared region IDs are used * for system processes that need to match and be able to inspect * a pre-existing task. */ int cpu_subtype = 0; /* all cpu_subtypes use the same shared region */ #if __has_feature(ptrauth_calls) char *shared_region_id = NULL; size_t len; char *base; const char *cbase; #define HARDENED_RUNTIME_CONTENT_ID "C-" #define TEAM_ID_PREFIX "T-" #define ENTITLE_PREFIX "E-" #define SR_PREFIX_LEN 2 #define SR_ENTITLEMENT "com.apple.pac.shared_region_id" if (cpu_type() == CPU_TYPE_ARM64 && arm64_cpusubtype_uses_ptrauth(p->p_cpusubtype) && (imgp->ip_flags & IMGPF_NOJOP) == 0) { assertf(p->p_cputype == CPU_TYPE_ARM64, "p %p cpu_type() 0x%x p->p_cputype 0x%x p->p_cpusubtype 0x%x", p, cpu_type(), p->p_cputype, p->p_cpusubtype); /* * arm64e uses pointer authentication, so request a separate * shared region for this CPU subtype. */ cpu_subtype = p->p_cpusubtype & ~CPU_SUBTYPE_MASK; /* * Determine which shared cache to select based on being told, * matching a team-id or matching an entitlement. */ if (load_result.hardened_browser & BrowserWebContentEntitlementMask) { len = sizeof(HARDENED_RUNTIME_CONTENT_ID); shared_region_id = kalloc_data(len, Z_WAITOK | Z_NOFAIL); strlcpy(shared_region_id, HARDENED_RUNTIME_CONTENT_ID, len); } else if (imgp->ip_inherited_shared_region_id) { len = strlen(imgp->ip_inherited_shared_region_id); shared_region_id = kalloc_data(len + 1, Z_WAITOK | Z_NOFAIL); memcpy(shared_region_id, imgp->ip_inherited_shared_region_id, len + 1); } else if ((cbase = get_teamid_for_shared_region(imgp)) != NULL) { len = strlen(cbase); if (vm_shared_region_per_team_id) { shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1, Z_WAITOK | Z_NOFAIL); memcpy(shared_region_id, TEAM_ID_PREFIX, SR_PREFIX_LEN); memcpy(shared_region_id + SR_PREFIX_LEN, cbase, len + 1); } } else if ((base = IOVnodeGetEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, SR_ENTITLEMENT)) != NULL) { len = strlen(base); if (vm_shared_region_by_entitlement) { shared_region_id = kalloc_data(len + SR_PREFIX_LEN + 1, Z_WAITOK | Z_NOFAIL); memcpy(shared_region_id, ENTITLE_PREFIX, SR_PREFIX_LEN); memcpy(shared_region_id + SR_PREFIX_LEN, base, len + 1); } /* Discard the copy of the entitlement */ kfree_data(base, len + 1); } } if (imgp->ip_flags & IMGPF_RESLIDE) { reslide = TRUE; } /* use "" as the default shared_region_id */ if (shared_region_id == NULL) { shared_region_id = kalloc_data(1, Z_WAITOK | Z_ZERO | Z_NOFAIL); } /* ensure there's a unique pointer signing key for this shared_region_id */ shared_region_key_alloc(shared_region_id, imgp->ip_inherited_shared_region_id != NULL, imgp->ip_inherited_jop_pid); task_set_shared_region_id(task, shared_region_id); shared_region_id = NULL; #endif /* __has_feature(ptrauth_calls) */ #if CONFIG_ROSETTA if (imgp->ip_flags & IMGPF_ROSETTA) { OSBitOrAtomic(P_TRANSLATED, &p->p_flag); } else if (p->p_flag & P_TRANSLATED) { OSBitAndAtomic(~P_TRANSLATED, &p->p_flag); } #endif int cputype = cpu_type(); uint32_t rsr_version = 0; #if XNU_TARGET_OS_OSX if (vnode_is_rsr(imgp->ip_vp)) { rsr_version = rsr_get_version(); os_atomic_or(&p->p_ladvflag, P_RSR, relaxed); os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALTLINK, relaxed); } #endif /* XNU_TARGET_OS_OSX */ error = vm_map_exec(map, task, load_result.is_64bit_addr, (void *)p->p_fd.fd_rdir, cputype, cpu_subtype, reslide, (imgp->ip_flags & IMGPF_DRIVER) != 0, rsr_version); if (error) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAP_EXEC_FAILURE, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAP_EXEC_FAILURE); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; exec_failure_reason->osr_flags |= OS_REASON_FLAG_CONSISTENT_FAILURE; } /* release new address space since we won't use it */ imgp->ip_free_map = map; map = VM_MAP_NULL; goto badtoolate; } /* * Close file descriptors which specify close-on-exec. */ fdt_exec(p, vfs_context_ucred(imgp->ip_vfs_context), psa != NULL ? psa->psa_flags : 0, imgp->ip_new_thread, exec); /* * deal with set[ug]id. */ error = exec_handle_sugid(imgp); if (error) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SUGID_FAILURE); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } /* release new address space since we won't use it */ imgp->ip_free_map = map; map = VM_MAP_NULL; goto badtoolate; } /* * Commit to new map. * * Swap the new map for the old for target task, which consumes * our new map reference but each leaves us responsible for the * old_map reference. That lets us get off the pmap associated * with it, and then we can release it. * * The map needs to be set on the target task which is different * than current task, thus swap_task_map is used instead of * vm_map_switch. */ old_map = swap_task_map(task, thread, map); #if MACH_ASSERT /* * Reset the pmap's process info to prevent ledger checks * which might fail due to the ledgers being shared between * the old and new pmaps. */ vm_map_pmap_set_process(old_map, -1, "<old_map>"); #endif /* MACH_ASSERT */ imgp->ip_free_map = old_map; old_map = NULL; lret = activate_exec_state(task, p, thread, &load_result); if (lret != KERN_SUCCESS) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_ACTV_THREADSTATE); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } /* * deal with voucher on exec-calling thread. */ if (imgp->ip_new_thread == NULL) { thread_set_mach_voucher(current_thread(), IPC_VOUCHER_NULL); } /* Make sure we won't interrupt ourself signalling a partial process */ if (!vfexec && !spawn && (p->p_lflag & P_LTRACED)) { psignal(p, SIGTRAP); } if (load_result.unixproc && create_unix_stack(get_task_map(task), &load_result, p) != KERN_SUCCESS) { error = load_return_to_errno(LOAD_NOSPACE); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_STACK_ALLOC); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } /* * The load result will have already been munged by AMFI to include the * platform binary flag if boot-args dictated it (AMFI will mark anything * that doesn't go through the upcall path as a platform binary if its * enforcement is disabled). */ if (load_result.platform_binary) { if (cs_debug) { printf("setting platform binary on task: pid = %d\n", proc_getpid(p)); } /* * We must use 'task' here because the proc's task has not yet been * switched to the new one. */ task_set_platform_binary(task, TRUE); } else { if (cs_debug) { printf("clearing platform binary on task: pid = %d\n", proc_getpid(p)); } task_set_platform_binary(task, FALSE); } #if XNU_TARGET_OS_OSX /* Disable mach hardening for all 1P tasks which load 3P plugins */ if (imgp->ip_flags & IMGPF_3P_PLUGINS) { if (cs_debug) { printf("Disabling some mach hardening on task due to 3P plugins: pid = %d\n", proc_getpid(p)); } task_disable_mach_hardening(task); } #if DEVELOPMENT || DEBUG /* Disable mach hardening for all tasks if amfi_get_out_of_my_way is set. * Customers will have to turn SIP off to use this boot-arg, and so this is * only needed internally since we disable this feature when SIP is off. */ if (AMFI_bootarg_disable_mach_hardening) { if (cs_debug) { printf("Disabling some mach hardening on task due to AMFI boot-args: pid = %d\n", proc_getpid(p)); } task_disable_mach_hardening(task); } #endif /* DEVELOPMENT || DEBUG */ #endif /* XNU_TARGET_OS_OSX */ error = exec_add_apple_strings(imgp, &load_result, task); /* copies out main thread port */ if (error) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_APPLE_STRING_INIT); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } /* Switch to target task's map to copy out strings */ switch_ctx = vm_map_switch_to(get_task_map(task)); if (load_result.unixproc) { user_addr_t ap; /* * Copy the strings area out into the new process address * space. */ ap = p->user_stack; error = exec_copyout_strings(imgp, &ap); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_STRINGS); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } /* Set the stack */ thread_setuserstack(thread, ap); } if (load_result.dynlinker || load_result.is_rosetta) { user_addr_t ap; int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4; /* Adjust the stack */ ap = thread_adjuserstack(thread, -new_ptr_size); error = copyoutptr(load_result.mach_header, ap, new_ptr_size); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_DYNLINKER); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } error = task_set_dyld_info(task, load_result.all_image_info_addr, load_result.all_image_info_size, false); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } error = EINVAL; goto badtoolate; } } else { /* * No dyld or rosetta loaded, set the TF_DYLD_ALL_IMAGE_FINAL bit on task. */ error = task_set_dyld_info(task, MACH_VM_MIN_ADDRESS, 0, true); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SET_DYLD_INFO); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } error = EINVAL; goto badtoolate; } } #if CONFIG_ROSETTA if (load_result.is_rosetta) { // Add an fd for the executable file for Rosetta's use int main_binary_fd; struct fileproc *fp; error = falloc_exec(p, imgp->ip_vfs_context, &fp, &main_binary_fd); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto badtoolate; } error = VNOP_OPEN(imgp->ip_vp, FREAD, imgp->ip_vfs_context); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MAIN_FD_ALLOC); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto cleanup_rosetta_fp; } fp->fp_glob->fg_flag = FREAD; fp->fp_glob->fg_ops = &vnops; fp_set_data(fp, imgp->ip_vp); vnode_ref(imgp->ip_vp); // Pass the dyld load address, main binary fd, and dyld fd on the stack uint64_t ap = thread_adjuserstack(thread, -24); error = copyoutptr((user_addr_t)load_result.dynlinker_fd, ap, 8); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto cleanup_rosetta_fp; } error = copyoutptr(load_result.dynlinker_mach_header, ap + 8, 8); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto cleanup_rosetta_fp; } error = copyoutptr((user_addr_t)main_binary_fd, ap + 16, 8); if (error) { vm_map_switch_back(switch_ctx); KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_COPYOUT_ROSETTA); if (bootarg_execfailurereports) { set_proc_name(imgp, p); exec_failure_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT; } goto cleanup_rosetta_fp; } /* Release file descriptor to userspace, from this point * ownership of the main_binary_fd is given to userspace */ proc_fdlock(p); procfdtbl_releasefd(p, main_binary_fd, NULL); fp_drop(p, main_binary_fd, fp, 1); proc_fdunlock(p); cleanup_rosetta_fp: if (error) { fp_free(p, load_result.dynlinker_fd, load_result.dynlinker_fp); fp_free(p, main_binary_fd, fp); goto badtoolate; } } #endif /* Avoid immediate VM faults back into kernel */ exec_prefault_data(p, imgp, &load_result); vm_map_switch_back(switch_ctx); /* * Reset signal state. */ execsigs(p, thread); /* * need to cancel async IO requests that can be cancelled and wait for those * already active. MAY BLOCK! */ _aio_exec( p ); #if SYSV_SHM /* FIXME: Till vmspace inherit is fixed: */ if (!vfexec && p->vm_shm) { shmexec(p); } #endif #if SYSV_SEM /* Clean up the semaphores */ semexit(p); #endif /* * Remember file name for accounting. */ p->p_acflag &= ~AFORK; set_proc_name(imgp, p); #if CONFIG_SECLUDED_MEMORY if (secluded_for_apps && load_result.platform_binary) { if (strncmp(p->p_name, "Camera", sizeof(p->p_name)) == 0) { task_set_could_use_secluded_mem(task, TRUE); } else { task_set_could_use_secluded_mem(task, FALSE); } if (strncmp(p->p_name, "mediaserverd", sizeof(p->p_name)) == 0) { task_set_could_also_use_secluded_mem(task, TRUE); } if (strncmp(p->p_name, "cameracaptured", sizeof(p->p_name)) == 0) { task_set_could_also_use_secluded_mem(task, TRUE); } } #endif /* CONFIG_SECLUDED_MEMORY */ #if __arm64__ if (load_result.legacy_footprint) { task_set_legacy_footprint(task); } #endif /* __arm64__ */ pal_dbg_set_task_name(task); #if DEVELOPMENT || DEBUG /* * Update the pid an proc name for importance base if any */ task_importance_update_owner_info(task); #endif proc_setexecutableuuid(p, &load_result.uuid[0]); #if CONFIG_DTRACE dtrace_proc_exec(p); #endif if (kdebug_enable) { long args[4] = {}; uintptr_t fsid = 0, fileid = 0; if (imgp->ip_vattr) { uint64_t fsid64 = vnode_get_va_fsid(imgp->ip_vattr); fsid = (uintptr_t)fsid64; fileid = (uintptr_t)imgp->ip_vattr->va_fileid; // check for (unexpected) overflow and trace zero in that case if (fsid != fsid64 || fileid != imgp->ip_vattr->va_fileid) { fsid = fileid = 0; } } KERNEL_DEBUG_CONSTANT_IST1(TRACE_DATA_EXEC, proc_getpid(p), fsid, fileid, 0, (uintptr_t)thread_tid(thread)); extern void kdebug_proc_name_args(struct proc *proc, long args[static 4]); kdebug_proc_name_args(p, args); KERNEL_DEBUG_CONSTANT_IST1(TRACE_STRING_EXEC, args[0], args[1], args[2], args[3], (uintptr_t)thread_tid(thread)); } /* * If posix_spawned with the START_SUSPENDED flag, stop the * process before it runs. */ if (imgp->ip_px_sa != NULL) { psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa->psa_flags & POSIX_SPAWN_START_SUSPENDED) { proc_lock(p); p->p_stat = SSTOP; proc_unlock(p); (void) task_suspend_internal(task); } } /* * mark as execed */ OSBitOrAtomic(P_EXEC, &p->p_flag); proc_resetregister(p); if (p->p_pptr && (p->p_lflag & P_LPPWAIT)) { proc_lock(p); p->p_lflag &= ~P_LPPWAIT; proc_unlock(p); wakeup((caddr_t)p->p_pptr); } /* * Set up dext coredumps on kernel panic. * This requires the following: * - dext_panic_coredump=1 boot-arg (enabled by default on DEVELOPMENT, DEBUG and certain Seed builds) * - process must be a driver * - process must have the com.apple.private.enable-coredump-on-panic entitlement, and the * entitlement has a string value. * - process must have the com.apple.private.enable-coredump-on-panic-seed-privacy-approved * entitlement (Seed builds only). * * The core dump file name is formatted with the entitlement string value, followed by a hyphen * and the process PID. */ if (enable_dext_coredumps_on_panic && (imgp->ip_flags & IMGPF_DRIVER) != 0 && (userspace_coredump_name = IOVnodeGetEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, USERSPACE_COREDUMP_PANIC_ENTITLEMENT)) != NULL) { size_t userspace_coredump_name_len = strlen(userspace_coredump_name); char core_name[MACH_CORE_FILEHEADER_NAMELEN]; /* 16 - NULL char - strlen("-") - maximum of 5 digits for pid */ snprintf(core_name, MACH_CORE_FILEHEADER_NAMELEN, "%.9s-%d", userspace_coredump_name, proc_getpid(p)); kern_register_userspace_coredump(task, core_name, FALSE); /* Discard the copy of the entitlement */ kfree_data(userspace_coredump_name, userspace_coredump_name_len + 1); userspace_coredump_name = NULL; } goto done; badtoolate: /* Don't allow child process to execute any instructions */ if (!spawn) { { assert(exec_failure_reason != OS_REASON_NULL); if (bootarg_execfailurereports) { set_proc_name(imgp, current_proc()); } psignal_with_reason(current_proc(), SIGKILL, exec_failure_reason); exec_failure_reason = OS_REASON_NULL; if (exec) { /* Terminate the exec copy task */ task_terminate_internal(task); } } /* We can't stop this system call at this point, so just pretend we succeeded */ error = 0; } else { os_reason_free(exec_failure_reason); exec_failure_reason = OS_REASON_NULL; } done: if (load_result.threadstate) { kfree_data(load_result.threadstate, load_result.threadstate_sz); load_result.threadstate = NULL; } bad: /* If we hit this, we likely would have leaked an exit reason */ assert(exec_failure_reason == OS_REASON_NULL); return error; } /* * Our image activator table; this is the table of the image types we are * capable of loading. We list them in order of preference to ensure the * fastest image load speed. * * XXX hardcoded, for now; should use linker sets */ struct execsw { int(*const ex_imgact)(struct image_params *); const char *ex_name; }const execsw[] = { { exec_mach_imgact, "Mach-o Binary" }, { exec_fat_imgact, "Fat Binary" }, { exec_shell_imgact, "Interpreter Script" }, { NULL, NULL} }; /* * exec_activate_image * * Description: Iterate through the available image activators, and activate * the image associated with the imgp structure. We start with * the activator for Mach-o binaries followed by that for Fat binaries * for Interpreter scripts. * * Parameters: struct image_params * Image parameter block * * Returns: 0 Success * ENOEXEC No activator for image. * EBADEXEC The executable is corrupt/unknown * execargs_alloc:EINVAL Invalid argument * execargs_alloc:EACCES Permission denied * execargs_alloc:EINTR Interrupted function * execargs_alloc:ENOMEM Not enough space * exec_save_path:EFAULT Bad address * exec_save_path:ENAMETOOLONG Filename too long * exec_check_permissions:EACCES Permission denied * exec_check_permissions:ENOEXEC Executable file format error * exec_check_permissions:ETXTBSY Text file busy [misuse of error code] * exec_check_permissions:??? * namei:??? * vn_rdwr:??? [anything vn_rdwr can return] * <ex_imgact>:??? [anything an imgact can return] * EDEADLK Process is being terminated */ static int exec_activate_image(struct image_params *imgp) { struct nameidata *ndp = NULL; const char *excpath; int error; int resid; int once = 1; /* save SGUID-ness for interpreted files */ int i; int itercount = 0; proc_t p = vfs_context_proc(imgp->ip_vfs_context); /* * For exec, the translock needs to be taken on old proc and not * on new shadow proc. */ if (imgp->ip_flags & IMGPF_EXEC) { p = current_proc(); } error = execargs_alloc(imgp); if (error) { goto bad_notrans; } error = exec_save_path(imgp, imgp->ip_user_fname, imgp->ip_seg, &excpath); if (error) { goto bad_notrans; } /* Use excpath, which contains the copyin-ed exec path */ DTRACE_PROC1(exec, uintptr_t, excpath); ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_ZERO | Z_NOFAIL); NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1, UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context); again: error = namei(ndp); if (error) { if (error == ERESTART) { error = EINTR; } goto bad_notrans; } imgp->ip_ndp = ndp; /* successful namei(); call nameidone() later */ imgp->ip_vp = ndp->ni_vp; /* if set, need to vnode_put() at some point */ /* * Before we start the transition from binary A to binary B, make * sure another thread hasn't started exiting the process. We grab * the proc lock to check p_lflag initially, and the transition * mechanism ensures that the value doesn't change after we release * the lock. */ proc_lock(p); if (p->p_lflag & P_LEXIT) { error = EDEADLK; proc_unlock(p); goto bad_notrans; } error = proc_transstart(p, 1, 0); proc_unlock(p); if (error) { goto bad_notrans; } error = exec_check_permissions(imgp); if (error) { goto bad; } /* Copy; avoid invocation of an interpreter overwriting the original */ if (once) { once = 0; *imgp->ip_origvattr = *imgp->ip_vattr; } error = vn_rdwr(UIO_READ, imgp->ip_vp, imgp->ip_vdata, PAGE_SIZE, 0, UIO_SYSSPACE, IO_NODELOCKED, vfs_context_ucred(imgp->ip_vfs_context), &resid, vfs_context_proc(imgp->ip_vfs_context)); if (error) { goto bad; } if (resid) { memset(imgp->ip_vdata + (PAGE_SIZE - resid), 0x0, resid); } encapsulated_binary: /* Limit the number of iterations we will attempt on each binary */ if (++itercount > EAI_ITERLIMIT) { error = EBADEXEC; goto bad; } error = -1; for (i = 0; error == -1 && execsw[i].ex_imgact != NULL; i++) { error = (*execsw[i].ex_imgact)(imgp); switch (error) { /* case -1: not claimed: continue */ case -2: /* Encapsulated binary, imgp->ip_XXX set for next iteration */ goto encapsulated_binary; case -3: /* Interpreter */ #if CONFIG_MACF /* * Copy the script label for later use. Note that * the label can be different when the script is * actually read by the interpreter. */ if (imgp->ip_scriptlabelp) { mac_vnode_label_free(imgp->ip_scriptlabelp); imgp->ip_scriptlabelp = NULL; } imgp->ip_scriptlabelp = mac_vnode_label_alloc(NULL); if (imgp->ip_scriptlabelp == NULL) { error = ENOMEM; break; } mac_vnode_label_copy(mac_vnode_label(imgp->ip_vp), imgp->ip_scriptlabelp); /* * Take a ref of the script vnode for later use. */ if (imgp->ip_scriptvp) { vnode_put(imgp->ip_scriptvp); imgp->ip_scriptvp = NULLVP; } if (vnode_getwithref(imgp->ip_vp) == 0) { imgp->ip_scriptvp = imgp->ip_vp; } #endif nameidone(ndp); vnode_put(imgp->ip_vp); imgp->ip_vp = NULL; /* already put */ imgp->ip_ndp = NULL; /* already nameidone */ /* Use excpath, which exec_shell_imgact reset to the interpreter */ NDINIT(ndp, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(excpath), imgp->ip_vfs_context); proc_transend(p, 0); goto again; default: break; } } if (error == -1) { error = ENOEXEC; } else if (error == 0) { if (imgp->ip_flags & IMGPF_INTERPRET && ndp->ni_vp) { AUDIT_ARG(vnpath, ndp->ni_vp, ARG_VNODE2); } /* * Call out to allow 3rd party notification of exec. * Ignore result of kauth_authorize_fileop call. */ if (kauth_authorize_fileop_has_listeners()) { kauth_authorize_fileop(vfs_context_ucred(imgp->ip_vfs_context), KAUTH_FILEOP_EXEC, (uintptr_t)ndp->ni_vp, 0); } } bad: proc_transend(p, 0); bad_notrans: if (imgp->ip_strings) { execargs_free(imgp); } if (imgp->ip_ndp) { nameidone(imgp->ip_ndp); } kfree_type(struct nameidata, ndp); return error; } /* * exec_validate_spawnattr_policy * * Description: Validates the entitlements required to set the apptype. * * Parameters: int psa_apptype posix spawn attribute apptype * * Returns: 0 Success * EPERM Failure */ static errno_t exec_validate_spawnattr_policy(int psa_apptype) { if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) { int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK; if (proctype == POSIX_SPAWN_PROC_TYPE_DRIVER) { if (!IOCurrentTaskHasEntitlement(POSIX_SPAWN_ENTITLEMENT_DRIVER)) { return EPERM; } } } return 0; } /* * exec_handle_spawnattr_policy * * Description: Decode and apply the posix_spawn apptype, qos clamp, and watchport ports to the task. * * Parameters: proc_t p process to apply attributes to * int psa_apptype posix spawn attribute apptype * * Returns: 0 Success */ static errno_t exec_handle_spawnattr_policy(proc_t p, thread_t thread, int psa_apptype, uint64_t psa_qos_clamp, task_role_t psa_darwin_role, struct exec_port_actions *port_actions) { int apptype = TASK_APPTYPE_NONE; int qos_clamp = THREAD_QOS_UNSPECIFIED; task_role_t role = TASK_UNSPECIFIED; if ((psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) != 0) { int proctype = psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK; switch (proctype) { case POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE: apptype = TASK_APPTYPE_DAEMON_INTERACTIVE; break; case POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD: apptype = TASK_APPTYPE_DAEMON_STANDARD; break; case POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE: apptype = TASK_APPTYPE_DAEMON_ADAPTIVE; break; case POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND: apptype = TASK_APPTYPE_DAEMON_BACKGROUND; break; case POSIX_SPAWN_PROC_TYPE_APP_DEFAULT: apptype = TASK_APPTYPE_APP_DEFAULT; break; case POSIX_SPAWN_PROC_TYPE_APP_NONUI: apptype = TASK_APPTYPE_APP_NONUI; break; case POSIX_SPAWN_PROC_TYPE_DRIVER: apptype = TASK_APPTYPE_DRIVER; break; default: apptype = TASK_APPTYPE_NONE; /* TODO: Should an invalid value here fail the spawn? */ break; } } if (psa_qos_clamp != POSIX_SPAWN_PROC_CLAMP_NONE) { switch (psa_qos_clamp) { case POSIX_SPAWN_PROC_CLAMP_UTILITY: qos_clamp = THREAD_QOS_UTILITY; break; case POSIX_SPAWN_PROC_CLAMP_BACKGROUND: qos_clamp = THREAD_QOS_BACKGROUND; break; case POSIX_SPAWN_PROC_CLAMP_MAINTENANCE: qos_clamp = THREAD_QOS_MAINTENANCE; break; default: qos_clamp = THREAD_QOS_UNSPECIFIED; /* TODO: Should an invalid value here fail the spawn? */ break; } } if (psa_darwin_role != PRIO_DARWIN_ROLE_DEFAULT) { proc_darwin_role_to_task_role(psa_darwin_role, &role); } if (apptype != TASK_APPTYPE_NONE || qos_clamp != THREAD_QOS_UNSPECIFIED || role != TASK_UNSPECIFIED || port_actions->portwatch_count) { proc_set_task_spawnpolicy(proc_task(p), thread, apptype, qos_clamp, role, port_actions->portwatch_array, port_actions->portwatch_count); } if (port_actions->registered_count) { if (_kernelrpc_mach_ports_register3(proc_task(p), port_actions->registered_array[0], port_actions->registered_array[1], port_actions->registered_array[2])) { return EINVAL; } /* mach_ports_register() consumed the array */ bzero(port_actions->registered_array, sizeof(port_actions->registered_array)); port_actions->registered_count = 0; } return 0; } static void exec_port_actions_destroy(struct exec_port_actions *port_actions) { if (port_actions->excport_array) { for (uint32_t i = 0; i < port_actions->exception_port_count; i++) { ipc_port_t port = NULL; if ((port = port_actions->excport_array[i].port) != NULL) { ipc_port_release_send(port); } } kfree_type(struct exception_port_action_t, port_actions->exception_port_count, port_actions->excport_array); } if (port_actions->portwatch_array) { for (uint32_t i = 0; i < port_actions->portwatch_count; i++) { ipc_port_t port = NULL; if ((port = port_actions->portwatch_array[i]) != NULL) { ipc_port_release_send(port); } } kfree_type(ipc_port_t, port_actions->portwatch_count, port_actions->portwatch_array); } for (uint32_t i = 0; i < port_actions->registered_count; i++) { ipc_port_t port = NULL; if ((port = port_actions->registered_array[i]) != NULL) { ipc_port_release_send(port); } } } /* * exec_handle_port_actions * * Description: Go through the _posix_port_actions_t contents, * calling task_set_special_port, task_set_exception_ports * and/or audit_session_spawnjoin for the current task. * * Parameters: struct image_params * Image parameter block * * Returns: 0 Success * EINVAL Failure * ENOTSUP Illegal posix_spawn attr flag was set */ static errno_t exec_handle_port_actions(struct image_params *imgp, struct exec_port_actions *actions) { _posix_spawn_port_actions_t pacts = imgp->ip_px_spa; #if CONFIG_AUDIT proc_t p = vfs_context_proc(imgp->ip_vfs_context); #endif _ps_port_action_t *act = NULL; task_t task = get_threadtask(imgp->ip_new_thread); ipc_port_t port = NULL; errno_t ret = 0; int i = 0, portwatch_i = 0, registered_i = 0, excport_i = 0; kern_return_t kr; boolean_t task_has_watchport_boost = task_has_watchports(current_task()); boolean_t in_exec = (imgp->ip_flags & IMGPF_EXEC); int ptrauth_task_port_count = 0; for (i = 0; i < pacts->pspa_count; i++) { act = &pacts->pspa_actions[i]; switch (act->port_type) { case PSPA_SPECIAL: #if CONFIG_AUDIT case PSPA_AU_SESSION: #endif break; case PSPA_EXCEPTION: if (++actions->exception_port_count > TASK_MAX_EXCEPTION_PORT_COUNT) { ret = EINVAL; goto done; } break; case PSPA_IMP_WATCHPORTS: if (++actions->portwatch_count > TASK_MAX_WATCHPORT_COUNT) { ret = EINVAL; goto done; } break; case PSPA_REGISTERED_PORTS: if (++actions->registered_count > TASK_PORT_REGISTER_MAX) { ret = EINVAL; goto done; } break; case PSPA_PTRAUTH_TASK_PORT: if (++ptrauth_task_port_count > 1) { ret = EINVAL; goto done; } break; default: ret = EINVAL; goto done; } } if (actions->exception_port_count) { actions->excport_array = kalloc_type(struct exception_port_action_t, actions->exception_port_count, Z_WAITOK | Z_ZERO); if (actions->excport_array == NULL) { ret = ENOMEM; goto done; } } if (actions->portwatch_count) { if (in_exec && task_has_watchport_boost) { ret = EINVAL; goto done; } actions->portwatch_array = kalloc_type(ipc_port_t, actions->portwatch_count, Z_WAITOK | Z_ZERO); if (actions->portwatch_array == NULL) { ret = ENOMEM; goto done; } } for (i = 0; i < pacts->pspa_count; i++) { act = &pacts->pspa_actions[i]; if (MACH_PORT_VALID(act->new_port)) { kr = ipc_typed_port_copyin_send(get_task_ipcspace(current_task()), act->new_port, IOT_ANY, &port); if (kr != KERN_SUCCESS) { ret = EINVAL; goto done; } } else { /* it's NULL or DEAD */ port = CAST_MACH_NAME_TO_PORT(act->new_port); } switch (act->port_type) { case PSPA_SPECIAL: kr = task_set_special_port(task, act->which, port); if (kr != KERN_SUCCESS) { ret = EINVAL; } break; #if CONFIG_AUDIT case PSPA_AU_SESSION: ret = audit_session_spawnjoin(p, port); if (ret) { /* audit_session_spawnjoin() has already dropped the reference in case of error. */ goto done; } break; #endif case PSPA_EXCEPTION: assert(excport_i < actions->exception_port_count); /* hold on to this till end of spawn */ actions->excport_array[excport_i].port_action = act; actions->excport_array[excport_i].port = port; excport_i++; break; case PSPA_IMP_WATCHPORTS: assert(portwatch_i < actions->portwatch_count); /* hold on to this till end of spawn */ actions->portwatch_array[portwatch_i++] = port; break; case PSPA_REGISTERED_PORTS: assert(registered_i < actions->registered_count); /* hold on to this till end of spawn */ actions->registered_array[registered_i++] = port; break; case PSPA_PTRAUTH_TASK_PORT: #if (DEVELOPMENT || DEBUG) #if defined(HAS_APPLE_PAC) { task_t ptr_auth_task = convert_port_to_task(port); if (ptr_auth_task == TASK_NULL) { ret = EINVAL; break; } imgp->ip_inherited_shared_region_id = task_get_vm_shared_region_id_and_jop_pid(ptr_auth_task, &imgp->ip_inherited_jop_pid); /* Deallocate task ref returned by convert_port_to_task */ task_deallocate(ptr_auth_task); } #endif /* HAS_APPLE_PAC */ #endif /* (DEVELOPMENT || DEBUG) */ /* consume the port right in case of success */ ipc_port_release_send(port); break; default: ret = EINVAL; break; } if (ret) { /* action failed, so release port resources */ ipc_port_release_send(port); break; } } done: if (0 != ret) { DTRACE_PROC1(spawn__port__failure, mach_port_name_t, act->new_port); } return ret; } /* * exec_handle_exception_port_actions * * Description: Go through the saved exception ports in exec_port_actions, * calling task_set_exception_ports for the current Task. * This must happen after image activation, and after exec_resettextvp() * because task_set_exception_ports checks the `TF_PLATFORM` bit and entitlements. * * Parameters: struct image_params * Image parameter block * struct exec_port_actions * Saved Port Actions * * Returns: 0 Success * EINVAL task_set_exception_ports failed */ static errno_t exec_handle_exception_port_actions(const struct image_params *imgp, const struct exec_port_actions *actions) { task_t task = get_threadtask(imgp->ip_new_thread); for (int i = 0; i < actions->exception_port_count; i++) { ipc_port_t port = actions->excport_array[i].port; _ps_port_action_t *act = actions->excport_array[i].port_action; assert(act != NULL); kern_return_t kr = task_set_exception_ports(task, act->mask, port, act->behavior, act->flavor); if (kr != KERN_SUCCESS) { DTRACE_PROC1(spawn__exception__port__failure, mach_port_name_t, act->new_port); return EINVAL; } actions->excport_array[i].port = NULL; } return 0; } /* * exec_handle_file_actions * * Description: Go through the _posix_file_actions_t contents applying the * open, close, and dup2 operations to the open file table for * the current process. * * Parameters: struct image_params * Image parameter block * * Returns: 0 Success * ??? * * Note: Actions are applied in the order specified, with the credential * of the parent process. This is done to permit the parent * process to utilize POSIX_SPAWN_RESETIDS to drop privilege in * the child following operations the child may in fact not be * normally permitted to perform. */ static int exec_handle_file_actions(struct image_params *imgp, short psa_flags) { int error = 0; int action; proc_t p = vfs_context_proc(imgp->ip_vfs_context); kauth_cred_t p_cred = vfs_context_ucred(imgp->ip_vfs_context); _posix_spawn_file_actions_t px_sfap = imgp->ip_px_sfa; int ival[2]; /* dummy retval for system calls) */ #if CONFIG_AUDIT struct uthread *uthread = current_uthread(); #endif for (action = 0; action < px_sfap->psfa_act_count; action++) { _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action]; switch (psfa->psfaa_type) { case PSFA_OPEN: { /* * Open is different, in that it requires the use of * a path argument, which is normally copied in from * user space; because of this, we have to support an * open from kernel space that passes an address space * context of UIO_SYSSPACE, and casts the address * argument to a user_addr_t. */ struct vnode_attr *vap; struct nameidata *ndp; int mode = psfa->psfaa_openargs.psfao_mode; int origfd; struct { struct vnode_attr va; struct nameidata nd; } *__open_data; __open_data = kalloc_type(typeof(*__open_data), Z_WAITOK | Z_ZERO); if (__open_data == NULL) { error = ENOMEM; break; } vap = &__open_data->va; ndp = &__open_data->nd; VATTR_INIT(vap); /* Mask off all but regular access permissions */ mode = ((mode & ~p->p_fd.fd_cmask) & ALLPERMS) & ~S_ISTXT; VATTR_SET(vap, va_mode, mode & ACCESSPERMS); AUDIT_SUBCALL_ENTER(OPEN, p, uthread); NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE, CAST_USER_ADDR_T(psfa->psfaa_openargs.psfao_path), imgp->ip_vfs_context); error = open1(imgp->ip_vfs_context, ndp, psfa->psfaa_openargs.psfao_oflag, vap, NULL, NULL, &origfd, AUTH_OPEN_NOAUTHFD); kfree_type(typeof(*__open_data), __open_data); AUDIT_SUBCALL_EXIT(uthread, error); /* * If there's an error, or we get the right fd by * accident, then drop out here. This is easier than * reworking all the open code to preallocate fd * slots, and internally taking one as an argument. */ if (error || origfd == psfa->psfaa_filedes) { break; } /* * If we didn't fall out from an error, we ended up * with the wrong fd; so now we've got to try to dup2 * it to the right one. */ AUDIT_SUBCALL_ENTER(DUP2, p, uthread); error = dup2(p, p_cred, origfd, psfa->psfaa_filedes, ival); AUDIT_SUBCALL_EXIT(uthread, error); if (error) { break; } /* * Finally, close the original fd. */ AUDIT_SUBCALL_ENTER(CLOSE, p, uthread); error = close_nocancel(p, p_cred, origfd); AUDIT_SUBCALL_EXIT(uthread, error); } break; case PSFA_DUP2: { AUDIT_SUBCALL_ENTER(DUP2, p, uthread); error = dup2(p, p_cred, psfa->psfaa_filedes, psfa->psfaa_dup2args.psfad_newfiledes, ival); AUDIT_SUBCALL_EXIT(uthread, error); } break; case PSFA_FILEPORT_DUP2: { ipc_port_t port; kern_return_t kr; int origfd; if (!MACH_PORT_VALID(psfa->psfaa_fileport)) { error = EINVAL; break; } kr = ipc_typed_port_copyin_send(get_task_ipcspace(current_task()), psfa->psfaa_fileport, IKOT_FILEPORT, &port); if (kr != KERN_SUCCESS) { error = EINVAL; break; } error = fileport_makefd(p, port, 0, &origfd); if (IPC_PORT_NULL != port) { ipc_typed_port_release_send(port, IKOT_FILEPORT); } if (error || origfd == psfa->psfaa_dup2args.psfad_newfiledes) { break; } AUDIT_SUBCALL_ENTER(DUP2, p, uthread); error = dup2(p, p_cred, origfd, psfa->psfaa_dup2args.psfad_newfiledes, ival); AUDIT_SUBCALL_EXIT(uthread, error); if (error) { break; } AUDIT_SUBCALL_ENTER(CLOSE, p, uthread); error = close_nocancel(p, p_cred, origfd); AUDIT_SUBCALL_EXIT(uthread, error); } break; case PSFA_CLOSE: { AUDIT_SUBCALL_ENTER(CLOSE, p, uthread); error = close_nocancel(p, p_cred, psfa->psfaa_filedes); AUDIT_SUBCALL_EXIT(uthread, error); } break; case PSFA_INHERIT: { struct fileproc *fp; /* * Check to see if the descriptor exists, and * ensure it's -not- marked as close-on-exec. * * Attempting to "inherit" a guarded fd will * result in a error. */ proc_fdlock(p); if ((fp = fp_get_noref_locked(p, psfa->psfaa_filedes)) == NULL) { error = EBADF; } else if (fp->fp_guard_attrs) { error = fp_guard_exception(p, psfa->psfaa_filedes, fp, kGUARD_EXC_NOCLOEXEC); } else { fp->fp_flags &= ~FP_CLOEXEC; error = 0; } proc_fdunlock(p); } break; case PSFA_CHDIR: { /* * Chdir is different, in that it requires the use of * a path argument, which is normally copied in from * user space; because of this, we have to support a * chdir from kernel space that passes an address space * context of UIO_SYSSPACE, and casts the address * argument to a user_addr_t. */ struct nameidata *nd; nd = kalloc_type(struct nameidata, Z_WAITOK | Z_ZERO | Z_NOFAIL); AUDIT_SUBCALL_ENTER(CHDIR, p, uthread); NDINIT(nd, LOOKUP, OP_CHDIR, FOLLOW | AUDITVNPATH1, UIO_SYSSPACE, CAST_USER_ADDR_T(psfa->psfaa_chdirargs.psfac_path), imgp->ip_vfs_context); error = chdir_internal(p, imgp->ip_vfs_context, nd, 0); kfree_type(struct nameidata, nd); AUDIT_SUBCALL_EXIT(uthread, error); } break; case PSFA_FCHDIR: { AUDIT_SUBCALL_ENTER(FCHDIR, p, uthread); error = fchdir(p, imgp->ip_vfs_context, psfa->psfaa_filedes, false); AUDIT_SUBCALL_EXIT(uthread, error); } break; default: error = EINVAL; break; } /* All file actions failures are considered fatal, per POSIX */ if (error) { if (PSFA_OPEN == psfa->psfaa_type) { DTRACE_PROC1(spawn__open__failure, uintptr_t, psfa->psfaa_openargs.psfao_path); } else { DTRACE_PROC1(spawn__fd__failure, int, psfa->psfaa_filedes); } break; } } if (error != 0 || (psa_flags & POSIX_SPAWN_CLOEXEC_DEFAULT) == 0) { return error; } /* * If POSIX_SPAWN_CLOEXEC_DEFAULT is set, behave (during * this spawn only) as if "close on exec" is the default * disposition of all pre-existing file descriptors. In this case, * the list of file descriptors mentioned in the file actions * are the only ones that can be inherited, so mark them now. * * The actual closing part comes later, in fdt_exec(). */ proc_fdlock(p); for (action = 0; action < px_sfap->psfa_act_count; action++) { _psfa_action_t *psfa = &px_sfap->psfa_act_acts[action]; int fd = psfa->psfaa_filedes; switch (psfa->psfaa_type) { case PSFA_DUP2: case PSFA_FILEPORT_DUP2: fd = psfa->psfaa_dup2args.psfad_newfiledes; OS_FALLTHROUGH; case PSFA_OPEN: case PSFA_INHERIT: *fdflags(p, fd) |= UF_INHERIT; break; case PSFA_CLOSE: case PSFA_CHDIR: case PSFA_FCHDIR: /* * Although PSFA_FCHDIR does have a file descriptor, it is not * *creating* one, thus we do not automatically mark it for * inheritance under POSIX_SPAWN_CLOEXEC_DEFAULT. A client that * wishes it to be inherited should use the PSFA_INHERIT action * explicitly. */ break; } } proc_fdunlock(p); return 0; } #if CONFIG_MACF /* * Check that the extension's data is within the bounds of the * allocation storing all extensions' data */ static inline errno_t exec_spawnattr_validate_policyext_data(const struct ip_px_smpx_s *px_s, const _ps_mac_policy_extension_t *ext) { uint64_t dataend; if (__improbable(os_add_overflow(ext->dataoff, ext->datalen, &dataend))) { return EOVERFLOW; } if (__improbable(dataend > px_s->datalen)) { return EINVAL; } return 0; } /* * exec_spawnattr_getmacpolicyinfo */ void * exec_spawnattr_getmacpolicyinfo(const void *macextensions, const char *policyname, size_t *lenp) { const struct ip_px_smpx_s *px_s = macextensions; const struct _posix_spawn_mac_policy_extensions *psmx = NULL; int i; if (px_s == NULL) { return NULL; } psmx = px_s->array; if (psmx == NULL) { return NULL; } for (i = 0; i < psmx->psmx_count; i++) { const _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i]; if (strncmp(extension->policyname, policyname, sizeof(extension->policyname)) == 0) { if (__improbable(exec_spawnattr_validate_policyext_data(px_s, extension))) { panic("invalid mac policy extension data"); } if (lenp != NULL) { *lenp = (size_t)extension->datalen; } return (void *)((uintptr_t)px_s->data + extension->dataoff); } } if (lenp != NULL) { *lenp = 0; } return NULL; } static int spawn_copyin_macpolicyinfo(const struct user__posix_spawn_args_desc *px_args, struct ip_px_smpx_s *pxsp) { _posix_spawn_mac_policy_extensions_t psmx = NULL; uint8_t *data = NULL; uint64_t datalen = 0; uint64_t dataoff = 0; int error = 0; bzero(pxsp, sizeof(*pxsp)); if (px_args->mac_extensions_size < PS_MAC_EXTENSIONS_SIZE(1) || px_args->mac_extensions_size > PAGE_SIZE) { error = EINVAL; goto bad; } psmx = kalloc_data(px_args->mac_extensions_size, Z_WAITOK); if (psmx == NULL) { error = ENOMEM; goto bad; } error = copyin(px_args->mac_extensions, psmx, px_args->mac_extensions_size); if (error) { goto bad; } size_t extsize = PS_MAC_EXTENSIONS_SIZE(psmx->psmx_count); if (extsize == 0 || extsize > px_args->mac_extensions_size) { error = EINVAL; goto bad; } for (int i = 0; i < psmx->psmx_count; i++) { _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i]; if (extension->datalen == 0 || extension->datalen > PAGE_SIZE) { error = EINVAL; goto bad; } if (__improbable(os_add_overflow(datalen, extension->datalen, &datalen))) { error = ENOMEM; goto bad; } } data = kalloc_data((vm_size_t)datalen, Z_WAITOK); if (data == NULL) { error = ENOMEM; goto bad; } for (int i = 0; i < psmx->psmx_count; i++) { _ps_mac_policy_extension_t *extension = &psmx->psmx_extensions[i]; #if !__LP64__ if (extension->data > UINT32_MAX) { error = EINVAL; goto bad; } #endif error = copyin((user_addr_t)extension->data, &data[dataoff], (size_t)extension->datalen); if (error) { error = ENOMEM; goto bad; } extension->dataoff = dataoff; dataoff += extension->datalen; } pxsp->array = psmx; pxsp->data = data; pxsp->datalen = datalen; return 0; bad: kfree_data(psmx, px_args->mac_extensions_size); kfree_data(data, (vm_size_t)datalen); return error; } #endif /* CONFIG_MACF */ #if CONFIG_COALITIONS static inline void spawn_coalitions_release_all(coalition_t coal[COALITION_NUM_TYPES]) { for (int c = 0; c < COALITION_NUM_TYPES; c++) { if (coal[c]) { coalition_remove_active(coal[c]); coalition_release(coal[c]); } } } #endif #if CONFIG_PERSONAS static int spawn_validate_persona(struct _posix_spawn_persona_info *px_persona) { int error = 0; struct persona *persona = NULL; kauth_cred_t mycred = kauth_cred_get(); if (!IOCurrentTaskHasEntitlement( PERSONA_MGMT_ENTITLEMENT)) { return EPERM; } if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) { if (px_persona->pspi_ngroups > NGROUPS_MAX) { return EINVAL; } } persona = persona_lookup(px_persona->pspi_id); if (!persona) { return ESRCH; } // non-root process should not be allowed to set persona with uid/gid 0 if (!kauth_cred_issuser(mycred) && (px_persona->pspi_uid == 0 || px_persona->pspi_gid == 0)) { error = EPERM; } persona_put(persona); return error; } static bool kauth_cred_model_setpersona( kauth_cred_t model, struct _posix_spawn_persona_info *px_persona) { bool updated = false; if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_UID) { updated |= kauth_cred_model_setresuid(model, px_persona->pspi_uid, px_persona->pspi_uid, px_persona->pspi_uid, KAUTH_UID_NONE); } if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GID) { updated |= kauth_cred_model_setresgid(model, px_persona->pspi_gid, px_persona->pspi_gid, px_persona->pspi_gid); } if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) { updated |= kauth_cred_model_setgroups(model, px_persona->pspi_groups, px_persona->pspi_ngroups, px_persona->pspi_gmuid); } return updated; } static int spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona) { struct persona *persona = NULL; /* * we want to spawn into the given persona, but we want to override * the kauth with a different UID/GID combo */ persona = persona_lookup(px_persona->pspi_id); if (!persona) { return ESRCH; } return persona_proc_adopt(p, persona, ^bool (kauth_cred_t parent __unused, kauth_cred_t model) { return kauth_cred_model_setpersona(model, px_persona); }); } #endif #if __arm64__ #if DEVELOPMENT || DEBUG TUNABLE(int, legacy_footprint_entitlement_mode, "legacy_footprint_entitlement_mode", LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE); __startup_func static void legacy_footprint_entitlement_mode_init(void) { /* * legacy_footprint_entitlement_mode specifies the behavior we want associated * with the entitlement. The supported modes are: * * LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE: * Indicates that we want every process to have the memory accounting * that is available in iOS 12.0 and beyond. * * LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT: * Indicates that for every process that has the 'legacy footprint entitlement', * we want to give it the old iOS 11.0 accounting behavior which accounted some * of the process's memory to the kernel. * * LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE: * Indicates that for every process that has the 'legacy footprint entitlement', * we want it to have a higher memory limit which will help them acclimate to the * iOS 12.0 (& beyond) accounting behavior that does the right accounting. * The bonus added to the system-wide task limit to calculate this higher memory limit * is available in legacy_footprint_bonus_mb. */ if (legacy_footprint_entitlement_mode < LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE || legacy_footprint_entitlement_mode > LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE) { legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE; } } STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, legacy_footprint_entitlement_mode_init); #else const int legacy_footprint_entitlement_mode = LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE; #endif static inline void proc_legacy_footprint_entitled(proc_t p, task_t task) { #pragma unused(p) boolean_t legacy_footprint_entitled; switch (legacy_footprint_entitlement_mode) { case LEGACY_FOOTPRINT_ENTITLEMENT_IGNORE: /* the entitlement is ignored */ break; case LEGACY_FOOTPRINT_ENTITLEMENT_IOS11_ACCT: /* the entitlement grants iOS11 legacy accounting */ legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p)); if (legacy_footprint_entitled) { task_set_legacy_footprint(task); } break; case LEGACY_FOOTPRINT_ENTITLEMENT_LIMIT_INCREASE: /* the entitlement grants a footprint limit increase */ legacy_footprint_entitled = memorystatus_task_has_legacy_footprint_entitlement(proc_task(p)); if (legacy_footprint_entitled) { task_set_extra_footprint_limit(task); } break; default: break; } } static inline void proc_ios13extended_footprint_entitled(proc_t p, task_t task) { #pragma unused(p) boolean_t ios13extended_footprint_entitled; /* the entitlement grants a footprint limit increase */ ios13extended_footprint_entitled = memorystatus_task_has_ios13extended_footprint_limit(proc_task(p)); if (ios13extended_footprint_entitled) { task_set_ios13extended_footprint_limit(task); } } static inline void proc_increased_memory_limit_entitled(proc_t p, task_t task) { if (memorystatus_task_has_increased_debugging_memory_limit_entitlement(task)) { memorystatus_act_on_entitled_developer_task_limit(p); } else if (memorystatus_task_has_increased_memory_limit_entitlement(task)) { memorystatus_act_on_entitled_task_limit(p); } } /* * Check for any of the various entitlements that permit a higher * task footprint limit or alternate accounting and apply them. */ static inline void proc_footprint_entitlement_hacks(proc_t p, task_t task) { proc_legacy_footprint_entitled(p, task); proc_ios13extended_footprint_entitled(p, task); proc_increased_memory_limit_entitled(p, task); } #endif /* __arm64__ */ /* * Processes with certain entitlements are granted a jumbo-size VM map. */ static inline void proc_apply_jit_and_vm_policies(struct image_params *imgp, proc_t p, task_t task) { #if CONFIG_MACF bool jit_entitled = false; #endif /* CONFIG_MACF */ bool needs_jumbo_va = false; bool needs_extra_jumbo_va = false; struct _posix_spawnattr *psa = imgp->ip_px_sa; #if CONFIG_MACF jit_entitled = (mac_proc_check_map_anon(p, proc_ucred_unsafe(p), 0, 0, 0, MAP_JIT, NULL) == 0); needs_jumbo_va = jit_entitled || IOTaskHasEntitlement(task, "com.apple.developer.kernel.extended-virtual-addressing") || memorystatus_task_has_increased_memory_limit_entitlement(task) || memorystatus_task_has_increased_debugging_memory_limit_entitlement(task); #else #pragma unused(p) #endif /* CONFIG_MACF */ #if HAS_MTE /* * If we are MTE enabled, communicate to the pmap layer that * we need the right configuration at each context switch. */ if (task_has_sec(task)) { vm_map_set_sec_enabled(get_task_map(task)); #if KERN_AMFI_SUPPORTS_MTE if (get_lockdown_mode_state() == 0 && amfi->has_mte_soft_mode && amfi->has_mte_soft_mode(p)) { EXEC_LOG("AMFI says: enable soft-mode\n"); task_set_sec_soft_mode(task); } #endif /* KERN_AMFI_SUPPORTS_MTE */ } /* Pipe through alias restrictions onto our backing map */ if (task_has_sec_restrict_receiving_aliases_to_tagged_memory(task)) { vm_map_set_restrict_receiving_aliases_to_tagged_memory(get_task_map(task), true); } #endif /* HAS_MTE */ #if HAS_MTE_EMULATION_SHIMS && XNU_TARGET_OS_IOS if (task_has_sec(task)) { /* Give Rosetta some breathing room for the shadow table. */ needs_jumbo_va = true; } #endif /* HAS_MTE_EMULATION_SHIMS && XNU_TARGET_OS_IOS */ if (needs_jumbo_va) { vm_map_set_jumbo(get_task_map(task)); } if (psa && psa->psa_max_addr) { vm_map_set_max_addr(get_task_map(task), psa->psa_max_addr, false); } #if CONFIG_MAP_RANGES if ((task_has_hardened_heap(task) || (task_get_platform_restrictions_version(task) == 1) || task_get_platform_binary(task)) && !proc_is_simulated(p)) { /* * This must be done last as it needs to observe * any kind of VA space growth that was requested. * This is used by the secure allocator, so * must be applied to all platform restrictions binaries */ #if XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT needs_extra_jumbo_va = IOTaskHasEntitlement(task, "com.apple.kernel.large-file-virtual-addressing"); #endif /* XNU_TARGET_OS_IOS && EXTENDED_USER_VA_SUPPORT */ vm_map_range_configure(get_task_map(task), needs_extra_jumbo_va); } #else #pragma unused(needs_extra_jumbo_va) #endif /* CONFIG_MAP_RANGES */ #if CONFIG_MACF if (jit_entitled) { vm_map_set_jit_entitled(get_task_map(task)); } #endif /* CONFIG_MACF */ #if XNU_TARGET_OS_OSX /* TPRO cannot be enforced on binaries that load 3P plugins on macos - rdar://107420220 */ const bool task_loads_3P_plugins = imgp->ip_flags & IMGPF_3P_PLUGINS; #endif /* XNU_TARGET_OS_OSX */ if (task_has_tpro(task) #if XNU_TARGET_OS_OSX && !task_loads_3P_plugins #endif /* XNU_TARGET_OS_OSX */ ) { /* * Pre-emptively disable TPRO remapping for * platform restrictions binaries (which do not load 3P plugins) */ vm_map_set_tpro_enforcement(get_task_map(task)); } } static int spawn_posix_cred_adopt(proc_t p, struct _posix_spawn_posix_cred_info *px_pcred_info) { int error = 0; if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GID) { struct setgid_args args = { .gid = px_pcred_info->pspci_gid, }; error = setgid(p, &args, NULL); if (error) { return error; } } if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) { error = setgroups_internal(p, px_pcred_info->pspci_ngroups, px_pcred_info->pspci_groups, px_pcred_info->pspci_gmuid); if (error) { return error; } } if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_UID) { struct setuid_args args = { .uid = px_pcred_info->pspci_uid, }; error = setuid(p, &args, NULL); if (error) { return error; } } return 0; } /* * posix_spawn * * Parameters: uap->pid Pointer to pid return area * uap->fname File name to exec * uap->argp Argument list * uap->envp Environment list * * Returns: 0 Success * EINVAL Invalid argument * ENOTSUP Not supported * ENOEXEC Executable file format error * exec_activate_image:EINVAL Invalid argument * exec_activate_image:EACCES Permission denied * exec_activate_image:EINTR Interrupted function * exec_activate_image:ENOMEM Not enough space * exec_activate_image:EFAULT Bad address * exec_activate_image:ENAMETOOLONG Filename too long * exec_activate_image:ENOEXEC Executable file format error * exec_activate_image:ETXTBSY Text file busy [misuse of error code] * exec_activate_image:EAUTH Image decryption failed * exec_activate_image:EBADEXEC The executable is corrupt/unknown * exec_activate_image:??? * mac_execve_enter:??? * * TODO: Expect to need __mac_posix_spawn() at some point... * Handle posix_spawnattr_t * Handle posix_spawn_file_actions_t */ int posix_spawn(proc_t ap, struct posix_spawn_args *uap, int32_t *retval) { proc_t p = ap; user_addr_t pid = uap->pid; int ival[2]; /* dummy retval for setpgid() */ char *subsystem_root_path = NULL; struct image_params *imgp = NULL; struct vnode_attr *vap = NULL; struct vnode_attr *origvap = NULL; struct uthread *uthread = 0; /* compiler complains if not set to 0*/ int error, sig; int is_64 = IS_64BIT_PROCESS(p); struct vfs_context context; struct user__posix_spawn_args_desc px_args = {}; struct _posix_spawnattr px_sa = {}; _posix_spawn_file_actions_t px_sfap = NULL; _posix_spawn_port_actions_t px_spap = NULL; struct __kern_sigaction vec; boolean_t spawn_no_exec = FALSE; boolean_t proc_transit_set = TRUE; boolean_t proc_signal_set = TRUE; boolean_t exec_done = FALSE; os_reason_t exec_failure_reason = NULL; struct exec_port_actions port_actions = { }; vm_size_t px_sa_offset = offsetof(struct _posix_spawnattr, psa_ports); task_t old_task = current_task(); task_t new_task = NULL; boolean_t should_release_proc_ref = FALSE; void *inherit = NULL; uint8_t crash_behavior = 0; uint64_t crash_behavior_deadline = 0; #if CONFIG_EXCLAVES char *task_conclave_id = NULL; #endif #if CONFIG_PERSONAS struct _posix_spawn_persona_info *px_persona = NULL; #endif struct _posix_spawn_posix_cred_info *px_pcred_info = NULL; struct { struct image_params imgp; struct vnode_attr va; struct vnode_attr origva; } *__spawn_data; /* * Allocate a big chunk for locals instead of using stack since these * structures are pretty big. */ __spawn_data = kalloc_type(typeof(*__spawn_data), Z_WAITOK | Z_ZERO); if (__spawn_data == NULL) { error = ENOMEM; goto bad; } imgp = &__spawn_data->imgp; vap = &__spawn_data->va; origvap = &__spawn_data->origva; /* Initialize the common data in the image_params structure */ imgp->ip_user_fname = uap->path; imgp->ip_user_argv = uap->argv; imgp->ip_user_envv = uap->envp; imgp->ip_vattr = vap; imgp->ip_origvattr = origvap; imgp->ip_vfs_context = &context; imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE); imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32); imgp->ip_mac_return = 0; imgp->ip_px_persona = NULL; imgp->ip_px_pcred_info = NULL; imgp->ip_cs_error = OS_REASON_NULL; imgp->ip_flags2 = 0; imgp->ip_subsystem_root_path = NULL; imgp->ip_inherited_shared_region_id = NULL; imgp->ip_inherited_jop_pid = 0; uthread_set_exec_data(current_uthread(), imgp); if (uap->adesc != USER_ADDR_NULL) { if (is_64) { error = copyin(uap->adesc, &px_args, sizeof(px_args)); } else { struct user32__posix_spawn_args_desc px_args32; error = copyin(uap->adesc, &px_args32, sizeof(px_args32)); /* * Convert arguments descriptor from external 32 bit * representation to internal 64 bit representation */ px_args.attr_size = px_args32.attr_size; px_args.attrp = CAST_USER_ADDR_T(px_args32.attrp); px_args.file_actions_size = px_args32.file_actions_size; px_args.file_actions = CAST_USER_ADDR_T(px_args32.file_actions); px_args.port_actions_size = px_args32.port_actions_size; px_args.port_actions = CAST_USER_ADDR_T(px_args32.port_actions); px_args.mac_extensions_size = px_args32.mac_extensions_size; px_args.mac_extensions = CAST_USER_ADDR_T(px_args32.mac_extensions); px_args.coal_info_size = px_args32.coal_info_size; px_args.coal_info = CAST_USER_ADDR_T(px_args32.coal_info); px_args.persona_info_size = px_args32.persona_info_size; px_args.persona_info = CAST_USER_ADDR_T(px_args32.persona_info); px_args.posix_cred_info_size = px_args32.posix_cred_info_size; px_args.posix_cred_info = CAST_USER_ADDR_T(px_args32.posix_cred_info); px_args.subsystem_root_path_size = px_args32.subsystem_root_path_size; px_args.subsystem_root_path = CAST_USER_ADDR_T(px_args32.subsystem_root_path); px_args.conclave_id_size = px_args32.conclave_id_size; px_args.conclave_id = CAST_USER_ADDR_T(px_args32.conclave_id); } if (error) { goto bad; } if (px_args.attr_size != 0) { /* * We are not copying the port_actions pointer, * because we already have it from px_args. * This is a bit fragile: <rdar://problem/16427422> */ if ((error = copyin(px_args.attrp, &px_sa, px_sa_offset)) != 0) { goto bad; } imgp->ip_px_sa = &px_sa; } if (px_args.file_actions_size != 0) { /* Limit file_actions to allowed number of open files */ size_t maxfa_size = PSF_ACTIONS_SIZE(proc_limitgetcur_nofile(p)); if (px_args.file_actions_size < PSF_ACTIONS_SIZE(1) || maxfa_size == 0 || px_args.file_actions_size > maxfa_size) { error = EINVAL; goto bad; } px_sfap = kalloc_data(px_args.file_actions_size, Z_WAITOK); if (px_sfap == NULL) { error = ENOMEM; goto bad; } imgp->ip_px_sfa = px_sfap; if ((error = copyin(px_args.file_actions, px_sfap, px_args.file_actions_size)) != 0) { goto bad; } /* Verify that the action count matches the struct size */ size_t psfsize = PSF_ACTIONS_SIZE(px_sfap->psfa_act_count); if (psfsize == 0 || psfsize != px_args.file_actions_size) { error = EINVAL; goto bad; } } if (px_args.port_actions_size != 0) { /* Limit port_actions to one page of data */ if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) || px_args.port_actions_size > PAGE_SIZE) { error = EINVAL; goto bad; } px_spap = kalloc_data(px_args.port_actions_size, Z_WAITOK); if (px_spap == NULL) { error = ENOMEM; goto bad; } imgp->ip_px_spa = px_spap; if ((error = copyin(px_args.port_actions, px_spap, px_args.port_actions_size)) != 0) { goto bad; } /* Verify that the action count matches the struct size */ size_t pasize = PS_PORT_ACTIONS_SIZE(px_spap->pspa_count); if (pasize == 0 || pasize != px_args.port_actions_size) { error = EINVAL; goto bad; } } #if CONFIG_PERSONAS /* copy in the persona info */ if (px_args.persona_info_size != 0 && px_args.persona_info != 0) { /* for now, we need the exact same struct in user space */ if (px_args.persona_info_size != sizeof(*px_persona)) { error = ERANGE; goto bad; } px_persona = kalloc_data(px_args.persona_info_size, Z_WAITOK); if (px_persona == NULL) { error = ENOMEM; goto bad; } imgp->ip_px_persona = px_persona; if ((error = copyin(px_args.persona_info, px_persona, px_args.persona_info_size)) != 0) { goto bad; } if ((error = spawn_validate_persona(px_persona)) != 0) { goto bad; } } #endif /* copy in the posix cred info */ if (px_args.posix_cred_info_size != 0 && px_args.posix_cred_info != 0) { /* for now, we need the exact same struct in user space */ if (px_args.posix_cred_info_size != sizeof(*px_pcred_info)) { error = ERANGE; goto bad; } if (!kauth_cred_issuser(kauth_cred_get())) { error = EPERM; goto bad; } px_pcred_info = kalloc_data(px_args.posix_cred_info_size, Z_WAITOK); if (px_pcred_info == NULL) { error = ENOMEM; goto bad; } imgp->ip_px_pcred_info = px_pcred_info; if ((error = copyin(px_args.posix_cred_info, px_pcred_info, px_args.posix_cred_info_size)) != 0) { goto bad; } if (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_GROUPS) { if (px_pcred_info->pspci_ngroups > NGROUPS_MAX) { error = EINVAL; goto bad; } } /* to align `setlogin` syscall behaviour and login name via posix_spawn: * we need to make sure that the logname is always null-terminated despite * the last character not being null (look at setlogin in kern_prot.c) */ px_pcred_info->pspci_login[MAXLOGNAME] = 0; } #if CONFIG_MACF if (px_args.mac_extensions_size != 0) { if ((error = spawn_copyin_macpolicyinfo(&px_args, (struct ip_px_smpx_s *)&imgp->ip_px_smpx)) != 0) { goto bad; } } #endif /* CONFIG_MACF */ if ((px_args.subsystem_root_path_size > 0) && (px_args.subsystem_root_path_size <= MAXPATHLEN)) { /* * If a valid-looking subsystem root has been * specified... */ if (IOTaskHasEntitlement(old_task, SPAWN_SUBSYSTEM_ROOT_ENTITLEMENT)) { /* * ...AND the parent has the entitlement, copy * the subsystem root path in. */ subsystem_root_path = zalloc_flags(ZV_NAMEI, Z_WAITOK | Z_ZERO | Z_NOFAIL); if ((error = copyin(px_args.subsystem_root_path, subsystem_root_path, px_args.subsystem_root_path_size))) { goto bad; } /* Paranoia */ subsystem_root_path[px_args.subsystem_root_path_size - 1] = 0; } } #if CONFIG_EXCLAVES /* * Calling exclaves_boot_wait() ensures that the conclave name * id will only be set when exclaves are actually * supported/enabled. In practice this will never actually block * as by the time this is called the system will have booted to * EXCLAVECORE if it's supported/enabled. */ if ((px_args.conclave_id_size > 0) && (px_args.conclave_id_size <= MAXCONCLAVENAME) && (exclaves_boot_wait(EXCLAVES_BOOT_STAGE_EXCLAVECORE) == KERN_SUCCESS)) { if (px_args.conclave_id) { if (imgp->ip_px_sa != NULL && (px_sa.psa_flags & POSIX_SPAWN_SETEXEC)) { /* Conclave id could be set only for true spawn */ error = EINVAL; goto bad; } task_conclave_id = kalloc_data(MAXCONCLAVENAME, Z_WAITOK | Z_ZERO | Z_NOFAIL); if ((error = copyin(px_args.conclave_id, task_conclave_id, MAXCONCLAVENAME))) { goto bad; } task_conclave_id[MAXCONCLAVENAME - 1] = 0; } } #endif } if (IOTaskHasEntitlement(old_task, SPAWN_SET_PANIC_CRASH_BEHAVIOR)) { /* Truncate to uint8_t since we only support 2 flags for now */ crash_behavior = (uint8_t)px_sa.psa_crash_behavior; crash_behavior_deadline = px_sa.psa_crash_behavior_deadline; } /* set uthread to parent */ uthread = current_uthread(); /* * <rdar://6640530>; this does not result in a behaviour change * relative to Leopard, so there should not be any existing code * which depends on it. */ bool start_pagein_telemetry = false; if (imgp->ip_px_sa != NULL) { struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if ((psa->psa_options & PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) == PSA_OPTION_PLUGIN_HOST_DISABLE_A_KEYS) { imgp->ip_flags |= IMGPF_PLUGIN_HOST_DISABLE_A_KEYS; } #if (DEVELOPMENT || DEBUG) if ((psa->psa_options & PSA_OPTION_ALT_ROSETTA) == PSA_OPTION_ALT_ROSETTA) { imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA); } #if HAS_MTE_EMULATION_SHIMS /* If the task has inheritance enabled, carry the emulation setup. */ if (task_has_sec(old_task) && task_has_sec_inherit(old_task)) { imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA); } #endif /* HAS_MTE_EMULATION_SHIMS */ #endif /* (DEVELOPMENT || DEBUG) */ if ((error = exec_validate_spawnattr_policy(psa->psa_apptype)) != 0) { goto bad; } if ((psa->psa_options & PSA_OPTION_PAGEIN_TELEMETRY) == PSA_OPTION_PAGEIN_TELEMETRY) { start_pagein_telemetry = true; } } /* * If we don't have the extension flag that turns "posix_spawn()" * into "execve() with options", then we will be creating a new * process which does not inherit memory from the parent process, * which is one of the most expensive things about using fork() * and execve(). */ if (imgp->ip_px_sa == NULL || !(px_sa.psa_flags & POSIX_SPAWN_SETEXEC)) { /* Set the new task's coalition, if it is requested. */ coalition_t coal[COALITION_NUM_TYPES] = { COALITION_NULL }; #if CONFIG_COALITIONS int i, ncoals; kern_return_t kr = KERN_SUCCESS; struct _posix_spawn_coalition_info coal_info; int coal_role[COALITION_NUM_TYPES]; if (imgp->ip_px_sa == NULL || !px_args.coal_info) { goto do_fork1; } memset(&coal_info, 0, sizeof(coal_info)); if (px_args.coal_info_size > sizeof(coal_info)) { px_args.coal_info_size = sizeof(coal_info); } error = copyin(px_args.coal_info, &coal_info, px_args.coal_info_size); if (error != 0) { goto bad; } ncoals = 0; for (i = 0; i < COALITION_NUM_TYPES; i++) { uint64_t cid = coal_info.psci_info[i].psci_id; if (cid != 0) { /* * don't allow tasks which are not in a * privileged coalition to spawn processes * into coalitions other than their own */ if (!task_is_in_privileged_coalition(proc_task(p), i) && !IOTaskHasEntitlement(proc_task(p), COALITION_SPAWN_ENTITLEMENT)) { coal_dbg("ERROR: %d not in privileged coalition of type %d", proc_getpid(p), i); spawn_coalitions_release_all(coal); error = EPERM; goto bad; } coal_dbg("searching for coalition id:%llu", cid); /* * take a reference and activation on the * coalition to guard against free-while-spawn * races */ coal[i] = coalition_find_and_activate_by_id(cid); if (coal[i] == COALITION_NULL) { coal_dbg("could not find coalition id:%llu " "(perhaps it has been terminated or reaped)", cid); /* * release any other coalition's we * may have a reference to */ spawn_coalitions_release_all(coal); error = ESRCH; goto bad; } if (coalition_type(coal[i]) != i) { coal_dbg("coalition with id:%lld is not of type:%d" " (it's type:%d)", cid, i, coalition_type(coal[i])); spawn_coalitions_release_all(coal); error = ESRCH; goto bad; } coal_role[i] = coal_info.psci_info[i].psci_role; ncoals++; } } if (start_pagein_telemetry) { void telemetry_pagein_start(void *coal); telemetry_pagein_start(coal[COALITION_TYPE_JETSAM]); } if (ncoals < COALITION_NUM_TYPES) { /* * If the user is attempting to spawn into a subset of * the known coalition types, then make sure they have * _at_least_ specified a resource coalition. If not, * the following fork1() call will implicitly force an * inheritance from 'p' and won't actually spawn the * new task into the coalitions the user specified. * (also the call to coalitions_set_roles will panic) */ if (coal[COALITION_TYPE_RESOURCE] == COALITION_NULL) { spawn_coalitions_release_all(coal); error = EINVAL; goto bad; } } do_fork1: #endif /* CONFIG_COALITIONS */ /* * note that this will implicitly inherit the * caller's persona (if it exists) */ error = fork1(p, &imgp->ip_new_thread, PROC_CREATE_SPAWN, coal); /* returns a thread and task reference */ if (error == 0) { new_task = get_threadtask(imgp->ip_new_thread); } #if CONFIG_COALITIONS /* set the roles of this task within each given coalition */ if (error == 0) { kr = coalitions_set_roles(coal, new_task, coal_role); if (kr != KERN_SUCCESS) { error = EINVAL; } if (kdebug_debugid_enabled(MACHDBG_CODE(DBG_MACH_COALITION, MACH_COALITION_ADOPT))) { for (i = 0; i < COALITION_NUM_TYPES; i++) { if (coal[i] != COALITION_NULL) { /* * On 32-bit targets, uniqueid * will get truncated to 32 bits */ KDBG_RELEASE(MACHDBG_CODE( DBG_MACH_COALITION, MACH_COALITION_ADOPT), coalition_id(coal[i]), get_task_uniqueid(new_task)); } } } } /* drop our references and activations - fork1() now holds them */ spawn_coalitions_release_all(coal); #endif /* CONFIG_COALITIONS */ if (error != 0) { goto bad; } imgp->ip_flags |= IMGPF_SPAWN; /* spawn w/o exec */ spawn_no_exec = TRUE; /* used in later tests */ } else { /* Adjust the user proc count */ (void)chgproccnt(kauth_getruid(), 1); /* * For execve case, create a new proc, task and thread * but don't make the proc visible to userland. After * image activation, the new proc would take place of * the old proc in pid hash and other lists that make * the proc visible to the system. */ imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_EXEC); /* task and thread ref returned by cloneproc */ if (imgp->ip_new_thread == NULL) { (void)chgproccnt(kauth_getruid(), -1); error = ENOMEM; goto bad; } new_task = get_threadtask(imgp->ip_new_thread); imgp->ip_flags |= IMGPF_EXEC; } p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread); if (spawn_no_exec) { /* * We had to wait until this point before firing the * proc:::create probe, otherwise p would not point to the * child process. */ DTRACE_PROC1(create, proc_t, p); } assert(p != NULL); if (subsystem_root_path) { /* If a subsystem root was specified, swap it in */ char * old_subsystem_root_path = p->p_subsystem_root_path; p->p_subsystem_root_path = subsystem_root_path; subsystem_root_path = old_subsystem_root_path; } p->p_crash_behavior = crash_behavior; p->p_crash_behavior_deadline = crash_behavior_deadline; p->p_crash_count = px_sa.psa_crash_count; p->p_throttle_timeout = px_sa.psa_throttle_timeout; /* We'll need the subsystem root for setting up Apple strings */ imgp->ip_subsystem_root_path = p->p_subsystem_root_path; context.vc_thread = imgp->ip_new_thread; context.vc_ucred = proc_ucred_unsafe(p); /* in init */ /* * Post fdt_fork(), pre exec_handle_sugid() - this is where we want * to handle the file_actions. */ /* Has spawn file actions? */ if (imgp->ip_px_sfa != NULL) { /* * The POSIX_SPAWN_CLOEXEC_DEFAULT flag * is handled in exec_handle_file_actions(). */ #if CONFIG_AUDIT /* * The file actions auditing can overwrite the upath of * AUE_POSIX_SPAWN audit record. Save the audit record. */ struct kaudit_record *save_uu_ar = uthread->uu_ar; uthread->uu_ar = NULL; #endif error = exec_handle_file_actions(imgp, imgp->ip_px_sa != NULL ? px_sa.psa_flags : 0); #if CONFIG_AUDIT /* Restore the AUE_POSIX_SPAWN audit record. */ uthread->uu_ar = save_uu_ar; #endif if (error != 0) { goto bad; } } /* Has spawn port actions? */ if (imgp->ip_px_spa != NULL) { #if CONFIG_AUDIT /* * Do the same for the port actions as we did for the file * actions. Save the AUE_POSIX_SPAWN audit record. */ struct kaudit_record *save_uu_ar = uthread->uu_ar; uthread->uu_ar = NULL; #endif error = exec_handle_port_actions(imgp, &port_actions); #if CONFIG_AUDIT /* Restore the AUE_POSIX_SPAWN audit record. */ uthread->uu_ar = save_uu_ar; #endif if (error != 0) { goto bad; } } /* Has spawn attr? */ if (imgp->ip_px_sa != NULL) { /* * Reset UID/GID to parent's RUID/RGID; This works only * because the operation occurs before the call * to exec_handle_sugid() by the image activator called * from exec_activate_image(). * * POSIX requires that any setuid/setgid bits on the process * image will take precedence over the spawn attributes * (re)setting them. * * Modifications to p_ucred must be guarded using the * proc's ucred lock. This prevents others from accessing * a garbage credential. */ if (px_sa.psa_flags & POSIX_SPAWN_RESETIDS) { kauth_cred_proc_update(p, PROC_SETTOKEN_NONE, ^bool (kauth_cred_t parent __unused, kauth_cred_t model){ return kauth_cred_model_setuidgid(model, kauth_cred_getruid(parent), kauth_cred_getrgid(parent)); }); } if (imgp->ip_px_pcred_info) { if (!spawn_no_exec) { error = ENOTSUP; goto bad; } error = spawn_posix_cred_adopt(p, imgp->ip_px_pcred_info); if (error != 0) { goto bad; } } #if CONFIG_PERSONAS if (imgp->ip_px_persona != NULL) { if (!spawn_no_exec) { error = ENOTSUP; goto bad; } /* * If we were asked to spawn a process into a new persona, * do the credential switch now (which may override the UID/GID * inherit done just above). It's important to do this switch * before image activation both for reasons stated above, and * to ensure that the new persona has access to the image/file * being executed. */ error = spawn_persona_adopt(p, imgp->ip_px_persona); if (error != 0) { goto bad; } } #endif /* CONFIG_PERSONAS */ #if !SECURE_KERNEL /* * Disable ASLR for the spawned process. * * But only do so if we are not embedded + RELEASE. * While embedded allows for a boot-arg (-disable_aslr) * to deal with this (which itself is only honored on * DEVELOPMENT or DEBUG builds of xnu), it is often * useful or necessary to disable ASLR on a per-process * basis for unit testing and debugging. */ if (px_sa.psa_flags & _POSIX_SPAWN_DISABLE_ASLR) { OSBitOrAtomic(P_DISABLE_ASLR, &p->p_flag); } #endif /* !SECURE_KERNEL */ /* Randomize high bits of ASLR slide */ if (px_sa.psa_flags & _POSIX_SPAWN_HIGH_BITS_ASLR) { imgp->ip_flags |= IMGPF_HIGH_BITS_ASLR; } #if !SECURE_KERNEL /* * Forcibly disallow execution from data pages for the spawned process * even if it would otherwise be permitted by the architecture default. */ if (px_sa.psa_flags & _POSIX_SPAWN_ALLOW_DATA_EXEC) { imgp->ip_flags |= IMGPF_ALLOW_DATA_EXEC; } #endif /* !SECURE_KERNEL */ #if __has_feature(ptrauth_calls) if (vm_shared_region_reslide_aslr && is_64 && (px_sa.psa_flags & _POSIX_SPAWN_RESLIDE)) { imgp->ip_flags |= IMGPF_RESLIDE; } #endif /* __has_feature(ptrauth_calls) */ if ((px_sa.psa_apptype & POSIX_SPAWN_PROC_TYPE_MASK) == POSIX_SPAWN_PROC_TYPE_DRIVER) { imgp->ip_flags |= IMGPF_DRIVER; } } /* * Disable ASLR during image activation. This occurs either if the * _POSIX_SPAWN_DISABLE_ASLR attribute was found above or if * P_DISABLE_ASLR was inherited from the parent process. */ if (p->p_flag & P_DISABLE_ASLR) { imgp->ip_flags |= IMGPF_DISABLE_ASLR; } /* * Clear transition flag so we won't hang if exec_activate_image() causes * an automount (and launchd does a proc sysctl to service it). * * <rdar://problem/6848672>, <rdar://problem/5959568>. */ proc_transend(p, 0); proc_transit_set = 0; if (!spawn_no_exec) { /* * Clear the signal lock in case of exec, since * image activation uses psignal on child process. */ proc_signalend(p, 0); proc_signal_set = 0; } #if MAC_SPAWN /* XXX */ if (uap->mac_p != USER_ADDR_NULL) { error = mac_execve_enter(uap->mac_p, imgp); if (error) { goto bad; } } #endif /* * Activate the image. * Warning: If activation failed after point of no return, it returns error * as 0 and pretends the call succeeded. */ error = exec_activate_image(imgp); #if defined(HAS_APPLE_PAC) const uint8_t disable_user_jop = imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE; ml_task_set_jop_pid_from_shared_region(new_task, disable_user_jop); ml_task_set_disable_user_jop(new_task, disable_user_jop); ml_thread_set_disable_user_jop(imgp->ip_new_thread, disable_user_jop); ml_thread_set_jop_pid(imgp->ip_new_thread, new_task); #endif /* * If you've come here to add support for some new HW feature or some per-process or per-vmmap * or per-pmap flag that needs to be set before the process runs, or are in general lost, here * is some help. This summary was accurate as of Jul 2022. Use git log as needed. This comment * is here to prevent a recurrence of rdar://96307913 * * In posix_spawn, following is what happens: * 1. Lots of prep and checking work * 2. Image activation via exec_activate_image(). The new task will get a new pmap here * 3. More prep work. (YOU ARE HERE) * 4. exec_resettextvp() is called * 5. At this point it is safe to check entitlements and code signatures * 6. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT); * The new thread is allowed to run in kernel. It cannot yet get to userland * 7. More things done here. This is your chance to affect the task before it runs in * userspace * 8. task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_FINAL_WAIT); * The new thread is allowed to run in userland */ if (error == 0 && !spawn_no_exec) { p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp, &inherit); /* proc ref returned */ should_release_proc_ref = TRUE; } if (error == 0) { /* process completed the exec, but may have failed after point of no return */ exec_done = TRUE; } #if CONFIG_EXCLAVES if (!error && task_conclave_id != NULL) { kern_return_t kr; kr = task_add_conclave(new_task, imgp->ip_vp, (int64_t)imgp->ip_arch_offset, task_conclave_id); if (kr != KERN_SUCCESS) { error = EINVAL; goto bad; } } #endif if (!error && imgp->ip_px_sa != NULL) { thread_t child_thread = imgp->ip_new_thread; uthread_t child_uthread = get_bsdthread_info(child_thread); /* * Because of POSIX_SPAWN_SETEXEC, we need to handle this after image * activation, else when image activation fails (before the point of no * return) would leave the parent process in a modified state. */ if (px_sa.psa_flags & POSIX_SPAWN_SETPGROUP) { struct setpgid_args spga; spga.pid = proc_getpid(p); spga.pgid = px_sa.psa_pgroup; /* * Effectively, call setpgid() system call; works * because there are no pointer arguments. */ if ((error = setpgid(p, &spga, ival)) != 0) { goto bad_px_sa; } } if (px_sa.psa_flags & POSIX_SPAWN_SETSID) { error = setsid_internal(p); if (error != 0) { goto bad_px_sa; } } /* * If we have a spawn attr, and it contains signal related flags, * the we need to process them in the "context" of the new child * process, so we have to process it following image activation, * prior to making the thread runnable in user space. This is * necessitated by some signal information being per-thread rather * than per-process, and we don't have the new allocation in hand * until after the image is activated. */ /* * Mask a list of signals, instead of them being unmasked, if * they were unmasked in the parent; note that some signals * are not maskable. */ if (px_sa.psa_flags & POSIX_SPAWN_SETSIGMASK) { child_uthread->uu_sigmask = (px_sa.psa_sigmask & ~sigcantmask); } /* * Default a list of signals instead of ignoring them, if * they were ignored in the parent. Note that we pass * spawn_no_exec to setsigvec() to indicate that we called * fork1() and therefore do not need to call proc_signalstart() * internally. */ if (px_sa.psa_flags & POSIX_SPAWN_SETSIGDEF) { vec.sa_handler = SIG_DFL; vec.sa_tramp = 0; vec.sa_mask = 0; vec.sa_flags = 0; for (sig = 1; sig < NSIG; sig++) { if (px_sa.psa_sigdefault & (1 << (sig - 1))) { error = setsigvec(p, child_thread, sig, &vec, spawn_no_exec); } } } /* * Activate the CPU usage monitor, if requested. This is done via a task-wide, per-thread CPU * usage limit, which will generate a resource exceeded exception if any one thread exceeds the * limit. * * Userland gives us interval in seconds, and the kernel SPI expects nanoseconds. */ if ((px_sa.psa_cpumonitor_percent != 0) && (px_sa.psa_cpumonitor_percent < UINT8_MAX)) { /* * Always treat a CPU monitor activation coming from spawn as entitled. Requiring * an entitlement to configure the monitor a certain way seems silly, since * whomever is turning it on could just as easily choose not to do so. */ error = proc_set_task_ruse_cpu(proc_task(p), TASK_POLICY_RESOURCE_ATTRIBUTE_NOTIFY_EXC, (uint8_t)px_sa.psa_cpumonitor_percent, px_sa.psa_cpumonitor_interval * NSEC_PER_SEC, 0, TRUE); } if (px_pcred_info && (px_pcred_info->pspci_flags & POSIX_SPAWN_POSIX_CRED_LOGIN)) { /* * setlogin() must happen after setsid() */ setlogin_internal(p, px_pcred_info->pspci_login); } bad_px_sa: if (error != 0) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR, 0, 0); exec_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_BAD_PSATTR); } } bad: if (error == 0) { /* reset delay idle sleep status if set */ #if CONFIG_DELAY_IDLE_SLEEP if ((p->p_flag & P_DELAYIDLESLEEP) == P_DELAYIDLESLEEP) { OSBitAndAtomic(~((uint32_t)P_DELAYIDLESLEEP), &p->p_flag); } #endif /* CONFIG_DELAY_IDLE_SLEEP */ /* upon successful spawn, re/set the proc control state */ if (imgp->ip_px_sa != NULL) { switch (px_sa.psa_pcontrol) { case POSIX_SPAWN_PCONTROL_THROTTLE: p->p_pcaction = P_PCTHROTTLE; break; case POSIX_SPAWN_PCONTROL_SUSPEND: p->p_pcaction = P_PCSUSP; break; case POSIX_SPAWN_PCONTROL_KILL: p->p_pcaction = P_PCKILL; break; case POSIX_SPAWN_PCONTROL_NONE: default: p->p_pcaction = 0; break; } ; } exec_resettextvp(p, imgp); vm_map_setup(get_task_map(new_task), new_task); /* * Set starting EXC_GUARD behavior for task now that platform * and platform restrictions bits are set. */ task_set_exc_guard_default(new_task, proc_best_name(p), strlen(proc_best_name(p)), proc_is_simulated(p), proc_platform(p), proc_sdk(p)); /* * Between proc_exec_switch_task and ipc_task_enable, there is a * window where proc_find will return the new proc, but task_for_pid * and similar functions will return an error as the task ipc is not * enabled yet. Configure the task control port during this window * before other process have access to this task port. * * Must enable after resettextvp so that task port policies are not evaluated * until the csblob in the textvp is accurately reflected. */ task_set_ctrl_port_default(new_task, imgp->ip_new_thread); /* * Enable new task IPC access if exec_activate_image() returned an * active task. (Checks active bit in ipc_task_enable() under lock). * Similarly, this must happen after resettextvp. */ ipc_task_enable(new_task); /* Set task exception ports now that we can check entitlements */ if (imgp->ip_px_spa != NULL) { error = exec_handle_exception_port_actions(imgp, &port_actions); } #if CONFIG_MEMORYSTATUS /* Set jetsam priority for DriverKit processes */ if (px_sa.psa_apptype == POSIX_SPAWN_PROC_TYPE_DRIVER) { px_sa.psa_priority = JETSAM_PRIORITY_DRIVER_APPLE; } /* Has jetsam attributes? */ if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_SET)) { int32_t memlimit_active = px_sa.psa_memlimit_active; int32_t memlimit_inactive = px_sa.psa_memlimit_inactive; memstat_priority_options_t priority_options = MEMSTAT_PRIORITY_OPTIONS_NONE; if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY)) { priority_options |= MEMSTAT_PRIORITY_IS_EFFECTIVE; } memorystatus_set_priority(p, px_sa.psa_priority, 0, priority_options); memlimit_options_t memlimit_options = MEMLIMIT_OPTIONS_NONE; if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_ACTIVE_FATAL)) { memlimit_options |= MEMLIMIT_ACTIVE_FATAL; } if ((px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_MEMLIMIT_INACTIVE_FATAL)) { memlimit_options |= MEMLIMIT_INACTIVE_FATAL; } if (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND) { /* * With 2-level high-water-mark support, * POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is no longer relevant, * as background limits are described via the inactive limit * slots. However, if the * POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND is passed in, we * attempt to mimic previous behavior by forcing the BG limit * data into the inactive/non-fatal mode and force the active * slots to hold system_wide/fatal mode. */ memlimit_options |= MEMLIMIT_ACTIVE_FATAL; memlimit_options &= ~MEMLIMIT_INACTIVE_FATAL; memlimit_active = -1; } memorystatus_set_memlimits(p, memlimit_active, memlimit_inactive, memlimit_options); } /* Has jetsam relaunch behavior? */ if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK)) { /* * Launchd has passed in data indicating the behavior of this process in response to jetsam. * This data would be used by the jetsam subsystem to determine the position and protection * offered to this process on dirty -> clean transitions. */ int relaunch_flags = P_MEMSTAT_RELAUNCH_UNKNOWN; switch (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MASK) { case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_LOW: relaunch_flags = P_MEMSTAT_RELAUNCH_LOW; break; case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_MED: relaunch_flags = P_MEMSTAT_RELAUNCH_MED; break; case POSIX_SPAWN_JETSAM_RELAUNCH_BEHAVIOR_HIGH: relaunch_flags = P_MEMSTAT_RELAUNCH_HIGH; break; default: break; } memorystatus_relaunch_flags_update(p, relaunch_flags); } #endif /* CONFIG_MEMORYSTATUS */ if (imgp->ip_px_sa != NULL && px_sa.psa_thread_limit > 0) { task_set_thread_limit(new_task, (uint16_t)px_sa.psa_thread_limit); } if (error == 0 && imgp->ip_px_sa != NULL && px_sa.psa_conclave_mem_limit > 0) { error = task_set_conclave_mem_limit_internal(new_task, px_sa.psa_conclave_mem_limit); } #if CONFIG_PROC_RESOURCE_LIMITS if (imgp->ip_px_sa != NULL && (px_sa.psa_port_soft_limit > 0 || px_sa.psa_port_hard_limit > 0)) { task_set_port_space_limits(new_task, (uint32_t)px_sa.psa_port_soft_limit, (uint32_t)px_sa.psa_port_hard_limit); } if (imgp->ip_px_sa != NULL && (px_sa.psa_filedesc_soft_limit > 0 || px_sa.psa_filedesc_hard_limit > 0)) { proc_set_filedesc_limits(p, (int)px_sa.psa_filedesc_soft_limit, (int)px_sa.psa_filedesc_hard_limit); } if (imgp->ip_px_sa != NULL && (px_sa.psa_kqworkloop_soft_limit > 0 || px_sa.psa_kqworkloop_hard_limit > 0)) { proc_set_kqworkloop_limits(p, (int)px_sa.psa_kqworkloop_soft_limit, (int)px_sa.psa_kqworkloop_hard_limit); } #endif /* CONFIG_PROC_RESOURCE_LIMITS */ if (imgp->ip_px_sa != NULL && (px_sa.psa_jetsam_flags & POSIX_SPAWN_JETSAM_REALTIME_AUDIO)) { task_set_jetsam_realtime_audio(new_task, TRUE); } } /* * If we successfully called fork1() or cloneproc, we always need * to do this. This is because we come back from that call with * signals blocked in the child, and we have to unblock them, for exec * case they are unblocked before activation, but for true spawn case * we want to wait until after we've performed any spawn actions. * This has to happen before process_signature(), which uses psignal. */ if (proc_transit_set) { proc_transend(p, 0); } /* * Drop the signal lock on the child which was taken on our * behalf by forkproc()/cloneproc() to prevent signals being * received by the child in a partially constructed state. */ if (proc_signal_set) { proc_signalend(p, 0); } if (error == 0) { /* * We need to initialize the bank context behind the protection of * the proc_trans lock to prevent a race with exit. We can't do this during * exec_activate_image because task_bank_init checks entitlements that * aren't loaded until subsequent calls (including exec_resettextvp). */ error = proc_transstart(p, 0, 0); if (error == 0) { task_bank_init(new_task); proc_transend(p, 0); } #if __arm64__ proc_footprint_entitlement_hacks(p, new_task); #endif /* __arm64__ */ memorystatus_set_proc_entitlement_flags(p); #if XNU_TARGET_OS_OSX #define SINGLE_JIT_ENTITLEMENT "com.apple.security.cs.single-jit" if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) { vm_map_single_jit(get_task_map(new_task)); } #endif /* XNU_TARGET_OS_OSX */ #if __has_feature(ptrauth_calls) task_set_pac_exception_fatal_flag(new_task); #endif /* __has_feature(ptrauth_calls) */ task_set_jit_flags(new_task); } /* Inherit task role from old task to new task for exec */ if (error == 0 && !spawn_no_exec) { proc_inherit_task_role(new_task, old_task); } #if CONFIG_ARCADE if (error == 0) { /* * Check to see if we need to trigger an arcade upcall AST now * that the vnode has been reset on the task. */ arcade_prepare(new_task, imgp->ip_new_thread); } #endif /* CONFIG_ARCADE */ if (error == 0) { proc_apply_jit_and_vm_policies(imgp, p, new_task); } /* Clear the initial wait on the thread before handling spawn policy */ if (imgp && imgp->ip_new_thread) { task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT); } /* * Apply the spawnattr policy, apptype (which primes the task for importance donation), * and bind any portwatch ports to the new task. * This must be done after the exec so that the child's thread is ready, * and after the in transit state has been released, because priority is * dropped here so we need to be prepared for a potentially long preemption interval * * TODO: Consider splitting this up into separate phases */ if (error == 0 && imgp->ip_px_sa != NULL) { struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa; error = exec_handle_spawnattr_policy(p, imgp->ip_new_thread, psa->psa_apptype, psa->psa_qos_clamp, psa->psa_darwin_role, &port_actions); } /* Transfer the turnstile watchport boost to new task if in exec */ if (error == 0 && !spawn_no_exec) { task_transfer_turnstile_watchports(old_task, new_task, imgp->ip_new_thread); } if (error == 0 && imgp->ip_px_sa != NULL) { struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa->psa_no_smt) { task_set_no_smt(new_task); } if (psa->psa_tecs) { task_set_tecs(new_task); } } struct _iopol_param_t iop_param = { .iop_scope = IOPOL_SCOPE_PROCESS, .iop_iotype = IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES, }; if (error == 0) { if (imgp->ip_px_sa != NULL) { struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa->psa_options & PSA_OPTION_DATALESS_IOPOLICY) { iop_param.iop_policy = psa->psa_dataless_iopolicy; } } else { error = iopolicysys_vfs_materialize_dataless_files(p, IOPOL_CMD_GET, iop_param.iop_scope, iop_param.iop_policy, &iop_param); } } if (error == 0 && iop_param.iop_policy != 0) { error = iopolicysys_vfs_materialize_dataless_files(p, IOPOL_CMD_SET, iop_param.iop_scope, (iop_param.iop_policy | IOPOL_MATERIALIZE_DATALESS_FILES_ORIG), &iop_param); } if (error == 0) { /* Apply the main thread qos */ thread_t main_thread = imgp->ip_new_thread; task_set_main_thread_qos(new_task, main_thread); } /* * Release any ports we kept around for binding to the new task * We need to release the rights even if the posix_spawn has failed. */ if (imgp->ip_px_spa != NULL) { exec_port_actions_destroy(&port_actions); } /* * We have to delay operations which might throw a signal until after * the signals have been unblocked; however, we want that to happen * after exec_resettextvp() so that the textvp is correct when they * fire. */ if (error == 0) { error = process_signature(p, imgp); /* * Pay for our earlier safety; deliver the delayed signals from * the incomplete spawn process now that it's complete. */ if (imgp != NULL && spawn_no_exec && (p->p_lflag & P_LTRACED)) { psignal_vfork(p, proc_task(p), imgp->ip_new_thread, SIGTRAP); } if (error == 0 && !spawn_no_exec) { extern uint64_t kdp_task_exec_meta_flags(task_t task); KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXEC), proc_getpid(p), kdp_task_exec_meta_flags(proc_task(p))); } } if (spawn_no_exec) { /* flag the 'fork' has occurred */ proc_knote(p->p_pptr, NOTE_FORK | proc_getpid(p)); } /* flag exec has occurred, notify only if it has not failed due to FP Key error */ if (!error && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) { proc_knote(p, NOTE_EXEC); } if (imgp != NULL) { uthread_set_exec_data(current_uthread(), NULL); if (imgp->ip_vp) { vnode_put(imgp->ip_vp); } if (imgp->ip_scriptvp) { vnode_put(imgp->ip_scriptvp); } if (imgp->ip_strings) { execargs_free(imgp); } if (imgp->ip_free_map) { /* Free the map after dropping iocount on vnode to avoid deadlock */ vm_map_deallocate(imgp->ip_free_map); } kfree_data(imgp->ip_px_sfa, px_args.file_actions_size); kfree_data(imgp->ip_px_spa, px_args.port_actions_size); #if CONFIG_PERSONAS kfree_data(imgp->ip_px_persona, px_args.persona_info_size); #endif kfree_data(imgp->ip_px_pcred_info, px_args.posix_cred_info_size); if (subsystem_root_path != NULL) { zfree(ZV_NAMEI, subsystem_root_path); } #if CONFIG_MACF struct ip_px_smpx_s *px_s = &imgp->ip_px_smpx; kfree_data(px_s->array, px_args.mac_extensions_size); kfree_data(px_s->data, (vm_size_t)px_s->datalen); if (imgp->ip_execlabelp) { mac_cred_label_free(imgp->ip_execlabelp); imgp->ip_execlabelp = NULL; } if (imgp->ip_scriptlabelp) { mac_vnode_label_free(imgp->ip_scriptlabelp); imgp->ip_scriptlabelp = NULL; } if (imgp->ip_cs_error != OS_REASON_NULL) { os_reason_free(imgp->ip_cs_error); imgp->ip_cs_error = OS_REASON_NULL; } if (imgp->ip_inherited_shared_region_id != NULL) { kfree_data(imgp->ip_inherited_shared_region_id, strlen(imgp->ip_inherited_shared_region_id) + 1); imgp->ip_inherited_shared_region_id = NULL; } #endif } #if CONFIG_DTRACE if (spawn_no_exec) { /* * In the original DTrace reference implementation, * posix_spawn() was a libc routine that just * did vfork(2) then exec(2). Thus the proc::: probes * are very fork/exec oriented. The details of this * in-kernel implementation of posix_spawn() is different * (while producing the same process-observable effects) * particularly w.r.t. errors, and which thread/process * is constructing what on behalf of whom. */ if (error) { DTRACE_PROC1(spawn__failure, int, error); } else { DTRACE_PROC(spawn__success); /* * Some DTrace scripts, e.g. newproc.d in * /usr/bin, rely on the the 'exec-success' * probe being fired in the child after the * new process image has been constructed * in order to determine the associated pid. * * So, even though the parent built the image * here, for compatibility, mark the new thread * so 'exec-success' fires on it as it leaves * the kernel. */ dtrace_thread_didexec(imgp->ip_new_thread); } } else { if (error) { DTRACE_PROC1(exec__failure, int, error); } else { dtrace_thread_didexec(imgp->ip_new_thread); } } if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) { (*dtrace_proc_waitfor_hook)(p); } #endif #if CONFIG_AUDIT if (!error && AUDIT_ENABLED() && p) { /* Add the CDHash of the new process to the audit record */ uint8_t *cdhash = cs_get_cdhash(p); if (cdhash) { AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN); } } #endif /* terminate the new task if exec failed */ if (new_task != NULL && task_is_exec_copy(new_task)) { task_terminate_internal(new_task); } if (exec_failure_reason && !spawn_no_exec) { psignal_with_reason(p, SIGKILL, exec_failure_reason); exec_failure_reason = NULL; } /* Return to both the parent and the child? */ if (imgp != NULL && spawn_no_exec) { /* * If the parent wants the pid, copy it out */ if (error == 0 && pid != USER_ADDR_NULL) { _Static_assert(sizeof(pid_t) == 4, "posix_spawn() assumes a 32-bit pid_t"); bool aligned = (pid & 3) == 0; if (aligned) { (void)copyout_atomic32(proc_getpid(p), pid); } else { (void)suword(pid, proc_getpid(p)); } } retval[0] = error; /* * If we had an error, perform an internal reap ; this is * entirely safe, as we have a real process backing us. */ if (error) { proc_list_lock(); p->p_listflag |= P_LIST_DEADPARENT; proc_list_unlock(); proc_lock(p); /* make sure no one else has killed it off... */ if (p->p_stat != SZOMB && p->exit_thread == NULL) { p->exit_thread = current_thread(); p->p_posix_spawn_failed = true; proc_unlock(p); exit1(p, 1, (int *)NULL); } else { /* someone is doing it for us; just skip it */ proc_unlock(p); } } } /* * Do not terminate the current task, if proc_exec_switch_task did not * switch the tasks, terminating the current task without the switch would * result in loosing the SIGKILL status. */ if (task_did_exec(old_task)) { /* Terminate the current task, since exec will start in new task */ task_terminate_internal(old_task); } /* Release the thread ref returned by cloneproc/fork1 */ if (imgp != NULL && imgp->ip_new_thread) { /* clear the exec complete flag if there is an error before point of no-return */ uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT; if (!spawn_no_exec && !exec_done && error != 0) { clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE; } /* wake up the new thread */ task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags); thread_deallocate(imgp->ip_new_thread); imgp->ip_new_thread = NULL; } /* Release the ref returned by cloneproc/fork1 */ if (new_task) { task_deallocate(new_task); new_task = NULL; } if (should_release_proc_ref) { proc_rele(p); } kfree_type(typeof(*__spawn_data), __spawn_data); if (inherit != NULL) { ipc_importance_release(inherit); } #if CONFIG_EXCLAVES if (task_conclave_id != NULL) { kfree_data(task_conclave_id, MAXCONCLAVENAME); } #endif assert(spawn_no_exec || exec_failure_reason == NULL); return error; } /* * proc_exec_switch_task * * Parameters: old_proc proc before exec * new_proc proc after exec * old_task task before exec * new_task task after exec * imgp image params * inherit resulting importance linkage * * Returns: proc. * * Note: The function will switch proc in pid hash from old proc to new proc. * The switch needs to happen after draining all proc refs and inside * a proc list lock. In the case of failure to switch the proc, which * might happen if the process received a SIGKILL or jetsam killed it, * it will make sure that the new tasks terminates. User proc ref returned * to caller. * * This function is called after point of no return, in the case * failure to switch, it will terminate the new task and swallow the * error and let the terminated process complete exec and die. */ proc_t proc_exec_switch_task(proc_t old_proc, proc_t new_proc, task_t old_task, task_t new_task, struct image_params *imgp, void **inherit) { boolean_t task_active; boolean_t proc_active; boolean_t thread_active; boolean_t reparent_traced_child = FALSE; thread_t old_thread = current_thread(); thread_t new_thread = imgp->ip_new_thread; thread_set_exec_promotion(old_thread); old_proc = proc_refdrain_will_exec(old_proc); new_proc = proc_refdrain_will_exec(new_proc); /* extra proc ref returned to the caller */ assert(get_threadtask(new_thread) == new_task); task_active = task_is_active(new_task); proc_active = !(old_proc->p_lflag & P_LEXIT); /* Check if the current thread is not aborted due to SIGKILL */ thread_active = thread_is_active(old_thread); /* * Do not switch the proc if the new task or proc is already terminated * as a result of error in exec past point of no return */ if (proc_active && task_active && thread_active) { uthread_t new_uthread = get_bsdthread_info(new_thread); uthread_t old_uthread = current_uthread(); /* Clear dispatchqueue and workloop ast offset */ new_proc->p_dispatchqueue_offset = 0; new_proc->p_dispatchqueue_serialno_offset = 0; new_proc->p_dispatchqueue_label_offset = 0; new_proc->p_return_to_kernel_offset = 0; new_proc->p_pthread_wq_quantum_offset = 0; /* If old_proc is session leader, change the leader to new proc */ session_replace_leader(old_proc, new_proc); proc_lock(old_proc); /* Copy the signal state, dtrace state and set bsd ast on new thread */ act_set_astbsd(new_thread); new_uthread->uu_siglist |= old_uthread->uu_siglist; new_uthread->uu_siglist |= old_proc->p_siglist; new_uthread->uu_sigwait = old_uthread->uu_sigwait; new_uthread->uu_sigmask = old_uthread->uu_sigmask; new_uthread->uu_oldmask = old_uthread->uu_oldmask; new_uthread->uu_exit_reason = old_uthread->uu_exit_reason; #if CONFIG_DTRACE new_uthread->t_dtrace_sig = old_uthread->t_dtrace_sig; new_uthread->t_dtrace_stop = old_uthread->t_dtrace_stop; new_uthread->t_dtrace_resumepid = old_uthread->t_dtrace_resumepid; assert(new_uthread->t_dtrace_scratch == NULL); new_uthread->t_dtrace_scratch = old_uthread->t_dtrace_scratch; old_uthread->t_dtrace_sig = 0; old_uthread->t_dtrace_stop = 0; old_uthread->t_dtrace_resumepid = 0; old_uthread->t_dtrace_scratch = NULL; #endif #if CONFIG_PROC_UDATA_STORAGE new_proc->p_user_data = old_proc->p_user_data; #endif /* CONFIG_PROC_UDATA_STORAGE */ /* Copy the resource accounting info */ thread_copy_resource_info(new_thread, current_thread()); /* Clear the exit reason and signal state on old thread */ old_uthread->uu_exit_reason = NULL; old_uthread->uu_siglist = 0; task_set_did_exec_flag(old_task); task_clear_exec_copy_flag(new_task); task_copy_fields_for_exec(new_task, old_task); /* * Need to transfer pending watch port boosts to the new task * while still making sure that the old task remains in the * importance linkage. Create an importance linkage from old task * to new task, then switch the task importance base of old task * and new task. After the switch the port watch boost will be * boosting the new task and new task will be donating importance * to old task. */ *inherit = ipc_importance_exec_switch_task(old_task, new_task); /* Transfer parent's ptrace state to child */ new_proc->p_lflag &= ~(P_LTRACED | P_LSIGEXC | P_LNOATTACH); new_proc->p_lflag |= (old_proc->p_lflag & (P_LTRACED | P_LSIGEXC | P_LNOATTACH)); new_proc->p_oppid = old_proc->p_oppid; if (old_proc->p_pptr != new_proc->p_pptr) { reparent_traced_child = TRUE; new_proc->p_lflag |= P_LTRACE_WAIT; } proc_unlock(old_proc); /* Update the list of proc knotes */ proc_transfer_knotes(old_proc, new_proc); /* Update the proc interval timers */ proc_inherit_itimers(old_proc, new_proc); proc_list_lock(); /* Insert the new proc in child list of parent proc */ p_reparentallchildren(old_proc, new_proc); /* Switch proc in pid hash */ phash_replace_locked(old_proc, new_proc); /* Transfer the shadow flag to old proc */ os_atomic_andnot(&new_proc->p_refcount, P_REF_SHADOW, relaxed); os_atomic_or(&old_proc->p_refcount, P_REF_SHADOW, relaxed); /* Change init proc if launchd exec */ if (old_proc == initproc) { /* Take the ref on new proc after proc_refwake_did_exec */ initproc = new_proc; /* Drop the proc ref on old proc */ proc_rele(old_proc); } proc_list_unlock(); #if CONFIG_EXCLAVES if (task_inherit_conclave(old_task, new_task, imgp->ip_vp, (int64_t)imgp->ip_arch_offset) != KERN_SUCCESS) { task_terminate_internal(new_task); } #endif } else { task_terminate_internal(new_task); } proc_refwake_did_exec(new_proc); proc_refwake_did_exec(old_proc); /* Take a ref on initproc if it changed */ if (new_proc == initproc) { initproc = proc_ref(new_proc, false); assert(initproc != PROC_NULL); } thread_clear_exec_promotion(old_thread); proc_rele(old_proc); if (reparent_traced_child) { proc_t pp = proc_parent(old_proc); assert(pp != PROC_NULL); proc_reparentlocked(new_proc, pp, 1, 0); proc_rele(pp); proc_lock(new_proc); new_proc->p_lflag &= ~P_LTRACE_WAIT; proc_unlock(new_proc); } return new_proc; } /* * execve * * Parameters: uap->fname File name to exec * uap->argp Argument list * uap->envp Environment list * * Returns: 0 Success * __mac_execve:EINVAL Invalid argument * __mac_execve:ENOTSUP Invalid argument * __mac_execve:EACCES Permission denied * __mac_execve:EINTR Interrupted function * __mac_execve:ENOMEM Not enough space * __mac_execve:EFAULT Bad address * __mac_execve:ENAMETOOLONG Filename too long * __mac_execve:ENOEXEC Executable file format error * __mac_execve:ETXTBSY Text file busy [misuse of error code] * __mac_execve:??? * * TODO: Dynamic linker header address on stack is copied via suword() */ /* ARGSUSED */ int execve(proc_t p, struct execve_args *uap, int32_t *retval) { struct __mac_execve_args muap; int err; memoryshot(DBG_VM_EXECVE, DBG_FUNC_NONE); muap.fname = uap->fname; muap.argp = uap->argp; muap.envp = uap->envp; muap.mac_p = USER_ADDR_NULL; err = __mac_execve(p, &muap, retval); return err; } /* * __mac_execve * * Parameters: uap->fname File name to exec * uap->argp Argument list * uap->envp Environment list * uap->mac_p MAC label supplied by caller * * Returns: 0 Success * EINVAL Invalid argument * ENOTSUP Not supported * ENOEXEC Executable file format error * exec_activate_image:EINVAL Invalid argument * exec_activate_image:EACCES Permission denied * exec_activate_image:EINTR Interrupted function * exec_activate_image:ENOMEM Not enough space * exec_activate_image:EFAULT Bad address * exec_activate_image:ENAMETOOLONG Filename too long * exec_activate_image:ENOEXEC Executable file format error * exec_activate_image:ETXTBSY Text file busy [misuse of error code] * exec_activate_image:EBADEXEC The executable is corrupt/unknown * exec_activate_image:??? * mac_execve_enter:??? * * TODO: Dynamic linker header address on stack is copied via suword() */ int __mac_execve(proc_t p, struct __mac_execve_args *uap, int32_t *retval __unused) { struct image_params *imgp = NULL; struct vnode_attr *vap = NULL; struct vnode_attr *origvap = NULL; int error; int is_64 = IS_64BIT_PROCESS(p); struct vfs_context context; struct uthread *uthread = NULL; task_t old_task = current_task(); task_t new_task = NULL; boolean_t should_release_proc_ref = FALSE; boolean_t exec_done = FALSE; void *inherit = NULL; struct { struct image_params imgp; struct vnode_attr va; struct vnode_attr origva; } *__execve_data; /* Allocate a big chunk for locals instead of using stack since these * structures are pretty big. */ __execve_data = kalloc_type(typeof(*__execve_data), Z_WAITOK | Z_ZERO); if (__execve_data == NULL) { error = ENOMEM; goto exit_with_error; } imgp = &__execve_data->imgp; vap = &__execve_data->va; origvap = &__execve_data->origva; /* Initialize the common data in the image_params structure */ imgp->ip_user_fname = uap->fname; imgp->ip_user_argv = uap->argp; imgp->ip_user_envv = uap->envp; imgp->ip_vattr = vap; imgp->ip_origvattr = origvap; imgp->ip_vfs_context = &context; imgp->ip_flags = (is_64 ? IMGPF_WAS_64BIT_ADDR : IMGPF_NONE) | ((p->p_flag & P_DISABLE_ASLR) ? IMGPF_DISABLE_ASLR : IMGPF_NONE); imgp->ip_seg = (is_64 ? UIO_USERSPACE64 : UIO_USERSPACE32); imgp->ip_mac_return = 0; imgp->ip_cs_error = OS_REASON_NULL; imgp->ip_flags2 = 0; imgp->ip_subsystem_root_path = NULL; uthread_set_exec_data(current_uthread(), imgp); #if CONFIG_MACF if (uap->mac_p != USER_ADDR_NULL) { error = mac_execve_enter(uap->mac_p, imgp); if (error) { goto exit_with_error; } } #endif uthread = current_uthread(); { imgp->ip_flags |= IMGPF_EXEC; /* Adjust the user proc count */ (void)chgproccnt(kauth_getruid(), 1); /* * For execve case, create a new proc, task and thread * but don't make the proc visible to userland. After * image activation, the new proc would take place of * the old proc in pid hash and other lists that make * the proc visible to the system. */ imgp->ip_new_thread = cloneproc(old_task, NULL, p, CLONEPROC_EXEC); /* task and thread ref returned by cloneproc */ if (imgp->ip_new_thread == NULL) { (void)chgproccnt(kauth_getruid(), -1); error = ENOMEM; goto exit_with_error; } new_task = get_threadtask(imgp->ip_new_thread); } #if HAS_MTE_EMULATION_SHIMS /* * ARM2ARM Rosetta doesn't carry over the configuration from the initial posix_spawn, * so we key the enablement of the runtime to whether inheritance is enabled or not * for the task. We will defer any MTE specific configuration to image activation. */ if (task_has_sec_inherit(old_task) && task_has_sec(old_task)) { imgp->ip_flags |= (IMGPF_ROSETTA | IMGPF_ALT_ROSETTA); } #endif /* HAS_MTE_EMULATION_SHIMS */ p = (proc_t)get_bsdthreadtask_info(imgp->ip_new_thread); context.vc_thread = imgp->ip_new_thread; context.vc_ucred = kauth_cred_proc_ref(p); /* XXX must NOT be kauth_cred_get() */ imgp->ip_subsystem_root_path = p->p_subsystem_root_path; proc_transend(p, 0); proc_signalend(p, 0); /* * Activate the image. * Warning: If activation failed after point of no return, it returns error * as 0 and pretends the call succeeded. */ error = exec_activate_image(imgp); /* thread and task ref returned for vfexec case */ if (imgp->ip_new_thread != NULL) { /* * task reference might be returned by exec_activate_image * for vfexec. */ new_task = get_threadtask(imgp->ip_new_thread); #if defined(HAS_APPLE_PAC) ml_task_set_disable_user_jop(new_task, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE); ml_thread_set_disable_user_jop(imgp->ip_new_thread, imgp->ip_flags & IMGPF_NOJOP ? TRUE : FALSE); #endif } if (!error) { p = proc_exec_switch_task(current_proc(), p, old_task, new_task, imgp, &inherit); /* proc ref returned */ should_release_proc_ref = TRUE; } kauth_cred_unref(&context.vc_ucred); if (!error) { exec_done = TRUE; assert(imgp->ip_new_thread != NULL); exec_resettextvp(p, imgp); vm_map_setup(get_task_map(new_task), new_task); /* * Set starting EXC_GUARD behavior for task now that platform * and platform restrictions bits are set. */ task_set_exc_guard_default(new_task, proc_best_name(p), strlen(proc_best_name(p)), proc_is_simulated(p), proc_platform(p), proc_sdk(p)); /* * Between proc_exec_switch_task and ipc_task_enable, there is a * window where proc_find will return the new proc, but task_for_pid * and similar functions will return an error as the task ipc is not * enabled yet. Configure the task control port during this window * before other process have access to this task port. * * Must enable after resettextvp so that task port policies are not evaluated * until the csblob in the textvp is accurately reflected. */ task_set_ctrl_port_default(new_task, imgp->ip_new_thread); /* * Enable new task IPC access if exec_activate_image() returned an * active task. (Checks active bit in ipc_task_enable() under lock). * Similarly, this must happen after resettextvp. */ ipc_task_enable(new_task); error = process_signature(p, imgp); } #if defined(HAS_APPLE_PAC) if (imgp->ip_new_thread && !error) { ml_task_set_jop_pid_from_shared_region(new_task, imgp->ip_flags & IMGPF_NOJOP); ml_thread_set_jop_pid(imgp->ip_new_thread, new_task); } #endif /* defined(HAS_APPLE_PAC) */ /* flag exec has occurred, notify only if it has not failed due to FP Key error */ if (exec_done && ((p->p_lflag & P_LTERM_DECRYPTFAIL) == 0)) { proc_knote(p, NOTE_EXEC); } if (imgp->ip_vp != NULLVP) { vnode_put(imgp->ip_vp); } if (imgp->ip_scriptvp != NULLVP) { vnode_put(imgp->ip_scriptvp); } if (imgp->ip_free_map) { /* Free the map after dropping iocount on vnode to avoid deadlock */ vm_map_deallocate(imgp->ip_free_map); } if (imgp->ip_strings) { execargs_free(imgp); } #if CONFIG_MACF if (imgp->ip_execlabelp) { mac_cred_label_free(imgp->ip_execlabelp); imgp->ip_execlabelp = NULL; } if (imgp->ip_scriptlabelp) { mac_vnode_label_free(imgp->ip_scriptlabelp); imgp->ip_scriptlabelp = NULL; } #endif if (imgp->ip_cs_error != OS_REASON_NULL) { os_reason_free(imgp->ip_cs_error); imgp->ip_cs_error = OS_REASON_NULL; } if (!error) { /* * We need to initialize the bank context behind the protection of * the proc_trans lock to prevent a race with exit. We can't do this during * exec_activate_image because task_bank_init checks entitlements that * aren't loaded until subsequent calls (including exec_resettextvp). */ error = proc_transstart(p, 0, 0); } if (!error) { task_bank_init(new_task); proc_transend(p, 0); // Don't inherit crash behavior across exec, but preserve crash behavior from bootargs p->p_crash_behavior = 0; p->p_crash_behavior_deadline = 0; set_crash_behavior_from_bootarg(p); #if __arm64__ proc_footprint_entitlement_hacks(p, new_task); #endif /* __arm64__ */ memorystatus_set_proc_entitlement_flags(p); #if XNU_TARGET_OS_OSX if (IOTaskHasEntitlement(new_task, SINGLE_JIT_ENTITLEMENT)) { vm_map_single_jit(get_task_map(new_task)); } #endif /* XNU_TARGET_OS_OSX */ /* Sever any extant thread affinity */ thread_affinity_exec(current_thread()); /* Inherit task role from old task to new task for exec */ proc_inherit_task_role(new_task, old_task); thread_t main_thread = imgp->ip_new_thread; task_set_main_thread_qos(new_task, main_thread); #if __has_feature(ptrauth_calls) task_set_pac_exception_fatal_flag(new_task); #endif /* __has_feature(ptrauth_calls) */ task_set_jit_flags(new_task); #if CONFIG_ARCADE /* * Check to see if we need to trigger an arcade upcall AST now * that the vnode has been reset on the task. */ arcade_prepare(new_task, imgp->ip_new_thread); #endif /* CONFIG_ARCADE */ proc_apply_jit_and_vm_policies(imgp, p, new_task); if (vm_darkwake_mode == TRUE) { /* * This process is being launched when the system * is in darkwake. So mark it specially. This will * cause all its pages to be entered in the background Q. */ task_set_darkwake_mode(new_task, vm_darkwake_mode); } #if CONFIG_DTRACE dtrace_thread_didexec(imgp->ip_new_thread); if ((dtrace_proc_waitfor_hook = dtrace_proc_waitfor_exec_ptr) != NULL) { (*dtrace_proc_waitfor_hook)(p); } #endif #if CONFIG_AUDIT if (!error && AUDIT_ENABLED() && p) { /* Add the CDHash of the new process to the audit record */ uint8_t *cdhash = cs_get_cdhash(p); if (cdhash) { AUDIT_ARG(data, cdhash, sizeof(uint8_t), CS_CDHASH_LEN); } } #endif } else { DTRACE_PROC1(exec__failure, int, error); } exit_with_error: /* terminate the new task it if exec failed */ if (new_task != NULL && task_is_exec_copy(new_task)) { task_terminate_internal(new_task); } if (imgp != NULL) { /* Clear the initial wait on the thread transferring watchports */ if (imgp->ip_new_thread) { task_clear_return_wait(get_threadtask(imgp->ip_new_thread), TCRW_CLEAR_INITIAL_WAIT); } /* Transfer the watchport boost to new task */ if (!error) { task_transfer_turnstile_watchports(old_task, new_task, imgp->ip_new_thread); } /* * Do not terminate the current task, if proc_exec_switch_task did not * switch the tasks, terminating the current task without the switch would * result in loosing the SIGKILL status. */ if (task_did_exec(old_task)) { /* Terminate the current task, since exec will start in new task */ task_terminate_internal(old_task); } /* Release the thread ref returned by cloneproc */ if (imgp->ip_new_thread) { /* clear the exec complete flag if there is an error before point of no-return */ uint32_t clearwait_flags = TCRW_CLEAR_FINAL_WAIT; if (!exec_done && error != 0) { clearwait_flags |= TCRW_CLEAR_EXEC_COMPLETE; } /* wake up the new exec thread */ task_clear_return_wait(get_threadtask(imgp->ip_new_thread), clearwait_flags); thread_deallocate(imgp->ip_new_thread); imgp->ip_new_thread = NULL; } } /* Release the ref returned by fork_create_child */ if (new_task) { task_deallocate(new_task); new_task = NULL; } if (should_release_proc_ref) { proc_rele(p); } uthread_set_exec_data(current_uthread(), NULL); kfree_type(typeof(*__execve_data), __execve_data); if (inherit != NULL) { ipc_importance_release(inherit); } return error; } /* * copyinptr * * Description: Copy a pointer in from user space to a user_addr_t in kernel * space, based on 32/64 bitness of the user space * * Parameters: froma User space address * toptr Address of kernel space user_addr_t * ptr_size 4/8, based on 'froma' address space * * Returns: 0 Success * EFAULT Bad 'froma' * * Implicit returns: * *ptr_size Modified */ static int copyinptr(user_addr_t froma, user_addr_t *toptr, int ptr_size) { int error; if (ptr_size == 4) { /* 64 bit value containing 32 bit address */ unsigned int i = 0; error = copyin(froma, &i, 4); *toptr = CAST_USER_ADDR_T(i); /* SAFE */ } else { error = copyin(froma, toptr, 8); } return error; } /* * copyoutptr * * Description: Copy a pointer out from a user_addr_t in kernel space to * user space, based on 32/64 bitness of the user space * * Parameters: ua User space address to copy to * ptr Address of kernel space user_addr_t * ptr_size 4/8, based on 'ua' address space * * Returns: 0 Success * EFAULT Bad 'ua' * */ static int copyoutptr(user_addr_t ua, user_addr_t ptr, int ptr_size) { int error; if (ptr_size == 4) { /* 64 bit value containing 32 bit address */ unsigned int i = CAST_DOWN_EXPLICIT(unsigned int, ua); /* SAFE */ error = copyout(&i, ptr, 4); } else { error = copyout(&ua, ptr, 8); } return error; } /* * exec_copyout_strings * * Copy out the strings segment to user space. The strings segment is put * on a preinitialized stack frame. * * Parameters: struct image_params * the image parameter block * int * a pointer to the stack offset variable * * Returns: 0 Success * !0 Faiure: errno * * Implicit returns: * (*stackp) The stack offset, modified * * Note: The strings segment layout is backward, from the beginning * of the top of the stack to consume the minimal amount of * space possible; the returned stack pointer points to the * end of the area consumed (stacks grow downward). * * argc is an int; arg[i] are pointers; env[i] are pointers; * the 0's are (void *)NULL's * * The stack frame layout is: * * +-------------+ <- p->user_stack * | 16b | * +-------------+ * | STRING AREA | * | : | * | : | * | : | * +- -- -- -- --+ * | PATH AREA | * +-------------+ * | 0 | * +-------------+ * | applev[n] | * +-------------+ * : * : * +-------------+ * | applev[1] | * +-------------+ * | exec_path / | * | applev[0] | * +-------------+ * | 0 | * +-------------+ * | env[n] | * +-------------+ * : * : * +-------------+ * | env[0] | * +-------------+ * | 0 | * +-------------+ * | arg[argc-1] | * +-------------+ * : * : * +-------------+ * | arg[0] | * +-------------+ * | argc | * sp-> +-------------+ * * Although technically a part of the STRING AREA, we treat the PATH AREA as * a separate entity. This allows us to align the beginning of the PATH AREA * to a pointer boundary so that the exec_path, env[i], and argv[i] pointers * which preceed it on the stack are properly aligned. */ __attribute__((noinline)) static int exec_copyout_strings(struct image_params *imgp, user_addr_t *stackp) { proc_t p = vfs_context_proc(imgp->ip_vfs_context); int ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4; int ptr_area_size; void *ptr_buffer_start, *ptr_buffer; size_t string_size; user_addr_t string_area; /* *argv[], *env[] */ user_addr_t ptr_area; /* argv[], env[], applev[] */ user_addr_t argc_area; /* argc */ user_addr_t stack; int error; unsigned i; struct copyout_desc { char *start_string; int count; #if CONFIG_DTRACE user_addr_t *dtrace_cookie; #endif boolean_t null_term; } descriptors[] = { { .start_string = imgp->ip_startargv, .count = imgp->ip_argc, #if CONFIG_DTRACE .dtrace_cookie = &p->p_dtrace_argv, #endif .null_term = TRUE }, { .start_string = imgp->ip_endargv, .count = imgp->ip_envc, #if CONFIG_DTRACE .dtrace_cookie = &p->p_dtrace_envp, #endif .null_term = TRUE }, { .start_string = imgp->ip_strings, .count = 1, #if CONFIG_DTRACE .dtrace_cookie = NULL, #endif .null_term = FALSE }, { .start_string = imgp->ip_endenvv, .count = imgp->ip_applec - 1, /* exec_path handled above */ #if CONFIG_DTRACE .dtrace_cookie = NULL, #endif .null_term = TRUE } }; stack = *stackp; /* * All previous contributors to the string area * should have aligned their sub-area */ if (imgp->ip_strspace % ptr_size != 0) { error = EINVAL; goto bad; } /* Grow the stack down for the strings we've been building up */ string_size = imgp->ip_strendp - imgp->ip_strings; stack -= string_size; string_area = stack; /* * Need room for one pointer for each string, plus * one for the NULLs terminating the argv, envv, and apple areas. */ ptr_area_size = (imgp->ip_argc + imgp->ip_envc + imgp->ip_applec + 3) * ptr_size; stack -= ptr_area_size; ptr_area = stack; /* We'll construct all the pointer arrays in our string buffer, * which we already know is aligned properly, and ip_argspace * was used to verify we have enough space. */ ptr_buffer_start = ptr_buffer = (void *)imgp->ip_strendp; /* * Need room for pointer-aligned argc slot. */ stack -= ptr_size; argc_area = stack; /* * Record the size of the arguments area so that sysctl_procargs() * can return the argument area without having to parse the arguments. */ proc_lock(p); p->p_argc = imgp->ip_argc; p->p_argslen = (int)(*stackp - string_area); proc_unlock(p); /* Return the initial stack address: the location of argc */ *stackp = stack; /* * Copy out the entire strings area. */ error = copyout(imgp->ip_strings, string_area, string_size); if (error) { goto bad; } for (i = 0; i < sizeof(descriptors) / sizeof(descriptors[0]); i++) { char *cur_string = descriptors[i].start_string; int j; #if CONFIG_DTRACE if (descriptors[i].dtrace_cookie) { proc_lock(p); *descriptors[i].dtrace_cookie = ptr_area + ((uintptr_t)ptr_buffer - (uintptr_t)ptr_buffer_start); /* dtrace convenience */ proc_unlock(p); } #endif /* CONFIG_DTRACE */ /* * For each segment (argv, envv, applev), copy as many pointers as requested * to our pointer buffer. */ for (j = 0; j < descriptors[i].count; j++) { user_addr_t cur_address = string_area + (cur_string - imgp->ip_strings); /* Copy out the pointer to the current string. Alignment has been verified */ if (ptr_size == 8) { *(uint64_t *)ptr_buffer = (uint64_t)cur_address; } else { *(uint32_t *)ptr_buffer = (uint32_t)cur_address; } ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size); cur_string += strlen(cur_string) + 1; /* Only a NUL between strings in the same area */ } if (descriptors[i].null_term) { if (ptr_size == 8) { *(uint64_t *)ptr_buffer = 0ULL; } else { *(uint32_t *)ptr_buffer = 0; } ptr_buffer = (void *)((uintptr_t)ptr_buffer + ptr_size); } } /* * Copy out all our pointer arrays in bulk. */ error = copyout(ptr_buffer_start, ptr_area, ptr_area_size); if (error) { goto bad; } /* argc (int32, stored in a ptr_size area) */ error = copyoutptr((user_addr_t)imgp->ip_argc, argc_area, ptr_size); if (error) { goto bad; } bad: return error; } /* * exec_extract_strings * * Copy arguments and environment from user space into work area; we may * have already copied some early arguments into the work area, and if * so, any arguments opied in are appended to those already there. * This function is the primary manipulator of ip_argspace, since * these are the arguments the client of execve(2) knows about. After * each argv[]/envv[] string is copied, we charge the string length * and argv[]/envv[] pointer slot to ip_argspace, so that we can * full preflight the arg list size. * * Parameters: struct image_params * the image parameter block * * Returns: 0 Success * !0 Failure: errno * * Implicit returns; * (imgp->ip_argc) Count of arguments, updated * (imgp->ip_envc) Count of environment strings, updated * (imgp->ip_argspace) Count of remaining of NCARGS * (imgp->ip_interp_buffer) Interpreter and args (mutated in place) * * * Note: The argument and environment vectors are user space pointers * to arrays of user space pointers. */ __attribute__((noinline)) static int exec_extract_strings(struct image_params *imgp) { int error = 0; int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT_ADDR) ? 8 : 4; int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4; user_addr_t argv = imgp->ip_user_argv; user_addr_t envv = imgp->ip_user_envv; /* * Adjust space reserved for the path name by however much padding it * needs. Doing this here since we didn't know if this would be a 32- * or 64-bit process back in exec_save_path. */ while (imgp->ip_strspace % new_ptr_size != 0) { *imgp->ip_strendp++ = '\0'; imgp->ip_strspace--; /* imgp->ip_argspace--; not counted towards exec args total */ } /* * From now on, we start attributing string space to ip_argspace */ imgp->ip_startargv = imgp->ip_strendp; imgp->ip_argc = 0; if ((imgp->ip_flags & IMGPF_INTERPRET) != 0) { user_addr_t arg; char *argstart, *ch; /* First, the arguments in the "#!" string are tokenized and extracted. */ argstart = imgp->ip_interp_buffer; while (argstart) { ch = argstart; while (*ch && !IS_WHITESPACE(*ch)) { ch++; } if (*ch == '\0') { /* last argument, no need to NUL-terminate */ error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE); argstart = NULL; } else { /* NUL-terminate */ *ch = '\0'; error = exec_add_user_string(imgp, CAST_USER_ADDR_T(argstart), UIO_SYSSPACE, TRUE); /* * Find the next string. We know spaces at the end of the string have already * been stripped. */ argstart = ch + 1; while (IS_WHITESPACE(*argstart)) { argstart++; } } /* Error-check, regardless of whether this is the last interpreter arg or not */ if (error) { goto bad; } if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */ imgp->ip_argc++; } if (argv != 0LL) { /* * If we are running an interpreter, replace the av[0] that was * passed to execve() with the path name that was * passed to execve() for interpreters which do not use the PATH * to locate their script arguments. */ error = copyinptr(argv, &arg, ptr_size); if (error) { goto bad; } if (arg != 0LL) { argv += ptr_size; /* consume without using */ } } if (imgp->ip_interp_sugid_fd != -1) { char temp[19]; /* "/dev/fd/" + 10 digits + NUL */ snprintf(temp, sizeof(temp), "/dev/fd/%d", imgp->ip_interp_sugid_fd); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(temp), UIO_SYSSPACE, TRUE); } else { error = exec_add_user_string(imgp, imgp->ip_user_fname, imgp->ip_seg, TRUE); } if (error) { goto bad; } if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */ imgp->ip_argc++; } while (argv != 0LL) { user_addr_t arg; error = copyinptr(argv, &arg, ptr_size); if (error) { goto bad; } if (arg == 0LL) { break; } argv += ptr_size; /* * av[n...] = arg[n] */ error = exec_add_user_string(imgp, arg, imgp->ip_seg, TRUE); if (error) { goto bad; } if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* to hold argv[] entry */ imgp->ip_argc++; } /* Save space for argv[] NULL terminator */ if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* Note where the args ends and env begins. */ imgp->ip_endargv = imgp->ip_strendp; imgp->ip_envc = 0; /* Now, get the environment */ while (envv != 0LL) { user_addr_t env; error = copyinptr(envv, &env, ptr_size); if (error) { goto bad; } envv += ptr_size; if (env == 0LL) { break; } /* * av[n...] = env[n] */ error = exec_add_user_string(imgp, env, imgp->ip_seg, TRUE); if (error) { goto bad; } if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* to hold envv[] entry */ imgp->ip_envc++; } /* Save space for envv[] NULL terminator */ if (imgp->ip_argspace < new_ptr_size) { error = E2BIG; goto bad; } imgp->ip_argspace -= new_ptr_size; /* Align the tail of the combined argv+envv area */ while (imgp->ip_strspace % new_ptr_size != 0) { if (imgp->ip_argspace < 1) { error = E2BIG; goto bad; } *imgp->ip_strendp++ = '\0'; imgp->ip_strspace--; imgp->ip_argspace--; } /* Note where the envv ends and applev begins. */ imgp->ip_endenvv = imgp->ip_strendp; /* * From now on, we are no longer charging argument * space to ip_argspace. */ bad: return error; } /* * Libc has an 8-element array set up for stack guard values. It only fills * in one of those entries, and both gcc and llvm seem to use only a single * 8-byte guard. Until somebody needs more than an 8-byte guard value, don't * do the work to construct them. */ #define GUARD_VALUES 1 #define GUARD_KEY "stack_guard=" /* * System malloc needs some entropy when it is initialized. */ #define ENTROPY_VALUES 2 #define ENTROPY_KEY "malloc_entropy=" /* * libplatform needs a random pointer-obfuscation value when it is initialized. */ #define PTR_MUNGE_VALUES 1 #define PTR_MUNGE_KEY "ptr_munge=" /* * System malloc engages nanozone for UIAPP. */ #define NANO_ENGAGE_KEY "MallocNanoZone=1" /* * Used to pass experiment flags up to libmalloc. */ #define LIBMALLOC_EXPERIMENT_FACTORS_KEY "MallocExperiment=" /* * Passes information about hardened heap/"hardened runtime" entitlements to libsystem/libmalloc */ #define HARDENED_RUNTIME_KEY "HardenedRuntime=" #define PFZ_KEY "pfz=" extern user32_addr_t commpage_text32_location; extern user64_addr_t commpage_text64_location; extern uuid_string_t bootsessionuuid_string; static TUNABLE(uint32_t, exe_boothash_salt, "exe_boothash_salt", 0); __startup_func static void exe_boothash_salt_generate(void) { if (!PE_parse_boot_argn("exe_boothash_salt", NULL, 0)) { read_random(&exe_boothash_salt, sizeof(exe_boothash_salt)); } } STARTUP(EARLY_BOOT, STARTUP_RANK_MIDDLE, exe_boothash_salt_generate); #define MAIN_STACK_VALUES 4 #define MAIN_STACK_KEY "main_stack=" #define FSID_KEY "executable_file=" #define DYLD_FSID_KEY "dyld_file=" #define CDHASH_KEY "executable_cdhash=" #define DYLD_FLAGS_KEY "dyld_flags=" #define SUBSYSTEM_ROOT_PATH_KEY "subsystem_root_path=" #define APP_BOOT_SESSION_KEY "executable_boothash=" #if __has_feature(ptrauth_calls) #define PTRAUTH_DISABLED_FLAG "ptrauth_disabled=1" #define DYLD_ARM64E_ABI_KEY "arm64e_abi=" #endif /* __has_feature(ptrauth_calls) */ #define MAIN_TH_PORT_KEY "th_port=" #define FSID_MAX_STRING "0x1234567890abcdef,0x1234567890abcdef" #define HEX_STR_LEN 18 // 64-bit hex value "0x0123456701234567" #define HEX_STR_LEN32 10 // 32-bit hex value "0x01234567" #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES #define VM_FORCE_4K_PAGES_KEY "vm_force_4k_pages=1" #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */ static int exec_add_entropy_key(struct image_params *imgp, const char *key, int values, boolean_t embedNUL) { const int limit = 8; uint64_t entropy[limit]; char str[strlen(key) + (HEX_STR_LEN + 1) * limit + 1]; if (values > limit) { values = limit; } read_random(entropy, sizeof(entropy[0]) * values); if (embedNUL) { entropy[0] &= ~(0xffull << 8); } int len = scnprintf(str, sizeof(str), "%s0x%llx", key, entropy[0]); size_t remaining = sizeof(str) - len; for (int i = 1; i < values && remaining > 0; ++i) { size_t start = sizeof(str) - remaining; len = scnprintf(&str[start], remaining, ",0x%llx", entropy[i]); remaining -= len; } return exec_add_user_string(imgp, CAST_USER_ADDR_T(str), UIO_SYSSPACE, FALSE); } /* * Build up the contents of the apple[] string vector */ #if (DEVELOPMENT || DEBUG) extern uint64_t dyld_flags; #endif #if __has_feature(ptrauth_calls) static inline bool is_arm64e_running_as_arm64(const struct image_params *imgp) { return (imgp->ip_origcpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E && (imgp->ip_flags & IMGPF_NOJOP); } #endif /* __has_feature(ptrauth_calls) */ _Atomic uint64_t libmalloc_experiment_factors = 0; static int exec_add_apple_strings(struct image_params *imgp, const load_result_t *load_result, task_t task) { int error; int img_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4; thread_t new_thread; ipc_port_t sright; uint64_t local_experiment_factors = 0; /* exec_save_path stored the first string */ imgp->ip_applec = 1; /* adding the pfz string */ { char pfz_string[strlen(PFZ_KEY) + HEX_STR_LEN + 1]; if (img_ptr_size == 8) { __assert_only size_t ret = snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%llx", commpage_text64_location); assert(ret < sizeof(pfz_string)); } else { snprintf(pfz_string, sizeof(pfz_string), PFZ_KEY "0x%x", commpage_text32_location); } error = exec_add_user_string(imgp, CAST_USER_ADDR_T(pfz_string), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add the pfz string with error %d\n", error); goto bad; } imgp->ip_applec++; } /* adding the NANO_ENGAGE_KEY key */ if (imgp->ip_px_sa) { struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa; int proc_flags = psa->psa_flags; if ((proc_flags & _POSIX_SPAWN_NANO_ALLOCATOR) == _POSIX_SPAWN_NANO_ALLOCATOR) { const char *nano_string = NANO_ENGAGE_KEY; error = exec_add_user_string(imgp, CAST_USER_ADDR_T(nano_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } } /* * Supply libc with a collection of random values to use when * implementing -fstack-protector. * * (The first random string always contains an embedded NUL so that * __stack_chk_guard also protects against C string vulnerabilities) */ error = exec_add_entropy_key(imgp, GUARD_KEY, GUARD_VALUES, TRUE); if (error) { goto bad; } imgp->ip_applec++; /* * Supply libc with entropy for system malloc. */ error = exec_add_entropy_key(imgp, ENTROPY_KEY, ENTROPY_VALUES, FALSE); if (error) { goto bad; } imgp->ip_applec++; /* * Supply libpthread & libplatform with a random value to use for pointer * obfuscation. */ error = exec_add_entropy_key(imgp, PTR_MUNGE_KEY, PTR_MUNGE_VALUES, FALSE); if (error) { goto bad; } imgp->ip_applec++; /* * Add MAIN_STACK_KEY: Supplies the address and size of the main thread's * stack if it was allocated by the kernel. * * The guard page is not included in this stack size as libpthread * expects to add it back in after receiving this value. */ if (load_result->unixproc) { char stack_string[strlen(MAIN_STACK_KEY) + (HEX_STR_LEN + 1) * MAIN_STACK_VALUES + 1]; snprintf(stack_string, sizeof(stack_string), MAIN_STACK_KEY "0x%llx,0x%llx,0x%llx,0x%llx", (uint64_t)load_result->user_stack, (uint64_t)load_result->user_stack_size, (uint64_t)load_result->user_stack_alloc, (uint64_t)load_result->user_stack_alloc_size); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(stack_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } if (imgp->ip_vattr) { uint64_t fsid = vnode_get_va_fsid(imgp->ip_vattr); uint64_t fsobjid = imgp->ip_vattr->va_fileid; char fsid_string[strlen(FSID_KEY) + strlen(FSID_MAX_STRING) + 1]; snprintf(fsid_string, sizeof(fsid_string), FSID_KEY "0x%llx,0x%llx", fsid, fsobjid); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } if (imgp->ip_dyld_fsid || imgp->ip_dyld_fsobjid) { char fsid_string[strlen(DYLD_FSID_KEY) + strlen(FSID_MAX_STRING) + 1]; snprintf(fsid_string, sizeof(fsid_string), DYLD_FSID_KEY "0x%llx,0x%llx", imgp->ip_dyld_fsid, imgp->ip_dyld_fsobjid); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(fsid_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } uint8_t cdhash[SHA1_RESULTLEN]; int cdhash_errror = ubc_cs_getcdhash(imgp->ip_vp, imgp->ip_arch_offset, cdhash, NULL); if (cdhash_errror == 0) { char hash_string[strlen(CDHASH_KEY) + 2 * SHA1_RESULTLEN + 1]; strncpy(hash_string, CDHASH_KEY, sizeof(hash_string)); char *p = hash_string + sizeof(CDHASH_KEY) - 1; for (int i = 0; i < SHA1_RESULTLEN; i++) { snprintf(p, 3, "%02x", (int) cdhash[i]); p += 2; } error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hash_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; /* hash together cd-hash and boot-session-uuid */ uint8_t sha_digest[SHA256_DIGEST_LENGTH]; SHA256_CTX sha_ctx; SHA256_Init(&sha_ctx); SHA256_Update(&sha_ctx, &exe_boothash_salt, sizeof(exe_boothash_salt)); SHA256_Update(&sha_ctx, bootsessionuuid_string, sizeof(bootsessionuuid_string)); SHA256_Update(&sha_ctx, cdhash, sizeof(cdhash)); SHA256_Final(sha_digest, &sha_ctx); char app_boot_string[strlen(APP_BOOT_SESSION_KEY) + 2 * SHA1_RESULTLEN + 1]; strncpy(app_boot_string, APP_BOOT_SESSION_KEY, sizeof(app_boot_string)); char *s = app_boot_string + sizeof(APP_BOOT_SESSION_KEY) - 1; for (int i = 0; i < SHA1_RESULTLEN; i++) { snprintf(s, 3, "%02x", (int) sha_digest[i]); s += 2; } error = exec_add_user_string(imgp, CAST_USER_ADDR_T(app_boot_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #if (DEVELOPMENT || DEBUG) if (dyld_flags) { char dyld_flags_string[strlen(DYLD_FLAGS_KEY) + HEX_STR_LEN + 1]; snprintf(dyld_flags_string, sizeof(dyld_flags_string), DYLD_FLAGS_KEY "0x%llx", dyld_flags); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_flags_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #endif if (imgp->ip_subsystem_root_path) { size_t buffer_len = MAXPATHLEN + strlen(SUBSYSTEM_ROOT_PATH_KEY); char subsystem_root_path_string[buffer_len]; int required_len = snprintf(subsystem_root_path_string, buffer_len, SUBSYSTEM_ROOT_PATH_KEY "%s", imgp->ip_subsystem_root_path); if (((size_t)required_len >= buffer_len) || (required_len < 0)) { error = ENAMETOOLONG; goto bad; } error = exec_add_user_string(imgp, CAST_USER_ADDR_T(subsystem_root_path_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #if __has_feature(ptrauth_calls) if (is_arm64e_running_as_arm64(imgp)) { error = exec_add_user_string(imgp, CAST_USER_ADDR_T(PTRAUTH_DISABLED_FLAG), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #endif /* __has_feature(ptrauth_calls) */ #if __has_feature(ptrauth_calls) && defined(XNU_TARGET_OS_OSX) { char dyld_abi_string[strlen(DYLD_ARM64E_ABI_KEY) + 8]; strlcpy(dyld_abi_string, DYLD_ARM64E_ABI_KEY, sizeof(dyld_abi_string)); bool allowAll = bootarg_arm64e_preview_abi; strlcat(dyld_abi_string, (allowAll ? "all" : "os"), sizeof(dyld_abi_string)); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(dyld_abi_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #endif /* * Add main thread mach port name * +1 uref on main thread port, this ref will be extracted by libpthread in __pthread_init * and consumed in _bsdthread_terminate. Leaking the main thread port name if not linked * against libpthread. */ if ((new_thread = imgp->ip_new_thread) != THREAD_NULL) { thread_reference(new_thread); sright = convert_thread_to_port_immovable(new_thread); task_t new_task = get_threadtask(new_thread); mach_port_name_t name = ipc_port_copyout_send_pinned(sright, get_task_ipcspace(new_task)); char port_name_hex_str[strlen(MAIN_TH_PORT_KEY) + HEX_STR_LEN32 + 1]; snprintf(port_name_hex_str, sizeof(port_name_hex_str), MAIN_TH_PORT_KEY "0x%x", name); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(port_name_hex_str), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } #if XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES if (imgp->ip_px_sa != NULL) { struct _posix_spawnattr* psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa->psa_flags & _POSIX_SPAWN_FORCE_4K_PAGES) { const char *vm_force_4k_string = VM_FORCE_4K_PAGES_KEY; error = exec_add_user_string(imgp, CAST_USER_ADDR_T(vm_force_4k_string), UIO_SYSSPACE, FALSE); if (error) { goto bad; } imgp->ip_applec++; } } #endif /* XNU_TARGET_OS_OSX && _POSIX_SPAWN_FORCE_4K_PAGES && PMAP_CREATE_FORCE_4K_PAGES */ /* adding the libmalloc experiment string */ local_experiment_factors = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed); if (__improbable(local_experiment_factors != 0)) { char libmalloc_experiment_factors_string[strlen(LIBMALLOC_EXPERIMENT_FACTORS_KEY) + HEX_STR_LEN + 1]; snprintf( libmalloc_experiment_factors_string, sizeof(libmalloc_experiment_factors_string), LIBMALLOC_EXPERIMENT_FACTORS_KEY "0x%llx", local_experiment_factors); error = exec_add_user_string( imgp, CAST_USER_ADDR_T(libmalloc_experiment_factors_string), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add the libmalloc experiment factors string with error %d\n", error); goto bad; } imgp->ip_applec++; } /* * Push down the task security configuration. To reduce confusion when userland parses the information * still push an empty security configuration if nothing is active. */ { #define SECURITY_CONFIG_KEY "security_config=" char security_config_str[strlen(SECURITY_CONFIG_KEY) + HEX_STR_LEN + 1]; snprintf(security_config_str, sizeof(security_config_str), SECURITY_CONFIG_KEY "0x%x", task_get_security_config(task)); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(security_config_str), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add the security config string with error %d\n", error); goto bad; } imgp->ip_applec++; } #if HAS_MTE || HAS_MTE_EMULATION_SHIMS if (task_has_sec(task)) { const char *sec_transition_shims = "has_sec_transition=1"; error = exec_add_user_string(imgp, CAST_USER_ADDR_T(sec_transition_shims), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add security translation shims notification\n"); goto bad; } imgp->ip_applec++; /* Push down MTE-specific configuration options that allocators may be interested into. */ #define SEC_TRANSITION_POLICY_KEY "sec_transition_policy=" char sec_transition_policy[strlen(SEC_TRANSITION_POLICY_KEY) + HEX_STR_LEN + 1]; snprintf(sec_transition_policy, sizeof(sec_transition_policy), SEC_TRANSITION_POLICY_KEY "0x%x", task_get_sec_policy(task)); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(sec_transition_policy), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add the security transition policy string with error %d\n", error); goto bad; } imgp->ip_applec++; } #endif /* HAS_MTE || HAS_MTE_EMULATION_SHIMS */ if (load_result->hardened_browser) { const size_t HR_STRING_SIZE = sizeof(HARDENED_RUNTIME_KEY) + HR_FLAGS_NUM_NIBBLES + 2 + 1; char hardened_runtime[HR_STRING_SIZE]; snprintf(hardened_runtime, HR_STRING_SIZE, HARDENED_RUNTIME_KEY"0x%x", load_result->hardened_browser); error = exec_add_user_string(imgp, CAST_USER_ADDR_T(hardened_runtime), UIO_SYSSPACE, FALSE); if (error) { printf("Failed to add hardened runtime flag with error %d\n", error); goto bad; } imgp->ip_applec++; } /* Align the tail of the combined applev area */ while (imgp->ip_strspace % img_ptr_size != 0) { *imgp->ip_strendp++ = '\0'; imgp->ip_strspace--; } bad: return error; } /* * exec_check_permissions * * Description: Verify that the file that is being attempted to be executed * is in fact allowed to be executed based on it POSIX file * permissions and other access control criteria * * Parameters: struct image_params * the image parameter block * * Returns: 0 Success * EACCES Permission denied * ENOEXEC Executable file format error * ETXTBSY Text file busy [misuse of error code] * vnode_getattr:??? * vnode_authorize:??? */ static int exec_check_permissions(struct image_params *imgp) { struct vnode *vp = imgp->ip_vp; struct vnode_attr *vap = imgp->ip_vattr; proc_t p = vfs_context_proc(imgp->ip_vfs_context); int error; kauth_action_t action; /* Only allow execution of regular files */ if (!vnode_isreg(vp)) { return EACCES; } /* Get the file attributes that we will be using here and elsewhere */ VATTR_INIT(vap); VATTR_WANTED(vap, va_uid); VATTR_WANTED(vap, va_gid); VATTR_WANTED(vap, va_mode); VATTR_WANTED(vap, va_fsid); VATTR_WANTED(vap, va_fsid64); VATTR_WANTED(vap, va_fileid); VATTR_WANTED(vap, va_data_size); if ((error = vnode_getattr(vp, vap, imgp->ip_vfs_context)) != 0) { return error; } /* * Ensure that at least one execute bit is on - otherwise root * will always succeed, and we don't want to happen unless the * file really is executable. */ if (!vfs_authopaque(vnode_mount(vp)) && ((vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)) { return EACCES; } /* Disallow zero length files */ if (vap->va_data_size == 0) { return ENOEXEC; } imgp->ip_arch_offset = (user_size_t)0; #if __LP64__ imgp->ip_arch_size = vap->va_data_size; #else if (vap->va_data_size > UINT32_MAX) { return ENOEXEC; } imgp->ip_arch_size = (user_size_t)vap->va_data_size; #endif /* Disable setuid-ness for traced programs or if MNT_NOSUID */ if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_lflag & P_LTRACED)) { vap->va_mode &= ~(VSUID | VSGID); } /* * Disable _POSIX_SPAWN_ALLOW_DATA_EXEC and _POSIX_SPAWN_DISABLE_ASLR * flags for setuid/setgid binaries. */ if (vap->va_mode & (VSUID | VSGID)) { imgp->ip_flags &= ~(IMGPF_ALLOW_DATA_EXEC | IMGPF_DISABLE_ASLR); } #if CONFIG_MACF error = mac_vnode_check_exec(imgp->ip_vfs_context, vp, imgp); if (error) { return error; } #endif /* Check for execute permission */ action = KAUTH_VNODE_EXECUTE; /* Traced images must also be readable */ if (p->p_lflag & P_LTRACED) { action |= KAUTH_VNODE_READ_DATA; } if ((error = vnode_authorize(vp, NULL, action, imgp->ip_vfs_context)) != 0) { return error; } #if 0 /* Don't let it run if anyone had it open for writing */ vnode_lock(vp); if (vp->v_writecount) { panic("going to return ETXTBSY %x", vp); vnode_unlock(vp); return ETXTBSY; } vnode_unlock(vp); #endif /* XXX May want to indicate to underlying FS that vnode is open */ return error; } /* * exec_handle_sugid * * Initially clear the P_SUGID in the process flags; if an SUGID process is * exec'ing a non-SUGID image, then this is the point of no return. * * If the image being activated is SUGID, then replace the credential with a * copy, disable tracing (unless the tracing process is root), reset the * mach task port to revoke it, set the P_SUGID bit, * * If the saved user and group ID will be changing, then make sure it happens * to a new credential, rather than a shared one. * * Set the security token (this is probably obsolete, given that the token * should not technically be separate from the credential itself). * * Parameters: struct image_params * the image parameter block * * Returns: void No failure indication * * Implicit returns: * <process credential> Potentially modified/replaced * <task port> Potentially revoked * <process flags> P_SUGID bit potentially modified * <security token> Potentially modified */ __attribute__((noinline)) static int exec_handle_sugid(struct image_params *imgp) { proc_t p = vfs_context_proc(imgp->ip_vfs_context); kauth_cred_t cred = vfs_context_ucred(imgp->ip_vfs_context); int i; int leave_sugid_clear = 0; int mac_reset_ipc = 0; int error = 0; #if CONFIG_MACF int mac_transition, disjoint_cred = 0; int label_update_return = 0; /* * Determine whether a call to update the MAC label will result in the * credential changing. * * Note: MAC policies which do not actually end up modifying * the label subsequently are strongly encouraged to * return 0 for this check, since a non-zero answer will * slow down the exec fast path for normal binaries. */ mac_transition = mac_cred_check_label_update_execve( imgp->ip_vfs_context, imgp->ip_vp, imgp->ip_arch_offset, imgp->ip_scriptvp, imgp->ip_scriptlabelp, imgp->ip_execlabelp, p, &imgp->ip_px_smpx); #endif OSBitAndAtomic(~((uint32_t)P_SUGID), &p->p_flag); /* * Order of the following is important; group checks must go last, * as we use the success of the 'ismember' check combined with the * failure of the explicit match to indicate that we will be setting * the egid of the process even though the new process did not * require VSUID/VSGID bits in order for it to set the new group as * its egid. * * Note: Technically, by this we are implying a call to * setegid() in the new process, rather than implying * it used its VSGID bit to set the effective group, * even though there is no code in that process to make * such a call. */ if (((imgp->ip_origvattr->va_mode & VSUID) != 0 && kauth_cred_getuid(cred) != imgp->ip_origvattr->va_uid) || ((imgp->ip_origvattr->va_mode & VSGID) != 0 && ((kauth_cred_ismember_gid(cred, imgp->ip_origvattr->va_gid, &leave_sugid_clear) || !leave_sugid_clear) || (kauth_cred_getgid(cred) != imgp->ip_origvattr->va_gid)))) { #if CONFIG_MACF /* label for MAC transition and neither VSUID nor VSGID */ handle_mac_transition: #endif #if CONFIG_SETUID /* * Replace the credential with a copy of itself if euid or * egid change. * * Note: setuid binaries will automatically opt out of * group resolver participation as a side effect * of this operation. This is an intentional * part of the security model, which requires a * participating credential be established by * escalating privilege, setting up all other * aspects of the credential including whether * or not to participate in external group * membership resolution, then dropping their * effective privilege to that of the desired * final credential state. * * Modifications to p_ucred must be guarded using the * proc's ucred lock. This prevents others from accessing * a garbage credential. */ if (imgp->ip_origvattr->va_mode & VSUID) { kauth_cred_proc_update(p, PROC_SETTOKEN_NONE, ^bool (kauth_cred_t parent __unused, kauth_cred_t model) { return kauth_cred_model_setresuid(model, KAUTH_UID_NONE, imgp->ip_origvattr->va_uid, imgp->ip_origvattr->va_uid, KAUTH_UID_NONE); }); } if (imgp->ip_origvattr->va_mode & VSGID) { kauth_cred_proc_update(p, PROC_SETTOKEN_NONE, ^bool (kauth_cred_t parent __unused, kauth_cred_t model) { return kauth_cred_model_setresgid(model, KAUTH_GID_NONE, imgp->ip_origvattr->va_gid, imgp->ip_origvattr->va_gid); }); } #endif /* CONFIG_SETUID */ #if CONFIG_MACF /* * If a policy has indicated that it will transition the label, * before making the call into the MAC policies, get a new * duplicate credential, so they can modify it without * modifying any others sharing it. */ if (mac_transition) { /* * This hook may generate upcalls that require * importance donation from the kernel. * (23925818) */ thread_t thread = current_thread(); thread_enable_send_importance(thread, TRUE); kauth_proc_label_update_execve(p, imgp->ip_vfs_context, imgp->ip_vp, imgp->ip_arch_offset, imgp->ip_scriptvp, imgp->ip_scriptlabelp, imgp->ip_execlabelp, &imgp->ip_csflags, &imgp->ip_px_smpx, &disjoint_cred, /* will be non zero if disjoint */ &label_update_return); thread_enable_send_importance(thread, FALSE); if (disjoint_cred) { /* * If updating the MAC label resulted in a * disjoint credential, flag that we need to * set the P_SUGID bit. This protects * against debuggers being attached by an * insufficiently privileged process onto the * result of a transition to a more privileged * credential. */ leave_sugid_clear = 0; } imgp->ip_mac_return = label_update_return; } mac_reset_ipc = mac_proc_check_inherit_ipc_ports(p, p->p_textvp, p->p_textoff, imgp->ip_vp, imgp->ip_arch_offset, imgp->ip_scriptvp); #endif /* CONFIG_MACF */ /* * If 'leave_sugid_clear' is non-zero, then we passed the * VSUID and MACF checks, and successfully determined that * the previous cred was a member of the VSGID group, but * that it was not the default at the time of the execve, * and that the post-labelling credential was not disjoint. * So we don't set the P_SUGID or reset mach ports and fds * on the basis of simply running this code. */ if (mac_reset_ipc || !leave_sugid_clear) { /* * Have mach reset the task and thread ports. * We don't want anyone who had the ports before * a setuid exec to be able to access/control the * task/thread after. */ ipc_task_reset((imgp->ip_new_thread != NULL) ? get_threadtask(imgp->ip_new_thread) : proc_task(p)); ipc_thread_reset((imgp->ip_new_thread != NULL) ? imgp->ip_new_thread : current_thread()); } if (!leave_sugid_clear) { /* * Flag the process as setuid. */ OSBitOrAtomic(P_SUGID, &p->p_flag); /* * Radar 2261856; setuid security hole fix * XXX For setuid processes, attempt to ensure that * stdin, stdout, and stderr are already allocated. * We do not want userland to accidentally allocate * descriptors in this range which has implied meaning * to libc. */ for (i = 0; i < 3; i++) { if (fp_get_noref_locked(p, i) != NULL) { continue; } /* * Do the kernel equivalent of * * if i == 0 * (void) open("/dev/null", O_RDONLY); * else * (void) open("/dev/null", O_WRONLY); */ struct fileproc *fp; int indx; int flag; struct nameidata *ndp = NULL; if (i == 0) { flag = FREAD; } else { flag = FWRITE; } if ((error = falloc_exec(p, imgp->ip_vfs_context, &fp, &indx)) != 0) { continue; } ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_ZERO | Z_NOFAIL); NDINIT(ndp, LOOKUP, OP_OPEN, FOLLOW, UIO_SYSSPACE, CAST_USER_ADDR_T("/dev/null"), imgp->ip_vfs_context); if ((error = vn_open(ndp, flag, 0)) != 0) { fp_free(p, indx, fp); kfree_type(struct nameidata, ndp); break; } struct fileglob *fg = fp->fp_glob; fg->fg_flag = flag; fg->fg_ops = &vnops; fp_set_data(fp, ndp->ni_vp); vnode_put(ndp->ni_vp); proc_fdlock(p); procfdtbl_releasefd(p, indx, NULL); fp_drop(p, indx, fp, 1); proc_fdunlock(p); kfree_type(struct nameidata, ndp); } } } #if CONFIG_MACF else { /* * We are here because we were told that the MAC label will * be transitioned, and the binary is not VSUID or VSGID; to * deal with this case, we could either duplicate a lot of * code, or we can indicate we want to default the P_SUGID * bit clear and jump back up. */ if (mac_transition) { leave_sugid_clear = 1; goto handle_mac_transition; } } #endif /* CONFIG_MACF */ /* Update the process' identity version and set the security token. * Also, ensure we always see a modified identity version (rdar://129775819). */ int previous_pid_version = proc_get_ro(p)->p_idversion; int new_pid_version; do { new_pid_version = OSIncrementAtomic(&nextpidversion); } while (new_pid_version == previous_pid_version); proc_setpidversion(p, new_pid_version); task_set_uniqueid(proc_task(p)); /* * Implement the semantic where the effective user and group become * the saved user and group in exec'ed programs. */ kauth_cred_proc_update(p, PROC_SETTOKEN_ALWAYS, ^bool (kauth_cred_t parent __unused, kauth_cred_t model) { posix_cred_t pcred = posix_cred_get(model); if (pcred->cr_svuid == pcred->cr_uid && pcred->cr_svgid == pcred->cr_gid) { return false; } pcred->cr_svuid = pcred->cr_uid; pcred->cr_svgid = pcred->cr_gid; return true; }); return error; } /* * create_unix_stack * * Description: Set the user stack address for the process to the provided * address. If a custom stack was not set as a result of the * load process (i.e. as specified by the image file for the * executable), then allocate the stack in the provided map and * set up appropriate guard pages for enforcing administrative * limits on stack growth, if they end up being needed. * * Parameters: p Process to set stack on * load_result Information from mach-o load commands * map Address map in which to allocate the new stack * * Returns: KERN_SUCCESS Stack successfully created * !KERN_SUCCESS Mach failure code */ __attribute__((noinline)) static kern_return_t create_unix_stack(vm_map_t map, load_result_t* load_result, proc_t p) { mach_vm_size_t size, prot_size; mach_vm_offset_t addr, prot_addr; kern_return_t kr; mach_vm_address_t user_stack = load_result->user_stack; proc_lock(p); p->user_stack = (uintptr_t)user_stack; if (load_result->custom_stack) { p->p_lflag |= P_LCUSTOM_STACK; } proc_unlock(p); if (vm_map_page_shift(map) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("map %p user_stack 0x%llx custom %d user_stack_alloc_size 0x%llx\n", map, user_stack, load_result->custom_stack, load_result->user_stack_alloc_size); } if (load_result->user_stack_alloc_size > 0) { /* * Allocate enough space for the maximum stack size we * will ever authorize and an extra page to act as * a guard page for stack overflows. For default stacks, * vm_initial_limit_stack takes care of the extra guard page. * Otherwise we must allocate it ourselves. */ if (mach_vm_round_page_overflow(load_result->user_stack_alloc_size, &size)) { return KERN_INVALID_ARGUMENT; } addr = vm_map_trunc_page(load_result->user_stack - size, vm_map_page_mask(map)); kr = mach_vm_allocate_kernel(map, &addr, size, VM_MAP_KERNEL_FLAGS_FIXED(.vm_tag = VM_MEMORY_STACK)); if (kr != KERN_SUCCESS) { // Can't allocate at default location, try anywhere addr = 0; kr = mach_vm_allocate_kernel(map, &addr, size, VM_MAP_KERNEL_FLAGS_ANYWHERE(.vm_tag = VM_MEMORY_STACK)); if (kr != KERN_SUCCESS) { return kr; } user_stack = addr + size; load_result->user_stack = (user_addr_t)user_stack; proc_lock(p); p->user_stack = (uintptr_t)user_stack; proc_unlock(p); } load_result->user_stack_alloc = (user_addr_t)addr; /* * And prevent access to what's above the current stack * size limit for this process. */ if (load_result->user_stack_size == 0) { load_result->user_stack_size = proc_limitgetcur(p, RLIMIT_STACK); prot_size = vm_map_trunc_page(size - load_result->user_stack_size, vm_map_page_mask(map)); } else { prot_size = PAGE_SIZE; } prot_addr = addr; kr = mach_vm_protect(map, prot_addr, prot_size, FALSE, VM_PROT_NONE); if (kr != KERN_SUCCESS) { (void)mach_vm_deallocate_kernel(map, addr, size); return kr; } } return KERN_SUCCESS; } #include <sys/reboot.h> /* * load_init_program_at_path * * Description: Load the "init" program; in most cases, this will be "launchd" * * Parameters: p Process to call execve() to create * the "init" program * scratch_addr Page in p, scratch space * path NULL terminated path * * Returns: KERN_SUCCESS Success * !KERN_SUCCESS See execve/mac_execve for error codes * * Notes: The process that is passed in is the first manufactured * process on the system, and gets here via bsd_ast() firing * for the first time. This is done to ensure that bsd_init() * has run to completion. * * The address map of the first manufactured process matches the * word width of the kernel. Once the self-exec completes, the * initproc might be different. */ static int load_init_program_at_path(proc_t p, user_addr_t scratch_addr, const char* path) { int retval[2]; int error; struct execve_args init_exec_args; user_addr_t argv0 = USER_ADDR_NULL, argv1 = USER_ADDR_NULL; /* * Validate inputs and pre-conditions */ assert(p); assert(scratch_addr); assert(path); /* * Copy out program name. */ size_t path_length = strlen(path) + 1; argv0 = scratch_addr; error = copyout(path, argv0, path_length); if (error) { return error; } scratch_addr = USER_ADDR_ALIGN(scratch_addr + path_length, sizeof(user_addr_t)); /* * Put out first (and only) argument, similarly. * Assumes everything fits in a page as allocated above. */ if (boothowto & RB_SINGLE) { const char *init_args = "-s"; size_t init_args_length = strlen(init_args) + 1; argv1 = scratch_addr; error = copyout(init_args, argv1, init_args_length); if (error) { return error; } scratch_addr = USER_ADDR_ALIGN(scratch_addr + init_args_length, sizeof(user_addr_t)); } if (proc_is64bit(p)) { user64_addr_t argv64bit[3] = {}; argv64bit[0] = argv0; argv64bit[1] = argv1; argv64bit[2] = USER_ADDR_NULL; error = copyout(argv64bit, scratch_addr, sizeof(argv64bit)); if (error) { return error; } } else { user32_addr_t argv32bit[3] = {}; argv32bit[0] = (user32_addr_t)argv0; argv32bit[1] = (user32_addr_t)argv1; argv32bit[2] = USER_ADDR_NULL; error = copyout(argv32bit, scratch_addr, sizeof(argv32bit)); if (error) { return error; } } /* * Set up argument block for fake call to execve. */ init_exec_args.fname = argv0; init_exec_args.argp = scratch_addr; init_exec_args.envp = USER_ADDR_NULL; /* * So that init task is set with uid,gid 0 token * * The access to the cred is safe: * the proc isn't running yet, it's stable. */ set_security_token(p, proc_ucred_unsafe(p)); return execve(p, &init_exec_args, retval); } static const char * init_programs[] = { #if DEBUG "/usr/appleinternal/sbin/launchd.debug", #endif #if DEVELOPMENT || DEBUG "/usr/appleinternal/sbin/launchd.development", #endif "/sbin/launchd", }; /* * load_init_program * * Description: Load the "init" program; in most cases, this will be "launchd" * * Parameters: p Process to call execve() to create * the "init" program * * Returns: (void) * * Notes: The process that is passed in is the first manufactured * process on the system, and gets here via bsd_ast() firing * for the first time. This is done to ensure that bsd_init() * has run to completion. * * In DEBUG & DEVELOPMENT builds, the launchdsuffix boot-arg * may be used to select a specific launchd executable. As with * the kcsuffix boot-arg, setting launchdsuffix to "" or "release" * will force /sbin/launchd to be selected. * * Search order by build: * * DEBUG DEVELOPMENT RELEASE PATH * ---------------------------------------------------------------------------------- * 1 1 NA /usr/appleinternal/sbin/launchd.$LAUNCHDSUFFIX * 2 NA NA /usr/appleinternal/sbin/launchd.debug * 3 2 NA /usr/appleinternal/sbin/launchd.development * 4 3 1 /sbin/launchd */ void load_init_program(proc_t p) { uint32_t i; int error; vm_map_t map = current_map(); mach_vm_offset_t scratch_addr = 0; mach_vm_size_t map_page_size = vm_map_page_size(map); #if DEVELOPMENT || DEBUG /* Use the opportunity to initialize exec's debug log stream */ exec_log_handle = os_log_create("com.apple.xnu.bsd", "exec"); #endif /* DEVELOPMENT || DEBUG */ (void) mach_vm_allocate_kernel(map, &scratch_addr, map_page_size, VM_MAP_KERNEL_FLAGS_ANYWHERE()); #if CONFIG_MEMORYSTATUS (void) memorystatus_init_at_boot_snapshot(); #endif /* CONFIG_MEMORYSTATUS */ #if DEBUG || DEVELOPMENT /* Check for boot-arg suffix first */ char launchd_suffix[64]; if (PE_parse_boot_argn("launchdsuffix", launchd_suffix, sizeof(launchd_suffix))) { char launchd_path[128]; boolean_t is_release_suffix = ((launchd_suffix[0] == 0) || (strcmp(launchd_suffix, "release") == 0)); if (is_release_suffix) { printf("load_init_program: attempting to load /sbin/launchd\n"); error = load_init_program_at_path(p, (user_addr_t)scratch_addr, "/sbin/launchd"); if (!error) { return; } panic("Process 1 exec of launchd.release failed, errno %d", error); } else { strlcpy(launchd_path, "/usr/appleinternal/sbin/launchd.", sizeof(launchd_path)); strlcat(launchd_path, launchd_suffix, sizeof(launchd_path)); printf("load_init_program: attempting to load %s\n", launchd_path); error = load_init_program_at_path(p, (user_addr_t)scratch_addr, launchd_path); if (!error) { return; } else if (error != ENOENT) { printf("load_init_program: failed loading %s: errno %d\n", launchd_path, error); } } } #endif error = ENOENT; for (i = 0; i < sizeof(init_programs) / sizeof(init_programs[0]); i++) { printf("load_init_program: attempting to load %s\n", init_programs[i]); error = load_init_program_at_path(p, (user_addr_t)scratch_addr, init_programs[i]); if (!error) { return; } else if (error != ENOENT) { printf("load_init_program: failed loading %s: errno %d\n", init_programs[i], error); } } panic("Process 1 exec of %s failed, errno %d", ((i == 0) ? "<null>" : init_programs[i - 1]), error); } /* * load_return_to_errno * * Description: Convert a load_return_t (Mach error) to an errno (BSD error) * * Parameters: lrtn Mach error number * * Returns: (int) BSD error number * 0 Success * EBADARCH Bad architecture * EBADMACHO Bad Mach object file * ESHLIBVERS Bad shared library version * ENOMEM Out of memory/resource shortage * EACCES Access denied * ENOENT Entry not found (usually "file does * does not exist") * EIO An I/O error occurred * EBADEXEC The executable is corrupt/unknown */ static int load_return_to_errno(load_return_t lrtn) { switch (lrtn) { case LOAD_SUCCESS: return 0; case LOAD_BADARCH: return EBADARCH; case LOAD_BADMACHO: case LOAD_BADMACHO_UPX: return EBADMACHO; case LOAD_SHLIB: return ESHLIBVERS; case LOAD_NOSPACE: case LOAD_RESOURCE: return ENOMEM; case LOAD_PROTECT: return EACCES; case LOAD_ENOENT: return ENOENT; case LOAD_IOERROR: return EIO; case LOAD_DECRYPTFAIL: return EAUTH; case LOAD_FAILURE: default: return EBADEXEC; } } #include <mach/mach_types.h> #include <mach/vm_prot.h> #include <mach/semaphore.h> #include <mach/sync_policy.h> #include <kern/clock.h> #include <mach/kern_return.h> /* * execargs_alloc * * Description: Allocate the block of memory used by the execve arguments. * At the same time, we allocate a page so that we can read in * the first page of the image. * * Parameters: struct image_params * the image parameter block * * Returns: 0 Success * EINVAL Invalid argument * EACCES Permission denied * EINTR Interrupted function * ENOMEM Not enough space * * Notes: This is a temporary allocation into the kernel address space * to enable us to copy arguments in from user space. This is * necessitated by not mapping the process calling execve() into * the kernel address space during the execve() system call. * * We assemble the argument and environment, etc., into this * region before copying it as a single block into the child * process address space (at the top or bottom of the stack, * depending on which way the stack grows; see the function * exec_copyout_strings() for details). * * This ends up with a second (possibly unnecessary) copy compared * with assembing the data directly into the child address space, * instead, but since we cannot be guaranteed that the parent has * not modified its environment, we can't really know that it's * really a block there as well. */ static int execargs_waiters = 0; static LCK_MTX_DECLARE_ATTR(execargs_cache_lock, &proc_lck_grp, &proc_lck_attr); static void execargs_lock_lock(void) { lck_mtx_lock_spin(&execargs_cache_lock); } static void execargs_lock_unlock(void) { lck_mtx_unlock(&execargs_cache_lock); } static wait_result_t execargs_lock_sleep(void) { return lck_mtx_sleep(&execargs_cache_lock, LCK_SLEEP_DEFAULT, &execargs_free_count, THREAD_INTERRUPTIBLE); } static kern_return_t execargs_purgeable_allocate(char **execarg_address) { mach_vm_offset_t addr = 0; kern_return_t kr = mach_vm_allocate_kernel(bsd_pageable_map, &addr, BSD_PAGEABLE_SIZE_PER_EXEC, VM_MAP_KERNEL_FLAGS_ANYWHERE(.vmf_purgeable = true)); *execarg_address = (char *)addr; assert(kr == KERN_SUCCESS); return kr; } static kern_return_t execargs_purgeable_reference(void *execarg_address) { int state = VM_PURGABLE_NONVOLATILE; kern_return_t kr = vm_map_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state); assert(kr == KERN_SUCCESS); return kr; } static kern_return_t execargs_purgeable_volatilize(void *execarg_address) { int state = VM_PURGABLE_VOLATILE | VM_PURGABLE_ORDERING_OBSOLETE; kern_return_t kr; kr = vm_map_purgable_control(bsd_pageable_map, (vm_offset_t) execarg_address, VM_PURGABLE_SET_STATE, &state); assert(kr == KERN_SUCCESS); return kr; } static void execargs_wakeup_waiters(void) { thread_wakeup(&execargs_free_count); } static int execargs_alloc(struct image_params *imgp) { kern_return_t kret; wait_result_t res; int i, cache_index = -1; execargs_lock_lock(); while (execargs_free_count == 0) { execargs_waiters++; res = execargs_lock_sleep(); execargs_waiters--; if (res != THREAD_AWAKENED) { execargs_lock_unlock(); return EINTR; } } execargs_free_count--; for (i = 0; i < execargs_cache_size; i++) { vm_offset_t element = execargs_cache[i]; if (element) { cache_index = i; imgp->ip_strings = (char *)(execargs_cache[i]); execargs_cache[i] = 0; break; } } assert(execargs_free_count >= 0); execargs_lock_unlock(); if (cache_index == -1) { kret = execargs_purgeable_allocate(&imgp->ip_strings); } else { kret = execargs_purgeable_reference(imgp->ip_strings); } assert(kret == KERN_SUCCESS); if (kret != KERN_SUCCESS) { return ENOMEM; } /* last page used to read in file headers */ imgp->ip_vdata = imgp->ip_strings + (NCARGS + PAGE_SIZE); imgp->ip_strendp = imgp->ip_strings; imgp->ip_argspace = NCARGS; imgp->ip_strspace = (NCARGS + PAGE_SIZE); return 0; } /* * execargs_free * * Description: Free the block of memory used by the execve arguments and the * first page of the executable by a previous call to the function * execargs_alloc(). * * Parameters: struct image_params * the image parameter block * * Returns: 0 Success * EINVAL Invalid argument * EINTR Oeration interrupted */ static int execargs_free(struct image_params *imgp) { kern_return_t kret; int i; boolean_t needs_wakeup = FALSE; kret = execargs_purgeable_volatilize(imgp->ip_strings); execargs_lock_lock(); execargs_free_count++; for (i = 0; i < execargs_cache_size; i++) { vm_offset_t element = execargs_cache[i]; if (element == 0) { execargs_cache[i] = (vm_offset_t) imgp->ip_strings; imgp->ip_strings = NULL; break; } } assert(imgp->ip_strings == NULL); if (execargs_waiters > 0) { needs_wakeup = TRUE; } execargs_lock_unlock(); if (needs_wakeup == TRUE) { execargs_wakeup_waiters(); } return kret == KERN_SUCCESS ? 0 : EINVAL; } void uthread_set_exec_data(struct uthread *uth, struct image_params *imgp) { uth->uu_save.uus_exec_data.imgp = imgp; } size_t thread_get_current_exec_path(char *path, size_t size) { struct uthread *uth = current_uthread(); struct image_params *imgp = uth->uu_save.uus_exec_data.imgp; size_t string_size = 0; char *exec_path; if (path == NULL || imgp == NULL || imgp->ip_strings == NULL) { return 0; } exec_path = imgp->ip_strings + strlen(EXECUTABLE_KEY); string_size = imgp->ip_strendp - exec_path; string_size = MIN(MAXPATHLEN, string_size); string_size = MIN(size, string_size); string_size = strlcpy(path, exec_path, string_size); return string_size; } static void exec_resettextvp(proc_t p, struct image_params *imgp) { vnode_t vp; off_t offset; vnode_t tvp = p->p_textvp; int ret; vp = imgp->ip_vp; offset = imgp->ip_arch_offset; if (vp == NULLVP) { panic("exec_resettextvp: expected valid vp"); } ret = vnode_ref(vp); proc_lock(p); if (ret == 0) { p->p_textvp = vp; p->p_textoff = offset; } else { p->p_textvp = NULLVP; /* this is paranoia */ p->p_textoff = 0; } proc_unlock(p); if (tvp != NULLVP) { if (vnode_getwithref(tvp) == 0) { vnode_rele(tvp); vnode_put(tvp); } } } // Includes the 0-byte (therefore "SIZE" instead of "LEN"). static const size_t CS_CDHASH_STRING_SIZE = CS_CDHASH_LEN * 2 + 1; static void cdhash_to_string(char str[CS_CDHASH_STRING_SIZE], uint8_t const * const cdhash) { static char const nibble[] = "0123456789abcdef"; /* Apparently still the safest way to get a hex representation * of binary data. * xnu's printf routines have %*D/%20D in theory, but "not really", see: * <rdar://problem/33328859> confusion around %*D/%nD in printf */ for (int i = 0; i < CS_CDHASH_LEN; ++i) { str[i * 2] = nibble[(cdhash[i] & 0xf0) >> 4]; str[i * 2 + 1] = nibble[cdhash[i] & 0x0f]; } str[CS_CDHASH_STRING_SIZE - 1] = 0; } /* * __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__ * * Description: Waits for the userspace daemon to respond to the request * we made. Function declared non inline to be visible in * stackshots and spindumps as well as debugging. */ __attribute__((noinline)) int __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(mach_port_t task_access_port, int32_t new_pid) { return find_code_signature(task_access_port, new_pid); } /* * Update signature dependent process state, called by * process_signature. */ static int proc_process_signature(proc_t p, os_reason_t *signature_failure_reason) { int error = 0; char const *error_msg = NULL; kern_return_t kr = machine_task_process_signature(proc_get_task_raw(p), proc_platform(p), proc_sdk(p), &error_msg); if (kr != KERN_SUCCESS) { error = EINVAL; if (error_msg != NULL) { uint32_t error_msg_len = (uint32_t)strlen(error_msg) + 1; mach_vm_address_t data_addr = 0; int reason_error = 0; int kcdata_error = 0; os_reason_t reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY); reason->osr_flags = OS_REASON_FLAG_GENERATE_CRASH_REPORT | OS_REASON_FLAG_CONSISTENT_FAILURE; if ((reason_error = os_reason_alloc_buffer_noblock(reason, kcdata_estimate_required_buffer_size(1, error_msg_len))) == 0 && (kcdata_error = kcdata_get_memory_addr(&reason->osr_kcd_descriptor, EXIT_REASON_USER_DESC, error_msg_len, &data_addr)) == KERN_SUCCESS) { kern_return_t mc_error = kcdata_memcpy(&reason->osr_kcd_descriptor, (mach_vm_address_t)data_addr, error_msg, error_msg_len); if (mc_error != KERN_SUCCESS) { printf("process_signature: failed to copy reason string (kcdata_memcpy error: %d)\n", mc_error); } } else { printf("failed to allocate space for reason string (os_reason_alloc_buffer error: %d, kcdata error: %d, length: %u)\n", reason_error, kcdata_error, error_msg_len); } assert(*signature_failure_reason == NULL); // shouldn't have gotten so far *signature_failure_reason = reason; } } return error; } #define DT_UNRESTRICTED_SUBSYSTEM_ROOT "unrestricted-subsystem-root" static bool allow_unrestricted_subsystem_root(void) { #if !(DEVELOPMENT || DEBUG) static bool allow_unrestricted_subsystem_root = false; static bool has_been_set = false; if (!has_been_set) { DTEntry chosen; const uint32_t *value; unsigned size; has_been_set = true; if (SecureDTLookupEntry(0, "/chosen", &chosen) == kSuccess && SecureDTGetProperty(chosen, DT_UNRESTRICTED_SUBSYSTEM_ROOT, (const void**)&value, &size) == kSuccess && value != NULL && size == sizeof(uint32_t)) { allow_unrestricted_subsystem_root = (bool)*value; } } return allow_unrestricted_subsystem_root; #else return true; #endif } static int process_signature(proc_t p, struct image_params *imgp) { mach_port_t port = IPC_PORT_NULL; kern_return_t kr = KERN_FAILURE; int error = EACCES; boolean_t unexpected_failure = FALSE; struct cs_blob *csb; boolean_t require_success = FALSE; int spawn = (imgp->ip_flags & IMGPF_SPAWN); const int vfexec = 0; os_reason_t signature_failure_reason = OS_REASON_NULL; /* * Override inherited code signing flags with the * ones for the process that is being successfully * loaded */ proc_lock(p); proc_csflags_update(p, imgp->ip_csflags); proc_unlock(p); /* Set the switch_protect flag on the map */ if (proc_getcsflags(p) & (CS_HARD | CS_KILL)) { vm_map_switch_protect(get_task_map(proc_task(p)), TRUE); } /* set the cs_enforced flags in the map */ if (proc_getcsflags(p) & CS_ENFORCEMENT) { vm_map_cs_enforcement_set(get_task_map(proc_task(p)), TRUE); } else { vm_map_cs_enforcement_set(get_task_map(proc_task(p)), FALSE); } /* * image activation may be failed due to policy * which is unexpected but security framework does not * approve of exec, kill and return immediately. */ if (imgp->ip_mac_return != 0) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY, 0, 0); signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY); error = imgp->ip_mac_return; unexpected_failure = TRUE; goto done; } if (imgp->ip_cs_error != OS_REASON_NULL) { signature_failure_reason = imgp->ip_cs_error; imgp->ip_cs_error = OS_REASON_NULL; error = EACCES; goto done; } /* call the launch constraints hook */ os_reason_t launch_constraint_reason; if ((error = mac_proc_check_launch_constraints(p, imgp, &launch_constraint_reason)) != 0) { signature_failure_reason = launch_constraint_reason; goto done; } /* * Reject when there's subsystem root path set, but the image is restricted, and doesn't require * library validation. This is to avoid subsystem root being used to inject unsigned code */ if (!allow_unrestricted_subsystem_root()) { if ((imgp->ip_csflags & CS_RESTRICT || proc_issetugid(p)) && !(imgp->ip_csflags & CS_REQUIRE_LV) && (imgp->ip_subsystem_root_path != NULL)) { signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_SECURITY_POLICY); error = EACCES; goto done; } } #if XNU_TARGET_OS_OSX /* Check for platform passed in spawn attr if iOS binary is being spawned */ if (proc_platform(p) == PLATFORM_IOS) { struct _posix_spawnattr *psa = (struct _posix_spawnattr *) imgp->ip_px_sa; if (psa == NULL || psa->psa_platform == 0) { boolean_t no_sandbox_entitled = FALSE; #if DEBUG || DEVELOPMENT /* * Allow iOS binaries to spawn on internal systems * if no-sandbox entitlement is present of unentitled_ios_sim_launch * boot-arg set to true */ if (unentitled_ios_sim_launch) { no_sandbox_entitled = TRUE; } else { no_sandbox_entitled = IOVnodeHasEntitlement(imgp->ip_vp, (int64_t)imgp->ip_arch_offset, "com.apple.private.security.no-sandbox"); } #endif /* DEBUG || DEVELOPMENT */ if (!no_sandbox_entitled) { signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_WRONG_PLATFORM); error = EACCES; goto done; } printf("Allowing spawn of iOS binary %s since it has " "com.apple.private.security.no-sandbox entitlement or unentitled_ios_sim_launch " "boot-arg set to true\n", p->p_name); } else if (psa->psa_platform != PLATFORM_IOS) { /* Simulator binary spawned with wrong platform */ signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_WRONG_PLATFORM); error = EACCES; goto done; } else { printf("Allowing spawn of iOS binary %s since correct platform was passed in spawn\n", p->p_name); } } #endif /* XNU_TARGET_OS_OSX */ /* If the code signature came through the image activation path, we skip the * taskgated / externally attached path. */ if (imgp->ip_csflags & CS_SIGNED) { error = 0; goto done; } /* The rest of the code is for signatures that either already have been externally * attached (likely, but not necessarily by a previous run through the taskgated * path), or that will now be attached by taskgated. */ kr = task_get_task_access_port(proc_task(p), &port); if (KERN_SUCCESS != kr || !IPC_PORT_VALID(port)) { error = 0; if (require_success) { KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT, 0, 0); signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT); error = EACCES; } goto done; } /* * taskgated returns KERN_SUCCESS if it has completed its work * and the exec should continue, KERN_FAILURE if the exec should * fail, or it may error out with different error code in an * event of mig failure (e.g. process was signalled during the * rpc call, taskgated died, mig server died etc.). */ kr = __EXEC_WAITING_ON_TASKGATED_CODE_SIGNATURE_UPCALL__(port, proc_getpid(p)); switch (kr) { case KERN_SUCCESS: error = 0; break; case KERN_FAILURE: error = EACCES; KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG, 0, 0); signature_failure_reason = os_reason_create(OS_REASON_CODESIGNING, CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG); goto done; default: error = EACCES; KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXITREASON_CREATE) | DBG_FUNC_NONE, proc_getpid(p), OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER, 0, 0); signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_TASKGATED_OTHER); unexpected_failure = TRUE; goto done; } /* Only do this if exec_resettextvp() did not fail */ if (p->p_textvp != NULLVP) { csb = ubc_cs_blob_get(p->p_textvp, -1, -1, p->p_textoff); if (csb != NULL) { /* As the enforcement we can do here is very limited, we only allow things that * are the only reason why this code path still exists: * Adhoc signed non-platform binaries without special cs_flags and without any * entitlements (unrestricted ones still pass AMFI). */ if ( /* Revalidate the blob if necessary through bumped generation count. */ (ubc_cs_generation_check(p->p_textvp) == 0 || ubc_cs_blob_revalidate(p->p_textvp, csb, imgp, 0, proc_platform(p)) == 0) && /* Only CS_ADHOC, no CS_KILL, CS_HARD etc. */ (csb->csb_flags & CS_ALLOWED_MACHO) == CS_ADHOC && /* If it has a CMS blob, it's not adhoc. The CS_ADHOC flag can lie. */ csblob_find_blob_bytes((const uint8_t *)csb->csb_mem_kaddr, csb->csb_mem_size, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER) == NULL && /* It could still be in a trust cache (unlikely with CS_ADHOC), or a magic path. */ csb->csb_platform_binary == 0 && /* No entitlements, not even unrestricted ones. */ csb->csb_entitlements_blob == NULL && csb->csb_der_entitlements_blob == NULL) { proc_lock(p); proc_csflags_set(p, CS_SIGNED | CS_VALID); proc_unlock(p); } else { uint8_t cdhash[CS_CDHASH_LEN]; char cdhash_string[CS_CDHASH_STRING_SIZE]; proc_getcdhash(p, cdhash); cdhash_to_string(cdhash_string, cdhash); printf("ignoring detached code signature on '%s' with cdhash '%s' " "because it is invalid, or not a simple adhoc signature.\n", p->p_name, cdhash_string); } } } done: if (0 == error) { /* * Update the new process's signature-dependent process state. * state. */ error = proc_process_signature(p, &signature_failure_reason); } if (0 == error) { /* * Update the new main thread's signature-dependent thread * state. This was also called when the thread was created, * but for the main thread the signature was not yet attached * at that time. */ kr = thread_process_signature(imgp->ip_new_thread, proc_get_task_raw(p)); if (kr != KERN_SUCCESS) { error = EINVAL; signature_failure_reason = os_reason_create(OS_REASON_EXEC, EXEC_EXIT_REASON_MACHINE_THREAD); } } if (0 == error) { /* The process's code signature related properties are * fully set up, so this is an opportune moment to log * platform binary execution, if desired. */ if (platform_exec_logging != 0 && csproc_get_platform_binary(p)) { uint8_t cdhash[CS_CDHASH_LEN]; char cdhash_string[CS_CDHASH_STRING_SIZE]; proc_getcdhash(p, cdhash); cdhash_to_string(cdhash_string, cdhash); os_log(peLog, "CS Platform Exec Logging: Executing platform signed binary " "'%s' with cdhash %s\n", p->p_name, cdhash_string); } } else { if (!unexpected_failure) { proc_csflags_set(p, CS_KILLED); } /* make very sure execution fails */ if (vfexec || spawn) { assert(signature_failure_reason != OS_REASON_NULL); psignal_vfork_with_reason(p, proc_task(p), imgp->ip_new_thread, SIGKILL, signature_failure_reason); signature_failure_reason = OS_REASON_NULL; error = 0; } else { assert(signature_failure_reason != OS_REASON_NULL); psignal_with_reason(p, SIGKILL, signature_failure_reason); signature_failure_reason = OS_REASON_NULL; } } if (port != IPC_PORT_NULL) { ipc_port_release_send(port); } /* If we hit this, we likely would have leaked an exit reason */ assert(signature_failure_reason == OS_REASON_NULL); return error; } /* * Typically as soon as we start executing this process, the * first instruction will trigger a VM fault to bring the text * pages (as executable) into the address space, followed soon * thereafter by dyld data structures (for dynamic executable). * To optimize this, as well as improve support for hardware * debuggers that can only access resident pages present * in the process' page tables, we prefault some pages if * possible. Errors are non-fatal. */ #ifndef PREVENT_CALLER_STACK_USE #define PREVENT_CALLER_STACK_USE __attribute__((noinline)) #endif /* * Prefaulting dyld data does not work (rdar://76621401) */ #define FIXED_76621401 0 static void PREVENT_CALLER_STACK_USE exec_prefault_data( __unused proc_t p, __unused struct image_params *imgp, __unused load_result_t *load_result) { #if FIXED_76621401 int ret; size_t expected_all_image_infos_size; #endif /* FIXED_76621401 */ kern_return_t kr; /* * Prefault executable or dyld entry point. */ if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("entry_point 0x%llx\n", (uint64_t)load_result->entry_point); } kr = vm_fault(current_map(), vm_map_trunc_page(load_result->entry_point, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_EXECUTE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { DEBUG4K_ERROR("map %p va 0x%llx -> 0x%x\n", current_map(), (uint64_t)vm_map_trunc_page(load_result->entry_point, vm_map_page_mask(current_map())), kr); } #if FIXED_76621401 if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) { expected_all_image_infos_size = sizeof(struct user64_dyld_all_image_infos); } else { expected_all_image_infos_size = sizeof(struct user32_dyld_all_image_infos); } /* Decode dyld anchor structure from <mach-o/dyld_images.h> */ if (load_result->dynlinker && load_result->all_image_info_addr && load_result->all_image_info_size >= expected_all_image_infos_size) { union { struct user64_dyld_all_image_infos infos64; struct user32_dyld_all_image_infos infos32; } all_image_infos; /* * Pre-fault to avoid copyin() going through the trap handler * and recovery path. */ if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("all_image_info_addr 0x%llx\n", load_result->all_image_info_addr); } kr = vm_fault(current_map(), vm_map_trunc_page(load_result->all_image_info_addr, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_WRITE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr, vm_map_page_mask(current_map())), kr); } if ((load_result->all_image_info_addr & PAGE_MASK) + expected_all_image_infos_size > PAGE_SIZE) { /* all_image_infos straddles a page */ kr = vm_fault(current_map(), vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size - 1, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_WRITE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(load_result->all_image_info_addr + expected_all_image_infos_size -1, vm_map_page_mask(current_map())), kr); } } if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("copyin(0x%llx, 0x%lx)\n", load_result->all_image_info_addr, expected_all_image_infos_size); } ret = copyin((user_addr_t)load_result->all_image_info_addr, &all_image_infos, expected_all_image_infos_size); if (ret == 0 && all_image_infos.infos32.version >= DYLD_ALL_IMAGE_INFOS_ADDRESS_MINIMUM_VERSION) { user_addr_t notification_address; user_addr_t dyld_image_address; user_addr_t dyld_version_address; user_addr_t dyld_all_image_infos_address; user_addr_t dyld_slide_amount; if (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) { notification_address = (user_addr_t)all_image_infos.infos64.notification; dyld_image_address = (user_addr_t)all_image_infos.infos64.dyldImageLoadAddress; dyld_version_address = (user_addr_t)all_image_infos.infos64.dyldVersion; dyld_all_image_infos_address = (user_addr_t)all_image_infos.infos64.dyldAllImageInfosAddress; } else { notification_address = all_image_infos.infos32.notification; dyld_image_address = all_image_infos.infos32.dyldImageLoadAddress; dyld_version_address = all_image_infos.infos32.dyldVersion; dyld_all_image_infos_address = all_image_infos.infos32.dyldAllImageInfosAddress; } /* * dyld statically sets up the all_image_infos in its Mach-O * binary at static link time, with pointers relative to its default * load address. Since ASLR might slide dyld before its first * instruction is executed, "dyld_slide_amount" tells us how far * dyld was loaded compared to its default expected load address. * All other pointers into dyld's image should be adjusted by this * amount. At some point later, dyld will fix up pointers to take * into account the slide, at which point the all_image_infos_address * field in the structure will match the runtime load address, and * "dyld_slide_amount" will be 0, if we were to consult it again. */ dyld_slide_amount = (user_addr_t)load_result->all_image_info_addr - dyld_all_image_infos_address; #if 0 kprintf("exec_prefault: 0x%016llx 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%016llx\n", (uint64_t)load_result->all_image_info_addr, all_image_infos.infos32.version, (uint64_t)notification_address, (uint64_t)dyld_image_address, (uint64_t)dyld_version_address, (uint64_t)dyld_all_image_infos_address); #endif if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("notification_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)notification_address, (uint64_t)dyld_slide_amount); } kr = vm_fault(current_map(), vm_map_trunc_page(notification_address + dyld_slide_amount, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_EXECUTE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(notification_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr); } if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("dyld_image_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_image_address, (uint64_t)dyld_slide_amount); } kr = vm_fault(current_map(), vm_map_trunc_page(dyld_image_address + dyld_slide_amount, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_EXECUTE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_image_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr); } if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("dyld_version_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount); } kr = vm_fault(current_map(), vm_map_trunc_page(dyld_version_address + dyld_slide_amount, vm_map_page_mask(current_map())), VM_PROT_READ, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_version_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr); } if (vm_map_page_shift(current_map()) < (int)PAGE_SHIFT) { DEBUG4K_LOAD("dyld_all_image_infos_address 0x%llx dyld_slide_amount 0x%llx\n", (uint64_t)dyld_version_address, (uint64_t)dyld_slide_amount); } kr = vm_fault(current_map(), vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount, vm_map_page_mask(current_map())), VM_PROT_READ | VM_PROT_WRITE, FALSE, VM_KERN_MEMORY_NONE, THREAD_UNINT, NULL, 0); if (kr != KERN_SUCCESS) { // printf("%s:%d map %p va 0x%llx -> 0x%x\n", __FUNCTION__, __LINE__, current_map(), vm_map_trunc_page(dyld_all_image_infos_address + dyld_slide_amount, vm_map_page_mask(current_map())), kr); } } } #endif /* FIXED_76621401 */ } static int sysctl_libmalloc_experiments SYSCTL_HANDLER_ARGS { #pragma unused(oidp, arg2, req) int changed; errno_t error; uint64_t value = os_atomic_load_wide(&libmalloc_experiment_factors, relaxed); error = sysctl_io_number(req, value, sizeof(value), &value, &changed); if (error) { return error; } if (changed) { os_atomic_store_wide(&libmalloc_experiment_factors, value, relaxed); } return 0; } EXPERIMENT_FACTOR_LEGACY_PROC(_kern, libmalloc_experiments, CTLTYPE_QUAD | CTLFLAG_RW, 0, 0, &sysctl_libmalloc_experiments, "A", ""); SYSCTL_NODE(_kern, OID_AUTO, sec_transition, CTLFLAG_RD | CTLFLAG_LOCKED, 0, "sec_transition"); #if DEBUG || DEVELOPMENT static int sysctl_setup_ensure_pidversion_changes_on_exec(__unused int64_t in, int64_t *out) { // Tweak nextpidversion to try to trigger a reuse (unless the exec code is doing the right thing) int current_pid_version = proc_get_ro(current_proc())->p_idversion; nextpidversion = current_pid_version; *out = 0; return KERN_SUCCESS; } SYSCTL_TEST_REGISTER(setup_ensure_pidversion_changes_on_exec, sysctl_setup_ensure_pidversion_changes_on_exec); #endif /* DEBUG || DEVELOPMENT */ #if HAS_MTE && (DEBUG || DEVELOPMENT) static int sysctl_is_mte_enabled SYSCTL_HANDLER_ARGS { int value = mte_enabled() ? 1 : 0; return SYSCTL_OUT(req, &value, sizeof(value)); } SYSCTL_PROC(_kern, OID_AUTO, is_mte_enabled, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, sysctl_is_mte_enabled, "I", "Return whether MTE is enabled"); #endif /* HAS_MTE && (DEBUG || DEVELOPMENT) */ |