summaryrefslogtreecommitdiffstats
path: root/python/samba/netcmd/gpo.py
blob: ba55b2ec7a772224c0679032894c982a2fca56a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
# implement samba_tool gpo commands
#
# Copyright Andrew Tridgell 2010
# Copyright Amitay Isaacs 2011-2012 <amitay@gmail.com>
#
# based on C implementation by Guenther Deschner and Wilco Baan Hofman
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
import os
import sys
import samba.getopt as options
import ldb
import re
import xml.etree.ElementTree as ET
import shutil
import tempfile

from samba.auth import system_session
from samba.netcmd import (
    Command,
    CommandError,
    Option,
    SuperCommand,
)
from samba.samdb import SamDB
from samba import dsdb
from samba.dcerpc import security
from samba.ndr import ndr_unpack, ndr_pack
from samba.dcerpc import preg
import samba.security
import samba.auth
from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
from samba.netcmd.common import netcmd_finddc
from samba import policy
from samba.samba3 import libsmb_samba_internal as libsmb
from samba import NTSTATUSError
import uuid
from samba.ntacls import dsacl2fsacl
from samba.dcerpc import nbt
from samba.net import Net
from samba.gp_parse import GPParser, GPNoParserException, GPGeneralizeException
from samba.gp_parse.gp_pol import GPPolParser
from samba.gp_parse.gp_ini import (
    GPIniParser,
    GPTIniParser,
    GPFDeploy1IniParser,
    GPScriptsIniParser
)
from samba.gp_parse.gp_csv import GPAuditCsvParser
from samba.gp_parse.gp_inf import GptTmplInfParser
from samba.gp_parse.gp_aas import GPAasParser
from samba import param
from samba.netcmd.common import attr_default
from samba.common import get_bytes, get_string
from configparser import ConfigParser
from io import StringIO, BytesIO
from samba.gp.vgp_files_ext import calc_mode, stat_from_mode
import hashlib
import json
from samba.registry import str_regtype
from samba.ntstatus import (
    NT_STATUS_OBJECT_NAME_INVALID,
    NT_STATUS_OBJECT_NAME_NOT_FOUND,
    NT_STATUS_OBJECT_PATH_NOT_FOUND,
    NT_STATUS_OBJECT_NAME_COLLISION,
    NT_STATUS_ACCESS_DENIED
)
from samba.netcmd.gpcommon import (
    create_directory_hier,
    smb_connection,
    get_gpo_dn
)
from samba.policies import RegistryGroupPolicies
from samba.dcerpc.misc import REG_MULTI_SZ
from samba.gp.gpclass import register_gp_extension, list_gp_extensions, \
    unregister_gp_extension


def gpo_flags_string(value):
    """return gpo flags string"""
    flags = policy.get_gpo_flags(value)
    if not flags:
        ret = 'NONE'
    else:
        ret = ' '.join(flags)
    return ret


def gplink_options_string(value):
    """return gplink options string"""
    options = policy.get_gplink_options(value)
    if not options:
        ret = 'NONE'
    else:
        ret = ' '.join(options)
    return ret


def parse_gplink(gplink):
    """parse a gPLink into an array of dn and options"""
    ret = []

    if gplink.strip() == '':
        return ret

    a = gplink.split(']')
    for g in a:
        if not g:
            continue
        d = g.split(';')
        if len(d) != 2 or not d[0].startswith("[LDAP://"):
            raise RuntimeError("Badly formed gPLink '%s'" % g)
        ret.append({'dn': d[0][8:], 'options': int(d[1])})
    return ret


def encode_gplink(gplist):
    """Encode an array of dn and options into gPLink string"""
    ret = "".join("[LDAP://%s;%d]" % (g['dn'], g['options']) for g in gplist)
    return ret


def dc_url(lp, creds, url=None, dc=None):
    """If URL is not specified, return URL for writable DC.
    If dc is provided, use that to construct ldap URL"""

    if url is None:
        if dc is None:
            try:
                dc = netcmd_finddc(lp, creds)
            except Exception as e:
                raise RuntimeError("Could not find a DC for domain", e)
        url = 'ldap://' + dc
    return url


def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
                 sd_flags=(security.SECINFO_OWNER |
                           security.SECINFO_GROUP |
                           security.SECINFO_DACL |
                           security.SECINFO_SACL)):
    """Get GPO information using gpo, displayname or dn"""

    policies_dn = samdb.get_default_basedn()
    policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))

    base_dn = policies_dn
    search_expr = "(objectClass=groupPolicyContainer)"
    search_scope = ldb.SCOPE_ONELEVEL

    if gpo is not None:
        search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)

    if displayname is not None:
        search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)

    if dn is not None:
        base_dn = dn
        search_scope = ldb.SCOPE_BASE

    try:
        msg = samdb.search(base=base_dn, scope=search_scope,
                           expression=search_expr,
                           attrs=['nTSecurityDescriptor',
                                  'versionNumber',
                                  'flags',
                                  'name',
                                  'displayName',
                                  'gPCFileSysPath',
                                  'gPCMachineExtensionNames',
                                  'gPCUserExtensionNames'],
                           controls=['sd_flags:1:%d' % sd_flags])
    except Exception as e:
        if gpo is not None:
            mesg = "Cannot get information for GPO %s" % gpo
        else:
            mesg = "Cannot get information for GPOs"
        raise CommandError(mesg, e)

    return msg


def get_gpo_containers(samdb, gpo):
    """lists dn of containers for a GPO"""

    search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
    try:
        msg = samdb.search(expression=search_expr, attrs=['gPLink'])
    except Exception as e:
        raise CommandError("Could not find container(s) with GPO %s" % gpo, e)

    return msg


def del_gpo_link(samdb, container_dn, gpo):
    """delete GPO link for the container"""
    # Check if valid Container DN and get existing GPlinks
    try:
        msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
                           expression="(objectClass=*)",
                           attrs=['gPLink'])[0]
    except Exception as e:
        raise CommandError("Container '%s' does not exist" % container_dn, e)

    found = False
    gpo_dn = str(get_gpo_dn(samdb, gpo))
    if 'gPLink' in msg:
        gplist = parse_gplink(str(msg['gPLink'][0]))
        for g in gplist:
            if g['dn'].lower() == gpo_dn.lower():
                gplist.remove(g)
                found = True
                break
    else:
        raise CommandError("No GPO(s) linked to this container")

    if not found:
        raise CommandError("GPO '%s' not linked to this container" % gpo)

    m = ldb.Message()
    m.dn = container_dn
    if gplist:
        gplink_str = encode_gplink(gplist)
        m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
    else:
        m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
    try:
        samdb.modify(m)
    except Exception as e:
        raise CommandError("Error removing GPO from container", e)


def parse_unc(unc):
    """Parse UNC string into a hostname, a service, and a filepath"""
    tmp = []
    if unc.startswith('\\\\'):
        tmp = unc[2:].split('\\', 2)
    elif unc.startswith('//'):
        tmp = unc[2:].split('/', 2)

    if len(tmp) != 3:
        raise ValueError("Invalid UNC string: %s" % unc)

    return tmp


def find_parser(name, flags=re.IGNORECASE):
    if re.match(r'fdeploy1\.ini$', name, flags=flags):
        return GPFDeploy1IniParser()
    if re.match(r'audit\.csv$', name, flags=flags):
        return GPAuditCsvParser()
    if re.match(r'GptTmpl\.inf$', name, flags=flags):
        return GptTmplInfParser()
    if re.match(r'GPT\.INI$', name, flags=flags):
        return GPTIniParser()
    if re.match(r'scripts\.ini$', name, flags=flags):
        return GPScriptsIniParser()
    if re.match(r'psscripts\.ini$', name, flags=flags):
        return GPScriptsIniParser()
    if re.match(r'GPE\.INI$', name, flags=flags):
        # This file does not appear in the protocol specifications!
        #
        # It appears to be a legacy file used to maintain gPCUserExtensionNames
        # and gPCMachineExtensionNames. We should just copy the file as binary.
        return GPParser()
    if re.match(r'.*\.ini$', name, flags=flags):
        return GPIniParser()
    if re.match(r'.*\.pol$', name, flags=flags):
        return GPPolParser()
    if re.match(r'.*\.aas$', name, flags=flags):
        return GPAasParser()

    return GPParser()


def backup_directory_remote_to_local(conn, remotedir, localdir):
    SUFFIX = '.SAMBABACKUP'
    if not os.path.isdir(localdir):
        os.mkdir(localdir)
    r_dirs = [ remotedir ]
    l_dirs = [ localdir ]
    while r_dirs:
        r_dir = r_dirs.pop()
        l_dir = l_dirs.pop()

        dirlist = conn.list(r_dir, attribs=attr_flags)
        dirlist.sort(key=lambda x : x['name'])
        for e in dirlist:
            r_name = r_dir + '\\' + e['name']
            l_name = os.path.join(l_dir, e['name'])

            if e['attrib'] & libsmb.FILE_ATTRIBUTE_DIRECTORY:
                r_dirs.append(r_name)
                l_dirs.append(l_name)
                os.mkdir(l_name)
            else:
                data = conn.loadfile(r_name)
                with open(l_name + SUFFIX, 'wb') as f:
                    f.write(data)

                parser = find_parser(e['name'])
                parser.parse(data)
                parser.write_xml(l_name + '.xml')


attr_flags = libsmb.FILE_ATTRIBUTE_SYSTEM | \
             libsmb.FILE_ATTRIBUTE_DIRECTORY | \
             libsmb.FILE_ATTRIBUTE_ARCHIVE | \
             libsmb.FILE_ATTRIBUTE_HIDDEN


def copy_directory_remote_to_local(conn, remotedir, localdir):
    if not os.path.isdir(localdir):
        os.mkdir(localdir)
    r_dirs = [remotedir]
    l_dirs = [localdir]
    while r_dirs:
        r_dir = r_dirs.pop()
        l_dir = l_dirs.pop()

        dirlist = conn.list(r_dir, attribs=attr_flags)
        dirlist.sort(key=lambda x : x['name'])
        for e in dirlist:
            r_name = r_dir + '\\' + e['name']
            l_name = os.path.join(l_dir, e['name'])

            if e['attrib'] & libsmb.FILE_ATTRIBUTE_DIRECTORY:
                r_dirs.append(r_name)
                l_dirs.append(l_name)
                os.mkdir(l_name)
            else:
                data = conn.loadfile(r_name)
                open(l_name, 'wb').write(data)


def copy_directory_local_to_remote(conn, localdir, remotedir,
                                   ignore_existing_dir=False,
                                   keep_existing_files=False):
    if not conn.chkpath(remotedir):
        conn.mkdir(remotedir)
    l_dirs = [localdir]
    r_dirs = [remotedir]
    while l_dirs:
        l_dir = l_dirs.pop()
        r_dir = r_dirs.pop()

        dirlist = os.listdir(l_dir)
        dirlist.sort()
        for e in dirlist:
            l_name = os.path.join(l_dir, e)
            r_name = r_dir + '\\' + e

            if os.path.isdir(l_name):
                l_dirs.append(l_name)
                r_dirs.append(r_name)
                try:
                    conn.mkdir(r_name)
                except NTSTATUSError:
                    if not ignore_existing_dir:
                        raise
            else:
                if keep_existing_files:
                    try:
                        conn.loadfile(r_name)
                        continue
                    except NTSTATUSError:
                        pass

                data = open(l_name, 'rb').read()
                conn.savefile(r_name, data)


