File size: 129,583 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using System.Management.Automation.SecurityAccountsManager.Native;
using System.Management.Automation.SecurityAccountsManager.Native.NtSam;
using System.Text;
using Microsoft.PowerShell.LocalAccounts;
using System.Diagnostics.CodeAnalysis;
[module: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")]
namespace System.Management.Automation.SecurityAccountsManager
{
/// <summary>
/// Defines enumeration constants for enabling and disabling something.
/// </summary>
internal enum Enabling
{
Disable = 0,
Enable
}
/// <summary>
/// Managed version of the SAM_RID_ENUMERATION native structure,
/// to be returned from the EnumerateLocalUsers method of Sam.
/// Contains the original structure's members along with additional
/// members of use.
/// </summary>
internal class SamRidEnumeration
{
#region Original struct members
public string Name;
public UInt32 RelativeId;
#endregion Original struct members
#region Additional members
public IntPtr domainHandle; // The domain handle used to acquire the data.
#endregion Additional members
}
/// <summary>
/// Provides methods for manipulating local Users and Groups.
/// </summary>
internal class Sam : IDisposable
{
#region Enums
[Flags]
private enum GroupProperties
{
Name = 0x0001, // NOT changeable through Set-LocalGroup
Description = 0x0002,
AllSetable = Description,
AllReadable = AllSetable | Name
}
/// <summary>
/// Defines a set of flags, each corresponding to a member of LocalUser,
/// which indicate fields to be updated.
/// </summary>
/// <remarks>
/// Although password can be set through Create-LocalUser and Set-LocalUser,
/// it is not a member of LocalUser so does not appear in this enumeration.
/// </remarks>
[Flags]
private enum UserProperties
{
None = 0x0000, // not actually a LocalUser member
Name = 0x0001, // NOT changeable through Set-LocalUser
AccountExpires = 0x0002,
Description = 0x0004,
Enabled = 0x0008, // NOT changeable through Set-LocalUser
FullName = 0x0010,
PasswordChangeableDate = 0x0020,
PasswordExpires = 0x0040,
PasswordNeverExpires = 0x0080,
UserMayChangePassword = 0x0100,
PasswordRequired = 0x0200,
PasswordLastSet = 0x0400, // CANNOT be set by cmdlet
LastLogon = 0x0800, // CANNOT be set by cmdlet
// All properties that can be set through Set-LocalUser
AllSetable = AccountExpires
| Description
| FullName
| PasswordChangeableDate
| PasswordExpires
| PasswordNeverExpires
| UserMayChangePassword
| PasswordRequired,
// Properties that can be set by Create-LocalUser
AllCreateable = AllSetable | Name | Enabled,
// Properties that can be read by e.g., Get-LocalUser
AllReadable = AllCreateable | PasswordLastSet | LastLogon
}
private enum PasswordExpiredState
{
Unchanged = -1,
NotExpired = 0,
Expired = 1
}
[Flags]
internal enum ObjectAccess : uint
{
AliasRead = Win32.STANDARD_RIGHTS_READ
| ALIAS_LIST_MEMBERS,
ALiasWrite = Win32.STANDARD_RIGHTS_WRITE
| ALIAS_WRITE_ACCOUNT
| ALIAS_ADD_MEMBER
| ALIAS_REMOVE_MEMBER,
UserAllAccess = Win32.STANDARD_RIGHTS_REQUIRED
| USER_READ_PREFERENCES
| USER_READ_LOGON
| USER_LIST_GROUPS
| USER_READ_GROUP_INFORMATION
| USER_WRITE_PREFERENCES
| USER_CHANGE_PASSWORD
| USER_FORCE_PASSWORD_CHANGE
| USER_READ_GENERAL
| USER_READ_ACCOUNT
| USER_WRITE_ACCOUNT
| USER_WRITE_GROUP_INFORMATION,
UserRead = Win32.STANDARD_RIGHTS_READ
| USER_READ_GENERAL // not in original USER_READ
| USER_READ_PREFERENCES
| USER_READ_LOGON
| USER_READ_ACCOUNT
| USER_LIST_GROUPS
| USER_READ_GROUP_INFORMATION,
UserWrite = Win32.STANDARD_RIGHTS_WRITE
| USER_WRITE_PREFERENCES
| USER_CHANGE_PASSWORD
}
[Flags]
internal enum DomainAccess : uint
{
AllAccess = Win32.STANDARD_RIGHTS_REQUIRED
| DOMAIN_READ_OTHER_PARAMETERS
| DOMAIN_WRITE_OTHER_PARAMETERS
| DOMAIN_WRITE_PASSWORD_PARAMS
| DOMAIN_CREATE_USER
| DOMAIN_CREATE_GROUP
| DOMAIN_CREATE_ALIAS
| DOMAIN_GET_ALIAS_MEMBERSHIP
| DOMAIN_LIST_ACCOUNTS
| DOMAIN_READ_PASSWORD_PARAMETERS
| DOMAIN_LOOKUP
| DOMAIN_ADMINISTER_SERVER,
Read = Win32.STANDARD_RIGHTS_READ
| DOMAIN_LIST_ACCOUNTS
| DOMAIN_GET_ALIAS_MEMBERSHIP
| DOMAIN_READ_OTHER_PARAMETERS,
Write = Win32.STANDARD_RIGHTS_WRITE
| DOMAIN_WRITE_OTHER_PARAMETERS
| DOMAIN_WRITE_PASSWORD_PARAMS
| DOMAIN_CREATE_USER
| DOMAIN_CREATE_GROUP
| DOMAIN_CREATE_ALIAS
| DOMAIN_ADMINISTER_SERVER,
Max = Win32.MAXIMUM_ALLOWED
}
/// <summary>
/// The operation under way. Used in the <see cref="Context"/> class.
/// </summary>
private enum ContextOperation
{
New = 1,
Enable,
Disable,
Get,
Remove,
Rename,
Set,
AddMember,
GetMember,
RemoveMember
}
/// <summary>
/// The type of object currently operating with.
/// used in the <see cref="Context"/> class.
/// </summary>
private enum ContextObjectType
{
User = 1,
Group
}
#endregion Enums
#region Internal Classes
/// <summary>
/// Holds information about the underway operation.
/// </summary>
/// <remarks>
/// Used primarily by the private ThrowOnFailure method when building
/// Exception objects to throw.
/// </remarks>
private sealed class Context
{
public ContextOperation operation;
public ContextObjectType type;
public object target;
public string objectId;
public string memberId;
/// <summary>
/// Initialize a new Context object.
/// </summary>
/// <param name="operation">
/// One of the <see cref="ContextOperation"/> enumerations indicating
/// the type of operation under way.
/// </param>
/// <param name="objectType">
/// One of the <see cref="ContextObjectType"/> enumerations indicating
/// the type of object (user or group) being used.
/// </param>
/// <param name="objectIdentifier">
/// A string containing the name of the object. This may be either a
/// user/group name or a string representation of a SID.
/// </param>
/// <param name="target">
/// The target being operated on.
/// </param>
/// <param name="memberIdentifier">
/// A string containing the name of the member being added or removed
/// from a group. Used only in such cases.
/// </param>
public Context(ContextOperation operation,
ContextObjectType objectType,
string objectIdentifier,
object target,
string memberIdentifier = null)
{
this.operation = operation;
this.type = objectType;
this.objectId = objectIdentifier;
this.target = target;
this.memberId = memberIdentifier;
}
/// <summary>
/// Default constructor.
/// </summary>
public Context()
{
}
/// <summary>
/// Gets a string containing the type of operation under way.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string OperationName
{
get { return operation.ToString(); }
}
/// <summary>
/// Gets a string containing the type of object ("User" or "Group")
/// being used.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string TypeNamne
{
get { return type.ToString(); }
}
/// <summary>
/// Gets a string containing the name of the object being used.
/// </summary>
public string ObjectName
{
get { return objectId; }
}
/// <summary>
/// Gets a string containing the name of the member being added to
/// or removed from a group. Returns null if the operation does not
/// involve group members.
/// </summary>
public string MemberName
{
get { return memberId; }
}
}
/// <summary>
/// Contains basic information about an Account.
/// </summary>
/// <remarks>
/// AccountInfo is the return type from the private
/// LookupAccountInfo method.
/// </remarks>
private sealed class AccountInfo
{
public string AccountName;
public string DomainName;
public SecurityIdentifier Sid;
public Native.SID_NAME_USE Use;
public override string ToString()
{
if (!string.IsNullOrEmpty(DomainName))
return DomainName + '\\' + AccountName;
else
return AccountName;
}
}
#endregion Internal Classes
#region Constants
//
// Access rights
//
private const UInt32 ALIAS_ADD_MEMBER = 0x0001;
private const UInt32 ALIAS_REMOVE_MEMBER = 0x0002;
private const UInt32 ALIAS_LIST_MEMBERS = 0x0004;
private const UInt32 ALIAS_READ_INFORMATION = 0x0008;
private const UInt32 ALIAS_WRITE_ACCOUNT = 0x0010;
private const UInt32 USER_READ_GENERAL = 0x0001;
private const UInt32 USER_READ_PREFERENCES = 0x0002;
private const UInt32 USER_WRITE_PREFERENCES = 0x0004;
private const UInt32 USER_READ_LOGON = 0x0008;
private const UInt32 USER_READ_ACCOUNT = 0x0010;
private const UInt32 USER_WRITE_ACCOUNT = 0x0020;
private const UInt32 USER_CHANGE_PASSWORD = 0x0040;
private const UInt32 USER_FORCE_PASSWORD_CHANGE = 0x0080;
private const UInt32 USER_LIST_GROUPS = 0x0100;
private const UInt32 USER_READ_GROUP_INFORMATION = 0x0200;
private const UInt32 USER_WRITE_GROUP_INFORMATION = 0x0400;
private const UInt32 DOMAIN_READ_PASSWORD_PARAMETERS = 0x0001;
private const UInt32 DOMAIN_WRITE_PASSWORD_PARAMS = 0x0002;
private const UInt32 DOMAIN_READ_OTHER_PARAMETERS = 0x0004;
private const UInt32 DOMAIN_WRITE_OTHER_PARAMETERS = 0x0008;
private const UInt32 DOMAIN_CREATE_USER = 0x0010;
private const UInt32 DOMAIN_CREATE_GROUP = 0x0020;
private const UInt32 DOMAIN_CREATE_ALIAS = 0x0040;
private const UInt32 DOMAIN_GET_ALIAS_MEMBERSHIP = 0x0080;
private const UInt32 DOMAIN_LIST_ACCOUNTS = 0x0100;
private const UInt32 DOMAIN_LOOKUP = 0x0200;
private const UInt32 DOMAIN_ADMINISTER_SERVER = 0x0400;
#endregion Constants
#region Static Data
private static SecurityIdentifier worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
#endregion Static Data
#region Instance Data
private IntPtr samHandle = IntPtr.Zero;
private IntPtr localDomainHandle = IntPtr.Zero;
private IntPtr builtinDomainHandle = IntPtr.Zero;
private Context context = null;
private string machineName = string.Empty;
#endregion Instance Data
#region Construction
internal Sam()
{
OpenHandles();
// CoreCLR does not have Environment.MachineName,
// so we'll use this instead.
machineName = System.Net.Dns.GetHostName();
}
#endregion Construction
#region Public (Internal) Methods
public string StripMachineName(string name)
{
var mn = machineName + '\\';
if (name.StartsWith(mn, StringComparison.CurrentCultureIgnoreCase))
return name.Substring(mn.Length);
return name;
}
#region Local Groups
/// <summary>
/// Retrieve a named local group.
/// </summary>
/// <param name="groupName">Name of the desired local group.</param>
/// <returns>
/// A <see cref="LocalGroup"/> object containing information about
/// the local group.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown when the named group cannot be found.
/// </exception>
internal LocalGroup GetLocalGroup(string groupName)
{
context = new Context(ContextOperation.Get, ContextObjectType.Group, groupName, groupName);
foreach (var sre in EnumerateGroups())
if (sre.Name.Equals(groupName, StringComparison.CurrentCultureIgnoreCase))
return MakeLocalGroupObject(sre); // return a populated group
throw new GroupNotFoundException(groupName, context.target);
}
/// <summary>
/// Retrieve a local group by SID.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the desired group.
/// </param>
/// <returns>
/// A <see cref="LocalGroup"/> object containing information about
/// the local group.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
internal LocalGroup GetLocalGroup(SecurityIdentifier sid)
{
context = new Context(ContextOperation.Get, ContextObjectType.Group, sid.ToString(), sid);
foreach (var sre in EnumerateGroups())
if (RidToSid(sre.domainHandle, sre.RelativeId) == sid)
return MakeLocalGroupObject(sre); // return a populated group
throw new GroupNotFoundException(sid.ToString(), context.target);
}
/// <summary>
/// Create a local group.
/// </summary>
/// <param name="group">A <see cref="LocalGroup"/> object containing
/// information about the local group to be created.
/// </param>
/// <returns>
/// A new LocalGroup object containing information about the newly
/// created local group.
/// </returns>
/// <exception cref="GroupExistsException">
/// Thrown when an attempt is made to create a local group that already
/// exists.
/// </exception>
internal LocalGroup CreateLocalGroup(LocalGroup group)
{
context = new Context(ContextOperation.New, ContextObjectType.Group, group.Name, group.Name);
return CreateGroup(group, localDomainHandle);
}
/// <summary>
/// Update a local group with new property values.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object representing the group to be updated.
/// </param>
/// <param name="changed">
/// A LocalGroup object containing the desired changes.
/// </param>
/// <remarks>
/// Currently, a group's description is the only changeable property.
/// </remarks>
internal void UpdateLocalGroup(LocalGroup group, LocalGroup changed)
{
context = new Context(ContextOperation.Set, ContextObjectType.Group, group.Name, group);
UpdateGroup(group, changed);
}
/// <summary>
/// Remove a local group.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the
/// local group to be removed.
/// </param>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
internal void RemoveLocalGroup(SecurityIdentifier sid)
{
context = new Context(ContextOperation.Remove, ContextObjectType.Group, sid.ToString(), sid);
RemoveGroup(sid);
}
/// <summary>
/// Remove a local group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object containing
/// information about the local group to be removed.
/// </param>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
internal void RemoveLocalGroup(LocalGroup group)
{
context = new Context(ContextOperation.Remove, ContextObjectType.Group, group.Name, group);
if (group.SID == null)
context.target = group = GetLocalGroup(group.Name);
RemoveGroup(group.SID);
}
/// <summary>
/// Rename a local group.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying
/// the local group to be renamed.
/// </param>
/// <param name="newName">
/// A string containing the new name for the local group.
/// </param>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
internal void RenameLocalGroup(SecurityIdentifier sid, string newName)
{
context = new Context(ContextOperation.Rename, ContextObjectType.Group, sid.ToString(), sid);
RenameGroup(sid, newName);
}
/// <summary>
/// Rename a local group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object containing
/// information about the local group to be renamed.
/// </param>
/// <param name="newName">
/// A string containing the new name for the local group.
/// </param>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
internal void RenameLocalGroup(LocalGroup group, string newName)
{
context = new Context(ContextOperation.Rename, ContextObjectType.Group, group.Name, group);
if (group.SID == null)
context.target = group = GetLocalGroup(group.Name);
RenameGroup(group.SID, newName);
}
/// <summary>
/// Get all local groups whose names satisfy the specified predicate.
/// </summary>
/// <param name="pred">
/// Predicate that determines whether a group satisfies the conditions.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{LocalGroup}"/> object containing LocalGroup
/// objects that satisfy the predicate condition.
/// </returns>
internal IEnumerable<LocalGroup> GetMatchingLocalGroups(Predicate<string> pred)
{
context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null);
foreach (var sre in EnumerateGroups())
{
if (pred(sre.Name))
{
context.target = sre.Name;
yield return MakeLocalGroupObject(sre);
}
}
}
/// <summary>
/// Get all local groups.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable{LocalGroup}"/> object containing a
/// LocalGroup object for each local group.
/// </returns>
internal IEnumerable<LocalGroup> GetAllLocalGroups()
{
context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null);
foreach (var sre in EnumerateGroups())
{
context.target = sre.Name;
yield return MakeLocalGroupObject(sre);
}
}
/// <summary>
/// Add members to a local group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object identifying the group to
/// which to add members.
/// </param>
/// <param name="member">
/// An object of type <see cref="LocalPrincipal"/> identifying
/// the member to be added.
/// </param>
/// <returns>
/// An Exception object indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
internal Exception AddLocalGroupMember(LocalGroup group, LocalPrincipal member)
{
context = new Context(ContextOperation.AddMember, ContextObjectType.Group, group.Name, group);
if (group.SID == null)
context.target = group = GetLocalGroup(group.Name);
return AddGroupMember(group.SID, member);
}
/// <summary>
/// Add members to a local group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group to
/// which to add members.
/// </param>
/// <param name="member">
/// An object of type <see cref="LocalPrincipal"/> identifying
/// the member to be added.
/// </param>
/// <returns>
/// An Exception object indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
internal Exception AddLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member)
{
context = new Context(ContextOperation.AddMember, ContextObjectType.Group, groupSid.ToString(), groupSid);
return AddGroupMember(groupSid, member);
}
/// <summary>
/// Retrieve members of a Local group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object identifying the group whose members
/// are requested.
/// </param>
/// <returns>
/// An IEnumerable of <see cref="LocalPrincipal"/> objects containing the group's
/// members.
/// </returns>
internal IEnumerable<LocalPrincipal> GetLocalGroupMembers(LocalGroup group)
{
context = new Context(ContextOperation.GetMember, ContextObjectType.Group, group.Name, group);
if (group.SID == null)
context.target = group = GetLocalGroup(group.Name);
return GetGroupMembers(group.SID);
}
/// <summary>
/// Retrieve members of a Local group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group whose members
/// are requested.
/// </param>
/// <returns>
/// An IEnumerable of <see cref="LocalPrincipal"/> objects containing the group's
/// members.
/// </returns>
internal IEnumerable<LocalPrincipal> GetLocalGroupMembers(SecurityIdentifier groupSid)
{
context = new Context(ContextOperation.GetMember, ContextObjectType.Group, groupSid.ToString(), groupSid);
return GetGroupMembers(groupSid);
}
/// <summary>
/// Remove members from a local group.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object identifying the group from
/// which to remove members
/// </param>
/// <param name="member">
/// An object of type <see cref="LocalPrincipal"/> identifying
/// the member to be removed.
/// </param>
/// <returns>
/// An Exception object indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
internal Exception RemoveLocalGroupMember(LocalGroup group, LocalPrincipal member)
{
context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, group.Name, group);
if (group.SID == null)
context.target = group = GetLocalGroup(group.Name);
return RemoveGroupMember(group.SID, member);
}
/// <summary>
/// Remove members from a local group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group from
/// which to remove members
/// </param>
/// <param name="member">
/// An Object of type <see cref="LocalPrincipal"/> identifying
/// the member to be removed.
/// </param>
/// <returns>
/// An Exception object indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
internal Exception RemoveLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member)
{
context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, groupSid.ToString(), groupSid);
return RemoveGroupMember(groupSid, member);
}
#endregion Local Groups
#region Local Users
/// <summary>
/// Retrieve a named local user.
/// </summary>
/// <param name="userName">Name of the desired local user.</param>
/// <returns>
/// A <see cref="LocalUser"/> object containing information about
/// the local user.
/// </returns>
/// <exception cref="UserNotFoundException">
/// Thrown when the named user cannot be found.
/// </exception>
internal LocalUser GetLocalUser(string userName)
{
context = new Context(ContextOperation.Get, ContextObjectType.User, userName, userName);
foreach (var sre in EnumerateUsers())
if (sre.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
return MakeLocalUserObject(sre);
throw new UserNotFoundException(userName, userName);
}
/// <summary>
/// Retrieve a local user by SID.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the desired user.
/// </param>
/// <returns>
/// A <see cref="LocalUser"/> object containing information about
/// the local user.
/// </returns>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user cannot be found.
/// </exception>
internal LocalUser GetLocalUser(SecurityIdentifier sid)
{
context = new Context(ContextOperation.Get, ContextObjectType.User, sid.ToString(), sid);
foreach (var sre in EnumerateUsers())
if (RidToSid(sre.domainHandle, sre.RelativeId) == sid)
return MakeLocalUserObject(sre); // return a populated user
throw new UserNotFoundException(sid.ToString(), sid);
}
/// <summary>
/// Create a local user.
/// </summary>
/// <param name="user">A <see cref="LocalUser"/> object containing
/// information about the local user to be created.
/// </param>
/// <param name="password">A <see cref="System.Security.SecureString"/> containing
/// the initial password to be set for the new local user. If this parameter is null,
/// no password is set.
/// </param>
/// <param name="setPasswordNeverExpires">
/// Indicates whether PasswordNeverExpires was specified
/// </param>
/// <returns>
/// A new LocalGroup object containing information about the newly
/// created local user.
/// </returns>
/// <exception cref="UserExistsException">
/// Thrown when an attempt is made to create a local user that already
/// exists.
/// </exception>
internal LocalUser CreateLocalUser(LocalUser user, System.Security.SecureString password, bool setPasswordNeverExpires)
{
context = new Context(ContextOperation.New, ContextObjectType.User, user.Name, user);
return CreateUser(user, password, localDomainHandle, setPasswordNeverExpires);
}
/// <summary>
/// Remove a local user.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying
/// the local user to be removed.
/// </param>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user cannot be found.
/// </exception>
internal void RemoveLocalUser(SecurityIdentifier sid)
{
context = new Context(ContextOperation.Remove, ContextObjectType.User, sid.ToString(), sid);
RemoveUser(sid);
}
/// <summary>
/// Remove a local user.
/// </summary>
/// <param name="user">
/// A <see cref="LocalUser"/> object containing
/// information about the local user to be removed.
/// </param>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user cannot be found.
/// </exception>
internal void RemoveLocalUser(LocalUser user)
{
context = new Context(ContextOperation.Remove, ContextObjectType.User, user.Name, user);
if (user.SID == null)
context.target = user = GetLocalUser(user.Name);
RemoveUser(user.SID);
}
/// <summary>
/// Rename a local user.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> objects identifying
/// the local user to be renamed.
/// </param>
/// <param name="newName">
/// A string containing the new name for the local user.
/// </param>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user cannot be found.
/// </exception>
internal void RenameLocalUser(SecurityIdentifier sid, string newName)
{
context = new Context(ContextOperation.Rename, ContextObjectType.User, sid.ToString(), sid);
RenameUser(sid, newName);
}
/// <summary>
/// Rename a local user.
/// </summary>
/// <param name="user">
/// A <see cref="LocalUser"/> objects containing
/// information about the local user to be renamed.
/// </param>
/// <param name="newName">
/// A string containing the new name for the local user.
/// </param>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user cannot be found.
/// </exception>
internal void RenameLocalUser(LocalUser user, string newName)
{
context = new Context(ContextOperation.Rename, ContextObjectType.User, user.Name, user);
if (user.SID == null)
context.target = user = GetLocalUser(user.Name);
RenameUser(user.SID, newName);
}
/// <summary>
/// Enable or disable a Local User.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the user to enable or disable.
/// </param>
/// <param name="enable">
/// One of the <see cref="Enabling"/> enumeration values, indicating whether to
/// enable or disable the user.
/// </param>
internal void EnableLocalUser(SecurityIdentifier sid, Enabling enable)
{
context = new Context(enable == Enabling.Enable ? ContextOperation.Enable
: ContextOperation.Disable,
ContextObjectType.User, sid.ToString(),
sid);
EnableUser(sid, enable);
}
/// <summary>
/// Enable or disable a Local User.
/// </summary>
/// <param name="user">
/// A <see cref="LocalUser"/> object representing the user to enable or disable.
/// </param>
/// <param name="enable">
/// One of the <see cref="Enabling"/> enumeration values, indicating whether to
/// enable or disable the user.
/// </param>
internal void EnableLocalUser(LocalUser user, Enabling enable)
{
context = new Context(enable == Enabling.Enable ? ContextOperation.Enable
: ContextOperation.Disable,
ContextObjectType.User, user.Name,
user);
if (user.SID == null)
context.target = user = GetLocalUser(user.Name);
EnableUser(user.SID, enable);
}
/// <summary>
/// Update a local user with new properties.
/// </summary>
/// <param name="user">
/// A <see cref="LocalUser"/> object representing the user to be updated.
/// </param>
/// <param name="changed">
/// A LocalUser object containing the desired changes.
/// </param>
/// <param name="password">A <see cref="System.Security.SecureString"/>
/// object containing the new password. A null value in this parameter
/// indicates that the password is not to be changed.
/// </param>
/// <param name="setPasswordNeverExpires">
/// Specifies whether the PasswordNeverExpires parameter was set.
/// </param>
/// <remarks>
/// Call this overload when intending to leave the password-expired
/// marker in its current state. To set the password and the
/// password-expired state, call the overload with a boolean as the
/// fourth parameter
/// </remarks>
internal void UpdateLocalUser(LocalUser user, LocalUser changed, System.Security.SecureString password, bool? setPasswordNeverExpires)
{
context = new Context(ContextOperation.Set, ContextObjectType.User, user.Name, user);
UpdateUser(user, changed, password, PasswordExpiredState.Unchanged, setPasswordNeverExpires);
}
/// <summary>
/// Get all local users whose names satisfy the specified predicate.
/// </summary>
/// <param name="pred">
/// Predicate that determines whether a user satisfies the conditions.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{LocalUser}"/> object containing LocalUser
/// objects that satisfy the predicate condition.
/// </returns>
internal IEnumerable<LocalUser> GetMatchingLocalUsers(Predicate<string> pred)
{
context = new Context(ContextOperation.Get, ContextObjectType.User, string.Empty, null);
foreach (var sre in EnumerateUsers())
{
if (pred(sre.Name))
{
context.target = sre.Name;
yield return MakeLocalUserObject(sre);
}
}
}
/// <summary>
/// Get all local users.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable{LocalUser}"/> object containing a
/// LocalUser object for each local user.
/// </returns>
internal IEnumerable<LocalUser> GetAllLocalUsers()
{
context = new Context(ContextOperation.Get, ContextObjectType.User, null, null);
foreach (var sre in EnumerateUsers())
yield return MakeLocalUserObject(sre);
}
#endregion Local Users
#region Local Principals
internal LocalPrincipal LookupAccount(string name)
{
var info = LookupAccountInfo(name);
if (info == null)
throw new PrincipalNotFoundException(name, name);
return MakeLocalPrincipalObject(info);
}
#endregion Local Principals
#endregion Public (Internal) Methods
#region Private Methods
/// <summary>
/// Open the handles stored by Sam instances.
/// </summary>
private void OpenHandles()
{
var systemName = new UNICODE_STRING();
var oa = new OBJECT_ATTRIBUTES();
IntPtr pInfo = IntPtr.Zero;
IntPtr pSid = IntPtr.Zero;
IntPtr lsaHandle = IntPtr.Zero;
UInt32 status = 0;
try
{
status = Win32.LsaOpenPolicy(ref systemName, ref oa, (UInt32)LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION, out lsaHandle);
ThrowOnFailure(status);
POLICY_PRIMARY_DOMAIN_INFO domainInfo;
status = Win32.LsaQueryInformationPolicy(lsaHandle,
POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation,
out pInfo);
ThrowOnFailure(status);
status = Win32.LsaClose(lsaHandle);
ThrowOnFailure(status);
lsaHandle = IntPtr.Zero;
domainInfo = Marshal.PtrToStructure<POLICY_PRIMARY_DOMAIN_INFO>(pInfo);
status = SamApi.SamConnect(ref systemName, out samHandle, SamApi.SAM_SERVER_LOOKUP_DOMAIN, ref oa);
ThrowOnFailure(status);
// Open the local domain
status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, domainInfo.Sid, out localDomainHandle);
ThrowOnFailure(status);
// Open the "BuiltIn" domain
SecurityIdentifier sid = new SecurityIdentifier("S-1-5-32");
byte[] bSid = new byte[sid.BinaryLength];
int size = Marshal.SizeOf<byte>() * bSid.Length;
pSid = Marshal.AllocHGlobal(size);
sid.GetBinaryForm(bSid, 0);
Marshal.Copy(bSid, 0, pSid, bSid.Length);
status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, pSid, out builtinDomainHandle);
ThrowOnFailure(status);
}
finally
{
if (pInfo != IntPtr.Zero)
status = Win32.LsaFreeMemory(pInfo);
Marshal.FreeHGlobal(pSid);
if (lsaHandle != IntPtr.Zero)
status = Win32.LsaClose(lsaHandle);
}
}
/// <summary>
/// Find a group by SID and return a <see cref="SamRidEnumeration"/> object
/// representing the group.
/// </summary>
/// <param name="sid">A <see cref="SecurityIdentifier"/> object identifying
/// the group to search for.</param>
/// <returns>
/// A SamRidEnumeration object representing the group.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group is not found.
/// </exception>
/// <remarks>
/// This method saves some time and effort over the GetGroup method
/// because it does not have to open a group to populate a full Group
/// object.
/// </remarks>
private SamRidEnumeration GetGroupSre(SecurityIdentifier sid)
{
foreach (var sre in EnumerateGroups())
if (RidToSid(sre.domainHandle, sre.RelativeId) == sid)
return sre;
throw new GroupNotFoundException(sid.ToString(), sid);
}
/// <summary>
/// Find a user by SID and return a <see cref="SamRidEnumeration"/> object
/// representing the user.
/// </summary>
/// <param name="sid">A <see cref="SecurityIdentifier"/> object identifying
/// the user to search for.</param>
/// <returns>
/// A SamRidEnumeration object representing the user.
/// </returns>
/// <exception cref="UserNotFoundException">
/// Thrown when the specified user is not found.
/// </exception>
/// <remarks>
/// This method saves some time and effort over the GetUser method
/// because it does not have to open a user to populate a full LocalUser
/// object.
/// </remarks>
private SamRidEnumeration GetUserSre(SecurityIdentifier sid)
{
foreach (var sre in EnumerateUsers())
if (RidToSid(sre.domainHandle, sre.RelativeId) == sid)
return sre;
throw new UserNotFoundException(sid.ToString(), sid);
}
/// <summary>
/// Enumerate local users with native SAM functions.
/// </summary>
/// <param name="domainHandle">Handle to the domain to enumerate over.</param>
/// <returns>
/// An IEnumerable of SamRidEnumeration objects, one for each local user.
/// </returns>
/// <remarks>
/// This is a "generator" method. Rather than returning an entire collection,
/// it uses 'yield return' to return each object in turn.
/// </remarks>
private static IEnumerable<SamRidEnumeration> EnumerateUsersInDomain(IntPtr domainHandle)
{
UInt32 status = 0;
UInt32 context = 0;
IntPtr buffer = IntPtr.Zero;
UInt32 countReturned;
do
{
status = SamApi.SamEnumerateUsersInDomain(domainHandle,
ref context,
0,
out buffer,
1,
out countReturned);
if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1)
{
if (buffer != IntPtr.Zero)
{
SAM_RID_ENUMERATION sre;
sre = Marshal.PtrToStructure<SAM_RID_ENUMERATION>(buffer);
SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
yield return new SamRidEnumeration
{
Name = sre.Name.ToString(),
RelativeId = sre.RelativeId,
domainHandle = domainHandle
};
}
}
} while (Succeeded(status) && status != 0 && countReturned != 0);
}
/// <summary>
/// Enumerate user objects in both the local and builtin domains.
/// </summary>
/// <returns>
/// An IEnumerable of SamRidEnumeration objects, one for each local user.
/// </returns>
/// <remarks>
/// This is a "generator" method. Rather than returning an entire collection,
/// it uses 'yield return' to return each object in turn.
/// </remarks>
private IEnumerable<SamRidEnumeration> EnumerateUsers()
{
foreach (var sre in EnumerateUsersInDomain(localDomainHandle))
yield return sre;
foreach (var sre in EnumerateUsersInDomain(builtinDomainHandle))
yield return sre;
}
/// <summary>
/// Create a new user in the specified domain.
/// </summary>
/// <param name="userInfo">
/// A <see cref="LocalUser"/> object containing information about the new user.
/// </param>
/// <param name="password">A <see cref="System.Security.SecureString"/> containing
/// the initial password to be set for the new local user. If this parameter is null,
/// no password is set.
/// </param>
/// <param name="domainHandle">
/// Handle to the domain in which to create the new user.
/// </param>
/// <param name="setPasswordNeverExpires">
/// Indicates whether PasswordNeverExpires was specified
/// </param>
/// <returns>
/// A LocalUser object that represents the newly-created user
/// </returns>
private LocalUser CreateUser(LocalUser userInfo, System.Security.SecureString password, IntPtr domainHandle, bool setPasswordNeverExpires)
{
IntPtr userHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
UNICODE_STRING str = new UNICODE_STRING();
UInt32 status = 0;
try
{
UInt32 relativeId = 0;
UInt32 grantedAccess = 0;
str = new UNICODE_STRING(userInfo.Name);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str));
Marshal.StructureToPtr(str, buffer, false);
status = SamApi.SamCreateUser2InDomain(domainHandle,
ref str,
(int) SamApi.USER_NORMAL_ACCOUNT,
Win32.MAXIMUM_ALLOWED,
out userHandle,
out grantedAccess,
out relativeId);
Marshal.DestroyStructure<UNICODE_STRING>(buffer);
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
ThrowOnFailure(status);
// set the various properties of the user. A SID is required because some
// operations depend on it.
userInfo.SID = RidToSid(domainHandle, relativeId);
SetUserData(userHandle, userInfo, UserProperties.AllCreateable, password, PasswordExpiredState.NotExpired, setPasswordNeverExpires);
return MakeLocalUserObject(new SamRidEnumeration
{
domainHandle = domainHandle,
Name = userInfo.Name,
RelativeId = relativeId
},
userHandle);
}
catch (Exception)
{
if (IntPtr.Zero != userHandle)
{
SamApi.SamDeleteUser(userHandle);
}
throw;
}
finally
{
if (buffer != IntPtr.Zero)
Marshal.FreeHGlobal(buffer);
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
/// <summary>
/// Remove a group identified by SID.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the
/// group to be removed.
/// </param>
private void RemoveGroup(SecurityIdentifier sid)
{
var sre = GetGroupSre(sid);
IntPtr aliasHandle = IntPtr.Zero;
UInt32 status;
try
{
status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
status = SamApi.SamDeleteAlias(aliasHandle);
ThrowOnFailure(status);
aliasHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteAlias succeeds
}
finally
{
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
}
/// <summary>
/// Rename a group identified by SID.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying
/// the local group to be renamed.
/// </param>
/// <param name="newName">
/// A string containing the new name for the group.
/// </param>
/// <exception cref="GroupNotFoundException">
/// Thrown when the specified group cannot be found.
/// </exception>
private void RenameGroup(SecurityIdentifier sid, string newName)
{
var sre = GetGroupSre(sid);
IntPtr aliasHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
UInt32 status = 0;
status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
try
{
ALIAS_NAME_INFORMATION info = new ALIAS_NAME_INFORMATION();
info.Name = new UNICODE_STRING(newName);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, buffer, false);
status = SamApi.SamSetInformationAlias(aliasHandle,
ALIAS_INFORMATION_CLASS.AliasNameInformation,
buffer);
ThrowOnFailure(status,
new Context {
objectId = newName,
operation = context.operation,
type = context.type
}
);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.DestroyStructure<ALIAS_NAME_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
}
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
}
/// <summary>
/// Add members to a group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group to
/// which to add members.
/// </param>
/// <param name="member">
/// An object of type <see cref="LocalPrincipal"/>identifying
/// the member to be added.
/// </param>
/// <returns>
/// An Exception object indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
private Exception AddGroupMember(SecurityIdentifier groupSid, LocalPrincipal member)
{
var sre = GetGroupSre(groupSid); // We'll let this throw if necessary
IntPtr aliasHandle = IntPtr.Zero;
UInt32 status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
Exception ex = null;
try
{
var sid = member.SID;
var binarySid = new byte[sid.BinaryLength];
sid.GetBinaryForm(binarySid, 0);
status = SamApi.SamAddMemberToAlias(aliasHandle, binarySid);
ex = MakeException(status,
new Context
{
memberId = member.ToString(),
objectId = context.objectId,
operation = context.operation,
target = context.target,
type = context.type
}
);
}
finally
{
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
return ex;
}
/// <summary>
/// Retrieve members of a group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object representing the group whose members
/// are requested.
/// </param>
/// <returns>
/// An IEnumerable of <see cref="LocalPrincipal"/> objects containing the group's
/// members.
/// </returns>
private IEnumerable<LocalPrincipal> GetGroupMembers(SecurityIdentifier groupSid)
{
var sre = GetGroupSre(groupSid);
IntPtr aliasHandle = IntPtr.Zero;
IntPtr memberIds = IntPtr.Zero;
UInt32 status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
try
{
UInt32 memberCount = 0;
status = SamApi.SamGetMembersInAlias(aliasHandle, out memberIds, out memberCount);
ThrowOnFailure(status);
if (memberCount != 0)
{
IntPtr[] idArray = new IntPtr[memberCount];
Marshal.Copy(memberIds, idArray, 0, (int)memberCount);
for (int i=0; i < memberCount; i++)
{
var sid = new SecurityIdentifier(idArray[i]);
yield return MakeLocalPrincipalObject(LookupAccountInfo(sid));
}
}
}
finally
{
if (aliasHandle != IntPtr.Zero)
SamApi.SamCloseHandle(aliasHandle);
if (memberIds != IntPtr.Zero)
SamApi.SamFreeMemory(memberIds);
}
}
/// <summary>
/// Remove members from a group.
/// </summary>
/// <param name="groupSid">
/// A <see cref="SecurityIdentifier"/> object identifying the group from
/// which to remove members
/// </param>
/// <param name="member">
/// An object of type <see cref="LocalPrincipal"/> identifying
/// the member to be removed.
/// </param>
/// <returns>
/// An IEnumerable of Exception objects indicating any errors encountered.
/// </returns>
/// <exception cref="GroupNotFoundException">
/// Thrown if the group could not be found.
/// </exception>
private Exception RemoveGroupMember(SecurityIdentifier groupSid, LocalPrincipal member)
{
var sre = GetGroupSre(groupSid); // We'll let this throw if necessary
IntPtr aliasHandle = IntPtr.Zero;
UInt32 status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
// Now we're processing each member, so any further exceptions will
// be stored in the collection and returned later.
var rv = new List<Exception>();
Exception ex = null;
try
{
var sid = member.SID;
var binarySid = new byte[sid.BinaryLength];
sid.GetBinaryForm(binarySid, 0);
status = SamApi.SamRemoveMemberFromAlias(aliasHandle, binarySid);
ex = MakeException(status,
new Context {
memberId = member.ToString(),
objectId = context.objectId,
operation = context.operation,
target = context.target,
type = context.type
}
);
}
finally
{
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
return ex;
}
/// <summary>
/// Create a populated LocalUser object from a SamRidEnumeration object.
/// </summary>
/// <param name="sre">
/// A <see cref="SamRidEnumeration"/> object containing minimal information
/// about a local user.
/// </param>
/// <returns>
/// A LocalUser object, populated with user information.
/// </returns>
private LocalUser MakeLocalUserObject(SamRidEnumeration sre)
{
IntPtr userHandle = IntPtr.Zero;
var status = SamApi.SamOpenUser(sre.domainHandle,
(UInt32)ObjectAccess.UserRead,
sre.RelativeId,
out userHandle);
ThrowOnFailure(status);
try
{
return MakeLocalUserObject(sre, userHandle);
}
finally
{
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
/// <summary>
/// Create a populated LocalUser object from a SamRidEnumeration object,
/// using an already-opened SAM user handle.
/// </summary>
/// <param name="sre">
/// A <see cref="SamRidEnumeration"/> object containing minimal information
/// about a local user.
/// </param>
/// <param name="userHandle">
/// Handle to an open SAM user.
/// </param>
/// <returns>
/// A LocalUser object, populated with user information.
/// </returns>
private LocalUser MakeLocalUserObject(SamRidEnumeration sre, IntPtr userHandle)
{
IntPtr buffer = IntPtr.Zero;
UInt32 status = 0;
try
{
USER_ALL_INFORMATION allInfo;
status = SamApi.SamQueryInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAllInformation,
out buffer);
ThrowOnFailure(status);
allInfo = Marshal.PtrToStructure<USER_ALL_INFORMATION>(buffer);
var userSid = RidToSid(sre.domainHandle, sre.RelativeId);
LocalUser user = new LocalUser()
{
PrincipalSource = GetPrincipalSource(sre),
SID = userSid,
Name = allInfo.UserName.ToString(),
FullName = allInfo.FullName.ToString(),
Description = allInfo.AdminComment.ToString(),
// TODO: why is this coming up as 864000000000 (number of ticks per day)?
PasswordChangeableDate = DateTimeFromSam(allInfo.PasswordCanChange.QuadPart),
PasswordExpires = DateTimeFromSam(allInfo.PasswordMustChange.QuadPart),
// TODO: why is this coming up as 0X7FFFFFFFFFFFFFFF (largest signed 64-bit, and well out of range of DateTime)?
AccountExpires = DateTimeFromSam(allInfo.AccountExpires.QuadPart),
LastLogon = DateTimeFromSam(allInfo.LastLogon.QuadPart),
PasswordLastSet = DateTimeFromSam(allInfo.PasswordLastSet.QuadPart),
UserMayChangePassword = GetUserMayChangePassword(userHandle, userSid),
PasswordRequired = (allInfo.UserAccountControl & SamApi.USER_PASSWORD_NOT_REQUIRED) == 0,
Enabled = !((allInfo.UserAccountControl & SamApi.USER_ACCOUNT_DISABLED) == SamApi.USER_ACCOUNT_DISABLED)
};
return user;
}
finally
{
if (buffer != IntPtr.Zero)
status = SamApi.SamFreeMemory(buffer);
}
}
/// <summary>
/// Enable or disable a user.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the user to be
/// enabled or disabled.
/// </param>
/// <param name="enable">
/// One of the <see cref="Enabling"/> enumeration values indicating
/// whether the user is to be enabled or disabled.
/// </param>
private void EnableUser(SecurityIdentifier sid, Enabling enable)
{
IntPtr userHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
UInt32 status = 0;
var sre = GetUserSre(sid);
status = SamApi.SamOpenUser(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out userHandle);
ThrowOnFailure(status);
try
{
USER_ALL_INFORMATION info;
status = SamApi.SamQueryInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAllInformation,
out buffer);
ThrowOnFailure(status);
info = Marshal.PtrToStructure<USER_ALL_INFORMATION>(buffer);
status = SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
UInt32 uac = info.UserAccountControl;
UInt32 enabled_state = uac & SamApi.USER_ACCOUNT_DISABLED;
if (enable == Enabling.Enable && enabled_state == SamApi.USER_ACCOUNT_DISABLED)
uac &= ~SamApi.USER_ACCOUNT_DISABLED;
else if (enable == Enabling.Disable && enabled_state != SamApi.USER_ACCOUNT_DISABLED)
uac |= SamApi.USER_ACCOUNT_DISABLED;
else
return;
if (uac != info.UserAccountControl)
{
info.UserAccountControl = uac;
info.WhichFields = SamApi.USER_ALL_USERACCOUNTCONTROL;
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, buffer, false);
status = SamApi.SamSetInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAllInformation,
buffer);
Marshal.DestroyStructure<USER_ALL_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
ThrowOnFailure(status);
}
}
finally
{
if (buffer != IntPtr.Zero)
Marshal.FreeHGlobal(buffer);
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
/// <summary>
/// Rename a user.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the user to be
/// renamed.
/// </param>
/// <param name="newName">The new user name.</param>
private void RenameUser(SecurityIdentifier sid, string newName)
{
IntPtr userHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
UInt32 status = 0;
var sre = GetUserSre(sid);
status = SamApi.SamOpenUser(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out userHandle);
ThrowOnFailure(status);
try
{
USER_ACCOUNT_NAME_INFORMATION info = new USER_ACCOUNT_NAME_INFORMATION();
info.UserName = new UNICODE_STRING(newName);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, buffer, false);
status = SamApi.SamSetInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAccountNameInformation,
buffer);
ThrowOnFailure(status,
new Context {
objectId = newName,
operation = context.operation,
type = context.type
}
);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.DestroyStructure<USER_ACCOUNT_NAME_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
}
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
/// <summary>
/// Delete a user.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the user to be
/// removed.
/// </param>
private void RemoveUser(SecurityIdentifier sid)
{
IntPtr userHandle = IntPtr.Zero;
var sre = GetUserSre(sid);
UInt32 status;
try
{
status = SamApi.SamOpenUser(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out userHandle);
ThrowOnFailure(status);
status = SamApi.SamDeleteUser(userHandle);
ThrowOnFailure(status);
userHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteUser succeeds
}
finally
{
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
/// <summary>
/// Enumerate local users with native SAM functions.
/// </summary>
/// <param name="domainHandle">Handle to the domain to enumerate over.</param>
/// <returns>
/// An IEnumerable of SamRidEnumeration objects, one for each local user.
/// </returns>
/// <remarks>
/// This is a "generator" method. Rather than returning an entire collection,
/// it uses 'yield return' to return each object in turn.
/// </remarks>
private static IEnumerable<SamRidEnumeration> EnumerateGroupsInDomain(IntPtr domainHandle)
{
UInt32 status = 0;
UInt32 context = 0;
IntPtr buffer = IntPtr.Zero;
UInt32 countReturned;
do
{
// Although the method name indicates that we are operating with "groups",
// it actually uses the SAM API's SamEnumerateAliasesInDomain function.
status = SamApi.SamEnumerateAliasesInDomain(domainHandle,
ref context,
out buffer,
1,
out countReturned);
if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1)
{
if (buffer != IntPtr.Zero)
{
SAM_RID_ENUMERATION sre;
sre = Marshal.PtrToStructure<SAM_RID_ENUMERATION>(buffer);
SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
yield return new SamRidEnumeration
{
Name = sre.Name.ToString(),
RelativeId = sre.RelativeId,
domainHandle = domainHandle
};
}
}
} while (Succeeded(status) && status != 0 && countReturned != 0);
}
/// <summary>
/// Enumerate group objects in both the local and builtin domains.
/// </summary>
/// <returns>
/// An IEnumerable of SamRidEnumeration objects, one for each local group.
/// </returns>
/// <remarks>
/// This is a "generator" method. Rather than returning an entire collection,
/// it uses 'yield return' to return each object in turn.
/// </remarks>
internal IEnumerable<SamRidEnumeration> EnumerateGroups()
{
foreach (var sre in EnumerateGroupsInDomain(localDomainHandle))
yield return sre;
foreach (var sre in EnumerateGroupsInDomain(builtinDomainHandle))
yield return sre;
}
/// <summary>
/// Create a new group in the specified domain.
/// </summary>
/// <param name="groupInfo">
/// A <see cref="LocalGroup"/> object containing information about the new group.
/// </param>
/// <param name="domainHandle">Handle to the domain in which to create the new group.</param>
/// <returns>
/// A LocalGroup object that represents the newly-created group.
/// </returns>
private LocalGroup CreateGroup(LocalGroup groupInfo, IntPtr domainHandle)
{
IntPtr aliasHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
UNICODE_STRING str = new UNICODE_STRING();
UInt32 status;
try
{
UInt32 relativeId;
str = new UNICODE_STRING(groupInfo.Name);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str));
Marshal.StructureToPtr(str, buffer, false);
status = SamApi.SamCreateAliasInDomain(domainHandle,
buffer,
Win32.MAXIMUM_ALLOWED,
out aliasHandle,
out relativeId);
Marshal.DestroyStructure<UNICODE_STRING>(buffer);
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
ThrowOnFailure(status);
if (!string.IsNullOrEmpty(groupInfo.Description))
{
ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION();
info.AdminComment = new UNICODE_STRING(groupInfo.Description);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, buffer, false);
status = SamApi.SamSetInformationAlias(aliasHandle,
ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation,
buffer);
Marshal.DestroyStructure<ALIAS_ADM_COMMENT_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
ThrowOnFailure(status);
}
return MakeLocalGroupObject(new SamRidEnumeration
{
domainHandle = domainHandle,
Name = groupInfo.Name,
RelativeId = relativeId
},
aliasHandle);
}
finally
{
if (buffer != IntPtr.Zero)
Marshal.FreeHGlobal(buffer);
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
}
/// <summary>
/// Update a local group with new property values. This method provides
/// the actual implementation.
/// </summary>
/// <param name="group">
/// A <see cref="LocalGroup"/> object representing the group to be updated.
/// </param>
/// <param name="changed">
/// A LocalGroup object containing the desired changes.
/// </param>
/// <remarks>
/// Currently, a group's description is the only changeable property.
/// </remarks>
private void UpdateGroup(LocalGroup group, LocalGroup changed)
{
// Only description may be changed
if (group.Description == changed.Description)
return;
IntPtr aliasHandle = IntPtr.Zero;
IntPtr buffer = IntPtr.Zero;
if (group.SID == null)
group = GetLocalGroup(group.Name);
var sre = GetGroupSre(group.SID);
UInt32 status;
try
{
status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION();
info.AdminComment = new UNICODE_STRING(changed.Description);
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr(info, buffer, false);
status = SamApi.SamSetInformationAlias(aliasHandle,
ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation,
buffer);
ThrowOnFailure(status);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.DestroyStructure<ALIAS_ADM_COMMENT_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
}
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
}
/// <summary>
/// Create a populated LocalGroup object from a SamRidEnumeration object.
/// </summary>
/// <param name="sre">
/// A <see cref="SamRidEnumeration"/> object containing minimal information
/// about a local group.
/// </param>
/// <returns>
/// A LocalGroup object, populated with group information.
/// </returns>
private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre)
{
IntPtr aliasHandle = IntPtr.Zero;
var status = SamApi.SamOpenAlias(sre.domainHandle,
Win32.MAXIMUM_ALLOWED,
sre.RelativeId,
out aliasHandle);
ThrowOnFailure(status);
try
{
return MakeLocalGroupObject(sre, aliasHandle);
}
finally
{
if (aliasHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(aliasHandle);
}
}
/// <summary>
/// Create a populated LocalGroup object from a SamRidEnumeration object,
/// using an already-opened SAM alias handle.
/// </summary>
/// <param name="sre">
/// A <see cref="SamRidEnumeration"/> object containing minimal information
/// about a local group.
/// </param>
/// <param name="aliasHandle">
/// Handle to an open SAM alias.
/// </param>
/// <returns>
/// A LocalGroup object, populated with group information.
/// </returns>
private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre, IntPtr aliasHandle)
{
IntPtr buffer = IntPtr.Zero;
UInt32 status = 0;
try
{
ALIAS_GENERAL_INFORMATION generalInfo;
status = SamApi.SamQueryInformationAlias(aliasHandle,
ALIAS_INFORMATION_CLASS.AliasGeneralInformation,
out buffer);
ThrowOnFailure(status);
generalInfo = Marshal.PtrToStructure<ALIAS_GENERAL_INFORMATION>(buffer);
LocalGroup group = new LocalGroup()
{
PrincipalSource = GetPrincipalSource(sre),
SID = RidToSid(sre.domainHandle, sre.RelativeId),
Name = generalInfo.Name.ToString(),
Description = generalInfo.AdminComment.ToString()
};
return group;
}
finally
{
if (buffer != IntPtr.Zero)
status = SamApi.SamFreeMemory(buffer);
}
}
/// <summary>
/// Update a local user with new properties.
/// </summary>
/// <param name="user">
/// A <see cref="LocalUser"/> object representing the user to be updated.
/// </param>
/// <param name="changed">
/// A LocalUser object containing the desired changes.
/// </param>
/// <param name="password">A <see cref="System.Security.SecureString"/>
/// object containing the new password. A null value in this parameter
/// indicates that the password is not to be changed.
/// </param>
/// <param name="passwordExpired">One of the
/// <see cref="PasswordExpiredState"/> enumeration values indicating
/// whether the password-expired state is to be explicitly set or
/// left as is.
/// If the <paramref name="password"/> parameter is null, this parameter
/// is ignored.
/// </param>
/// <param name="setPasswordNeverExpires">
/// Indicates whether the PasswordNeverExpires parameter was specified.
/// </param>
private void UpdateUser(LocalUser user,
LocalUser changed,
System.Security.SecureString password,
PasswordExpiredState passwordExpired,
bool? setPasswordNeverExpires)
{
UserProperties properties = UserProperties.None;
if (user.AccountExpires != changed.AccountExpires)
properties |= UserProperties.AccountExpires;
if (user.Description != changed.Description)
properties |= UserProperties.Description;
if (user.FullName != changed.FullName)
properties |= UserProperties.FullName;
if (setPasswordNeverExpires.HasValue)
properties |= UserProperties.PasswordNeverExpires;
if (user.UserMayChangePassword != changed.UserMayChangePassword)
properties |= UserProperties.UserMayChangePassword;
if (user.PasswordRequired != changed.PasswordRequired)
properties |= UserProperties.PasswordRequired;
if ( properties != UserProperties.None
|| passwordExpired != PasswordExpiredState.Unchanged
|| password != null)
{
IntPtr userHandle = IntPtr.Zero;
UInt32 status = 0;
try
{
status = SamApi.SamOpenUser(localDomainHandle,
Win32.MAXIMUM_ALLOWED,
user.SID.GetRid(),
out userHandle);
ThrowOnFailure(status);
SetUserData(userHandle, changed, properties, password, passwordExpired, setPasswordNeverExpires);
}
finally
{
if (userHandle != IntPtr.Zero)
status = SamApi.SamCloseHandle(userHandle);
}
}
}
/// <summary>
/// Set selected properties of a user.
/// </summary>
/// <param name="userHandle">Handle to an open SAM user.</param>
/// <param name="sourceUser">
/// A <see cref="LocalUser"/> object containing the data to set into the user.
/// </param>
/// <param name="setFlags">
/// A combination of <see cref="UserProperties"/> values indicating the properties to be set.
/// </param>
/// <param name="password">A <see cref="System.Security.SecureString"/>
/// object containing the new password.
/// </param>
/// <param name="passwordExpired">One of the
/// <see cref="PasswordExpiredState"/> enumeration values indicating
/// whether the password-expired state is to be explicitly set or
/// left as is. If the <paramref name="password"/> parameter is null,
/// this parameter is ignored.
/// </param>
/// <param name="setPasswordNeverExpires">
/// Nullable value the specifies whether the PasswordNeverExpires bit should be flipped
/// </param>
private void SetUserData(IntPtr userHandle,
LocalUser sourceUser,
UserProperties setFlags,
System.Security.SecureString password,
PasswordExpiredState passwordExpired,
bool? setPasswordNeverExpires)
{
IntPtr buffer = IntPtr.Zero;
try
{
UInt32 which = 0;
UInt32 status = 0;
UInt32 uac = GetUserAccountControl(userHandle);
USER_ALL_INFORMATION info = new USER_ALL_INFORMATION();
if (setFlags.HasFlag(UserProperties.AccountExpires))
{
which |= SamApi.USER_ALL_ACCOUNTEXPIRES;
info.AccountExpires.QuadPart = sourceUser.AccountExpires.HasValue
? sourceUser.AccountExpires.Value.ToFileTime()
: 0L;
}
if (setFlags.HasFlag(UserProperties.Description))
{
which |= SamApi.USER_ALL_ADMINCOMMENT;
info.AdminComment = new UNICODE_STRING(sourceUser.Description);
}
if (setFlags.HasFlag(UserProperties.Enabled))
{
which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
if (sourceUser.Enabled)
uac &= ~SamApi.USER_ACCOUNT_DISABLED;
else
uac |= SamApi.USER_ACCOUNT_DISABLED;
}
if (setFlags.HasFlag(UserProperties.FullName))
{
which |= SamApi.USER_ALL_FULLNAME;
info.FullName = new UNICODE_STRING(sourceUser.FullName);
}
if (setFlags.HasFlag(UserProperties.PasswordNeverExpires))
{
// Only modify the bit if a change was requested
if (setPasswordNeverExpires.HasValue)
{
which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
if (setPasswordNeverExpires.Value)
uac |= SamApi.USER_DONT_EXPIRE_PASSWORD;
else
uac &= ~SamApi.USER_DONT_EXPIRE_PASSWORD;
}
}
if (setFlags.HasFlag(UserProperties.PasswordRequired))
{
which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
if (sourceUser.PasswordRequired)
uac &= ~SamApi.USER_PASSWORD_NOT_REQUIRED;
else
uac |= SamApi.USER_PASSWORD_NOT_REQUIRED;
}
if (which != 0)
{
info.WhichFields = which;
if ((which & SamApi.USER_ALL_USERACCOUNTCONTROL) != 0)
info.UserAccountControl = uac;
buffer = Marshal.AllocHGlobal(Marshal.SizeOf<USER_ALL_INFORMATION>());
Marshal.StructureToPtr<USER_ALL_INFORMATION>(info, buffer, false);
status = SamApi.SamSetInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAllInformation,
buffer);
ThrowOnFailure(status);
status = SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
}
if (setFlags.HasFlag(UserProperties.UserMayChangePassword))
SetUserMayChangePassword(userHandle, sourceUser.SID, sourceUser.UserMayChangePassword);
if (password != null)
SetUserPassword(userHandle, password, passwordExpired);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.DestroyStructure<USER_ALL_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
}
}
}
/// <summary>
/// Retrieve the User's User Account Control flags.
/// </summary>
/// <param name="userHandle">
/// Handle to an open user.
/// </param>
/// <returns>
/// A 32-bit unsigned integer containing the User Account Control
/// flags as a set of bits.
/// </returns>
private UInt32 GetUserAccountControl(IntPtr userHandle)
{
IntPtr buffer = IntPtr.Zero;
USER_LOGON_INFORMATION info;
UInt32 status;
try
{
status = SamApi.SamQueryInformationUser(userHandle,
USER_INFORMATION_CLASS.UserLogonInformation,
out buffer);
ThrowOnFailure(status);
info = Marshal.PtrToStructure<USER_LOGON_INFORMATION>(buffer);
status = SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
return info.UserAccountControl;
}
finally
{
if (buffer != IntPtr.Zero)
status = SamApi.SamFreeMemory(buffer);
}
}
/// <summary>
/// Retrieve the DACL from a SAM object.
/// </summary>
/// <param name="objectHandle">
/// A handle to the SAM object whose DACL is to be retrieved.
/// </param>
/// <returns>
/// A <see cref="RawAcl"/> object containing the DACL retrieved from
/// the SAM object.
/// </returns>
private RawAcl GetSamDacl(IntPtr objectHandle)
{
RawAcl rv = null;
IntPtr securityObject = IntPtr.Zero;
UInt32 status = 0;
try
{
status = SamApi.SamQuerySecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, out securityObject);
ThrowOnFailure(status);
SECURITY_DESCRIPTOR sd = Marshal.PtrToStructure<SECURITY_DESCRIPTOR>(securityObject);
bool daclPresent;
bool daclDefaulted;
IntPtr dacl;
bool ok = Win32.GetSecurityDescriptorDacl(securityObject, out daclPresent, out dacl, out daclDefaulted);
if (!ok)
{
var error = Marshal.GetLastWin32Error();
if (error == Win32.ERROR_ACCESS_DENIED)
throw new AccessDeniedException(context.target);
else
throw new Win32InternalException(error, context.target);
}
if (daclPresent)
{
ACL acl = Marshal.PtrToStructure<ACL>(dacl);
if (acl.AclSize != 0)
{
// put the DACL into managed data
var bytes = new byte[acl.AclSize];
Marshal.Copy(dacl, bytes, 0, acl.AclSize);
rv = new RawAcl(bytes, 0);
}
}
}
finally
{
if (IntPtr.Zero != securityObject)
status = SamApi.SamFreeMemory(securityObject);
}
return rv;
}
/// <summary>
/// Set the DACL of a SAM object.
/// </summary>
/// <param name="objectHandle">
/// A handle to the SAM object whose DACL is to be retrieved.
/// </param>
/// <param name="rawAcl">
/// A <see cref="RawAcl"/> object containing the DACL to be set into
/// the SAM object.
/// </param>
private void SetSamDacl(IntPtr objectHandle, RawAcl rawAcl)
{
IntPtr ipsd = IntPtr.Zero;
IntPtr ipDacl = IntPtr.Zero;
try
{
bool present = false;
// create a new security descriptor
var sd = new SECURITY_DESCRIPTOR() { Revision = 1 };
ipsd = Marshal.AllocHGlobal(Marshal.SizeOf<SECURITY_DESCRIPTOR>());
if (rawAcl != null && rawAcl.BinaryLength > 0)
{
Marshal.StructureToPtr<SECURITY_DESCRIPTOR>(sd, ipsd, false);
// put the DACL into unmanaged memory
var length = rawAcl.BinaryLength;
var bytes = new byte[length];
rawAcl.GetBinaryForm(bytes, 0);
ipDacl = Marshal.AllocHGlobal(length);
Marshal.Copy(bytes, 0, ipDacl, length);
present = true;
}
// set the DACL into our new security descriptor
var ok = Win32.SetSecurityDescriptorDacl(ipsd, present, ipDacl, false);
if (!ok)
{
var error = Marshal.GetLastWin32Error();
if (error == Win32.ERROR_ACCESS_DENIED)
throw new AccessDeniedException(context.target);
else
throw new Win32InternalException(error, context.target);
}
var status = SamApi.SamSetSecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, ipsd);
ThrowOnFailure(status);
}
finally
{
Marshal.FreeHGlobal(ipDacl);
Marshal.FreeHGlobal(ipsd);
}
}
/// <summary>
/// Determine if a user account password may be changed by the user.
/// </summary>
/// <param name="userHandle">
/// Handle to a SAM user object.
/// </param>
/// <param name="userSid">
/// A <see cref="SecurityIdentifier"/> object identifying the SAM
/// object's associated user.
/// </param>
/// <returns>
/// True if the user account password may be changed by its user,
/// false otherwise.
/// </returns>
/// <remarks>
/// The ability to for the user to change the user account password
/// is a permission in the object's DACL. This method walks through
/// the ACEs in the DACL, checking if the permission is granted to
/// either Everyone or the user identified by the userSid parameter.
/// </remarks>
private bool GetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid)
{
var rawAcl = GetSamDacl(userHandle);
// if there is no DACL, then access is granted
if (rawAcl == null)
return true;
foreach (var a in rawAcl)
{
var ace = a as CommonAce;
if (ace != null && ace.AceType == AceType.AccessAllowed)
{
if (ace.SecurityIdentifier == worldSid ||
ace.SecurityIdentifier == userSid)
{
if ((ace.AccessMask & SamApi.USER_CHANGE_PASSWORD) != 0)
return true;
}
}
}
return false;
}
/// <summary>
/// Set whether a user account password may be changed by the user.
/// </summary>
/// <param name="userHandle">
/// Handle to a SAM user object.
/// </param>
/// <param name="userSid">
/// A <see cref="SecurityIdentifier"/> object identifying the SAM
/// object's associated user.
/// </param>
/// <param name="enable">
/// A boolean indicating whether the permission is to be enabled or
/// disabled.
/// </param>
/// <remarks>
/// The ability to for the user to change the user account password
/// is a permission in the object's DACL. This method walks through
/// the ACEs in the DACL, enabling or disabling the permission on ACEs
/// associated with either Everyone or the user identified by the
/// userSid parameter.
/// </remarks>
private void SetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid, bool enable)
{
var changed = false;
var rawAcl = GetSamDacl(userHandle);
if (rawAcl != null)
{
foreach (var a in rawAcl)
{
var ace = a as CommonAce;
if (ace != null && ace.AceType == AceType.AccessAllowed)
{
if (ace.SecurityIdentifier == worldSid ||
ace.SecurityIdentifier == userSid)
{
if (enable)
ace.AccessMask |= SamApi.USER_CHANGE_PASSWORD;
else
ace.AccessMask &= ~SamApi.USER_CHANGE_PASSWORD;
changed = true;
}
}
}
if (changed)
SetSamDacl(userHandle, rawAcl);
}
}
/// <summary>
/// Determine if a user's password has expired.
/// </summary>
/// <param name="userHandle">
/// Handle to an open User.
/// </param>
/// <returns>
/// True if the user's password has expired, false otherwise.
/// </returns>
private bool IsPasswordExpired(IntPtr userHandle)
{
IntPtr buffer = IntPtr.Zero;
USER_ALL_INFORMATION info;
UInt32 status;
try
{
status = SamApi.SamQueryInformationUser(userHandle,
USER_INFORMATION_CLASS.UserAllInformation,
out buffer);
ThrowOnFailure(status);
info = Marshal.PtrToStructure<USER_ALL_INFORMATION>(buffer);
status = SamApi.SamFreeMemory(buffer);
buffer = IntPtr.Zero;
return info.PasswordExpired;
}
finally
{
if (buffer != IntPtr.Zero)
status = SamApi.SamFreeMemory(buffer);
}
}
/// <summary>
/// Set a user's password.
/// </summary>
/// <param name="userHandle">Handle to an open User.</param>
/// <param name="password">A <see cref="System.Security.SecureString"/>
/// object containing the new password.
/// </param>
/// <param name="passwordExpired">One of the
/// <see cref="PasswordExpiredState"/> enumeration values indicating
/// whether the password-expired state is to be explicitly set or
/// left as is.
/// </param>
private void SetUserPassword(IntPtr userHandle,
System.Security.SecureString password,
PasswordExpiredState passwordExpired)
{
if (password != null)
{
USER_SET_PASSWORD_INFORMATION info = new USER_SET_PASSWORD_INFORMATION();
IntPtr buffer = IntPtr.Zero;
try
{
bool setPwExpire = false;
switch (passwordExpired)
{
case PasswordExpiredState.Expired:
setPwExpire = true;
break;
case PasswordExpiredState.NotExpired:
setPwExpire = false;
break;
case PasswordExpiredState.Unchanged:
setPwExpire = IsPasswordExpired(userHandle);
break;
}
info.Password = new UNICODE_STRING(password.AsString());
info.PasswordExpired = setPwExpire;
buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info));
Marshal.StructureToPtr<USER_SET_PASSWORD_INFORMATION>(info, buffer, false);
var status = SamApi.SamSetInformationUser(userHandle,
USER_INFORMATION_CLASS.UserSetPasswordInformation,
buffer);
ThrowOnFailure(status);
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.DestroyStructure<USER_SET_PASSWORD_INFORMATION>(buffer);
Marshal.FreeHGlobal(buffer);
}
}
}
}
#region Utility Methods
/// <summary>
/// Create a <see cref="System.Security.Principal.SecurityIdentifier"/>
/// object from a relative ID.
/// </summary>
/// <param name="domainHandle">
/// Handle to the domain from which the ID was acquired.
/// </param>
/// <param name="rid">
/// The Relative ID value.
/// </param>
/// <returns>
/// A SecurityIdentifier object containing the SID of the
/// object identified by the <paramref name="rid"/> parameter.
/// </returns>
private SecurityIdentifier RidToSid(IntPtr domainHandle, uint rid)
{
IntPtr sidBytes = IntPtr.Zero;
UInt32 status = 0;
SecurityIdentifier sid = null;
try
{
status = SamApi.SamRidToSid(domainHandle, rid, out sidBytes);
if (status == NtStatus.STATUS_NOT_FOUND)
throw new InternalException(status,
StringUtil.Format(Strings.RidToSidFailed, rid),
ErrorCategory.ObjectNotFound);
ThrowOnFailure(status);
sid = new SecurityIdentifier(sidBytes);
}
finally
{
if (IntPtr.Zero != sidBytes)
status = SamApi.SamFreeMemory(sidBytes);
}
return sid;
}
/// <summary>
/// Lookup the account identified by the specified SID.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the account
/// to look up.
/// </param>
/// <returns>
/// A <see cref="AccountInfo"/> object contains information about the
/// account, or null if no matching account was found.
/// </returns>
private AccountInfo LookupAccountInfo(SecurityIdentifier sid)
{
var sbAccountName = new StringBuilder();
var sbDomainName = new StringBuilder();
var accountNameLength = sbAccountName.Capacity;
var domainNameLength = sbDomainName.Capacity;
SID_NAME_USE use;
var error = Win32.NO_ERROR;
var bytes = new byte[sid.BinaryLength];
sid.GetBinaryForm(bytes, 0);
if (!Win32.LookupAccountSid(null,
bytes,
sbAccountName, ref accountNameLength,
sbDomainName, ref domainNameLength,
out use))
{
error = Marshal.GetLastWin32Error();
if (error == Win32.ERROR_INSUFFICIENT_BUFFER)
{
sbAccountName.EnsureCapacity(accountNameLength);
sbDomainName.EnsureCapacity((int)domainNameLength);
error = Win32.NO_ERROR;
if (!Win32.LookupAccountSid(null,
bytes,
sbAccountName, ref accountNameLength,
sbDomainName, ref domainNameLength,
out use))
error = Marshal.GetLastWin32Error();
}
}
if (error == Win32.ERROR_SUCCESS)
return new AccountInfo
{
AccountName = sbAccountName.ToString(),
DomainName = sbDomainName.ToString(),
Sid = sid,
Use = use
};
else if (error == Win32.ERROR_NONE_MAPPED)
return null;
else
throw new Win32InternalException(error, context.target);
}
/// <summary>
/// Lookup the account identified by specified account name.
/// </summary>
/// <param name="accountName">
/// A string containing the name of the account to look up.
/// </param>
/// <returns>
/// A <see cref="AccountInfo"/> object contains information about the
/// account, or null if no matching account was found.
/// </returns>
private AccountInfo LookupAccountInfo(string accountName)
{
var sbDomainName = new StringBuilder();
var domainNameLength = (uint)sbDomainName.Capacity;
byte [] sid = null;
uint sidLength = 0;
SID_NAME_USE use;
int error = Win32.NO_ERROR;
if (!Win32.LookupAccountName(null,
accountName,
sid,
ref sidLength,
sbDomainName,
ref domainNameLength,
out use))
{
error = Marshal.GetLastWin32Error();
if (error == Win32.ERROR_INSUFFICIENT_BUFFER || error == Win32.ERROR_INVALID_FLAGS)
{
sid = new byte[sidLength];
sbDomainName.EnsureCapacity((int)domainNameLength);
error = Win32.NO_ERROR;
if (!Win32.LookupAccountName(null,
accountName,
sid,
ref sidLength,
sbDomainName,
ref domainNameLength,
out use))
error = Marshal.GetLastWin32Error();
}
}
if (error == Win32.ERROR_SUCCESS)
{
// Bug: 7407413 :
// If accountname is in the format domain1\user1,
// then AccountName.ToString() will return domain1\domain1\user1
// Ideally , accountname should be processed to hold only account name (without domain)
// as we are keeping the domain in 'DomainName' variable.
int index = accountName.IndexOf("\\", StringComparison.CurrentCultureIgnoreCase);
if (index > -1)
{
accountName = accountName.Substring(index + 1);
}
return new AccountInfo
{
AccountName = accountName,
DomainName = sbDomainName.ToString(),
Sid = new SecurityIdentifier(sid, 0),
Use = use
};
}
else if (error == Win32.ERROR_NONE_MAPPED)
return null;
else if (error == Win32.ERROR_ACCESS_DENIED)
throw new AccessDeniedException(context.target);
else
throw new Win32InternalException(error, context.target);
}
/// <summary>
/// Create a <see cref="LocalPrincipal"/> object from information in
/// an AccountInfo object.
/// </summary>
/// <param name="info">
/// An AccountInfo object containing information about the account
/// for which the LocalPrincipal object is being created. This parameter
/// may be null, in which case this method returns null.
/// </param>
/// <returns>
/// A new LocalPrincipal object representing the account, or null if the
/// <paramref name="info"/> parameter is null.
/// </returns>
private LocalPrincipal MakeLocalPrincipalObject(AccountInfo info)
{
if (info == null)
return null; // this is a legitimate case
var rv = new LocalPrincipal(info.ToString());
rv.SID = info.Sid;
rv.PrincipalSource = GetPrincipalSource(info);
switch (info.Use)
{
case SID_NAME_USE.SidTypeAlias: // TODO: is this the right thing to do???
case SID_NAME_USE.SidTypeGroup:
case SID_NAME_USE.SidTypeWellKnownGroup:
rv.ObjectClass = Strings.ObjectClassGroup;
break;
case SID_NAME_USE.SidTypeUser:
rv.ObjectClass = Strings.ObjectClassUser;
break;
default:
rv.ObjectClass = Strings.ObjectClassOther;
break;
}
return rv;
}
/// <summary>
/// Indicate whether a Status code is a successful value.
/// </summary>
/// <param name="ntStatus">
/// One of the NTSTATUS code values indicating the error, if any.
/// </param>
/// <returns>
/// True if the Status code represents a success, false otherwise.
/// </returns>
private static bool Succeeded(UInt32 ntStatus)
{
return NtStatus.IsSuccess(ntStatus);
}
/// <summary>
/// Helper to throw an exception if the provided Status code
/// represents a failure.
/// </summary>
/// <param name="ntStatus">
/// One of the NTSTATUS code values indicating the error, if any.
/// </param>
/// <param name="context">
/// A <see cref="Context"/> object containing information about the
/// current operation. If this parameter is null, the class's context
/// is used.
/// </param>
private void ThrowOnFailure(UInt32 ntStatus, Context context = null)
{
if (NtStatus.IsError(ntStatus))
{
var ex = MakeException(ntStatus, context);
if (ex != null)
throw ex;
}
}
/// <summary>
/// Create an appropriate exception from the specified status code.
/// </summary>
/// <param name="ntStatus">
/// One of the NTSTATUS code values indicating the error, if any.
/// </param>
/// <param name="context">
/// A <see cref="Context"/> object containing information about the
/// current operation. If this parameter is null, the class's context
/// is used.
/// </param>
/// <returns>
/// An <see cref="Exception"/> object, or an object derived from Exception,
/// appropriate to the error. If <paramref name="ntStatus"/> does not
/// indicate an error, the method returns null.
/// </returns>
private Exception MakeException(UInt32 ntStatus, Context context = null)
{
if (!NtStatus.IsError(ntStatus))
return null;
if (context == null)
context = this.context;
switch (ntStatus)
{
case NtStatus.STATUS_ACCESS_DENIED:
return new AccessDeniedException(context.target);
case NtStatus.STATUS_INVALID_ACCOUNT_NAME:
return new InvalidNameException(context.ObjectName, context.target);
case NtStatus.STATUS_USER_EXISTS:
if (context.operation == ContextOperation.New &&
context.type == ContextObjectType.User)
{
return new UserExistsException(context.ObjectName, context.target);
}
else
{
return new NameInUseException(context.ObjectName, context.target);
}
case NtStatus.STATUS_ALIAS_EXISTS:
if (context.operation == ContextOperation.New &&
context.type == ContextObjectType.Group)
{
return new GroupExistsException(context.ObjectName, context.target);
}
else
{
return new NameInUseException(context.ObjectName, context.target);
}
case NtStatus.STATUS_GROUP_EXISTS:
return new NameInUseException(context.ObjectName, context.target);
case NtStatus.STATUS_NO_SUCH_ALIAS:
case NtStatus.STATUS_NO_SUCH_GROUP:
return new GroupNotFoundException(context.ObjectName, context.target);
case NtStatus.STATUS_NO_SUCH_USER:
return new UserNotFoundException(context.ObjectName, context.target);
case NtStatus.STATUS_SPECIAL_GROUP: // The group specified is a special group and cannot be operated on in the requested fashion.
// case NtStatus.STATUS_SPECIAL_ALIAS: // referred to in source for SAM api, but not in ntstatus.h!!!
return new InvalidOperationException(StringUtil.Format(Strings.InvalidForGroup, context.ObjectName));
case NtStatus.STATUS_SPECIAL_USER: // The user specified is a special user and cannot be operated on in the requested fashion.
return new InvalidOperationException(StringUtil.Format(Strings.InvalidForUser, context.ObjectName));
case NtStatus.STATUS_NO_SUCH_MEMBER:
return new MemberNotFoundException(context.MemberName, context.ObjectName);
case NtStatus.STATUS_MEMBER_IN_ALIAS:
case NtStatus.STATUS_MEMBER_IN_GROUP:
if (context.operation == ContextOperation.Remove &&
context.type == ContextObjectType.Group)
{
return new InvalidOperationException(StringUtil.Format(Strings.GroupHasMembers, context.ObjectName));
}
else
{
return new MemberExistsException(context.MemberName, context.ObjectName, context.target);
}
case NtStatus.STATUS_MEMBER_NOT_IN_ALIAS:
case NtStatus.STATUS_MEMBER_NOT_IN_GROUP:
return new MemberNotFoundException(context.MemberName, context.ObjectName);
case NtStatus.STATUS_MEMBERS_PRIMARY_GROUP:
return new InvalidOperationException(StringUtil.Format(Strings.MembersPrimaryGroup, context.ObjectName));
case NtStatus.STATUS_LAST_ADMIN: // Cannot delete the last administrator.
return new InvalidOperationException(Strings.LastAdmin);
case NtStatus.STATUS_ILL_FORMED_PASSWORD:
case NtStatus.STATUS_PASSWORD_RESTRICTION:
return new InvalidPasswordException(Native.Win32.RtlNtStatusToDosError(ntStatus));
// TODO: do we want to handle these?
// they appear to be returned only in functions we are not calling
case NtStatus.STATUS_INVALID_SID: // member sid is corrupted
case NtStatus.STATUS_INVALID_MEMBER: // member has wrong account type
default:
return new InternalException(ntStatus, context.target);
}
}
/// <summary>
/// Create a DateTime object from a 64-bit value from one of the SAM
/// structures.
/// </summary>
/// <param name="samValue">
/// A signed 64-bit value representing a date and time.
/// </param>
/// <returns>
/// A nullable DateTime object representing a date and time,
/// or null if the <paramref name="samValue"/> parameter is zero.
/// </returns>
private static DateTime? DateTimeFromSam(Int64 samValue)
{
if (samValue == 0 || samValue == 0X7FFFFFFFFFFFFFFF)
return null;
return DateTime.FromFileTime(samValue);
}
/// <summary>
/// Determine the source of a user or group. Either local, Active Directory,
/// or Azure AD.
/// </summary>
/// <param name="sid">
/// A <see cref="SecurityIdentifier"/> object identifying the user or group.
/// </param>
/// <returns>
/// One of the <see cref="PrincipalSource"/> enumerations identifying the
/// source of the object.
/// </returns>
private PrincipalSource? GetPrincipalSource(SecurityIdentifier sid)
{
var bSid = new byte[sid.BinaryLength];
sid.GetBinaryForm(bSid, 0);
var type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType;
// Use LsaLookupUserAccountType for Windows 10 and later.
// Earlier versions of the OS will leave the property NULL because
// it is too error prone to attempt to replicate the decisions of
// LsaLookupUserAccountType.
var os = GetOperatingSystem();
if (os.Version.Major >= 10)
{
UInt32 status = Native.Win32.LsaLookupUserAccountType(bSid, out type);
if (NtStatus.IsError(status))
type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType;
switch (type)
{
case LSA_USER_ACCOUNT_TYPE.ExternalDomainUserAccountType:
case LSA_USER_ACCOUNT_TYPE.PrimaryDomainUserAccountType:
return PrincipalSource.ActiveDirectory;
case LSA_USER_ACCOUNT_TYPE.LocalUserAccountType:
return PrincipalSource.Local;
case LSA_USER_ACCOUNT_TYPE.AADUserAccountType:
return PrincipalSource.AzureAD;
// Currently, there is no value returned by LsaLookupUserAccountType
// that corresponds to LSA_USER_ACCOUNT_TYPE.MSAUserAccountType,
// but there may be in the future, so we'll account for it here.
case LSA_USER_ACCOUNT_TYPE.MSAUserAccountType:
case LSA_USER_ACCOUNT_TYPE.LocalConnectedUserAccountType:
return PrincipalSource.MicrosoftAccount;
case LSA_USER_ACCOUNT_TYPE.InternetUserAccountType:
return sid.IsMsaAccount()
? PrincipalSource.MicrosoftAccount
: PrincipalSource.Unknown;
case LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType:
default:
return PrincipalSource.Unknown;
}
}
else
{
return null;
}
}
/// <summary>
/// Determine the source of a user or group. Either local, Active Directory,
/// or Azure AD.
/// </summary>
/// <param name="info">
/// An <see cref="AccountInfo"/> object containing information about the
/// user or group.
/// </param>
/// <returns>
/// One of the <see cref="PrincipalSource"/> enumerations identifying the
/// source of the object.
/// </returns>
private PrincipalSource? GetPrincipalSource(AccountInfo info)
{
return GetPrincipalSource(info.Sid);
}
/// <summary>
/// Determine the source of a user or group. Either local, Active Directory,
/// or Azure AD.
/// </summary>
/// <param name="sre">
/// A <see cref="SamRidEnumeration"/> object identifying the user or group.
/// </param>
/// <returns>
/// One of the <see cref="PrincipalSource"/> enumerations identifying the
/// source of the object.
/// </returns>
private PrincipalSource? GetPrincipalSource(SamRidEnumeration sre)
{
return GetPrincipalSource(RidToSid(sre.domainHandle, sre.RelativeId));
}
#if CORECLR
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct OSVERSIONINFOEX
{
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
public int OSVersionInfoSize;
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
public ushort ServicePackMajor;
public ushort ServicePackMinor;
public short SuiteMask;
public byte ProductType;
public byte Reserved;
}
[DllImport(PInvokeDllNames.GetVersionExDllName, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx);
private static volatile OperatingSystem localOs;
/// <summary>
/// It only contains the properties that get used in powershell.
/// </summary>
internal sealed class OperatingSystem
{
private Version _version;
private string _servicePack;
private string _versionString;
internal OperatingSystem(Version version, string servicePack)
{
ArgumentNullException.ThrowIfNull(version);
_version = version;
_servicePack = servicePack;
}
/// <summary>
/// OS version.
/// </summary>
public Version Version
{
get { return _version; }
}
/// <summary>
/// VersionString.
/// </summary>
public string VersionString
{
get
{
if (_versionString != null)
{
return _versionString;
}
// It's always 'VER_PLATFORM_WIN32_NT' for NanoServer and IoT
const string os = "Microsoft Windows NT ";
if (string.IsNullOrEmpty(_servicePack))
{
_versionString = os + _version.ToString();
}
else
{
_versionString = os + _version.ToString(3) + " " + _servicePack;
}
return _versionString;
}
}
}
#endif
// Wraps calls to acquire the OperatingSystem version
private OperatingSystem GetOperatingSystem()
{
#if CORECLR
if (localOs == null)
{
OSVERSIONINFOEX osviex = new OSVERSIONINFOEX();
osviex.OSVersionInfoSize = Marshal.SizeOf(osviex);
if (!GetVersionEx(ref osviex))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode);
}
Version ver = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor);
localOs = new OperatingSystem(ver, osviex.CSDVersion);
}
return localOs;
#else
return Environment.OSVersion;
#endif
}
#endregion Utility Methods
#endregion Private Methods
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
UInt32 status = 0;
if (disposing)
{
// no managed objects need disposing.
}
if (builtinDomainHandle != IntPtr.Zero)
{
status = SamApi.SamCloseHandle(builtinDomainHandle);
builtinDomainHandle = IntPtr.Zero;
}
if (localDomainHandle != IntPtr.Zero)
{
status = SamApi.SamCloseHandle(localDomainHandle);
localDomainHandle = IntPtr.Zero;
}
if (samHandle != IntPtr.Zero)
{
status = SamApi.SamCloseHandle(samHandle);
samHandle = IntPtr.Zero;
}
if (NtStatus.IsError(status))
{
// Do nothing to satisfy CA1806: Do not ignore method results. We want the dispose to proceed regardless of the handle close status.
}
disposedValue = true;
}
}
// override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
~Sam()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(false);
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// uncomment the following line if the finalizer is overridden above.
GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
}
|