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
|
%global _empty_manifest_terminate_build 0
Name: python-ms-active-directory
Version: 1.12.1
Release: 1
Summary: Python library for integrating with Microsoft Active Directory
License: MIT License
URL: https://github.com/zorn96/ms_active_directory/
Source0: https://mirrors.aliyun.com/pypi/web/packages/96/9f/2e039410cc4043235738730c899ceed6436cbf1656f59353bedf9717036d/ms_active_directory-1.12.1.tar.gz
BuildArch: noarch
%description
# ms_active_directory - A Library for Integrating with Microsoft Active Directory
This is a library for integrating with Microsoft Active Directory domains.
It supports a variety of common, critical functionality for integration of computers
into a domain, including the ability to discover domain resources, optimize
communication for speed, join a computer to the domain, and look up information
about users and groups in the domain.
It primarily builds on the LDAP protocol, and supports LDAP over TLS with channel bindings,
and all LDAP basic, NTLM, and SASL authentication mechanisms (e.g. Kerberos) supported by the
`ldap3` python library.
For more detailed documentation, please see the docs at:\
**https://ms-active-directory.readthedocs.io/**
**Author**: Azaria Zornberg
\
**Email**: a.zornberg96@gmail.com
# Key Features
1. Joining a computer to a domain, either by creating a new computer account or taking over an existing
account.
2. Discovering domain resources and properties, optimizing domain communication for the network
3. Discovering trusted domains, including MIT Kerberos domains and trusted Active Directory domains, and their
attributes (e.g. are the trusts transitive? is SID filtering used? what direction is the trust?)
4. Transferring authenticated sessions from one domain to its trusted domains, allowing for easy querying
capability across domains for widely trusted users. This can be used to trace foreign security principals
across domains without needing to spin up and manage new domain objects for each.
5. Finding users, computers, and groups based on a variety of properties (e.g. name, SID, user-specified properties)
6. Querying information about users, computers, groups, and generic objects
7. Looking up user, computer, and group memberships
8. Looking up members of groups, regardless of type, and their attributes. This can also be done with auto-recursion
for nested groups.
9. Adding and removing users, computers, and groups to and from other groups
10. Account management functionality for both users and computers, such as password changes/resets, enabling, disabling, and unlocking accounts
11. Looking up information about the permissions set on a user, computer, group, or generic object
12. Adding permissions to the security descriptor for a user, computer, group, or generic object
13. Support for creating users and groups
14. Support for updating attributes of users, computers, groups, and generic objects. Support exists for atomically appending
or overwriting values.
15. Support for finding policies within a domain, and for finding the policies directly attached to any given object.
# Examples
## Discovering a domain
The library supports discovering LDAP and Kerberos servers within a domain using special DNS
entries defined for Active Directory.
### Smart Defaults
By default, it will use the system DNS configuration, find LDAP servers that support TLS, and sort
LDAP and Kerberos servers by the RTT to communicate with them.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
domain = ADDomain(example_domain_dns_name)
ldap_servers = domain.get_ldap_uris()
kerberos_servers = domain.get_kerberos_uris()
# re-discover servers in dns and sort them by RTT again at a later time to pick up changes
domain.refresh_ldap_server_discovery()
domain.refresh_kerberos_server_discovery()
```
### Site Awareness and Flexible DNS
The library also supports site awareness, which will result in only discovering servers within a specified
Active Directory Site. You can also specify alternative DNS nameservers to use instead of the system ones.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
site_name = 'us-eastern-datacenter'
domain = ADDomain(example_domain_dns_name, site=site_name,
dns_nameservers=['eastern-private-dns-01.local'])
```
### Network Multi-Tenancy and Security Support
You can also specify exactly which LDAP or Kerberos servers should be used, and skip discovery.
Additional configurations are available such as configuring the CA file path to use for
trust, and the source IP to use for outbound traffic to the domain, which is helpful when
there are firewall rules in place, or when a machine has both private and public IP addresses.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
local_machine_ip = '10.251.12.1'
local_ldap_ip = '10.251.12.30'
public_machine_ip = '194.32.21.30'
# the servers that live on the public internet use well-known public
# CAs for trust, but we have a local CA for the private network servers
private_securing_cas = '/etc/internal-ca.cert'
# set up an object for the local domain in the same network as this machine,
# but also have an instance that can be used to make instances to reach out
# to the rest of the domain outside of the local private network
local_domain = ADDomain(example_domain_dns_name, ldap_servers_or_uris=[local_ldap_ip],
source_ip=local_ldap_ip, ca_certificates_file_path=private_securing_cas)
global_domain = ADDomain(example_domain_dns_name, source_ip=public_machine_ip)
```
## Establishing a session with a domain
You can establish a session with the AD Domain on behalf of either a user or computer.
Broadly, any keyword arguments that would normally be supported when creating a `Connection`
with the `ldap3` library are supported when creating a session, allowing
for flexibility while still providing an "it just works" option for
most users.
### Support for Computer Authentication
Computers default to using Kerberos SASL authentication, as SIMPLE authentication is
not support for computers with Active Directory.
To use kerberos, either `gssapi` or `winkerberos` must be
installed.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# when using kerberos auth, the default is to use the kerberos
# credential cache on the machine, so no password is needed
computer_name = 'machine01'
session1 = domain.create_session_as_computer(computer_name)
# but you can pass sasl credentials, and if you use gssapi you can
# specify a username and password
# see the ldap3 documentation for details on SASL credentials and other
# connection options
other_name = 'other-machine-identity'
password = 'password01'
session2 = domain.create_session_as_computer(other_name, sasl_credentials=('', other_name, password))
```
You can also use other authentication mechanisms like NTLM.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
ntlm_name = 'EXAMPLE.COM\\computer01'
password = 'password1'
session = domain.create_session_as_computer(ntlm_name, password, authentication_mechanism=NTLM)
```
### Support for User Authentication
You can authenticate as a user by using simple binds, or by using SASL
mechanisms or NTLM as computers do.
The default for users is simple binds.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
ntlm_session = domain.create_session_as_user('username@example.com', 'password',
authentication_mechanism=NTLM)
```
## Discovering additional domain resources
The library supports discovering a wide variety of information about the domain beyond
the basics needed to communicate with it. This discovery doesn't require you to know any
niche information about Active Directory.
Discoverable resources include but are not limited to:
- Supported SASL mechanisms, which is important for authentication
- The current domain time, which is important for NTP synchronization
- Domain Functional Level, which governs things like support encryption types
- DNS servers
- Issuing certificates for CAs in the domain
### Finding supported SASL mechanisms
Discovering SASL mechanisms can be done without needing to create a session
with a domain, as it's needed before authentication in many cases.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# might print "['EXTERNAL', 'DIGEST-MD5']"
print(domain.find_supported_sasl_mechanisms())
```
### Finding the current domain time
Discovering the domain time can be done without needing to create a session
with a domain, as time synchronization is necessary for kerberos authentication
to succeed and can impact TLS negotiation as well.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# returns a python datetime object in utc time
curr_time = domain.find_current_time()
# allowed drift defaults to 5 minutes which is the kerberos standard,
# but we can use a shorter window to detect drift before it causes an
# outage. this returns a boolean
synced = domain.is_close_in_time_to_localhost(allowed_drift_seconds=60)
```
### Finding the domain functional level
Discovering the domain time can be done without needing to create a session
with a domain, as it can inform us as to what encryption types and TLS versions/ciphers
will be supported by the domain.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# find_functional_level returns an enum indicating the level.
# decision making based on level should be done based on the
# needs of your application
print(domain.find_functional_level())
```
### Finding DNS servers
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for computers that run a DNS
service is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a map that maps server hostnames -> ip addresses, where
# the hostnames are computers running dns services
dns_map = session.find_dns_servers_for_domain()
ip_addrs = dns_map.values()
hostnames = dns_map.keys()
```
### Finding CA certificates
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for records that are indicated
as being certificate authorities is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a list of PEM-formatted strings representing the signing certificates
# of all certificate authorities in the domain
pem_certs = session.find_certificate_authorities_for_domain()
# you can also get the certificates in DER format, which might be
# preferred on windows
der_certs = session.find_certificate_authorities_for_domain(pem_format=False)
```
## Joining an Active Directory domain
The action of joining a computer to a domain is not a well-defined operation,
and so the exact mechanics of how you utilize the domain joining functionality
and how its outputs are integrated with the rest of your system will vary depending on
your use case.
This will try to cover some common examples.
### Join the domain with default configurations for everything
The default behavior requires only the domain name and the credentials of a user with
sufficient administrative rights to create computers within the domain.
```
from ms_active_directory import join_ad_domain
comp = join_ad_domain('example.com', 'Administrator@example.com', 'example-password')
```
The `join_ad_domain` function returns a `ManagedADComputer` object with many helpful functions
describing properties of the created computer.
This will use the local hostname of the machine running this code as the computer name.
It will create the computer in AD's default `Computers` container.
It enables `AES256-SHA1` as an encryption type for both receiving and initiating kerberos
contexts, and it configures `<local hostname>.<domain dns name>` as the hostname of the
computer in AD and registers the default `HOST` service.
It then writes kerberos keys for the new computer account to `/etc/krb5.keytab`, which is
the default location for kerberos keytabs.
This all enables the account to be used for authenticating with other domain resources as a client
over protocols like SMB and LDAP using kerberos, as well as receiving incoming kerberos authentication
as a server for things like SSH. This is because the `HOST` service encapsulates many standard services
in the domain.
However, it is still up to the caller to do things like configure sshd to utilize the keytab.
### Join the domain with customization of the account for security reasons
A number of customizations exist for security reasons.
You can change things like the encryption types enabled on the account to support older clients.
You can also change location where the account is created when joining a domain in order to use
a less privileged user for the act of joining. Locations can be LDAP distinguished names or windows
path style canonical names.
You can also set the computer name if you have a desired naming scheme. This will impact the hostnames
configured in the domain for the computer.
```
from ms_active_directory import join_ad_domain, ADEncryptionType
domain = 'example.com'
less_privileged_user = 'ops-manager@example.com'
password = 'password2'
# ldap-style relative distinguished name of a location
less_privileged_loc = 'OU=service-machines,OU=ops'
computer_name = 'workstation10'
legacy_enc_type = ADEncryptionType.RC4_HMAC
new_enc_type = ADEncryptionType.AES256_CTS_HMAC_SHA1_96
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=less_privileged_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
alt_format_loc = '/ops/service-machines'
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=alt_format_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
```
You can also manually set the computer password. The default is to generate a random 120
character password, but if you want to share this computer across services, and some cannot
interact with the generated kerberos keys, then you may wish to set a password manually.
You can also change where the kerberos keys are written to.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
kerberos_key_location = '/usr/shared/keys/workstation-key.keytab'
computer_name = 'workstation10'
computer_password = 'workstation-shared-pw'
comp = join_ad_domain(domain, user, password, computer_key_file_path=kerberos_key_location,
computer_name=computer_name, computer_password=computer_password)
```
### Join the domain with different network or service settings
You can configure different hostnames for your computer when joining the
domain. This is useful when you have multiple different hostnames for
a single device, or want to use a computer name that doesn't match your
network name.
You can also configure services in order to restrict or broaden what is
supported by the computer when acting as a server (e.g. you can add `nfs`
if the machine will be an nfs server).
Joining will fail if another computer in the domain is using the services
you specify on any of the hostnames you specify in order to avoid conflicts
that cause undefined behavior.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
computer_host1 = 'central-mount-point.example.com'
computer_host2 = 'example-web-server.example.com'
comp = join_ad_domain(domain, user, password, computer_name=computer_name,
computer_hostnames=[computer_host1, computer_host2],
computer_services=services)
```
### Join using a domain object
You can use an `ADDomain` object to join the domain as well, using a `join` function.
This allows you to combine all of the functionality mentioned earlier around site-awareness,
server preferences, TLS settings, and network multi-tenancy with the domain joining
functionality mentioned in this section.
The parameters are all the same, except the domain need not be provided when using an
`ADDomain` object, so it just adds more functionality in exchange for a slightly less simple
workflow.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com', site='us-eastern-dc',
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
user = 'ops-manager@example.com'
password = 'password2'
less_privileged_loc = 'OU=service-machines,OU=ops'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
comp = domain.join(user, password, computer_hostnames=[computer_host1, computer_host2],
computer_services=services, computer_location=less_privileged_loc)
```
### Join the domain by taking over an existing account
For some setups, accounts may be pre-created and then taken over by the computers that will use them.
This can be done in order to greatly restrict the permissions of the user that is used for joining,
as they only need `RESET PASSWORD` permissions on the computer account, or `CHANGE PASSWORD` if
the current computer password is provided.
```
from ms_active_directory import ADDomain, join_ad_domain_by_taking_over_existing_computer
domain_dns_name = 'example.com'
site = 'us-eastern-dc'
existing_computer_name = 'precreated-comp'
user = 'single-account-admin@example.com'
password = 'password2'
computer_obj = join_ad_domain_by_taking_over_existing_computer(domain_dns_name, user, password,
ad_site=site, computer_name=existing_computer_name)
# or use a domain object to use various power-user domain features
domain = ADDomain(domain_dns_name, site=site,
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
domain.join_by_taking_over_existing_computer(user, password, computer_name=existing_computer_name)
```
# Managing users, computers, and groups
The library provides a number of different functions for finding users, computers, and groups by different
identifiers, and for querying information about them.
It also has functions for checking their memberships and adding or removing users, computers, and groups
to or from groups.
## Looking up users, computers, groups, and information about them
Users, computers, and groups can both be looked up by one of:
- sAMAccountName
- distinguished name
- common name
- a generic "name" that will attempt the above 3
- an attribute
### Look up by sAMAccountName
A `sAMAccountName` is unique within a domain, and so looking up users or
groups by `sAMAccountName` returns a single result.
`sAMAccountName` was a user's windows logon name in older versions of windows,
and may be referred to as such in some documentation.
For computers, the standard convention is for their `sAMAccountName` to end with
a `$`, but many tools/docs leave that out. So if a `sAMAccountName` is specified
that does not end with a `$` and cannot be found, a lookup will also be
attempted after adding a `$` to the end.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user = session.find_user_by_sam_name('user1', ['employeeID'])
group = session.find_group_by_sam_name('group1', ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by distinguished name
A distinguished name is unique within a forest, and so looking up users or
groups by it returns a single result.
A distinguished name should not be escaped when provided to the search function.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_dn = 'CN=user one,CN=Users,DC=example,DC=com'
user = session.find_user_by_distinguished_name(user_dn, ['employeeID'])
group_dn = 'CN=group one,OU=employee-groups,DC=example,DC=com'
group = session.find_group_by_distinguished_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by common name
A common name is not unique within a domain, and so looking up users or
groups by it returns a list of results, which may have 0 or more entries.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_cn = 'John Doe'
users = session.find_users_by_common_name(user_cn, ['employeeID'])
group_dn = 'operations managers'
groups = session.find_groups_by_common_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.get('employeeID'))
for group in groups:
print(group.get('gidNumber'))
```
### Look up by generic name
You can also query by a generic "name", and the library will attempt to find a
unique user or group with that name. The library will either lookup by DN or will
attempt `sAMAccountName` and common name lookups depending on the name format.
If more than one result is found by common name and no result is found by
`sAMAccountName` then this will produce an error.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'John Doe'
user = session.find_user_by_name(user_name, ['employeeID'])
group_name = 'operations managers'
groups = session.find_groups_by_name(group_name, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by attribute
You can also query for users, computers, or groups that possess a certain value for a
specified attribute. This can produce any number of results, so a list is
returned.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
desired_employee_type = 'temporary'
users = session.find_users_by_attribute('employeeType', desired_employee_type, ['employeeID'])
desired_group_manager = 'Alice P Hacker'
groups = session.find_groups_by_attribute('managedBy', desired_group_manager, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.distinguished_name)
print(user.get('employeeID'))
for group in groups:
print(group.distinguished_name)
print(group.get('gidNumber'))
```
## Querying user, computer, and group membership
You can also look up the groups that a user belongs to, the groups that a computer belongs to,
or the groups that a group belongs to. Active Directory supports nested groups, which is why
there's `user->groups`, `computer->groups`, and `group->groups` mapping capability.
When querying the membership information for users or groups, the input type for any
user or group must either be a string name identifying the user, computer, or group as described in the prior
section, or must be an `ADUser`, `ADComputer`, or `ADGroup` object returned by one of the functions described
in the prior section.
Similarly to looking up users, computers, and groups, you can query for attributes of the parent groups
by providing a list of LDAP attributes to look up for them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_sam_account_name = 'user-sam-1'
user_dn = 'CN=user sam 1,CN=users,DC=example,DC=com'
user_cn = 'user same 1'
desired_group_attrs = ['gidNumber', 'managedBy']
# all 3 of these do the same thing, and internally map the different
# name types to a user object
groups_res1 = session.find_groups_for_user(user_sam_account_name, desired_group_attrs)
groups_res2 = session.find_groups_for_user(user_dn, desired_group_attrs)
groups_res3 = session.find_groups_for_user(user_cn, desired_group_attrs)
# you can also directly use a user object to query groups
user_obj = session.find_user_by_name(user_sam_account_name)
groups_res4 = session.find_groups_for_user(user_obj, desired_group_attrs)
# you can also look up the parents of groups in the same way
example_group_obj = groups_res4[0]
example_group_dn = example_group_obj.distinguished_name
# these both work. sAMAccountName could also be used, etc.
second_level_groups_res1 = session.find_groups_for_group(example_group_obj, desired_group_attrs)
second_level_groups_res2 = session.find_groups_for_group(example_group_dn, desired_group_attrs)
```
You can also query `users->groups`, `computers->groups`, and `groups->groups` to find the memberships of multiple
users, computers, and groups, and the library will make a minimal number of queries to determine membership;
it will be more efficient that doing a `user->groups` for each user (or similar for computers and groups).
The result will be a map that maps the input users or groups to lists of parent groups.
The input lists' elements must be the same format as what's provided when looking up group
memberships for a single user or group.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
users = [user1_name, user2_name]
desired_group_attrs = ['gidNumber', 'managedBy']
user_group_map = session.find_groups_for_users(users, desired_group_attrs)
# the dictionary result keys are the users from the input
user1_groups = user_group_map[user1_name]
user2_groups = user_group_map[user2_name]
# you can use the groups->groups mapping functionality to enumerate the
# full tree of a users' group memberships (or a groups' group memberships)
user1_second_level_groups_map = session.find_groups_for_groups(user1_groups, desired_group_attrs)
all_second_level_groups = []
for group_list in user1_second_level_groups_map.values():
for group in group_list:
if group not in all_second_level_groups:
all_second_level_groups.append(group)
all_user1_groups_in_2_levels = user1_groups + all_second_level_groups
```
## Finding the members of groups
You can look up the members of one or more groups and get attributes about those
members.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
# look up members of a single group
single_group_member_list = session.find_members_of_group('group1', desired_attrs)
# look up members of multiple groups at once
groups = ['group1', 'group2']
group_to_member_list_map = session.find_members_of_groups(groups, desired_attrs)
group2_member_list = group_to_member_list_map['group2']
group2_user_members = [mem for mem in group2_member_list if isintance(mem, ADUser)]
group2_group_members = [mem for mem in group2_member_list if isintance(mem, ADGroup)]
```
You can also look up members recursively to handle nesting.
A maximum depth for lookups may be specified, but by default all
nesting will be enumerated.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
group_name = 'has-groups-as-members'
groups_to_member_lists_maps = session.find_members_of_groups_recursive(group_name, desired_attrs)
```
## Adding users to groups
You can add users to groups by specifying a list of `ADUser` objects or string names of
AD users to be added to the groups, and a list of `ADGroup` objects or string names of AD
groups to add the users to.
If string names are specified, they'll be mapped to users/groups using the functions
discussed in the prior sections.
If a user is already in a group, this is idempotent and will not re-add them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name])
```
By default, if we fail to add users to one of the groups specified, we'll attempt to rollback
and remove users from any groups they were added to. You can choose to forgo this and a list of
groups that users were successfully added to will be returned instead.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
privileged_group = 'group-that-will-fail'
succeeeded = session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name, privileged_group],
stop_and_rollback_on_error=False)
# this will print "['target-group1', 'target-group2']" assuming that
# adding users to 'group-that-will-fail' failed
print(succeeeded)
```
## Adding groups to groups
Adding groups to other groups works exactly the same way as adding users to groups, but
the function is called `add_groups_to_groups` and both inputs are lists of groups.
## Adding computers to groups
Adding computers to groups works exactly the same way as adding users to groups, but
the function is called `add_computers_to_groups` and the first input is a list of computers.
## Removing users, computers, or groups from groups
Removing users, computers, or groups from groups works identically to adding users, computers, or groups to groups,
including input format, idempotency, and rollback functionality.
The only difference is that the functions are called `remove_users_from_groups`, `remove_computers_from_groups`, and
`remove_groups_from_groups` instead.
## Updating user, computer, or group attributes.
You can use this library to modify the values of various LDAP attributes on
users, computers, groups, or generic objects.
Users, computers, and groups provide the convenient name lookup functionality mentioned above,
while for generic objects you either need to pass an `ADObject` or a distinguished name.
### Appending to one or more attributes
You can atomically append values to multi-valued attributes, such as `accountNameHistory`.
This allows you to update their values without needing to know the current value or worry
about race conditions, as it's handled server-side.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'sarah1'
previous_account_name = 'sarah'
success = session.atomic_append_to_attribute_for_user(user_name, 'accountNameHistory',
previous_account_name)
# you can also append multiple values at once, or append to multiple
# attributes at once
user_name = 'monica pham-chen'
previous_account_names = ['monica pham', 'monica chen']
previous_uid = 'mpham'
update_map = {
'accountNameHistory': previous_account_names,
'uid': previous_uid
}
success = session.atomic_append_to_attributes_for_user(user_name, update_map)
```
You can also perform these actions on groups and objects using the similarly named
functions `atomic_append_to_attribute_for_group`, `atomic_append_to_attributes_for_group`,
`atomic_append_to_attribute_for_computer`, `atomic_append_to_attributes_for_computer`,
`atomic_append_to_attribute_for_object`, and `atomic_append_to_attributes_for_object`.
### Overwriting one or more attributes
If you want to totally replace the value of an attribute, that's supported as well.
This can be done for single-valued or multi-valued attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'arjun'
new_uid_number = 1093
success = session.overwrite_attribute_for_user(user_name, 'uidNumber',
new_uid_number)
# just like appending, we can do multiple attributes at once atomically
user_name = 'nikita'
new_employee_type = 'Director'
new_gid = 0
new_addresses = [
'123 mulberry lane',
'456 vacation home drive'
]
new_value_map = {
'employeeType': new_employee_type,
'gidNumber': new_gid,
'postalAddress': new_addresses
}
success = session.overwrite_attributes_for_user(user_name, new_value_map)
```
You can also perform these actions on groups and objects using the similarly named
functions, just like with appending.
# Discovering and Managing Trusted Domains
You can discover trusted domains using a session, and check properties about them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
trusted_domains = session.find_trusted_domains_for_domain()
# split domains up based on trust type
trusted_mit_domains = [dom for dom in trusted_domains if dom.is_mit_trust()]
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# print a few attributes that may be relevant
for ad_dom in trusted_ad_domains:
print('FQDN: {}'.format(ad_dom.get_netbios_name()))
print('Netbios name: {}'.format(ad_dom.get_netbios_name()))
print('Disabled: {}'.format(ad_dom.is_disabled())
print('Bi-directional: {}'.format(ad_dom.is_bidirectional_trust())
print('Transitive: {}'.format(ad_dom.is_transitive_trust())
```
You can also convert AD domains that are trusted into fully usable `ADDomain`
objects for the purpose of creating sessions and looking up information there.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# convert them into domains where our user should be trusted
domains_our_user_can_auth_with = []
for trusted_dom in trusted_ad_domains:
if trusted_dom.trusts_primary_domain() and not trusted_dom.is_disabled():
full_domain = trusted_dom.convert_to_ad_domain()
domains_our_user_can_auth_with.append(full_domain)
# create sessions so we can search across many domains
all_user_sessions = [primary_session]
for dom in domains_our_user_can_auth_with:
# SASL is needed for cross-domain authentication in general
session = dom.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
all_user_sessions.append(session)
```
You can convert an existing authenticated session with one domain into an
authenticated session with a trusted AD domain that trusts the first domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
# filter for a domain being AD and it trusting the primary domain
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()
and dom.trusts_primary_domain()]
# create a new session with the trusted domain using our existing primary domain session,
# and use it to look up users/groups/etc. in the other domain
transferred_session = trusted_ad_domains[0].create_transfer_session_to_trusted_domain(primary_session)
transferred_session.find_user_by_name('other-domain-user')
```
You can also automatically have a session create sessions for all its trusted domains
that trust the session's domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# find a user that we know exists somewhere, but not the primary domain
user_to_find = 'some-lost-user'
# by default this filters to AD domains, and further filters to domains that trust the session's domain
# if the user used for the session is from the session's domain (which they are in this
# example)
trust_sessions = primary_session.create_transfer_sessions_to_all_trusted_domains()
user = None
for session in trust_sessions:
user = session.find_user_by_name(user_to_find)
if user is not None:
print('Found user in {}'.format(session.get_domain_dns_name()))
break
```
%package -n python3-ms-active-directory
Summary: Python library for integrating with Microsoft Active Directory
Provides: python-ms-active-directory
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-ms-active-directory
# ms_active_directory - A Library for Integrating with Microsoft Active Directory
This is a library for integrating with Microsoft Active Directory domains.
It supports a variety of common, critical functionality for integration of computers
into a domain, including the ability to discover domain resources, optimize
communication for speed, join a computer to the domain, and look up information
about users and groups in the domain.
It primarily builds on the LDAP protocol, and supports LDAP over TLS with channel bindings,
and all LDAP basic, NTLM, and SASL authentication mechanisms (e.g. Kerberos) supported by the
`ldap3` python library.
For more detailed documentation, please see the docs at:\
**https://ms-active-directory.readthedocs.io/**
**Author**: Azaria Zornberg
\
**Email**: a.zornberg96@gmail.com
# Key Features
1. Joining a computer to a domain, either by creating a new computer account or taking over an existing
account.
2. Discovering domain resources and properties, optimizing domain communication for the network
3. Discovering trusted domains, including MIT Kerberos domains and trusted Active Directory domains, and their
attributes (e.g. are the trusts transitive? is SID filtering used? what direction is the trust?)
4. Transferring authenticated sessions from one domain to its trusted domains, allowing for easy querying
capability across domains for widely trusted users. This can be used to trace foreign security principals
across domains without needing to spin up and manage new domain objects for each.
5. Finding users, computers, and groups based on a variety of properties (e.g. name, SID, user-specified properties)
6. Querying information about users, computers, groups, and generic objects
7. Looking up user, computer, and group memberships
8. Looking up members of groups, regardless of type, and their attributes. This can also be done with auto-recursion
for nested groups.
9. Adding and removing users, computers, and groups to and from other groups
10. Account management functionality for both users and computers, such as password changes/resets, enabling, disabling, and unlocking accounts
11. Looking up information about the permissions set on a user, computer, group, or generic object
12. Adding permissions to the security descriptor for a user, computer, group, or generic object
13. Support for creating users and groups
14. Support for updating attributes of users, computers, groups, and generic objects. Support exists for atomically appending
or overwriting values.
15. Support for finding policies within a domain, and for finding the policies directly attached to any given object.
# Examples
## Discovering a domain
The library supports discovering LDAP and Kerberos servers within a domain using special DNS
entries defined for Active Directory.
### Smart Defaults
By default, it will use the system DNS configuration, find LDAP servers that support TLS, and sort
LDAP and Kerberos servers by the RTT to communicate with them.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
domain = ADDomain(example_domain_dns_name)
ldap_servers = domain.get_ldap_uris()
kerberos_servers = domain.get_kerberos_uris()
# re-discover servers in dns and sort them by RTT again at a later time to pick up changes
domain.refresh_ldap_server_discovery()
domain.refresh_kerberos_server_discovery()
```
### Site Awareness and Flexible DNS
The library also supports site awareness, which will result in only discovering servers within a specified
Active Directory Site. You can also specify alternative DNS nameservers to use instead of the system ones.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
site_name = 'us-eastern-datacenter'
domain = ADDomain(example_domain_dns_name, site=site_name,
dns_nameservers=['eastern-private-dns-01.local'])
```
### Network Multi-Tenancy and Security Support
You can also specify exactly which LDAP or Kerberos servers should be used, and skip discovery.
Additional configurations are available such as configuring the CA file path to use for
trust, and the source IP to use for outbound traffic to the domain, which is helpful when
there are firewall rules in place, or when a machine has both private and public IP addresses.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
local_machine_ip = '10.251.12.1'
local_ldap_ip = '10.251.12.30'
public_machine_ip = '194.32.21.30'
# the servers that live on the public internet use well-known public
# CAs for trust, but we have a local CA for the private network servers
private_securing_cas = '/etc/internal-ca.cert'
# set up an object for the local domain in the same network as this machine,
# but also have an instance that can be used to make instances to reach out
# to the rest of the domain outside of the local private network
local_domain = ADDomain(example_domain_dns_name, ldap_servers_or_uris=[local_ldap_ip],
source_ip=local_ldap_ip, ca_certificates_file_path=private_securing_cas)
global_domain = ADDomain(example_domain_dns_name, source_ip=public_machine_ip)
```
## Establishing a session with a domain
You can establish a session with the AD Domain on behalf of either a user or computer.
Broadly, any keyword arguments that would normally be supported when creating a `Connection`
with the `ldap3` library are supported when creating a session, allowing
for flexibility while still providing an "it just works" option for
most users.
### Support for Computer Authentication
Computers default to using Kerberos SASL authentication, as SIMPLE authentication is
not support for computers with Active Directory.
To use kerberos, either `gssapi` or `winkerberos` must be
installed.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# when using kerberos auth, the default is to use the kerberos
# credential cache on the machine, so no password is needed
computer_name = 'machine01'
session1 = domain.create_session_as_computer(computer_name)
# but you can pass sasl credentials, and if you use gssapi you can
# specify a username and password
# see the ldap3 documentation for details on SASL credentials and other
# connection options
other_name = 'other-machine-identity'
password = 'password01'
session2 = domain.create_session_as_computer(other_name, sasl_credentials=('', other_name, password))
```
You can also use other authentication mechanisms like NTLM.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
ntlm_name = 'EXAMPLE.COM\\computer01'
password = 'password1'
session = domain.create_session_as_computer(ntlm_name, password, authentication_mechanism=NTLM)
```
### Support for User Authentication
You can authenticate as a user by using simple binds, or by using SASL
mechanisms or NTLM as computers do.
The default for users is simple binds.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
ntlm_session = domain.create_session_as_user('username@example.com', 'password',
authentication_mechanism=NTLM)
```
## Discovering additional domain resources
The library supports discovering a wide variety of information about the domain beyond
the basics needed to communicate with it. This discovery doesn't require you to know any
niche information about Active Directory.
Discoverable resources include but are not limited to:
- Supported SASL mechanisms, which is important for authentication
- The current domain time, which is important for NTP synchronization
- Domain Functional Level, which governs things like support encryption types
- DNS servers
- Issuing certificates for CAs in the domain
### Finding supported SASL mechanisms
Discovering SASL mechanisms can be done without needing to create a session
with a domain, as it's needed before authentication in many cases.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# might print "['EXTERNAL', 'DIGEST-MD5']"
print(domain.find_supported_sasl_mechanisms())
```
### Finding the current domain time
Discovering the domain time can be done without needing to create a session
with a domain, as time synchronization is necessary for kerberos authentication
to succeed and can impact TLS negotiation as well.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# returns a python datetime object in utc time
curr_time = domain.find_current_time()
# allowed drift defaults to 5 minutes which is the kerberos standard,
# but we can use a shorter window to detect drift before it causes an
# outage. this returns a boolean
synced = domain.is_close_in_time_to_localhost(allowed_drift_seconds=60)
```
### Finding the domain functional level
Discovering the domain time can be done without needing to create a session
with a domain, as it can inform us as to what encryption types and TLS versions/ciphers
will be supported by the domain.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# find_functional_level returns an enum indicating the level.
# decision making based on level should be done based on the
# needs of your application
print(domain.find_functional_level())
```
### Finding DNS servers
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for computers that run a DNS
service is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a map that maps server hostnames -> ip addresses, where
# the hostnames are computers running dns services
dns_map = session.find_dns_servers_for_domain()
ip_addrs = dns_map.values()
hostnames = dns_map.keys()
```
### Finding CA certificates
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for records that are indicated
as being certificate authorities is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a list of PEM-formatted strings representing the signing certificates
# of all certificate authorities in the domain
pem_certs = session.find_certificate_authorities_for_domain()
# you can also get the certificates in DER format, which might be
# preferred on windows
der_certs = session.find_certificate_authorities_for_domain(pem_format=False)
```
## Joining an Active Directory domain
The action of joining a computer to a domain is not a well-defined operation,
and so the exact mechanics of how you utilize the domain joining functionality
and how its outputs are integrated with the rest of your system will vary depending on
your use case.
This will try to cover some common examples.
### Join the domain with default configurations for everything
The default behavior requires only the domain name and the credentials of a user with
sufficient administrative rights to create computers within the domain.
```
from ms_active_directory import join_ad_domain
comp = join_ad_domain('example.com', 'Administrator@example.com', 'example-password')
```
The `join_ad_domain` function returns a `ManagedADComputer` object with many helpful functions
describing properties of the created computer.
This will use the local hostname of the machine running this code as the computer name.
It will create the computer in AD's default `Computers` container.
It enables `AES256-SHA1` as an encryption type for both receiving and initiating kerberos
contexts, and it configures `<local hostname>.<domain dns name>` as the hostname of the
computer in AD and registers the default `HOST` service.
It then writes kerberos keys for the new computer account to `/etc/krb5.keytab`, which is
the default location for kerberos keytabs.
This all enables the account to be used for authenticating with other domain resources as a client
over protocols like SMB and LDAP using kerberos, as well as receiving incoming kerberos authentication
as a server for things like SSH. This is because the `HOST` service encapsulates many standard services
in the domain.
However, it is still up to the caller to do things like configure sshd to utilize the keytab.
### Join the domain with customization of the account for security reasons
A number of customizations exist for security reasons.
You can change things like the encryption types enabled on the account to support older clients.
You can also change location where the account is created when joining a domain in order to use
a less privileged user for the act of joining. Locations can be LDAP distinguished names or windows
path style canonical names.
You can also set the computer name if you have a desired naming scheme. This will impact the hostnames
configured in the domain for the computer.
```
from ms_active_directory import join_ad_domain, ADEncryptionType
domain = 'example.com'
less_privileged_user = 'ops-manager@example.com'
password = 'password2'
# ldap-style relative distinguished name of a location
less_privileged_loc = 'OU=service-machines,OU=ops'
computer_name = 'workstation10'
legacy_enc_type = ADEncryptionType.RC4_HMAC
new_enc_type = ADEncryptionType.AES256_CTS_HMAC_SHA1_96
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=less_privileged_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
alt_format_loc = '/ops/service-machines'
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=alt_format_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
```
You can also manually set the computer password. The default is to generate a random 120
character password, but if you want to share this computer across services, and some cannot
interact with the generated kerberos keys, then you may wish to set a password manually.
You can also change where the kerberos keys are written to.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
kerberos_key_location = '/usr/shared/keys/workstation-key.keytab'
computer_name = 'workstation10'
computer_password = 'workstation-shared-pw'
comp = join_ad_domain(domain, user, password, computer_key_file_path=kerberos_key_location,
computer_name=computer_name, computer_password=computer_password)
```
### Join the domain with different network or service settings
You can configure different hostnames for your computer when joining the
domain. This is useful when you have multiple different hostnames for
a single device, or want to use a computer name that doesn't match your
network name.
You can also configure services in order to restrict or broaden what is
supported by the computer when acting as a server (e.g. you can add `nfs`
if the machine will be an nfs server).
Joining will fail if another computer in the domain is using the services
you specify on any of the hostnames you specify in order to avoid conflicts
that cause undefined behavior.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
computer_host1 = 'central-mount-point.example.com'
computer_host2 = 'example-web-server.example.com'
comp = join_ad_domain(domain, user, password, computer_name=computer_name,
computer_hostnames=[computer_host1, computer_host2],
computer_services=services)
```
### Join using a domain object
You can use an `ADDomain` object to join the domain as well, using a `join` function.
This allows you to combine all of the functionality mentioned earlier around site-awareness,
server preferences, TLS settings, and network multi-tenancy with the domain joining
functionality mentioned in this section.
The parameters are all the same, except the domain need not be provided when using an
`ADDomain` object, so it just adds more functionality in exchange for a slightly less simple
workflow.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com', site='us-eastern-dc',
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
user = 'ops-manager@example.com'
password = 'password2'
less_privileged_loc = 'OU=service-machines,OU=ops'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
comp = domain.join(user, password, computer_hostnames=[computer_host1, computer_host2],
computer_services=services, computer_location=less_privileged_loc)
```
### Join the domain by taking over an existing account
For some setups, accounts may be pre-created and then taken over by the computers that will use them.
This can be done in order to greatly restrict the permissions of the user that is used for joining,
as they only need `RESET PASSWORD` permissions on the computer account, or `CHANGE PASSWORD` if
the current computer password is provided.
```
from ms_active_directory import ADDomain, join_ad_domain_by_taking_over_existing_computer
domain_dns_name = 'example.com'
site = 'us-eastern-dc'
existing_computer_name = 'precreated-comp'
user = 'single-account-admin@example.com'
password = 'password2'
computer_obj = join_ad_domain_by_taking_over_existing_computer(domain_dns_name, user, password,
ad_site=site, computer_name=existing_computer_name)
# or use a domain object to use various power-user domain features
domain = ADDomain(domain_dns_name, site=site,
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
domain.join_by_taking_over_existing_computer(user, password, computer_name=existing_computer_name)
```
# Managing users, computers, and groups
The library provides a number of different functions for finding users, computers, and groups by different
identifiers, and for querying information about them.
It also has functions for checking their memberships and adding or removing users, computers, and groups
to or from groups.
## Looking up users, computers, groups, and information about them
Users, computers, and groups can both be looked up by one of:
- sAMAccountName
- distinguished name
- common name
- a generic "name" that will attempt the above 3
- an attribute
### Look up by sAMAccountName
A `sAMAccountName` is unique within a domain, and so looking up users or
groups by `sAMAccountName` returns a single result.
`sAMAccountName` was a user's windows logon name in older versions of windows,
and may be referred to as such in some documentation.
For computers, the standard convention is for their `sAMAccountName` to end with
a `$`, but many tools/docs leave that out. So if a `sAMAccountName` is specified
that does not end with a `$` and cannot be found, a lookup will also be
attempted after adding a `$` to the end.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user = session.find_user_by_sam_name('user1', ['employeeID'])
group = session.find_group_by_sam_name('group1', ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by distinguished name
A distinguished name is unique within a forest, and so looking up users or
groups by it returns a single result.
A distinguished name should not be escaped when provided to the search function.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_dn = 'CN=user one,CN=Users,DC=example,DC=com'
user = session.find_user_by_distinguished_name(user_dn, ['employeeID'])
group_dn = 'CN=group one,OU=employee-groups,DC=example,DC=com'
group = session.find_group_by_distinguished_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by common name
A common name is not unique within a domain, and so looking up users or
groups by it returns a list of results, which may have 0 or more entries.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_cn = 'John Doe'
users = session.find_users_by_common_name(user_cn, ['employeeID'])
group_dn = 'operations managers'
groups = session.find_groups_by_common_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.get('employeeID'))
for group in groups:
print(group.get('gidNumber'))
```
### Look up by generic name
You can also query by a generic "name", and the library will attempt to find a
unique user or group with that name. The library will either lookup by DN or will
attempt `sAMAccountName` and common name lookups depending on the name format.
If more than one result is found by common name and no result is found by
`sAMAccountName` then this will produce an error.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'John Doe'
user = session.find_user_by_name(user_name, ['employeeID'])
group_name = 'operations managers'
groups = session.find_groups_by_name(group_name, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by attribute
You can also query for users, computers, or groups that possess a certain value for a
specified attribute. This can produce any number of results, so a list is
returned.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
desired_employee_type = 'temporary'
users = session.find_users_by_attribute('employeeType', desired_employee_type, ['employeeID'])
desired_group_manager = 'Alice P Hacker'
groups = session.find_groups_by_attribute('managedBy', desired_group_manager, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.distinguished_name)
print(user.get('employeeID'))
for group in groups:
print(group.distinguished_name)
print(group.get('gidNumber'))
```
## Querying user, computer, and group membership
You can also look up the groups that a user belongs to, the groups that a computer belongs to,
or the groups that a group belongs to. Active Directory supports nested groups, which is why
there's `user->groups`, `computer->groups`, and `group->groups` mapping capability.
When querying the membership information for users or groups, the input type for any
user or group must either be a string name identifying the user, computer, or group as described in the prior
section, or must be an `ADUser`, `ADComputer`, or `ADGroup` object returned by one of the functions described
in the prior section.
Similarly to looking up users, computers, and groups, you can query for attributes of the parent groups
by providing a list of LDAP attributes to look up for them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_sam_account_name = 'user-sam-1'
user_dn = 'CN=user sam 1,CN=users,DC=example,DC=com'
user_cn = 'user same 1'
desired_group_attrs = ['gidNumber', 'managedBy']
# all 3 of these do the same thing, and internally map the different
# name types to a user object
groups_res1 = session.find_groups_for_user(user_sam_account_name, desired_group_attrs)
groups_res2 = session.find_groups_for_user(user_dn, desired_group_attrs)
groups_res3 = session.find_groups_for_user(user_cn, desired_group_attrs)
# you can also directly use a user object to query groups
user_obj = session.find_user_by_name(user_sam_account_name)
groups_res4 = session.find_groups_for_user(user_obj, desired_group_attrs)
# you can also look up the parents of groups in the same way
example_group_obj = groups_res4[0]
example_group_dn = example_group_obj.distinguished_name
# these both work. sAMAccountName could also be used, etc.
second_level_groups_res1 = session.find_groups_for_group(example_group_obj, desired_group_attrs)
second_level_groups_res2 = session.find_groups_for_group(example_group_dn, desired_group_attrs)
```
You can also query `users->groups`, `computers->groups`, and `groups->groups` to find the memberships of multiple
users, computers, and groups, and the library will make a minimal number of queries to determine membership;
it will be more efficient that doing a `user->groups` for each user (or similar for computers and groups).
The result will be a map that maps the input users or groups to lists of parent groups.
The input lists' elements must be the same format as what's provided when looking up group
memberships for a single user or group.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
users = [user1_name, user2_name]
desired_group_attrs = ['gidNumber', 'managedBy']
user_group_map = session.find_groups_for_users(users, desired_group_attrs)
# the dictionary result keys are the users from the input
user1_groups = user_group_map[user1_name]
user2_groups = user_group_map[user2_name]
# you can use the groups->groups mapping functionality to enumerate the
# full tree of a users' group memberships (or a groups' group memberships)
user1_second_level_groups_map = session.find_groups_for_groups(user1_groups, desired_group_attrs)
all_second_level_groups = []
for group_list in user1_second_level_groups_map.values():
for group in group_list:
if group not in all_second_level_groups:
all_second_level_groups.append(group)
all_user1_groups_in_2_levels = user1_groups + all_second_level_groups
```
## Finding the members of groups
You can look up the members of one or more groups and get attributes about those
members.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
# look up members of a single group
single_group_member_list = session.find_members_of_group('group1', desired_attrs)
# look up members of multiple groups at once
groups = ['group1', 'group2']
group_to_member_list_map = session.find_members_of_groups(groups, desired_attrs)
group2_member_list = group_to_member_list_map['group2']
group2_user_members = [mem for mem in group2_member_list if isintance(mem, ADUser)]
group2_group_members = [mem for mem in group2_member_list if isintance(mem, ADGroup)]
```
You can also look up members recursively to handle nesting.
A maximum depth for lookups may be specified, but by default all
nesting will be enumerated.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
group_name = 'has-groups-as-members'
groups_to_member_lists_maps = session.find_members_of_groups_recursive(group_name, desired_attrs)
```
## Adding users to groups
You can add users to groups by specifying a list of `ADUser` objects or string names of
AD users to be added to the groups, and a list of `ADGroup` objects or string names of AD
groups to add the users to.
If string names are specified, they'll be mapped to users/groups using the functions
discussed in the prior sections.
If a user is already in a group, this is idempotent and will not re-add them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name])
```
By default, if we fail to add users to one of the groups specified, we'll attempt to rollback
and remove users from any groups they were added to. You can choose to forgo this and a list of
groups that users were successfully added to will be returned instead.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
privileged_group = 'group-that-will-fail'
succeeeded = session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name, privileged_group],
stop_and_rollback_on_error=False)
# this will print "['target-group1', 'target-group2']" assuming that
# adding users to 'group-that-will-fail' failed
print(succeeeded)
```
## Adding groups to groups
Adding groups to other groups works exactly the same way as adding users to groups, but
the function is called `add_groups_to_groups` and both inputs are lists of groups.
## Adding computers to groups
Adding computers to groups works exactly the same way as adding users to groups, but
the function is called `add_computers_to_groups` and the first input is a list of computers.
## Removing users, computers, or groups from groups
Removing users, computers, or groups from groups works identically to adding users, computers, or groups to groups,
including input format, idempotency, and rollback functionality.
The only difference is that the functions are called `remove_users_from_groups`, `remove_computers_from_groups`, and
`remove_groups_from_groups` instead.
## Updating user, computer, or group attributes.
You can use this library to modify the values of various LDAP attributes on
users, computers, groups, or generic objects.
Users, computers, and groups provide the convenient name lookup functionality mentioned above,
while for generic objects you either need to pass an `ADObject` or a distinguished name.
### Appending to one or more attributes
You can atomically append values to multi-valued attributes, such as `accountNameHistory`.
This allows you to update their values without needing to know the current value or worry
about race conditions, as it's handled server-side.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'sarah1'
previous_account_name = 'sarah'
success = session.atomic_append_to_attribute_for_user(user_name, 'accountNameHistory',
previous_account_name)
# you can also append multiple values at once, or append to multiple
# attributes at once
user_name = 'monica pham-chen'
previous_account_names = ['monica pham', 'monica chen']
previous_uid = 'mpham'
update_map = {
'accountNameHistory': previous_account_names,
'uid': previous_uid
}
success = session.atomic_append_to_attributes_for_user(user_name, update_map)
```
You can also perform these actions on groups and objects using the similarly named
functions `atomic_append_to_attribute_for_group`, `atomic_append_to_attributes_for_group`,
`atomic_append_to_attribute_for_computer`, `atomic_append_to_attributes_for_computer`,
`atomic_append_to_attribute_for_object`, and `atomic_append_to_attributes_for_object`.
### Overwriting one or more attributes
If you want to totally replace the value of an attribute, that's supported as well.
This can be done for single-valued or multi-valued attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'arjun'
new_uid_number = 1093
success = session.overwrite_attribute_for_user(user_name, 'uidNumber',
new_uid_number)
# just like appending, we can do multiple attributes at once atomically
user_name = 'nikita'
new_employee_type = 'Director'
new_gid = 0
new_addresses = [
'123 mulberry lane',
'456 vacation home drive'
]
new_value_map = {
'employeeType': new_employee_type,
'gidNumber': new_gid,
'postalAddress': new_addresses
}
success = session.overwrite_attributes_for_user(user_name, new_value_map)
```
You can also perform these actions on groups and objects using the similarly named
functions, just like with appending.
# Discovering and Managing Trusted Domains
You can discover trusted domains using a session, and check properties about them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
trusted_domains = session.find_trusted_domains_for_domain()
# split domains up based on trust type
trusted_mit_domains = [dom for dom in trusted_domains if dom.is_mit_trust()]
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# print a few attributes that may be relevant
for ad_dom in trusted_ad_domains:
print('FQDN: {}'.format(ad_dom.get_netbios_name()))
print('Netbios name: {}'.format(ad_dom.get_netbios_name()))
print('Disabled: {}'.format(ad_dom.is_disabled())
print('Bi-directional: {}'.format(ad_dom.is_bidirectional_trust())
print('Transitive: {}'.format(ad_dom.is_transitive_trust())
```
You can also convert AD domains that are trusted into fully usable `ADDomain`
objects for the purpose of creating sessions and looking up information there.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# convert them into domains where our user should be trusted
domains_our_user_can_auth_with = []
for trusted_dom in trusted_ad_domains:
if trusted_dom.trusts_primary_domain() and not trusted_dom.is_disabled():
full_domain = trusted_dom.convert_to_ad_domain()
domains_our_user_can_auth_with.append(full_domain)
# create sessions so we can search across many domains
all_user_sessions = [primary_session]
for dom in domains_our_user_can_auth_with:
# SASL is needed for cross-domain authentication in general
session = dom.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
all_user_sessions.append(session)
```
You can convert an existing authenticated session with one domain into an
authenticated session with a trusted AD domain that trusts the first domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
# filter for a domain being AD and it trusting the primary domain
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()
and dom.trusts_primary_domain()]
# create a new session with the trusted domain using our existing primary domain session,
# and use it to look up users/groups/etc. in the other domain
transferred_session = trusted_ad_domains[0].create_transfer_session_to_trusted_domain(primary_session)
transferred_session.find_user_by_name('other-domain-user')
```
You can also automatically have a session create sessions for all its trusted domains
that trust the session's domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# find a user that we know exists somewhere, but not the primary domain
user_to_find = 'some-lost-user'
# by default this filters to AD domains, and further filters to domains that trust the session's domain
# if the user used for the session is from the session's domain (which they are in this
# example)
trust_sessions = primary_session.create_transfer_sessions_to_all_trusted_domains()
user = None
for session in trust_sessions:
user = session.find_user_by_name(user_to_find)
if user is not None:
print('Found user in {}'.format(session.get_domain_dns_name()))
break
```
%package help
Summary: Development documents and examples for ms-active-directory
Provides: python3-ms-active-directory-doc
%description help
# ms_active_directory - A Library for Integrating with Microsoft Active Directory
This is a library for integrating with Microsoft Active Directory domains.
It supports a variety of common, critical functionality for integration of computers
into a domain, including the ability to discover domain resources, optimize
communication for speed, join a computer to the domain, and look up information
about users and groups in the domain.
It primarily builds on the LDAP protocol, and supports LDAP over TLS with channel bindings,
and all LDAP basic, NTLM, and SASL authentication mechanisms (e.g. Kerberos) supported by the
`ldap3` python library.
For more detailed documentation, please see the docs at:\
**https://ms-active-directory.readthedocs.io/**
**Author**: Azaria Zornberg
\
**Email**: a.zornberg96@gmail.com
# Key Features
1. Joining a computer to a domain, either by creating a new computer account or taking over an existing
account.
2. Discovering domain resources and properties, optimizing domain communication for the network
3. Discovering trusted domains, including MIT Kerberos domains and trusted Active Directory domains, and their
attributes (e.g. are the trusts transitive? is SID filtering used? what direction is the trust?)
4. Transferring authenticated sessions from one domain to its trusted domains, allowing for easy querying
capability across domains for widely trusted users. This can be used to trace foreign security principals
across domains without needing to spin up and manage new domain objects for each.
5. Finding users, computers, and groups based on a variety of properties (e.g. name, SID, user-specified properties)
6. Querying information about users, computers, groups, and generic objects
7. Looking up user, computer, and group memberships
8. Looking up members of groups, regardless of type, and their attributes. This can also be done with auto-recursion
for nested groups.
9. Adding and removing users, computers, and groups to and from other groups
10. Account management functionality for both users and computers, such as password changes/resets, enabling, disabling, and unlocking accounts
11. Looking up information about the permissions set on a user, computer, group, or generic object
12. Adding permissions to the security descriptor for a user, computer, group, or generic object
13. Support for creating users and groups
14. Support for updating attributes of users, computers, groups, and generic objects. Support exists for atomically appending
or overwriting values.
15. Support for finding policies within a domain, and for finding the policies directly attached to any given object.
# Examples
## Discovering a domain
The library supports discovering LDAP and Kerberos servers within a domain using special DNS
entries defined for Active Directory.
### Smart Defaults
By default, it will use the system DNS configuration, find LDAP servers that support TLS, and sort
LDAP and Kerberos servers by the RTT to communicate with them.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
domain = ADDomain(example_domain_dns_name)
ldap_servers = domain.get_ldap_uris()
kerberos_servers = domain.get_kerberos_uris()
# re-discover servers in dns and sort them by RTT again at a later time to pick up changes
domain.refresh_ldap_server_discovery()
domain.refresh_kerberos_server_discovery()
```
### Site Awareness and Flexible DNS
The library also supports site awareness, which will result in only discovering servers within a specified
Active Directory Site. You can also specify alternative DNS nameservers to use instead of the system ones.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
site_name = 'us-eastern-datacenter'
domain = ADDomain(example_domain_dns_name, site=site_name,
dns_nameservers=['eastern-private-dns-01.local'])
```
### Network Multi-Tenancy and Security Support
You can also specify exactly which LDAP or Kerberos servers should be used, and skip discovery.
Additional configurations are available such as configuring the CA file path to use for
trust, and the source IP to use for outbound traffic to the domain, which is helpful when
there are firewall rules in place, or when a machine has both private and public IP addresses.
```
from ms_active_directory import ADDomain
example_domain_dns_name = 'example.com'
local_machine_ip = '10.251.12.1'
local_ldap_ip = '10.251.12.30'
public_machine_ip = '194.32.21.30'
# the servers that live on the public internet use well-known public
# CAs for trust, but we have a local CA for the private network servers
private_securing_cas = '/etc/internal-ca.cert'
# set up an object for the local domain in the same network as this machine,
# but also have an instance that can be used to make instances to reach out
# to the rest of the domain outside of the local private network
local_domain = ADDomain(example_domain_dns_name, ldap_servers_or_uris=[local_ldap_ip],
source_ip=local_ldap_ip, ca_certificates_file_path=private_securing_cas)
global_domain = ADDomain(example_domain_dns_name, source_ip=public_machine_ip)
```
## Establishing a session with a domain
You can establish a session with the AD Domain on behalf of either a user or computer.
Broadly, any keyword arguments that would normally be supported when creating a `Connection`
with the `ldap3` library are supported when creating a session, allowing
for flexibility while still providing an "it just works" option for
most users.
### Support for Computer Authentication
Computers default to using Kerberos SASL authentication, as SIMPLE authentication is
not support for computers with Active Directory.
To use kerberos, either `gssapi` or `winkerberos` must be
installed.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# when using kerberos auth, the default is to use the kerberos
# credential cache on the machine, so no password is needed
computer_name = 'machine01'
session1 = domain.create_session_as_computer(computer_name)
# but you can pass sasl credentials, and if you use gssapi you can
# specify a username and password
# see the ldap3 documentation for details on SASL credentials and other
# connection options
other_name = 'other-machine-identity'
password = 'password01'
session2 = domain.create_session_as_computer(other_name, sasl_credentials=('', other_name, password))
```
You can also use other authentication mechanisms like NTLM.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
ntlm_name = 'EXAMPLE.COM\\computer01'
password = 'password1'
session = domain.create_session_as_computer(ntlm_name, password, authentication_mechanism=NTLM)
```
### Support for User Authentication
You can authenticate as a user by using simple binds, or by using SASL
mechanisms or NTLM as computers do.
The default for users is simple binds.
```
from ldap3 import NTLM
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
ntlm_session = domain.create_session_as_user('username@example.com', 'password',
authentication_mechanism=NTLM)
```
## Discovering additional domain resources
The library supports discovering a wide variety of information about the domain beyond
the basics needed to communicate with it. This discovery doesn't require you to know any
niche information about Active Directory.
Discoverable resources include but are not limited to:
- Supported SASL mechanisms, which is important for authentication
- The current domain time, which is important for NTP synchronization
- Domain Functional Level, which governs things like support encryption types
- DNS servers
- Issuing certificates for CAs in the domain
### Finding supported SASL mechanisms
Discovering SASL mechanisms can be done without needing to create a session
with a domain, as it's needed before authentication in many cases.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# might print "['EXTERNAL', 'DIGEST-MD5']"
print(domain.find_supported_sasl_mechanisms())
```
### Finding the current domain time
Discovering the domain time can be done without needing to create a session
with a domain, as time synchronization is necessary for kerberos authentication
to succeed and can impact TLS negotiation as well.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# returns a python datetime object in utc time
curr_time = domain.find_current_time()
# allowed drift defaults to 5 minutes which is the kerberos standard,
# but we can use a shorter window to detect drift before it causes an
# outage. this returns a boolean
synced = domain.is_close_in_time_to_localhost(allowed_drift_seconds=60)
```
### Finding the domain functional level
Discovering the domain time can be done without needing to create a session
with a domain, as it can inform us as to what encryption types and TLS versions/ciphers
will be supported by the domain.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
# find_functional_level returns an enum indicating the level.
# decision making based on level should be done based on the
# needs of your application
print(domain.find_functional_level())
```
### Finding DNS servers
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for computers that run a DNS
service is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a map that maps server hostnames -> ip addresses, where
# the hostnames are computers running dns services
dns_map = session.find_dns_servers_for_domain()
ip_addrs = dns_map.values()
hostnames = dns_map.keys()
```
### Finding CA certificates
Discovering DNS servers requires an authenticated session with the domain,
as searching the records within the domain for records that are indicated
as being certificate authorities is privileged.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# returns a list of PEM-formatted strings representing the signing certificates
# of all certificate authorities in the domain
pem_certs = session.find_certificate_authorities_for_domain()
# you can also get the certificates in DER format, which might be
# preferred on windows
der_certs = session.find_certificate_authorities_for_domain(pem_format=False)
```
## Joining an Active Directory domain
The action of joining a computer to a domain is not a well-defined operation,
and so the exact mechanics of how you utilize the domain joining functionality
and how its outputs are integrated with the rest of your system will vary depending on
your use case.
This will try to cover some common examples.
### Join the domain with default configurations for everything
The default behavior requires only the domain name and the credentials of a user with
sufficient administrative rights to create computers within the domain.
```
from ms_active_directory import join_ad_domain
comp = join_ad_domain('example.com', 'Administrator@example.com', 'example-password')
```
The `join_ad_domain` function returns a `ManagedADComputer` object with many helpful functions
describing properties of the created computer.
This will use the local hostname of the machine running this code as the computer name.
It will create the computer in AD's default `Computers` container.
It enables `AES256-SHA1` as an encryption type for both receiving and initiating kerberos
contexts, and it configures `<local hostname>.<domain dns name>` as the hostname of the
computer in AD and registers the default `HOST` service.
It then writes kerberos keys for the new computer account to `/etc/krb5.keytab`, which is
the default location for kerberos keytabs.
This all enables the account to be used for authenticating with other domain resources as a client
over protocols like SMB and LDAP using kerberos, as well as receiving incoming kerberos authentication
as a server for things like SSH. This is because the `HOST` service encapsulates many standard services
in the domain.
However, it is still up to the caller to do things like configure sshd to utilize the keytab.
### Join the domain with customization of the account for security reasons
A number of customizations exist for security reasons.
You can change things like the encryption types enabled on the account to support older clients.
You can also change location where the account is created when joining a domain in order to use
a less privileged user for the act of joining. Locations can be LDAP distinguished names or windows
path style canonical names.
You can also set the computer name if you have a desired naming scheme. This will impact the hostnames
configured in the domain for the computer.
```
from ms_active_directory import join_ad_domain, ADEncryptionType
domain = 'example.com'
less_privileged_user = 'ops-manager@example.com'
password = 'password2'
# ldap-style relative distinguished name of a location
less_privileged_loc = 'OU=service-machines,OU=ops'
computer_name = 'workstation10'
legacy_enc_type = ADEncryptionType.RC4_HMAC
new_enc_type = ADEncryptionType.AES256_CTS_HMAC_SHA1_96
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=less_privileged_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
alt_format_loc = '/ops/service-machines'
comp = join_ad_domain(domain, less_privileged_user, password, computer_name=computer_name,
computer_location=alt_format_loc, computer_encryption_types=[legacy_enc_type, new_enc_type])
```
You can also manually set the computer password. The default is to generate a random 120
character password, but if you want to share this computer across services, and some cannot
interact with the generated kerberos keys, then you may wish to set a password manually.
You can also change where the kerberos keys are written to.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
kerberos_key_location = '/usr/shared/keys/workstation-key.keytab'
computer_name = 'workstation10'
computer_password = 'workstation-shared-pw'
comp = join_ad_domain(domain, user, password, computer_key_file_path=kerberos_key_location,
computer_name=computer_name, computer_password=computer_password)
```
### Join the domain with different network or service settings
You can configure different hostnames for your computer when joining the
domain. This is useful when you have multiple different hostnames for
a single device, or want to use a computer name that doesn't match your
network name.
You can also configure services in order to restrict or broaden what is
supported by the computer when acting as a server (e.g. you can add `nfs`
if the machine will be an nfs server).
Joining will fail if another computer in the domain is using the services
you specify on any of the hostnames you specify in order to avoid conflicts
that cause undefined behavior.
```
from ms_active_directory import join_ad_domain
domain = 'example.com'
user = 'ops-manager@example.com'
password = 'password2'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
computer_host1 = 'central-mount-point.example.com'
computer_host2 = 'example-web-server.example.com'
comp = join_ad_domain(domain, user, password, computer_name=computer_name,
computer_hostnames=[computer_host1, computer_host2],
computer_services=services)
```
### Join using a domain object
You can use an `ADDomain` object to join the domain as well, using a `join` function.
This allows you to combine all of the functionality mentioned earlier around site-awareness,
server preferences, TLS settings, and network multi-tenancy with the domain joining
functionality mentioned in this section.
The parameters are all the same, except the domain need not be provided when using an
`ADDomain` object, so it just adds more functionality in exchange for a slightly less simple
workflow.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com', site='us-eastern-dc',
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
user = 'ops-manager@example.com'
password = 'password2'
less_privileged_loc = 'OU=service-machines,OU=ops'
services = ['HOST', 'nfs', 'cifs', 'HTTP']
computer_name = 'workstation10'
comp = domain.join(user, password, computer_hostnames=[computer_host1, computer_host2],
computer_services=services, computer_location=less_privileged_loc)
```
### Join the domain by taking over an existing account
For some setups, accounts may be pre-created and then taken over by the computers that will use them.
This can be done in order to greatly restrict the permissions of the user that is used for joining,
as they only need `RESET PASSWORD` permissions on the computer account, or `CHANGE PASSWORD` if
the current computer password is provided.
```
from ms_active_directory import ADDomain, join_ad_domain_by_taking_over_existing_computer
domain_dns_name = 'example.com'
site = 'us-eastern-dc'
existing_computer_name = 'precreated-comp'
user = 'single-account-admin@example.com'
password = 'password2'
computer_obj = join_ad_domain_by_taking_over_existing_computer(domain_dns_name, user, password,
ad_site=site, computer_name=existing_computer_name)
# or use a domain object to use various power-user domain features
domain = ADDomain(domain_dns_name, site=site,
source_ip='10.25.21.30', dns_nameservers=['10.25.21.20'])
domain.join_by_taking_over_existing_computer(user, password, computer_name=existing_computer_name)
```
# Managing users, computers, and groups
The library provides a number of different functions for finding users, computers, and groups by different
identifiers, and for querying information about them.
It also has functions for checking their memberships and adding or removing users, computers, and groups
to or from groups.
## Looking up users, computers, groups, and information about them
Users, computers, and groups can both be looked up by one of:
- sAMAccountName
- distinguished name
- common name
- a generic "name" that will attempt the above 3
- an attribute
### Look up by sAMAccountName
A `sAMAccountName` is unique within a domain, and so looking up users or
groups by `sAMAccountName` returns a single result.
`sAMAccountName` was a user's windows logon name in older versions of windows,
and may be referred to as such in some documentation.
For computers, the standard convention is for their `sAMAccountName` to end with
a `$`, but many tools/docs leave that out. So if a `sAMAccountName` is specified
that does not end with a `$` and cannot be found, a lookup will also be
attempted after adding a `$` to the end.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user = session.find_user_by_sam_name('user1', ['employeeID'])
group = session.find_group_by_sam_name('group1', ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by distinguished name
A distinguished name is unique within a forest, and so looking up users or
groups by it returns a single result.
A distinguished name should not be escaped when provided to the search function.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_dn = 'CN=user one,CN=Users,DC=example,DC=com'
user = session.find_user_by_distinguished_name(user_dn, ['employeeID'])
group_dn = 'CN=group one,OU=employee-groups,DC=example,DC=com'
group = session.find_group_by_distinguished_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by common name
A common name is not unique within a domain, and so looking up users or
groups by it returns a list of results, which may have 0 or more entries.
When looking up users, computers, and groups, you can also query for additional information
about them by specifying a list of LDAP attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_cn = 'John Doe'
users = session.find_users_by_common_name(user_cn, ['employeeID'])
group_dn = 'operations managers'
groups = session.find_groups_by_common_name(group_dn, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.get('employeeID'))
for group in groups:
print(group.get('gidNumber'))
```
### Look up by generic name
You can also query by a generic "name", and the library will attempt to find a
unique user or group with that name. The library will either lookup by DN or will
attempt `sAMAccountName` and common name lookups depending on the name format.
If more than one result is found by common name and no result is found by
`sAMAccountName` then this will produce an error.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'John Doe'
user = session.find_user_by_name(user_name, ['employeeID'])
group_name = 'operations managers'
groups = session.find_groups_by_name(group_name, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
print(user.get('employeeID'))
print(group.get('gidNumber'))
```
### Look up by attribute
You can also query for users, computers, or groups that possess a certain value for a
specified attribute. This can produce any number of results, so a list is
returned.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
desired_employee_type = 'temporary'
users = session.find_users_by_attribute('employeeType', desired_employee_type, ['employeeID'])
desired_group_manager = 'Alice P Hacker'
groups = session.find_groups_by_attribute('managedBy', desired_group_manager, ['gidNumber'])
# users and groups support a generic "get" for any attributes queried
for user in users:
print(user.distinguished_name)
print(user.get('employeeID'))
for group in groups:
print(group.distinguished_name)
print(group.get('gidNumber'))
```
## Querying user, computer, and group membership
You can also look up the groups that a user belongs to, the groups that a computer belongs to,
or the groups that a group belongs to. Active Directory supports nested groups, which is why
there's `user->groups`, `computer->groups`, and `group->groups` mapping capability.
When querying the membership information for users or groups, the input type for any
user or group must either be a string name identifying the user, computer, or group as described in the prior
section, or must be an `ADUser`, `ADComputer`, or `ADGroup` object returned by one of the functions described
in the prior section.
Similarly to looking up users, computers, and groups, you can query for attributes of the parent groups
by providing a list of LDAP attributes to look up for them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_sam_account_name = 'user-sam-1'
user_dn = 'CN=user sam 1,CN=users,DC=example,DC=com'
user_cn = 'user same 1'
desired_group_attrs = ['gidNumber', 'managedBy']
# all 3 of these do the same thing, and internally map the different
# name types to a user object
groups_res1 = session.find_groups_for_user(user_sam_account_name, desired_group_attrs)
groups_res2 = session.find_groups_for_user(user_dn, desired_group_attrs)
groups_res3 = session.find_groups_for_user(user_cn, desired_group_attrs)
# you can also directly use a user object to query groups
user_obj = session.find_user_by_name(user_sam_account_name)
groups_res4 = session.find_groups_for_user(user_obj, desired_group_attrs)
# you can also look up the parents of groups in the same way
example_group_obj = groups_res4[0]
example_group_dn = example_group_obj.distinguished_name
# these both work. sAMAccountName could also be used, etc.
second_level_groups_res1 = session.find_groups_for_group(example_group_obj, desired_group_attrs)
second_level_groups_res2 = session.find_groups_for_group(example_group_dn, desired_group_attrs)
```
You can also query `users->groups`, `computers->groups`, and `groups->groups` to find the memberships of multiple
users, computers, and groups, and the library will make a minimal number of queries to determine membership;
it will be more efficient that doing a `user->groups` for each user (or similar for computers and groups).
The result will be a map that maps the input users or groups to lists of parent groups.
The input lists' elements must be the same format as what's provided when looking up group
memberships for a single user or group.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
users = [user1_name, user2_name]
desired_group_attrs = ['gidNumber', 'managedBy']
user_group_map = session.find_groups_for_users(users, desired_group_attrs)
# the dictionary result keys are the users from the input
user1_groups = user_group_map[user1_name]
user2_groups = user_group_map[user2_name]
# you can use the groups->groups mapping functionality to enumerate the
# full tree of a users' group memberships (or a groups' group memberships)
user1_second_level_groups_map = session.find_groups_for_groups(user1_groups, desired_group_attrs)
all_second_level_groups = []
for group_list in user1_second_level_groups_map.values():
for group in group_list:
if group not in all_second_level_groups:
all_second_level_groups.append(group)
all_user1_groups_in_2_levels = user1_groups + all_second_level_groups
```
## Finding the members of groups
You can look up the members of one or more groups and get attributes about those
members.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
# look up members of a single group
single_group_member_list = session.find_members_of_group('group1', desired_attrs)
# look up members of multiple groups at once
groups = ['group1', 'group2']
group_to_member_list_map = session.find_members_of_groups(groups, desired_attrs)
group2_member_list = group_to_member_list_map['group2']
group2_user_members = [mem for mem in group2_member_list if isintance(mem, ADUser)]
group2_group_members = [mem for mem in group2_member_list if isintance(mem, ADGroup)]
```
You can also look up members recursively to handle nesting.
A maximum depth for lookups may be specified, but by default all
nesting will be enumerated.
```
from ms_active_directory import ADDomain, ADUser, ADGroup
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
# get emails of users and groups that are members
desired_attrs = ['mail']
group_name = 'has-groups-as-members'
groups_to_member_lists_maps = session.find_members_of_groups_recursive(group_name, desired_attrs)
```
## Adding users to groups
You can add users to groups by specifying a list of `ADUser` objects or string names of
AD users to be added to the groups, and a list of `ADGroup` objects or string names of AD
groups to add the users to.
If string names are specified, they'll be mapped to users/groups using the functions
discussed in the prior sections.
If a user is already in a group, this is idempotent and will not re-add them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name])
```
By default, if we fail to add users to one of the groups specified, we'll attempt to rollback
and remove users from any groups they were added to. You can choose to forgo this and a list of
groups that users were successfully added to will be returned instead.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user1_name = 'user1'
user2_name = 'user2'
group1_name = 'target-group1'
group2_name = 'target-group2'
privileged_group = 'group-that-will-fail'
succeeeded = session.add_users_to_groups([user1_name, user2_name],
[group1_name, group2_name, privileged_group],
stop_and_rollback_on_error=False)
# this will print "['target-group1', 'target-group2']" assuming that
# adding users to 'group-that-will-fail' failed
print(succeeeded)
```
## Adding groups to groups
Adding groups to other groups works exactly the same way as adding users to groups, but
the function is called `add_groups_to_groups` and both inputs are lists of groups.
## Adding computers to groups
Adding computers to groups works exactly the same way as adding users to groups, but
the function is called `add_computers_to_groups` and the first input is a list of computers.
## Removing users, computers, or groups from groups
Removing users, computers, or groups from groups works identically to adding users, computers, or groups to groups,
including input format, idempotency, and rollback functionality.
The only difference is that the functions are called `remove_users_from_groups`, `remove_computers_from_groups`, and
`remove_groups_from_groups` instead.
## Updating user, computer, or group attributes.
You can use this library to modify the values of various LDAP attributes on
users, computers, groups, or generic objects.
Users, computers, and groups provide the convenient name lookup functionality mentioned above,
while for generic objects you either need to pass an `ADObject` or a distinguished name.
### Appending to one or more attributes
You can atomically append values to multi-valued attributes, such as `accountNameHistory`.
This allows you to update their values without needing to know the current value or worry
about race conditions, as it's handled server-side.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'sarah1'
previous_account_name = 'sarah'
success = session.atomic_append_to_attribute_for_user(user_name, 'accountNameHistory',
previous_account_name)
# you can also append multiple values at once, or append to multiple
# attributes at once
user_name = 'monica pham-chen'
previous_account_names = ['monica pham', 'monica chen']
previous_uid = 'mpham'
update_map = {
'accountNameHistory': previous_account_names,
'uid': previous_uid
}
success = session.atomic_append_to_attributes_for_user(user_name, update_map)
```
You can also perform these actions on groups and objects using the similarly named
functions `atomic_append_to_attribute_for_group`, `atomic_append_to_attributes_for_group`,
`atomic_append_to_attribute_for_computer`, `atomic_append_to_attributes_for_computer`,
`atomic_append_to_attribute_for_object`, and `atomic_append_to_attributes_for_object`.
### Overwriting one or more attributes
If you want to totally replace the value of an attribute, that's supported as well.
This can be done for single-valued or multi-valued attributes.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
user_name = 'arjun'
new_uid_number = 1093
success = session.overwrite_attribute_for_user(user_name, 'uidNumber',
new_uid_number)
# just like appending, we can do multiple attributes at once atomically
user_name = 'nikita'
new_employee_type = 'Director'
new_gid = 0
new_addresses = [
'123 mulberry lane',
'456 vacation home drive'
]
new_value_map = {
'employeeType': new_employee_type,
'gidNumber': new_gid,
'postalAddress': new_addresses
}
success = session.overwrite_attributes_for_user(user_name, new_value_map)
```
You can also perform these actions on groups and objects using the similarly named
functions, just like with appending.
# Discovering and Managing Trusted Domains
You can discover trusted domains using a session, and check properties about them.
```
from ms_active_directory import ADDomain
domain = ADDomain('example.com')
session = domain.create_session_as_user('username@example.com', 'password')
trusted_domains = session.find_trusted_domains_for_domain()
# split domains up based on trust type
trusted_mit_domains = [dom for dom in trusted_domains if dom.is_mit_trust()]
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# print a few attributes that may be relevant
for ad_dom in trusted_ad_domains:
print('FQDN: {}'.format(ad_dom.get_netbios_name()))
print('Netbios name: {}'.format(ad_dom.get_netbios_name()))
print('Disabled: {}'.format(ad_dom.is_disabled())
print('Bi-directional: {}'.format(ad_dom.is_bidirectional_trust())
print('Transitive: {}'.format(ad_dom.is_transitive_trust())
```
You can also convert AD domains that are trusted into fully usable `ADDomain`
objects for the purpose of creating sessions and looking up information there.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()]
# convert them into domains where our user should be trusted
domains_our_user_can_auth_with = []
for trusted_dom in trusted_ad_domains:
if trusted_dom.trusts_primary_domain() and not trusted_dom.is_disabled():
full_domain = trusted_dom.convert_to_ad_domain()
domains_our_user_can_auth_with.append(full_domain)
# create sessions so we can search across many domains
all_user_sessions = [primary_session]
for dom in domains_our_user_can_auth_with:
# SASL is needed for cross-domain authentication in general
session = dom.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
all_user_sessions.append(session)
```
You can convert an existing authenticated session with one domain into an
authenticated session with a trusted AD domain that trusts the first domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# get our trusted AD domains
trusted_domains = session.find_trusted_domains_for_domain()
# filter for a domain being AD and it trusting the primary domain
trusted_ad_domains = [dom for dom in trusted_domains if dom.is_active_directory_domain_trust()
and dom.trusts_primary_domain()]
# create a new session with the trusted domain using our existing primary domain session,
# and use it to look up users/groups/etc. in the other domain
transferred_session = trusted_ad_domains[0].create_transfer_session_to_trusted_domain(primary_session)
transferred_session.find_user_by_name('other-domain-user')
```
You can also automatically have a session create sessions for all its trusted domains
that trust the session's domain.
```
from ms_active_directory import ADDomain
from ldap3 import NTLM
domain = ADDomain('example.com')
widely_trusted_user = 'example.com\\org-admin'
password = 'password'
primary_session = domain.create_session_as_user(widely_trusted_user, password,
authentication_mechanism=NTLM)
# find a user that we know exists somewhere, but not the primary domain
user_to_find = 'some-lost-user'
# by default this filters to AD domains, and further filters to domains that trust the session's domain
# if the user used for the session is from the session's domain (which they are in this
# example)
trust_sessions = primary_session.create_transfer_sessions_to_all_trusted_domains()
user = None
for session in trust_sessions:
user = session.find_user_by_name(user_to_find)
if user is not None:
print('Found user in {}'.format(session.get_domain_dns_name()))
break
```
%prep
%autosetup -n ms_active_directory-1.12.1
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-ms-active-directory -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Tue Jun 20 2023 Python_Bot <Python_Bot@openeuler.org> - 1.12.1-1
- Package Spec generated
|