class GPOCommand(Command):
    def construct_tmpdir(self, tmpdir, gpo):
        """Ensure that the temporary directory structure used in fetch,
        backup, create, and restore is consistent.

        If --tmpdir is used the named directory must be present, which may
        contain a 'policy' subdirectory, but 'policy' must not itself have
        a subdirectory with the gpo name. The policy and gpo directories
        will be created.

        If --tmpdir is not used, a temporary directory is securely created.
        """
        if tmpdir is None:
            tmpdir = tempfile.mkdtemp()
            print("Using temporary directory %s (use --tmpdir to change)" % tmpdir,
                  file=self.outf)

        if not os.path.isdir(tmpdir):
            raise CommandError("Temporary directory '%s' does not exist" % tmpdir)

        localdir = os.path.join(tmpdir, "policy")
        if not os.path.isdir(localdir):
            os.mkdir(localdir)

        gpodir = os.path.join(localdir, gpo)
        if os.path.isdir(gpodir):
            raise CommandError(
                "GPO directory '%s' already exists, refusing to overwrite" % gpodir)

        try:
            os.mkdir(gpodir)
        except (IOError, OSError) as e:
            raise CommandError("Error creating teporary GPO directory", e)

        return tmpdir, gpodir

    def samdb_connect(self):
        """make a ldap connection to the server"""
        try:
            self.samdb = SamDB(url=self.url,
                               session_info=system_session(),
                               credentials=self.creds, lp=self.lp)
        except Exception as e:
            raise CommandError("LDAP connection to %s failed " % self.url, e)


class cmd_listall(GPOCommand):
    """List all GPOs."""

    synopsis = "%prog [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H")
    ]

    def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        msg = get_gpo_info(self.samdb, None)

        for m in msg:
            self.outf.write("GPO          : %s\n" % m['name'][0])
            self.outf.write("display name : %s\n" % m['displayName'][0])
            self.outf.write("path         : %s\n" % m['gPCFileSysPath'][0])
            self.outf.write("dn           : %s\n" % m.dn)
            self.outf.write("version      : %s\n" % attr_default(m, 'versionNumber', '0'))
            self.outf.write("flags        : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
            self.outf.write("\n")


class cmd_list(GPOCommand):
    """List GPOs for an account."""

    synopsis = "%prog <username|machinename> [options]"

    takes_args = ['accountname']
    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server",
               type=str, metavar="URL", dest="H")
    ]

    def run(self, accountname, H=None, sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        try:
            msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
                                    (ldb.binary_encode(accountname), ldb.binary_encode(accountname)))
            user_dn = msg[0].dn
        except Exception:
            raise CommandError("Failed to find account %s" % accountname)

        # check if its a computer account
        try:
            msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
            is_computer = 'computer' in msg['objectClass']
        except Exception:
            raise CommandError("Failed to find objectClass for %s" % accountname)

        session_info_flags = (AUTH_SESSION_INFO_DEFAULT_GROUPS |
                              AUTH_SESSION_INFO_AUTHENTICATED)

        # When connecting to a remote server, don't look up the local privilege DB
        if self.url is not None and self.url.startswith('ldap'):
            session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES

        session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
                                          session_info_flags=session_info_flags)

        token = session.security_token

        gpos = []

        inherit = True
        dn = ldb.Dn(self.samdb, str(user_dn)).parent()
        while True:
            msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
            if 'gPLink' in msg:
                glist = parse_gplink(str(msg['gPLink'][0]))
                for g in glist:
                    if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
                        continue
                    if g['options'] & dsdb.GPLINK_OPT_DISABLE:
                        continue

                    try:
                        sd_flags = (security.SECINFO_OWNER |
                                    security.SECINFO_GROUP |
                                    security.SECINFO_DACL)
                        gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
                                                 attrs=['name', 'displayName', 'flags',
                                                        'nTSecurityDescriptor'],
                                                 controls=['sd_flags:1:%d' % sd_flags])
                        secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
                        secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
                    except Exception:
                        self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
                                        g['dn'])
                        continue

                    try:
                        samba.security.access_check(secdesc, token,
                                                    security.SEC_STD_READ_CONTROL |
                                                    security.SEC_ADS_LIST |
                                                    security.SEC_ADS_READ_PROP)
                    except RuntimeError:
                        self.outf.write("Failed access check on %s\n" % msg.dn)
                        continue

                    # check the flags on the GPO
                    flags = int(attr_default(gmsg[0], 'flags', 0))
                    if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
                        continue
                    if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
                        continue
                    gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))

            # check if this blocks inheritance
            gpoptions = int(attr_default(msg, 'gPOptions', 0))
            if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
                inherit = False

            if dn == self.samdb.get_default_basedn():
                break
            dn = dn.parent()

        if is_computer:
            msg_str = 'computer'
        else:
            msg_str = 'user'

        self.outf.write("GPOs for %s %s\n" % (msg_str, accountname))
        for g in gpos:
            self.outf.write("    %s %s\n" % (g[0], g[1]))


class cmd_show(GPOCommand):
    """Show information for a GPO."""

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str)
    ]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()

        try:
            msg = get_gpo_info(self.samdb, gpo)[0]
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)

        try:
            secdesc_ndr = msg['nTSecurityDescriptor'][0]
            secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
            secdesc_sddl = secdesc.as_sddl()
        except Exception:
            secdesc_sddl = "<hidden>"

        self.outf.write("GPO          : %s\n" % msg['name'][0])
        self.outf.write("display name : %s\n" % msg['displayName'][0])
        self.outf.write("path         : %s\n" % msg['gPCFileSysPath'][0])
        if 'gPCMachineExtensionNames' in msg:
            self.outf.write("Machine Exts : %s\n" % msg['gPCMachineExtensionNames'][0])
        if 'gPCUserExtensionNames' in msg:
            self.outf.write("User Exts    : %s\n" % msg['gPCUserExtensionNames'][0])
        self.outf.write("dn           : %s\n" % msg.dn)
        self.outf.write("version      : %s\n" % attr_default(msg, 'versionNumber', '0'))
        self.outf.write("flags        : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
        self.outf.write("ACL          : %s\n" % secdesc_sddl)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        pol_file = '\\'.join([realm.lower(), 'Policies', gpo,
                                '%s\\Registry.pol'])
        policy_defs = []
        for policy_class in ['MACHINE', 'USER']:
            try:
                pol_data = ndr_unpack(preg.file,
                                      conn.loadfile(pol_file % policy_class))
            except NTSTATUSError as e:
                if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                                 NT_STATUS_OBJECT_NAME_NOT_FOUND,
                                 NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                    continue # The file doesn't exist, so there is nothing to list
                if e.args[0] == NT_STATUS_ACCESS_DENIED:
                    raise CommandError("The authenticated user does "
                                       "not have sufficient privileges")
                raise

            for entry in pol_data.entries:
                if entry.valuename == "**delvals.":
                    continue
                defs = {}
                defs['keyname'] = entry.keyname
                defs['valuename'] = entry.valuename
                defs['class'] = policy_class
                defs['type'] = str_regtype(entry.type)
                defs['data'] = entry.data
                # Bytes aren't JSON serializable
                if type(defs['data']) == bytes:
                    if entry.type == REG_MULTI_SZ:
                        data = defs['data'].decode('utf-16-le')
                        defs['data'] = data.rstrip('\x00').split('\x00')
                    else:
                        defs['data'] = list(defs['data'])
                policy_defs.append(defs)
        self.outf.write("Policies     :\n")
        json.dump(policy_defs, self.outf, indent=4)
        self.outf.write("\n")


class cmd_load(GPOCommand):
    """Load policies onto a GPO.

    Reads json from standard input until EOF, unless a json formatted
    file is provided via --content.

    Example json_input:
    [
        {
            "keyname": "Software\\Policies\\Mozilla\\Firefox\\Homepage",
            "valuename": "StartPage",
            "class": "USER",
            "type": "REG_SZ",
            "data": "homepage"
        },
        {
            "keyname": "Software\\Policies\\Mozilla\\Firefox\\Homepage",
            "valuename": "URL",
            "class": "USER",
            "type": "REG_SZ",
            "data": "google.com"
        },
        {
            "keyname": "Software\\Microsoft\\Internet Explorer\\Toolbar",
            "valuename": "IEToolbar",
            "class": "USER",
            "type": "REG_BINARY",
            "data": [0]
        },
        {
            "keyname": "Software\\Policies\\Microsoft\\InputPersonalization",
            "valuename": "RestrictImplicitTextCollection",
            "class": "USER",
            "type": "REG_DWORD",
            "data": 1
        }
    ]

    Valid class attributes: MACHINE|USER|BOTH
    Data arrays are interpreted as bytes.

    The --machine-ext-name and --user-ext-name options are multi-value inputs
    which respectively set the gPCMachineExtensionNames and gPCUserExtensionNames
    ldap attributes on the GPO. These attributes must be set to the correct GUID
    names for Windows Group Policy to work correctly. These GUIDs represent
    the client side extensions to apply on the machine. Linux Group Policy does
    not enforce this constraint.
    {35378EAC-683F-11D2-A89A-00C04FBBCFA2} is provided by default, which
    enables most Registry policies.
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--content", help="JSON file of policy inputs", type=str),
        Option("--machine-ext-name",
            action="append", dest="machine_exts",
            default=['{35378EAC-683F-11D2-A89A-00C04FBBCFA2}'],
            help="A machine extension name to add to gPCMachineExtensionNames"),
        Option("--user-ext-name",
            action="append", dest="user_exts",
            default=['{35378EAC-683F-11D2-A89A-00C04FBBCFA2}'],
            help="A user extension name to add to gPCUserExtensionNames"),
        Option("--replace", action='store_true', default=False,
               help="Replace the existing Group Policies, rather than merging")
    ]

    def run(self, gpo, H=None, content=None,
            machine_exts=None,
            user_exts=None,
            replace=False, sambaopts=None, credopts=None, versionopts=None):
        if machine_exts is None:
            machine_exts = ['{35378EAC-683F-11D2-A89A-00C04FBBCFA2}']
        if user_exts is None:
            user_exts = ['{35378EAC-683F-11D2-A89A-00C04FBBCFA2}']
        if content is None:
            policy_defs = json.loads(sys.stdin.read())
        elif os.path.exists(content):
            with open(content, 'rb') as r:
                policy_defs = json.load(r)
        else:
            raise CommandError("The JSON content file does not exist")

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
        self.url = dc_url(self.lp, self.creds, H)
        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)
        for ext_name in machine_exts:
            reg.register_extension_name(ext_name, 'gPCMachineExtensionNames')
        for ext_name in user_exts:
            reg.register_extension_name(ext_name, 'gPCUserExtensionNames')
        try:
            if replace:
                reg.replace_s(policy_defs)
            else:
                reg.merge_s(policy_defs)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise


class cmd_remove(GPOCommand):
    """Remove policies from a GPO.

    Reads json from standard input until EOF, unless a json formatted
    file is provided via --content.

    Example json_input:
    [
        {
            "keyname": "Software\\Policies\\Mozilla\\Firefox\\Homepage",
            "valuename": "StartPage",
            "class": "USER",
        },
        {
            "keyname": "Software\\Policies\\Mozilla\\Firefox\\Homepage",
            "valuename": "URL",
            "class": "USER",
        },
        {
            "keyname": "Software\\Microsoft\\Internet Explorer\\Toolbar",
            "valuename": "IEToolbar",
            "class": "USER"
        },
        {
            "keyname": "Software\\Policies\\Microsoft\\InputPersonalization",
            "valuename": "RestrictImplicitTextCollection",
            "class": "USER"
        }
    ]

    Valid class attributes: MACHINE|USER|BOTH
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--content", help="JSON file of policy inputs", type=str),
        Option("--machine-ext-name",
            action="append", default=[], dest="machine_exts",
            help="A machine extension name to remove from gPCMachineExtensionNames"),
        Option("--user-ext-name",
            action="append", default=[], dest="user_exts",
            help="A user extension name to remove from gPCUserExtensionNames")
    ]

    def run(self, gpo, H=None, content=None, machine_exts=None, user_exts=None,
            sambaopts=None, credopts=None, versionopts=None):
        if machine_exts is None:
            machine_exts = []
        if user_exts is None:
            user_exts = []
        if content is None:
            policy_defs = json.loads(sys.stdin.read())
        elif os.path.exists(content):
            with open(content, 'rb') as r:
                policy_defs = json.load(r)
        else:
            raise CommandError("The JSON content file does not exist")

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
        self.url = dc_url(self.lp, self.creds, H)
        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)
        for ext_name in machine_exts:
            reg.unregister_extension_name(ext_name, 'gPCMachineExtensionNames')
        for ext_name in user_exts:
            reg.unregister_extension_name(ext_name, 'gPCUserExtensionNames')
        try:
            reg.remove_s(policy_defs)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise


class cmd_getlink(GPOCommand):
    """List GPO Links for a container."""

    synopsis = "%prog <container_dn> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['container_dn']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str)
    ]

    def run(self, container_dn, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        try:
            msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
                                    expression="(objectClass=*)",
                                    attrs=['gPLink'])[0]
        except Exception:
            raise CommandError("Container '%s' does not exist" % container_dn)

        if 'gPLink' in msg and msg['gPLink']:
            self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
            gplist = parse_gplink(str(msg['gPLink'][0]))
            for g in gplist:
                msg = get_gpo_info(self.samdb, dn=g['dn'])
                self.outf.write("    GPO     : %s\n" % msg[0]['name'][0])
                self.outf.write("    Name    : %s\n" % msg[0]['displayName'][0])
                self.outf.write("    Options : %s\n" % gplink_options_string(g['options']))
                self.outf.write("\n")
        else:
            self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)


class cmd_setlink(GPOCommand):
    """Add or update a GPO link to a container."""

    synopsis = "%prog <container_dn> <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['container_dn', 'gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--disable", dest="disabled", default=False, action='store_true',
               help="Disable policy"),
        Option("--enforce", dest="enforced", default=False, action='store_true',
               help="Enforce policy")
    ]

    def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
            sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        gplink_options = 0
        if disabled:
            gplink_options |= dsdb.GPLINK_OPT_DISABLE
        if enforced:
            gplink_options |= dsdb.GPLINK_OPT_ENFORCE

        # Check if valid GPO DN
        try:
            get_gpo_info(self.samdb, gpo=gpo)[0]
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)
        gpo_dn = str(get_gpo_dn(self.samdb, gpo))

        # Check if valid Container DN
        try:
            msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
                                    expression="(objectClass=*)",
                                    attrs=['gPLink'])[0]
        except Exception:
            raise CommandError("Container '%s' does not exist" % container_dn)

        # Update existing GPlinks or Add new one
        existing_gplink = False
        if 'gPLink' in msg:
            gplist = parse_gplink(str(msg['gPLink'][0]))
            existing_gplink = True
            found = False
            for g in gplist:
                if g['dn'].lower() == gpo_dn.lower():
                    g['options'] = gplink_options
                    found = True
                    break
            if found:
                raise CommandError("GPO '%s' already linked to this container" % gpo)
            else:
                gplist.insert(0, {'dn': gpo_dn, 'options': gplink_options})
        else:
            gplist = []
            gplist.append({'dn': gpo_dn, 'options': gplink_options})

        gplink_str = encode_gplink(gplist)

        m = ldb.Message()
        m.dn = ldb.Dn(self.samdb, container_dn)

        if existing_gplink:
            m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
        else:
            m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')

        try:
            self.samdb.modify(m)
        except Exception as e:
            raise CommandError("Error adding GPO Link", e)

        self.outf.write("Added/Updated GPO link\n")
        cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)


class cmd_dellink(GPOCommand):
    """Delete GPO link from a container."""

    synopsis = "%prog <container_dn> <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['container', 'gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
    ]

    def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        # Check if valid GPO
        try:
            get_gpo_info(self.samdb, gpo=gpo)[0]
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)

        container_dn = ldb.Dn(self.samdb, container)
        del_gpo_link(self.samdb, container_dn, gpo)
        self.outf.write("Deleted GPO link.\n")
        cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)


class cmd_listcontainers(GPOCommand):
    """List all linked containers for a GPO."""

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str)
    ]

    def run(self, gpo, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        msg = get_gpo_containers(self.samdb, gpo)
        if len(msg):
            self.outf.write("Container(s) using GPO %s\n" % gpo)
            for m in msg:
                self.outf.write("    DN: %s\n" % m['dn'])
        else:
            self.outf.write("No Containers using GPO %s\n" % gpo)


class cmd_getinheritance(GPOCommand):
    """Get inheritance flag for a container."""

    synopsis = "%prog <container_dn> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['container_dn']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str)
    ]

    def run(self, container_dn, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()

        try:
            msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
                                    expression="(objectClass=*)",
                                    attrs=['gPOptions'])[0]
        except Exception:
            raise CommandError("Container '%s' does not exist" % container_dn)

        inheritance = 0
        if 'gPOptions' in msg:
            inheritance = int(msg['gPOptions'][0])

        if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
            self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
        else:
            self.outf.write("Container has GPO_INHERIT\n")


class cmd_setinheritance(GPOCommand):
    """Set inheritance flag on a container."""

    synopsis = "%prog <container_dn> <block|inherit> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['container_dn', 'inherit_state']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str)
    ]

    def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        if inherit_state.lower() == 'block':
            inheritance = dsdb.GPO_BLOCK_INHERITANCE
        elif inherit_state.lower() == 'inherit':
            inheritance = dsdb.GPO_INHERIT
        else:
            raise CommandError("Unknown inheritance state (%s)" % inherit_state)

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        self.samdb_connect()
        try:
            msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
                                    expression="(objectClass=*)",
                                    attrs=['gPOptions'])[0]
        except Exception:
            raise CommandError("Container '%s' does not exist" % container_dn)

        m = ldb.Message()
        m.dn = ldb.Dn(self.samdb, container_dn)

        if 'gPOptions' in msg:
            m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
        else:
            m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')

        try:
            self.samdb.modify(m)
        except Exception as e:
            raise CommandError("Error setting inheritance state %s" % inherit_state, e)


class cmd_fetch(GPOCommand):
    """Download a GPO."""

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
    ]

    def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()
        try:
            msg = get_gpo_info(self.samdb, gpo)[0]
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)

        # verify UNC path
        unc = str(msg['gPCFileSysPath'][0])
        try:
            [dom_name, service, sharepath] = parse_unc(unc)
        except ValueError:
            raise CommandError("Invalid GPO path (%s)" % unc)

        # SMB connect to DC
        conn = smb_connection(dc_hostname, service, lp=self.lp,
                              creds=self.creds)

        # Copy GPT
        tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)

        try:
            copy_directory_remote_to_local(conn, sharepath, gpodir)
        except Exception as e:
            # FIXME: Catch more specific exception
            raise CommandError("Error copying GPO from DC", e)
        self.outf.write('GPO copied to %s\n' % gpodir)


class cmd_backup(GPOCommand):
    """Backup a GPO."""

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
        Option("--generalize", help="Generalize XML entities to restore",
               default=False, action='store_true'),
        Option("--entities", help="File to export defining XML entities for the restore",
               dest='ent_file', type=str)
    ]

    def run(self, gpo, H=None, tmpdir=None, generalize=False, sambaopts=None,
            credopts=None, versionopts=None, ent_file=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()
        try:
            msg = get_gpo_info(self.samdb, gpo)[0]
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)

        # verify UNC path
        unc = str(msg['gPCFileSysPath'][0])
        try:
            [dom_name, service, sharepath] = parse_unc(unc)
        except ValueError:
            raise CommandError("Invalid GPO path (%s)" % unc)

        # SMB connect to DC
        conn = smb_connection(dc_hostname, service, lp=self.lp,
                              creds=self.creds)

        # Copy GPT
        tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)

        try:
            backup_directory_remote_to_local(conn, sharepath, gpodir)
        except Exception as e:
            # FIXME: Catch more specific exception
            raise CommandError("Error copying GPO from DC", e)

        self.outf.write('GPO copied to %s\n' % gpodir)

        if generalize:
            self.outf.write('\nAttempting to generalize XML entities:\n')
            entities = cmd_backup.generalize_xml_entities(self.outf, gpodir,
                                                          gpodir)
            import operator
            ents = "".join('<!ENTITY {} "{}\n">'.format(ent[1].strip('&;'), ent[0]) \
                             for ent in sorted(entities.items(), key=operator.itemgetter(1)))

            if ent_file:
                with open(ent_file, 'w') as f:
                    f.write(ents)
                self.outf.write('Entities successfully written to %s\n' %
                                ent_file)
            else:
                self.outf.write('\nEntities:\n')
                self.outf.write(ents)

        # Backup the enabled GPO extension names
        for ext in ('gPCMachineExtensionNames', 'gPCUserExtensionNames'):
            if ext in msg:
                with open(os.path.join(gpodir, ext + '.SAMBAEXT'), 'wb') as f:
                    f.write(msg[ext][0])

    @staticmethod
    def generalize_xml_entities(outf, sourcedir, targetdir):
        entities = {}

        if not os.path.exists(targetdir):
            os.mkdir(targetdir)

        l_dirs = [ sourcedir ]
        r_dirs = [ targetdir ]
        while l_dirs:
            l_dir = l_dirs.pop()
            r_dir = r_dirs.pop()

            dirlist = os.listdir(l_dir)
            dirlist.sort()
            for e in dirlist:
                l_name = os.path.join(l_dir, e)
                r_name = os.path.join(r_dir, e)

                if os.path.isdir(l_name):
                    l_dirs.append(l_name)
                    r_dirs.append(r_name)
                    if not os.path.exists(r_name):
                        os.mkdir(r_name)
                else:
                    if l_name.endswith('.xml'):
                        # Restore the xml file if possible

                        # Get the filename to find the parser
                        to_parse = os.path.basename(l_name)[:-4]

                        parser = find_parser(to_parse)
                        try:
                            with open(l_name, 'r') as ltemp:
                                data = ltemp.read()

                            concrete_xml = ET.fromstring(data)
                            found_entities = parser.generalize_xml(concrete_xml, r_name, entities)
                        except GPGeneralizeException:
                            outf.write('SKIPPING: Generalizing failed for %s\n' % to_parse)

                    else:
                        # No need to generalize non-xml files.
                        #
                        # TODO This could be improved with xml files stored in
                        # the renamed backup file (with custom extension) by
                        # inlining them into the exported backups.
                        if not os.path.samefile(l_name, r_name):
                            shutil.copy2(l_name, r_name)

        return entities


class cmd_create(GPOCommand):
    """Create an empty GPO."""

    synopsis = "%prog <displayname> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['displayname']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
    ]

    def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        net = Net(creds=self.creds, lp=self.lp)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
            flags = (nbt.NBT_SERVER_LDAP |
                     nbt.NBT_SERVER_DS |
                     nbt.NBT_SERVER_WRITABLE)
            cldap_ret = net.finddc(address=dc_hostname, flags=flags)
        else:
            flags = (nbt.NBT_SERVER_LDAP |
                     nbt.NBT_SERVER_DS |
                     nbt.NBT_SERVER_WRITABLE)
            cldap_ret = net.finddc(domain=self.lp.get('realm'), flags=flags)
            dc_hostname = cldap_ret.pdc_dns_name
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()

        msg = get_gpo_info(self.samdb, displayname=displayname)
        if msg.count > 0:
            raise CommandError("A GPO already existing with name '%s'" % displayname)

        # Create new GUID
        guid  = str(uuid.uuid4())
        gpo = "{%s}" % guid.upper()

        self.gpo_name = gpo

        realm = cldap_ret.dns_domain
        unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)

        # Create GPT
        self.tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)
        self.gpodir = gpodir

        try:
            os.mkdir(os.path.join(gpodir, "Machine"))
            os.mkdir(os.path.join(gpodir, "User"))
            gpt_contents = "[General]\r\nVersion=0\r\n"
            open(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
        except Exception as e:
            raise CommandError("Error Creating GPO files", e)

        # Connect to DC over SMB
        [dom_name, service, sharepath] = parse_unc(unc_path)
        self.sharepath = sharepath
        conn = smb_connection(dc_hostname, service, lp=self.lp,
                              creds=self.creds)

        self.conn = conn

        self.samdb.transaction_start()
        try:
            # Add cn=<guid>
            gpo_dn = get_gpo_dn(self.samdb, gpo)

            m = ldb.Message()
            m.dn = gpo_dn
            m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
            self.samdb.add(m)

            # Add cn=User,cn=<guid>
            m = ldb.Message()
            m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
            m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
            self.samdb.add(m)

            # Add cn=Machine,cn=<guid>
            m = ldb.Message()
            m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
            m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
            self.samdb.add(m)

            # Get new security descriptor
            ds_sd_flags = (security.SECINFO_OWNER |
                           security.SECINFO_GROUP |
                           security.SECINFO_DACL)
            msg = get_gpo_info(self.samdb, gpo=gpo, sd_flags=ds_sd_flags)[0]
            ds_sd_ndr = msg['nTSecurityDescriptor'][0]
            ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()

            # Create a file system security descriptor
            domain_sid = security.dom_sid(self.samdb.get_domain_sid())
            sddl = dsacl2fsacl(ds_sd, domain_sid)
            fs_sd = security.descriptor.from_sddl(sddl, domain_sid)

            # Copy GPO directory
            create_directory_hier(conn, sharepath)

            # Set ACL
            sio = (security.SECINFO_OWNER |
                   security.SECINFO_GROUP |
                   security.SECINFO_DACL |
                   security.SECINFO_PROTECTED_DACL)
            conn.set_acl(sharepath, fs_sd, sio)

            # Copy GPO files over SMB
            copy_directory_local_to_remote(conn, gpodir, sharepath)

            m = ldb.Message()
            m.dn = gpo_dn
            m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_REPLACE, "displayName")
            m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_REPLACE, "gPCFileSysPath")
            m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "versionNumber")
            m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_REPLACE, "gpcFunctionalityVersion")
            m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "flags")
            controls = ["permissive_modify:0"]
            self.samdb.modify(m, controls=controls)
        except Exception:
            self.samdb.transaction_cancel()
            raise
        else:
            self.samdb.transaction_commit()

        if tmpdir is None:
            # Without --tmpdir, we created one in /tmp/. It must go.
            shutil.rmtree(self.tmpdir)

        self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))


class cmd_restore(cmd_create):
    """Restore a GPO to a new container."""

    synopsis = "%prog <displayname> <backup location> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['displayname', 'backup']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
        Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
        Option("--entities", help="File defining XML entities to insert into DOCTYPE header", type=str),
        Option("--restore-metadata", help="Keep the old GPT.INI file and associated version number",
               default=False, action="store_true")
    ]

    def restore_from_backup_to_local_dir(self, sourcedir, targetdir, dtd_header=''):
        SUFFIX = '.SAMBABACKUP'

        if not os.path.exists(targetdir):
            os.mkdir(targetdir)

        l_dirs = [ sourcedir ]
        r_dirs = [ targetdir ]
        while l_dirs:
            l_dir = l_dirs.pop()
            r_dir = r_dirs.pop()

            dirlist = os.listdir(l_dir)
            dirlist.sort()
            for e in dirlist:
                l_name = os.path.join(l_dir, e)
                r_name = os.path.join(r_dir, e)

                if os.path.isdir(l_name):
                    l_dirs.append(l_name)
                    r_dirs.append(r_name)
                    if not os.path.exists(r_name):
                        os.mkdir(r_name)
                else:
                    if l_name.endswith('.xml'):
                        # Restore the xml file if possible

                        # Get the filename to find the parser
                        to_parse = os.path.basename(l_name)[:-4]

                        parser = find_parser(to_parse)
                        try:
                            with open(l_name, 'r') as ltemp:
                                data = ltemp.read()
                                xml_head = '<?xml version="1.0" encoding="utf-8"?>'

                                if data.startswith(xml_head):
                                    # It appears that sometimes the DTD rejects
                                    # the xml header being after it.
                                    data = data[len(xml_head):]

                                    # Load the XML file with the DTD (entity) header
                                    parser.load_xml(ET.fromstring(xml_head + dtd_header + data))
                                else:
                                    parser.load_xml(ET.fromstring(dtd_header + data))

                                # Write out the substituted files in the output
                                # location, ready to copy over.
                                parser.write_binary(r_name[:-4])

                        except GPNoParserException:
                            # In the failure case, we fallback
                            original_file = l_name[:-4] + SUFFIX
                            shutil.copy2(original_file, r_name[:-4])

                            self.outf.write('WARNING: No such parser for %s\n' % to_parse)
                            self.outf.write('WARNING: Falling back to simple copy-restore.\n')
                        except:
                            import traceback
                            traceback.print_exc()

                            # In the failure case, we fallback
                            original_file = l_name[:-4] + SUFFIX
                            shutil.copy2(original_file, r_name[:-4])

                            self.outf.write('WARNING: Error during parsing for %s\n' % l_name)
                            self.outf.write('WARNING: Falling back to simple copy-restore.\n')

    def run(self, displayname, backup, H=None, tmpdir=None, entities=None, sambaopts=None, credopts=None,
            versionopts=None, restore_metadata=None):

        dtd_header = ''

        if not os.path.exists(backup):
            raise CommandError("Backup directory does not exist %s" % backup)

        if entities is not None:
            # DOCTYPE name is meant to match root element, but ElementTree does
            # not seem to care, so this seems to be enough.

            dtd_header = '<!DOCTYPE foobar [\n'

            if not os.path.exists(entities):
                raise CommandError("Entities file does not exist %s" %
                                   entities)
            with open(entities, 'r') as entities_file:
                entities_content = entities_file.read()

                # Do a basic regex test of the entities file format
                if re.match(r'(\s*<!ENTITY\s*[a-zA-Z0-9_]+\s*.*?>)+\s*\Z',
                            entities_content, flags=re.MULTILINE) is None:
                    raise CommandError("Entities file does not appear to "
                                       "conform to format\n"
                                       'e.g. <!ENTITY entity "value">')
                dtd_header += entities_content.strip()

            dtd_header += '\n]>\n'

        super().run(displayname, H, tmpdir, sambaopts, credopts, versionopts)

        try:
            if tmpdir is None:
                # Create GPT
                self.tmpdir, gpodir = self.construct_tmpdir(tmpdir, self.gpo_name)
                self.gpodir = gpodir

            # Iterate over backup files and restore with DTD
            self.restore_from_backup_to_local_dir(backup, self.gpodir,
                                                  dtd_header)

            keep_new_files = not restore_metadata

            # Copy GPO files over SMB
            copy_directory_local_to_remote(self.conn, self.gpodir,
                                           self.sharepath,
                                           ignore_existing_dir=True,
                                           keep_existing_files=keep_new_files)

            gpo_dn = get_gpo_dn(self.samdb, self.gpo_name)

            # Restore the enabled extensions
            for ext in ('gPCMachineExtensionNames', 'gPCUserExtensionNames'):
                ext_file = os.path.join(backup, ext + '.SAMBAEXT')
                if os.path.exists(ext_file):
                    with open(ext_file, 'rb') as f:
                        data = f.read()

                    m = ldb.Message()
                    m.dn = gpo_dn
                    m[ext] = ldb.MessageElement(data, ldb.FLAG_MOD_REPLACE,
                                                ext)

                    self.samdb.modify(m)

            if tmpdir is None:
                # Without --tmpdir, we created one in /tmp/. It must go.
                shutil.rmtree(self.tmpdir)

        except Exception as e:
            import traceback
            traceback.print_exc()
            self.outf.write(str(e) + '\n')

            self.outf.write("Failed to restore GPO -- deleting...\n")
            cmd = cmd_del()
            cmd.run(self.gpo_name, H, sambaopts, credopts, versionopts)

            raise CommandError("Failed to restore: %s" % e)


class cmd_del(GPOCommand):
    """Delete a GPO."""

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ['gpo']

    takes_options = [
        Option("-H", help="LDB URL for database or target server", type=str),
    ]

    def run(self, gpo, H=None, sambaopts=None, credopts=None,
            versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()

        # Check if valid GPO
        try:
            msg = get_gpo_info(self.samdb, gpo=gpo)[0]
            unc_path = str(msg['gPCFileSysPath'][0])
        except Exception:
            raise CommandError("GPO '%s' does not exist" % gpo)

        # Connect to DC over SMB
        [dom_name, service, sharepath] = parse_unc(unc_path)
        conn = smb_connection(dc_hostname, service, lp=self.lp,
                              creds=self.creds)

        self.samdb.transaction_start()
        try:
            # Check for existing links
            msg = get_gpo_containers(self.samdb, gpo)

            if len(msg):
                self.outf.write("GPO %s is linked to containers\n" % gpo)
                for m in msg:
                    del_gpo_link(self.samdb, m['dn'], gpo)
                    self.outf.write("    Removed link from %s.\n" % m['dn'])

            # Remove LDAP entries
            gpo_dn = get_gpo_dn(self.samdb, gpo)
            self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
            self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
            self.samdb.delete(gpo_dn)

            # Remove GPO files
            conn.deltree(sharepath)

        except Exception:
            self.samdb.transaction_cancel()
            raise
        else:
            self.samdb.transaction_commit()

        self.outf.write("GPO %s deleted.\n" % gpo)


class cmd_aclcheck(GPOCommand):
    """Check all GPOs have matching LDAP and DS ACLs."""

    synopsis = "%prog [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H")
    ]

    def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        self.url = dc_url(self.lp, self.creds, H)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        self.samdb_connect()

        msg = get_gpo_info(self.samdb, None)

        for m in msg:
            # verify UNC path
            unc = str(m['gPCFileSysPath'][0])
            try:
                [dom_name, service, sharepath] = parse_unc(unc)
            except ValueError:
                raise CommandError("Invalid GPO path (%s)" % unc)

            # SMB connect to DC
            conn = smb_connection(dc_hostname, service, lp=self.lp,
                                  creds=self.creds)

            fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)

            if 'nTSecurityDescriptor' not in m:
                raise CommandError("Could not read nTSecurityDescriptor. "
                                   "This requires an Administrator account")

            ds_sd_ndr = m['nTSecurityDescriptor'][0]
            ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()

            # Create a file system security descriptor
            domain_sid = security.dom_sid(self.samdb.get_domain_sid())
            expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)

            if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
                raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))

class cmd_admxload(Command):
    """Loads samba admx files to sysvol"""

    synopsis = "%prog [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
        Option("--admx-dir", help="Directory where admx templates are stored",
                type=str, default=os.path.join(param.data_dir(), 'samba/admx'))
    ]

    def run(self, H=None, sambaopts=None, credopts=None, versionopts=None,
            admx_dir=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        smb_dir = '\\'.join([self.lp.get('realm').lower(),
                             'Policies', 'PolicyDefinitions'])
        try:
            conn.mkdir(smb_dir)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            elif e.args[0] != NT_STATUS_OBJECT_NAME_COLLISION:
                raise

        for dirname, dirs, files in os.walk(admx_dir):
            for fname in files:
                path_in_admx = dirname.replace(admx_dir, '')
                full_path = os.path.join(dirname, fname)
                sub_dir = '\\'.join([smb_dir, path_in_admx]).replace('/', '\\')
                smb_path = '\\'.join([sub_dir, fname])
                try:
                    create_directory_hier(conn, sub_dir)
                except NTSTATUSError as e:
                    if e.args[0] == NT_STATUS_ACCESS_DENIED:
                        raise CommandError("The authenticated user does "
                                           "not have sufficient privileges")
                    elif e.args[0] != NT_STATUS_OBJECT_NAME_COLLISION:
                        raise
                with open(full_path, 'rb') as f:
                    try:
                        conn.savefile(smb_path, f.read())
                    except NTSTATUSError as e:
                        if e.args[0] == NT_STATUS_ACCESS_DENIED:
                            raise CommandError("The authenticated user does "
                                               "not have sufficient privileges")
        self.outf.write('Installing ADMX templates to the Central Store '
                        'prevents Windows from displaying its own templates '
                        'in the Group Policy Management Console. You will '
                        'need to install these templates '
                        'from https://www.microsoft.com/en-us/download/102157 '
                        'to continue using Windows Administrative Templates.\n')

class cmd_add_sudoers(GPOCommand):
    """Adds a Samba Sudoers Group Policy to the sysvol

This command adds a sudo rule to the sysvol for applying to winbind clients.

The command argument indicates the final field in the sudo rule.
The user argument indicates the user specified in the parentheses.
The users and groups arguments are comma separated lists, which are combined to
form the first field in the sudo rule.
The --passwd argument specifies whether the sudo entry will require a password
be specified. The default is False, meaning the NOPASSWD field will be
specified in the sudo entry.

Example:
samba-tool gpo manage sudoers add {31B2F340-016D-11D2-945F-00C04FB984F9} ALL ALL fakeu fakeg

The example command will generate the following sudoers entry:
fakeu,fakeg% ALL=(ALL) NOPASSWD: ALL
    """

    synopsis = "%prog <gpo> <command> <user> <users> [groups] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
        Option("--passwd", action='store_true', default=False,
               help="Specify to indicate that sudo entry must provide a password")
    ]

    takes_args = ["gpo", "command", "user", "users", "groups?"]

    def run(self, gpo, command, user, users, groups=None, passwd=None,
            H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Sudo',
                             'SudoersConfiguration'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policysetting = xml_data.getroot().find('policysetting')
            data = policysetting.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Sudo Policy'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Sudoers File Configuration Policy'
                apply_mode = ET.SubElement(policysetting, 'apply_mode')
                apply_mode.text = 'merge'
                data = ET.SubElement(policysetting, 'data')
                load_plugin = ET.SubElement(data, 'load_plugin')
                load_plugin.text = 'true'
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        sudoers_entry = ET.SubElement(data, 'sudoers_entry')
        if passwd:
            ET.SubElement(sudoers_entry, 'password')
        command_elm = ET.SubElement(sudoers_entry, 'command')
        command_elm.text = command
        user_elm = ET.SubElement(sudoers_entry, 'user')
        user_elm.text = user
        listelement = ET.SubElement(sudoers_entry, 'listelement')
        for u in users.split(','):
            principal = ET.SubElement(listelement, 'principal')
            principal.text = u
            principal.attrib['type'] = 'user'
        if groups is not None:
            for g in groups.split():
                principal = ET.SubElement(listelement, 'principal')
                principal.text = g
                principal.attrib['type'] = 'group'

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_list_sudoers(Command):
    """List Samba Sudoers Group Policy from the sysvol

This command lists sudo rules from the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage sudoers list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Sudo',
                                'SudoersConfiguration\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so there is nothing to list
                xml_data = None
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        if xml_data is not None:
            policy = xml_data.find('policysetting')
            data = policy.find('data')
            for entry in data.findall('sudoers_entry'):
                command = entry.find('command').text
                user = entry.find('user').text
                listelements = entry.findall('listelement')
                principals = []
                for listelement in listelements:
                    principals.extend(listelement.findall('principal'))
                if len(principals) > 0:
                    uname = ','.join([u.text if u.attrib['type'] == 'user' \
                        else '%s%%' % u.text for u in principals])
                else:
                    uname = 'ALL'
                nopassword = entry.find('password') is None
                np_entry = ' NOPASSWD:' if nopassword else ''
                p = '%s ALL=(%s)%s %s' % (uname, user, np_entry, command)
                self.outf.write('%s\n' % p)

        pol_file = '\\'.join([realm.lower(), 'Policies', gpo,
                              'MACHINE\\Registry.pol'])
        try:
            pol_data = ndr_unpack(preg.file, conn.loadfile(pol_file))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        # Also list the policies set from the GPME
        keyname = b'Software\\Policies\\Samba\\Unix Settings\\Sudo Rights'
        for entry in pol_data.entries:
            if get_bytes(entry.keyname) == keyname and \
                    get_string(entry.data).strip():
                self.outf.write('%s\n' % entry.data)

class cmd_remove_sudoers(GPOCommand):
    """Removes a Samba Sudoers Group Policy from the sysvol

This command removes a sudo rule from the sysvol from applying to winbind clients.

Example:
samba-tool gpo manage sudoers remove {31B2F340-016D-11D2-945F-00C04FB984F9} 'fakeu ALL=(ALL) NOPASSWD: ALL'
    """

    synopsis = "%prog <gpo> <entry> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "entry"]

    def run(self, gpo, entry, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Sudo',
                             'SudoersConfiguration'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policysetting = xml_data.getroot().find('policysetting')
            data = policysetting.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                data = None
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        pol_file = '\\'.join([realm.lower(), 'Policies', gpo,
                              'MACHINE\\Registry.pol'])
        try:
            pol_data = ndr_unpack(preg.file, conn.loadfile(pol_file))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                pol_data = None
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        entries = {}
        for e in data.findall('sudoers_entry') if data else []:
            command = e.find('command').text
            user = e.find('user').text
            listelements = e.findall('listelement')
            principals = []
            for listelement in listelements:
                principals.extend(listelement.findall('principal'))
            if len(principals) > 0:
                uname = ','.join([u.text if u.attrib['type'] == 'user' \
                    else '%s%%' % u.text for u in principals])
            else:
                uname = 'ALL'
            nopassword = e.find('password') is None
            np_entry = ' NOPASSWD:' if nopassword else ''
            p = '%s ALL=(%s)%s %s' % (uname, user, np_entry, command)
            entries[p] = e

        if entry in entries.keys():
            data.remove(entries[entry])

            out = BytesIO()
            xml_data.write(out, encoding='UTF-8', xml_declaration=True)
            out.seek(0)
            try:
                create_directory_hier(conn, vgp_dir)
                conn.savefile(vgp_xml, out.read())
                reg.increment_gpt_ini(machine_changed=True)
            except NTSTATUSError as e:
                if e.args[0] == NT_STATUS_ACCESS_DENIED:
                    raise CommandError("The authenticated user does "
                                       "not have sufficient privileges")
                raise
        elif entry in ([e.data for e in pol_data.entries] if pol_data else []):
            entries = [e for e in pol_data.entries if e.data != entry]
            pol_data.num_entries = len(entries)
            pol_data.entries = entries

            try:
                conn.savefile(pol_file, ndr_pack(pol_data))
                reg.increment_gpt_ini(machine_changed=True)
            except NTSTATUSError as e:
                if e.args[0] == NT_STATUS_ACCESS_DENIED:
                    raise CommandError("The authenticated user does "
                                       "not have sufficient privileges")
                raise
        else:
            raise CommandError("Cannot remove '%s' because it does not exist" %
                               entry)

class cmd_sudoers(SuperCommand):
    """Manage Sudoers Group Policy Objects"""
    subcommands = {}
    subcommands["add"] = cmd_add_sudoers()
    subcommands["list"] = cmd_list_sudoers()
    subcommands["remove"] = cmd_remove_sudoers()

class cmd_set_security(GPOCommand):
    """Set Samba Security Group Policy to the sysvol

This command sets a security setting to the sysvol for applying to winbind
clients. Not providing a value will unset the policy.
These settings only apply to the ADDC.

Example:
samba-tool gpo manage security set {31B2F340-016D-11D2-945F-00C04FB984F9} MaxTicketAge 10

Possible policies:
MaxTicketAge            Maximum lifetime for user ticket
                        Defined in hours

MaxServiceAge           Maximum lifetime for service ticket
                        Defined in minutes

MaxRenewAge             Maximum lifetime for user ticket renewal
                        Defined in minutes

MinimumPasswordAge      Minimum password age
                        Defined in days

MaximumPasswordAge      Maximum password age
                        Defined in days

MinimumPasswordLength   Minimum password length
                        Defined in characters

PasswordComplexity      Password must meet complexity requirements
                        1 is Enabled, 0 is Disabled
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "policy", "value?"]

    def run(self, gpo, policy, value=None, H=None, sambaopts=None,
            credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        inf_dir = '\\'.join([realm.lower(), 'Policies', gpo,
            'MACHINE\\Microsoft\\Windows NT\\SecEdit'])
        inf_file = '\\'.join([inf_dir, 'GptTmpl.inf'])
        try:
            inf_data = ConfigParser(interpolation=None)
            inf_data.optionxform=str
            raw = conn.loadfile(inf_file)
            try:
                inf_data.read_file(StringIO(raw.decode()))
            except UnicodeDecodeError:
                inf_data.read_file(StringIO(raw.decode('utf-16')))
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            if e.args[0] not in [NT_STATUS_OBJECT_NAME_INVALID,
                                 NT_STATUS_OBJECT_NAME_NOT_FOUND,
                                 NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                raise

        section_map = { 'MaxTicketAge' : 'Kerberos Policy',
                        'MaxServiceAge' : 'Kerberos Policy',
                        'MaxRenewAge' : 'Kerberos Policy',
                        'MinimumPasswordAge' : 'System Access',
                        'MaximumPasswordAge' : 'System Access',
                        'MinimumPasswordLength' : 'System Access',
                        'PasswordComplexity' : 'System Access'
                    }

        section = section_map[policy]
        if not inf_data.has_section(section):
            inf_data.add_section(section)
        if value is not None:
            inf_data.set(section, policy, value)
        else:
            inf_data.remove_option(section, policy)
            if len(inf_data.options(section)) == 0:
                inf_data.remove_section(section)

        out = StringIO()
        inf_data.write(out)
        try:
            create_directory_hier(conn, inf_dir)
            conn.savefile(inf_file, get_bytes(out.getvalue()))
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

class cmd_list_security(Command):
    """List Samba Security Group Policy from the sysvol

This command lists security settings from the sysvol that will be applied to winbind clients.
These settings only apply to the ADDC.

Example:
samba-tool gpo manage security list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        inf_file = '\\'.join([realm.lower(), 'Policies', gpo,
            'MACHINE\\Microsoft\\Windows NT\\SecEdit\\GptTmpl.inf'])
        try:
            inf_data = ConfigParser(interpolation=None)
            inf_data.optionxform=str
            raw = conn.loadfile(inf_file)
            try:
                inf_data.read_file(StringIO(raw.decode()))
            except UnicodeDecodeError:
                inf_data.read_file(StringIO(raw.decode('utf-16')))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        for section in inf_data.sections():
            if section not in ['Kerberos Policy', 'System Access']:
                continue
            for key, value in inf_data.items(section):
                self.outf.write('%s = %s\n' % (key, value))

class cmd_security(SuperCommand):
    """Manage Security Group Policy Objects"""
    subcommands = {}
    subcommands["set"] = cmd_set_security()
    subcommands["list"] = cmd_list_security()

class cmd_list_smb_conf(Command):
    """List Samba smb.conf Group Policy from the sysvol

This command lists smb.conf settings from the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage smb_conf list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        pol_file = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\Registry.pol'])
        try:
            pol_data = ndr_unpack(preg.file, conn.loadfile(pol_file))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        keyname = b'Software\\Policies\\Samba\\smb_conf'
        lp = param.LoadParm()
        for entry in pol_data.entries:
            if get_bytes(entry.keyname) == keyname:
                lp.set(entry.valuename, str(entry.data))
                val = lp.get(entry.valuename)
                self.outf.write('%s = %s\n' % (entry.valuename, val))

class cmd_set_smb_conf(GPOCommand):
    """Sets a Samba smb.conf Group Policy to the sysvol

This command sets an smb.conf setting to the sysvol for applying to winbind
clients. Not providing a value will unset the policy.

Example:
samba-tool gpo manage smb_conf set {31B2F340-016D-11D2-945F-00C04FB984F9} 'apply gpo policies' yes
    """

    synopsis = "%prog <gpo> <entry> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "setting", "value?"]

    def run(self, gpo, setting, value=None, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        pol_dir = '\\'.join([realm.lower(), 'Policies', gpo, 'MACHINE'])
        pol_file = '\\'.join([pol_dir, 'Registry.pol'])
        try:
            pol_data = ndr_unpack(preg.file, conn.loadfile(pol_file))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                pol_data = preg.file() # The file doesn't exist
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        if value is None:
            if setting not in [e.valuename for e in pol_data.entries]:
                raise CommandError("Cannot remove '%s' because it does "
                                    "not exist" % setting)
            entries = [e for e in pol_data.entries \
                if e.valuename != setting]
            pol_data.entries = entries
            pol_data.num_entries = len(entries)
        else:
            if get_string(value).lower() in ['yes', 'true', '1']:
                etype = 4
                val = 1
            elif get_string(value).lower() in ['no', 'false', '0']:
                etype = 4
                val = 0
            elif get_string(value).isnumeric():
                etype = 4
                val = int(get_string(value))
            else:
                etype = 1
                val = get_bytes(value)
            e = preg.entry()
            e.keyname = b'Software\\Policies\\Samba\\smb_conf'
            e.valuename = get_bytes(setting)
            e.type = etype
            e.data = val
            entries = list(pol_data.entries)
            entries.append(e)
            pol_data.entries = entries
            pol_data.num_entries = len(entries)

        try:
            create_directory_hier(conn, pol_dir)
            conn.savefile(pol_file, ndr_pack(pol_data))
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_smb_conf(SuperCommand):
    """Manage smb.conf Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_smb_conf()
    subcommands["set"] = cmd_set_smb_conf()

class cmd_list_symlink(Command):
    """List VGP Symbolic Link Group Policy from the sysvol

This command lists symlink settings from the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage symlink list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Unix',
                                'Symlink\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        for file_properties in data.findall('file_properties'):
            source = file_properties.find('source')
            target = file_properties.find('target')
            self.outf.write('ln -s %s %s\n' % (source.text, target.text))

class cmd_add_symlink(GPOCommand):
    """Adds a VGP Symbolic Link Group Policy to the sysvol

This command adds a symlink setting to the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage symlink add {31B2F340-016D-11D2-945F-00C04FB984F9} /tmp/source /tmp/target
    """

    synopsis = "%prog <gpo> <source> <target> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "source", "target"]

    def run(self, gpo, source, target, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Symlink'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Symlink Policy'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Specifies symbolic link data'
                data = ET.SubElement(policysetting, 'data')
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        file_properties = ET.SubElement(data, 'file_properties')
        source_elm = ET.SubElement(file_properties, 'source')
        source_elm.text = source
        target_elm = ET.SubElement(file_properties, 'target')
        target_elm.text = target

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_remove_symlink(GPOCommand):
    """Removes a VGP Symbolic Link Group Policy from the sysvol

This command removes a symlink setting from the sysvol from applying to winbind
clients.

Example:
samba-tool gpo manage symlink remove {31B2F340-016D-11D2-945F-00C04FB984F9} /tmp/source /tmp/target
    """

    synopsis = "%prog <gpo> <source> <target> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "source", "target"]

    def run(self, gpo, source, target, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Symlink'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                raise CommandError("Cannot remove link from '%s' to '%s' "
                    "because it does not exist" % source, target)
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        for file_properties in data.findall('file_properties'):
            source_elm = file_properties.find('source')
            target_elm = file_properties.find('target')
            if source_elm.text == source and target_elm.text == target:
                data.remove(file_properties)
                break
        else:
            raise CommandError("Cannot remove link from '%s' to '%s' "
                               "because it does not exist" % source, target)


        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_symlink(SuperCommand):
    """Manage symlink Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_symlink()
    subcommands["add"] = cmd_add_symlink()
    subcommands["remove"] = cmd_remove_symlink()

class cmd_list_files(Command):
    """List VGP Files Group Policy from the sysvol

This command lists files which will be copied from the sysvol and applied to winbind clients.

Example:
samba-tool gpo manage files list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Unix',
                                'Files\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        for entry in data.findall('file_properties'):
            source = entry.find('source').text
            target = entry.find('target').text
            user = entry.find('user').text
            group = entry.find('group').text
            mode = calc_mode(entry)
            p = '%s\t%s\t%s\t%s -> %s' % \
                    (stat_from_mode(mode), user, group, target, source)
            self.outf.write('%s\n' % p)

class cmd_add_files(GPOCommand):
    """Add VGP Files Group Policy to the sysvol

This command adds files which will be copied from the sysvol and applied to winbind clients.

Example:
samba-tool gpo manage files add {31B2F340-016D-11D2-945F-00C04FB984F9} ./source.txt /usr/share/doc/target.txt root root 600
    """

    synopsis = "%prog <gpo> <source> <target> <user> <group> <mode> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "source", "target", "user", "group", "mode"]

    def run(self, gpo, source, target, user, group, mode, H=None,
            sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        if not os.path.exists(source):
            raise CommandError("Source '%s' does not exist" % source)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Files'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Files'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Represents file data to set/copy on clients'
                data = ET.SubElement(policysetting, 'data')
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        file_properties = ET.SubElement(data, 'file_properties')
        source_elm = ET.SubElement(file_properties, 'source')
        source_elm.text = os.path.basename(source)
        target_elm = ET.SubElement(file_properties, 'target')
        target_elm.text = target
        user_elm = ET.SubElement(file_properties, 'user')
        user_elm.text = user
        group_elm = ET.SubElement(file_properties, 'group')
        group_elm.text = group
        for ptype, shift in [('user', 6), ('group', 3), ('other', 0)]:
            permissions = ET.SubElement(file_properties, 'permissions')
            permissions.set('type', ptype)
            if int(mode, 8) & (0o4 << shift):
                ET.SubElement(permissions, 'read')
            if int(mode, 8) & (0o2 << shift):
                ET.SubElement(permissions, 'write')
            if int(mode, 8) & (0o1 << shift):
                ET.SubElement(permissions, 'execute')

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        source_data = open(source, 'rb').read()
        sysvol_source = '\\'.join([vgp_dir, os.path.basename(source)])
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            conn.savefile(sysvol_source, source_data)
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_remove_files(GPOCommand):
    """Remove VGP Files Group Policy from the sysvol

This command removes files which would be copied from the sysvol and applied to winbind clients.

Example:
samba-tool gpo manage files remove {31B2F340-016D-11D2-945F-00C04FB984F9} /usr/share/doc/target.txt
    """

    synopsis = "%prog <gpo> <target> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "target"]

    def run(self, gpo, target, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Files'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                raise CommandError("Cannot remove file '%s' "
                    "because it does not exist" % target)
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        for file_properties in data.findall('file_properties'):
            source_elm = file_properties.find('source')
            target_elm = file_properties.find('target')
            if target_elm.text == target:
                source = '\\'.join([vgp_dir, source_elm.text])
                conn.unlink(source)
                data.remove(file_properties)
                break
        else:
            raise CommandError("Cannot remove file '%s' "
                               "because it does not exist" % target)


        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_files(SuperCommand):
    """Manage Files Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_files()
    subcommands["add"] = cmd_add_files()
    subcommands["remove"] = cmd_remove_files()

class cmd_list_openssh(Command):
    """List VGP OpenSSH Group Policy from the sysvol

This command lists openssh options from the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage openssh list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\SshCfg',
                                'SshD\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        configfile = data.find('configfile')
        for configsection in configfile.findall('configsection'):
            if configsection.find('sectionname').text:
                continue
            for kv in configsection.findall('keyvaluepair'):
                self.outf.write('%s %s\n' % (kv.find('key').text,
                                             kv.find('value').text))

class cmd_set_openssh(GPOCommand):
    """Sets a VGP OpenSSH Group Policy to the sysvol

This command sets an openssh setting to the sysvol for applying to winbind
clients. Not providing a value will unset the policy.

Example:
samba-tool gpo manage openssh set {31B2F340-016D-11D2-945F-00C04FB984F9} KerberosAuthentication Yes
    """

    synopsis = "%prog <gpo> <setting> [value] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "setting", "value?"]

    def run(self, gpo, setting, value=None, H=None, sambaopts=None,
            credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\SshCfg\\SshD'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
            configfile = data.find('configfile')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Configuration File'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Represents Unix configuration file settings'
                apply_mode = ET.SubElement(policysetting, 'apply_mode')
                apply_mode.text = 'merge'
                data = ET.SubElement(policysetting, 'data')
                configfile = ET.SubElement(data, 'configfile')
                configsection = ET.SubElement(configfile, 'configsection')
                ET.SubElement(configsection, 'sectionname')
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        if value is not None:
            for configsection in configfile.findall('configsection'):
                if configsection.find('sectionname').text:
                    continue # Ignore Quest SSH settings
                settings = {}
                for kv in configsection.findall('keyvaluepair'):
                    settings[kv.find('key')] = kv
                if setting in settings.keys():
                    settings[setting].text = value
                else:
                    keyvaluepair = ET.SubElement(configsection, 'keyvaluepair')
                    key = ET.SubElement(keyvaluepair, 'key')
                    key.text = setting
                    dvalue = ET.SubElement(keyvaluepair, 'value')
                    dvalue.text = value
        else:
            for configsection in configfile.findall('configsection'):
                if configsection.find('sectionname').text:
                    continue # Ignore Quest SSH settings
                settings = {}
                for kv in configsection.findall('keyvaluepair'):
                    settings[kv.find('key').text] = kv
                if setting in settings.keys():
                    configsection.remove(settings[setting])
                else:
                    raise CommandError("Cannot remove '%s' because it does " \
                                       "not exist" % setting)

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_openssh(SuperCommand):
    """Manage OpenSSH Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_openssh()
    subcommands["set"] = cmd_set_openssh()

class cmd_list_startup(Command):
    """List VGP Startup Script Group Policy from the sysvol

This command lists the startup script policies currently set on the sysvol.

Example:
samba-tool gpo manage scripts startup list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Unix',
                                'Scripts\\Startup\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        for listelement in data.findall('listelement'):
            script = listelement.find('script')
            script_path = '\\'.join(['\\', realm.lower(), 'Policies', gpo,
                                     'MACHINE\\VGP\\VTLA\\Unix\\Scripts',
                                     'Startup', script.text])
            parameters = listelement.find('parameters')
            run_as = listelement.find('run_as')
            if run_as is not None:
                run_as = run_as.text
            else:
                run_as = 'root'
            if parameters is not None:
                parameters = parameters.text
            else:
                parameters = ''
            self.outf.write('@reboot %s %s %s\n' % (run_as, script_path,
                                                  parameters))

class cmd_add_startup(GPOCommand):
    """Adds VGP Startup Script Group Policy to the sysvol

This command adds a startup script policy to the sysvol.

Example:
samba-tool gpo manage scripts startup add {31B2F340-016D-11D2-945F-00C04FB984F9} test_script.sh '\\-n \\-p all'
    """

    synopsis = "%prog <gpo> <script> [args] [run_as] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
        Option("--run-once", dest="run_once", default=False, action='store_true',
               help="Whether to run the script only once"),
    ]

    takes_args = ["gpo", "script", "args?", "run_as?"]

    def run(self, gpo, script, args=None, run_as=None, run_once=None,
            H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        if not os.path.exists(script):
            raise CommandError("Script '%s' does not exist" % script)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Scripts\\Startup'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Unix Scripts'
                description = ET.SubElement(policysetting, 'description')
                description.text = \
                    'Represents Unix scripts to run on Group Policy clients'
                data = ET.SubElement(policysetting, 'data')
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        script_data = open(script, 'rb').read()
        listelement = ET.SubElement(data, 'listelement')
        script_elm = ET.SubElement(listelement, 'script')
        script_elm.text = os.path.basename(script)
        hash = ET.SubElement(listelement, 'hash')
        hash.text = hashlib.md5(script_data).hexdigest().upper()
        if args is not None:
            parameters = ET.SubElement(listelement, 'parameters')
            parameters.text = args.strip('"').strip("'").replace('\\-', '-')
        if run_as is not None:
            run_as_elm = ET.SubElement(listelement, 'run_as')
            run_as_elm.text = run_as
        if run_once:
            ET.SubElement(listelement, 'run_once')

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        sysvol_script = '\\'.join([vgp_dir, os.path.basename(script)])
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            conn.savefile(sysvol_script, script_data)
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_remove_startup(GPOCommand):
    """Removes VGP Startup Script Group Policy from the sysvol

This command removes a startup script policy from the sysvol.

Example:
samba-tool gpo manage scripts startup remove {31B2F340-016D-11D2-945F-00C04FB984F9} test_script.sh
    """

    synopsis = "%prog <gpo> <script> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "script"]

    def run(self, gpo, script, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Scripts\\Startup'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                raise CommandError("Cannot remove script '%s' "
                    "because it does not exist" % script)
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        for listelement in data.findall('listelement'):
            script_elm = listelement.find('script')
            if script_elm.text == os.path.basename(script.replace('\\', '/')):
                data.remove(listelement)
                break
        else:
            raise CommandError("Cannot remove script '%s' "
                "because it does not exist" % script)

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_startup(SuperCommand):
    """Manage Startup Scripts Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_startup()
    subcommands["add"] = cmd_add_startup()
    subcommands["remove"] = cmd_remove_startup()

class cmd_scripts(SuperCommand):
    """Manage Scripts Group Policy Objects"""
    subcommands = {}
    subcommands["startup"] = cmd_startup()

class cmd_list_motd(Command):
    """List VGP MOTD Group Policy from the sysvol

This command lists the Message of the Day from the sysvol that will be applied
to winbind clients.

Example:
samba-tool gpo manage motd list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Unix',
                                'MOTD\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        text = data.find('text')
        self.outf.write(text.text)

class cmd_set_motd(GPOCommand):
    """Sets a VGP MOTD Group Policy to the sysvol

This command sets the Message of the Day to the sysvol for applying to winbind
clients. Not providing a value will unset the policy.

Example:
samba-tool gpo manage motd set {31B2F340-016D-11D2-945F-00C04FB984F9} "Message for today"
    """

    synopsis = "%prog <gpo> [value] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "value?"]

    def run(self, gpo, value=None, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\MOTD'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])

        if value is None:
            conn.unlink(vgp_xml)
            reg.increment_gpt_ini(machine_changed=True)
            return

        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Text File'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Represents a Generic Text File'
                apply_mode = ET.SubElement(policysetting, 'apply_mode')
                apply_mode.text = 'replace'
                data = ET.SubElement(policysetting, 'data')
                filename = ET.SubElement(data, 'filename')
                filename.text = 'motd'
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        text = ET.SubElement(data, 'text')
        text.text = value

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_motd(SuperCommand):
    """Manage Message of the Day Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_motd()
    subcommands["set"] = cmd_set_motd()

class cmd_list_issue(Command):
    """List VGP Issue Group Policy from the sysvol

This command lists the Prelogin Message from the sysvol that will be applied
to winbind clients.

Example:
samba-tool gpo manage issue list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                                'MACHINE\\VGP\\VTLA\\Unix',
                                'Issue\\manifest.xml'])
        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                return # The file doesn't exist, so there is nothing to list
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

        policy = xml_data.find('policysetting')
        data = policy.find('data')
        text = data.find('text')
        self.outf.write(text.text)

class cmd_set_issue(GPOCommand):
    """Sets a VGP Issue Group Policy to the sysvol

This command sets the Prelogin Message to the sysvol for applying to winbind
clients. Not providing a value will unset the policy.

Example:
samba-tool gpo manage issue set {31B2F340-016D-11D2-945F-00C04FB984F9} "Welcome to Samba!"
    """

    synopsis = "%prog <gpo> [value] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "value?"]

    def run(self, gpo, value=None, H=None, sambaopts=None, credopts=None,
            versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\Unix\\Issue'])
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])

        if value is None:
            conn.unlink(vgp_xml)
            reg.increment_gpt_ini(machine_changed=True)
            return

        try:
            xml_data = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Text File'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Represents a Generic Text File'
                apply_mode = ET.SubElement(policysetting, 'apply_mode')
                apply_mode.text = 'replace'
                data = ET.SubElement(policysetting, 'data')
                filename = ET.SubElement(data, 'filename')
                filename.text = 'issue'
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        text = ET.SubElement(data, 'text')
        text.text = value

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_issue(SuperCommand):
    """Manage Issue Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_issue()
    subcommands["set"] = cmd_set_issue()

class cmd_list_access(Command):
    """List VGP Host Access Group Policy from the sysvol

This command lists host access rules from the sysvol that will be applied to winbind clients.

Example:
samba-tool gpo manage access list {31B2F340-016D-11D2-945F-00C04FB984F9}
    """

    synopsis = "%prog <gpo> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo"]

    def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        realm = self.lp.get('realm')
        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\VAS',
                             'HostAccessControl\\Allow\\manifest.xml'])
        try:
            allow = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                allow = None # The file doesn't exist, ignore it
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        if allow is not None:
            policy = allow.find('policysetting')
            data = policy.find('data')
            for listelement in data.findall('listelement'):
                adobject = listelement.find('adobject')
                name = adobject.find('name')
                domain = adobject.find('domain')
                self.outf.write('+:%s\\%s:ALL\n' % (domain.text, name.text))

        vgp_xml = '\\'.join([realm.lower(), 'Policies', gpo,
                             'MACHINE\\VGP\\VTLA\\VAS',
                             'HostAccessControl\\Deny\\manifest.xml'])
        try:
            deny = ET.fromstring(conn.loadfile(vgp_xml))
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                deny = None # The file doesn't exist, ignore it
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        if deny is not None:
            policy = deny.find('policysetting')
            data = policy.find('data')
            for listelement in data.findall('listelement'):
                adobject = listelement.find('adobject')
                name = adobject.find('name')
                domain = adobject.find('domain')
                self.outf.write('-:%s\\%s:ALL\n' % (domain.text, name.text))

class cmd_add_access(GPOCommand):
    """Adds a VGP Host Access Group Policy to the sysvol

This command adds a host access setting to the sysvol for applying to winbind
clients. Any time an allow entry is detected by the client, an implicit deny
ALL will be assumed.

Example:
samba-tool gpo manage access add {31B2F340-016D-11D2-945F-00C04FB984F9} allow goodguy example.com
    """

    synopsis = "%prog <gpo> <allow/deny> <cn> <domain> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "etype", "cn", "domain"]

    def run(self, gpo, etype, cn, domain, H=None, sambaopts=None,
            credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        if etype == 'allow':
            vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                                 'MACHINE\\VGP\\VTLA\\VAS',
                                 'HostAccessControl\\Allow'])
        elif etype == 'deny':
            vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                                 'MACHINE\\VGP\\VTLA\\VAS',
                                 'HostAccessControl\\Deny'])
        else:
            raise CommandError("The entry type must be either 'allow' or "
                               "'deny'. Unknown type '%s'" % etype)
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                # The file doesn't exist, so create the xml structure
                xml_data = ET.ElementTree(ET.Element('vgppolicy'))
                policysetting = ET.SubElement(xml_data.getroot(),
                                              'policysetting')
                pv = ET.SubElement(policysetting, 'version')
                pv.text = '1'
                name = ET.SubElement(policysetting, 'name')
                name.text = 'Host Access Control'
                description = ET.SubElement(policysetting, 'description')
                description.text = 'Represents host access control data (pam_access)'
                apply_mode = ET.SubElement(policysetting, 'apply_mode')
                apply_mode.text = 'merge'
                data = ET.SubElement(policysetting, 'data')
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        url = dc_url(self.lp, self.creds, dc=domain)
        samdb = SamDB(url=url, session_info=system_session(),
                      credentials=self.creds, lp=self.lp)

        res = samdb.search(base=samdb.domain_dn(),
                           scope=ldb.SCOPE_SUBTREE,
                           expression="(cn=%s)" % cn,
                           attrs=['userPrincipalName',
                                  'samaccountname',
                                  'objectClass'])
        if len(res) == 0:
            raise CommandError('Unable to find user or group "%s"' % cn)

        objectclass = get_string(res[0]['objectClass'][-1])
        if objectclass not in ['user', 'group']:
            raise CommandError('%s is not a user or group' % cn)

        listelement = ET.SubElement(data, 'listelement')
        etype = ET.SubElement(listelement, 'type')
        etype.text = objectclass.upper()
        entry = ET.SubElement(listelement, 'entry')
        entry.text = '%s\\%s' % (samdb.domain_netbios_name(),
                                 get_string(res[0]['samaccountname'][-1]))
        if objectclass == 'group':
            groupattr = ET.SubElement(data, 'groupattr')
            groupattr.text = 'samAccountName'
        adobject = ET.SubElement(listelement, 'adobject')
        name = ET.SubElement(adobject, 'name')
        name.text = get_string(res[0]['samaccountname'][-1])
        domain_elm = ET.SubElement(adobject, 'domain')
        domain_elm.text = domain
        etype = ET.SubElement(adobject, 'type')
        etype.text = objectclass

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_remove_access(GPOCommand):
    """Remove a VGP Host Access Group Policy from the sysvol

This command removes a host access setting from the sysvol for applying to
winbind clients.

Example:
samba-tool gpo manage access remove {31B2F340-016D-11D2-945F-00C04FB984F9} allow goodguy example.com
    """

    synopsis = "%prog <gpo> <allow/deny> <name> <domain> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
    ]

    takes_args = ["gpo", "etype", "name", "domain"]

    def run(self, gpo, etype, name, domain, H=None, sambaopts=None,
            credopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        # We need to know writable DC to setup SMB connection
        if H and H.startswith('ldap://'):
            dc_hostname = H[7:]
            self.url = H
        else:
            dc_hostname = netcmd_finddc(self.lp, self.creds)
            self.url = dc_url(self.lp, self.creds, dc=dc_hostname)

        # SMB connect to DC
        conn = smb_connection(dc_hostname,
                              'sysvol',
                              lp=self.lp,
                              creds=self.creds)

        self.samdb_connect()
        reg = RegistryGroupPolicies(gpo, self.lp, self.creds, self.samdb, H)

        realm = self.lp.get('realm')
        if etype == 'allow':
            vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                                 'MACHINE\\VGP\\VTLA\\VAS',
                                 'HostAccessControl\\Allow'])
        elif etype == 'deny':
            vgp_dir = '\\'.join([realm.lower(), 'Policies', gpo,
                                 'MACHINE\\VGP\\VTLA\\VAS',
                                 'HostAccessControl\\Deny'])
        else:
            raise CommandError("The entry type must be either 'allow' or "
                               "'deny'. Unknown type '%s'" % etype)
        vgp_xml = '\\'.join([vgp_dir, 'manifest.xml'])
        try:
            xml_data = ET.ElementTree(ET.fromstring(conn.loadfile(vgp_xml)))
            policy = xml_data.getroot().find('policysetting')
            data = policy.find('data')
        except NTSTATUSError as e:
            if e.args[0] in [NT_STATUS_OBJECT_NAME_INVALID,
                             NT_STATUS_OBJECT_NAME_NOT_FOUND,
                             NT_STATUS_OBJECT_PATH_NOT_FOUND]:
                raise CommandError("Cannot remove %s entry because it does "
                                   "not exist" % etype)
            elif e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            else:
                raise

        for listelement in data.findall('listelement'):
            adobject = listelement.find('adobject')
            name_elm = adobject.find('name')
            domain_elm = adobject.find('domain')
            if name_elm is not None and name_elm.text == name and \
               domain_elm is not None and domain_elm.text == domain:
                data.remove(listelement)
                break
        else:
            raise CommandError("Cannot remove %s entry because it does "
                                   "not exist" % etype)

        out = BytesIO()
        xml_data.write(out, encoding='UTF-8', xml_declaration=True)
        out.seek(0)
        try:
            create_directory_hier(conn, vgp_dir)
            conn.savefile(vgp_xml, out.read())
            reg.increment_gpt_ini(machine_changed=True)
        except NTSTATUSError as e:
            if e.args[0] == NT_STATUS_ACCESS_DENIED:
                raise CommandError("The authenticated user does "
                                   "not have sufficient privileges")
            raise

class cmd_cse_register(Command):
    """Register a Client Side Extension (CSE) on the current host

This command takes a CSE filename as an argument, and registers it for
applying policy on the current host. This is not necessary for CSEs which
are distributed with the current version of Samba, but is useful for installing
experimental CSEs or custom built CSEs.
The <cse_file> argument MUST be a permanent location for the CSE. The register
command does not copy the file to some other directory. The samba-gpupdate
command will execute the CSE from the exact location specified from this
command.

Example:
samba-tool gpo cse register ./gp_chromium_ext.py gp_chromium_ext --machine
    """

    synopsis = "%prog <cse_file> <cse_name> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("--machine", default=False, action='store_true',
               help="Whether to register the CSE as Machine policy"),
        Option("--user", default=False, action='store_true',
               help="Whether to register the CSE as User policy"),
    ]

    takes_args = ["cse_file", "cse_name"]

    def run(self, cse_file, cse_name, machine=False, user=False,
            sambaopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()

        if machine == False and user == False:
            raise CommandError("Either --machine or --user must be selected")

        ext_guid = "{%s}" % str(uuid.uuid4())
        ext_path = os.path.realpath(cse_file)
        ret = register_gp_extension(ext_guid, cse_name, ext_path,
                                    smb_conf=self.lp.configfile,
                                    machine=machine, user=user)
        if not ret:
            raise CommandError('Failed to register CSE "%s"' % cse_name)

class cmd_cse_list(Command):
    """List the registered Client Side Extensions (CSEs) on the current host

This command lists the currently registered CSEs on the host.

Example:
samba-tool gpo cse list
    """

    synopsis = "%prog [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
    }

    def run(self, sambaopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()

        cses = list_gp_extensions(self.lp.configfile)
        for guid, gp_ext in cses.items():
            self.outf.write("UniqueGUID         : %s\n" % guid)
            self.outf.write("FileName           : %s\n" % gp_ext['DllName'])
            self.outf.write("ProcessGroupPolicy : %s\n" % \
                    gp_ext['ProcessGroupPolicy'])
            self.outf.write("MachinePolicy      : %s\n" % \
                    str(gp_ext['MachinePolicy']))
            self.outf.write("UserPolicy         : %s\n\n" % \
                    str(gp_ext['UserPolicy']))

class cmd_cse_unregister(Command):
    """Unregister a Client Side Extension (CSE) from the current host

This command takes a unique GUID as an argument (representing a registered
CSE), and unregisters it for applying policy on the current host. Use the
`samba-tool gpo cse list` command to determine the unique GUIDs of CSEs.

Example:
samba-tool gpo cse unregister {3F60F344-92BF-11ED-A1EB-0242AC120002}
    """

    synopsis = "%prog <guid> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
    }

    takes_args = ["guid"]

    def run(self, guid, sambaopts=None, versionopts=None):
        self.lp = sambaopts.get_loadparm()

        ret = unregister_gp_extension(guid, self.lp.configfile)
        if not ret:
            raise CommandError('Failed to unregister CSE "%s"' % guid)

class cmd_cse(SuperCommand):
    """Manage Client Side Extensions"""
    subcommands = {}
    subcommands["register"] = cmd_cse_register()
    subcommands["list"] = cmd_cse_list()
    subcommands["unregister"] = cmd_cse_unregister()

class cmd_access(SuperCommand):
    """Manage Host Access Group Policy Objects"""
    subcommands = {}
    subcommands["list"] = cmd_list_access()
    subcommands["add"] = cmd_add_access()
    subcommands["remove"] = cmd_remove_access()

class cmd_manage(SuperCommand):
    """Manage Group Policy Objects"""
    subcommands = {}
    subcommands["sudoers"] = cmd_sudoers()
    subcommands["security"] = cmd_security()
    subcommands["smb_conf"] = cmd_smb_conf()
    subcommands["symlink"] = cmd_symlink()
    subcommands["files"] = cmd_files()
    subcommands["openssh"] = cmd_openssh()
    subcommands["scripts"] = cmd_scripts()
    subcommands["motd"] = cmd_motd()
    subcommands["issue"] = cmd_issue()
    subcommands["access"] = cmd_access()

class cmd_gpo(SuperCommand):
    """Group Policy Object (GPO) management."""

    subcommands = {}
    subcommands["listall"] = cmd_listall()
    subcommands["list"] = cmd_list()
    subcommands["show"] = cmd_show()
    subcommands["load"] = cmd_load()
    subcommands["remove"] = cmd_remove()
    subcommands["getlink"] = cmd_getlink()
    subcommands["setlink"] = cmd_setlink()
    subcommands["dellink"] = cmd_dellink()
    subcommands["listcontainers"] = cmd_listcontainers()
    subcommands["getinheritance"] = cmd_getinheritance()
    subcommands["setinheritance"] = cmd_setinheritance()
    subcommands["fetch"] = cmd_fetch()
    subcommands["create"] = cmd_create()
    subcommands["del"] = cmd_del()
    subcommands["aclcheck"] = cmd_aclcheck()
    subcommands["backup"] = cmd_backup()
    subcommands["restore"] = cmd_restore()
    subcommands["admxload"] = cmd_admxload()
    subcommands["manage"] = cmd_manage()
    subcommands["cse"] = cmd_cse()