Codebase list msldap / run/1869e8aa-0abb-49b0-8d26-93af1865b60a/upstream msldap / client.py
run/1869e8aa-0abb-49b0-8d26-93af1865b60a/upstream

Tree @run/1869e8aa-0abb-49b0-8d26-93af1865b60a/upstream (Download .tar.gz)

client.py @run/1869e8aa-0abb-49b0-8d26-93af1865b60a/upstreamraw · history · blame

   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
#!/usr/bin/env python3
#
# Author:
#  Tamas Jos (@skelsec)
#

import copy
import asyncio

from msldap import logger
from msldap.commons.common import MSLDAPClientStatus
from msldap.wintypes.asn1.sdflagsrequest import SDFlagsRequest, SDFlagsRequestValue
from msldap.protocol.constants import BASE, ALL_ATTRIBUTES, LEVEL

from msldap.protocol.query import escape_filter_chars
from msldap.connection import MSLDAPClientConnection
from msldap.protocol.messages import Control
from msldap.ldap_objects import *
from msldap.commons.utils import KNOWN_SIDS

from winacl.dtyp.security_descriptor import SECURITY_DESCRIPTOR
from winacl.dtyp.ace import ACCESS_ALLOWED_OBJECT_ACE, ADS_ACCESS_MASK
from winacl.dtyp.sid import SID
from winacl.dtyp.guid import GUID

class MSLDAPClient:
	"""
	High level API for LDAP operations.

	target, creds, ldap_query_page_size

	:param target: The target object describing the connection info
	:type target: :class:`MSLDAPTarget`
	:param creds: The credential object describing the authentication to be used
	:type creds: :class:`MSLDAPCredential`
	:param ldap_query_page_size: 
	:type ldap_query_page_size: int
	:return: A dictionary representing the LDAP tree
	:rtype: dict

	"""
	def __init__(self, target, creds, connection = None, keepalive = False):
		self.creds = creds
		self.target = target
		self.keepalive = keepalive
		self.ldap_query_page_size = 1000
		if self.target is not None:
			self.ldap_query_page_size = self.target.ldap_query_page_size
		
		self.ldap_query_ratelimit = 0
		if self.target is not None:
			self.ldap_query_ratelimit = self.target.ldap_query_ratelimit

		self._tree = None
		self._ldapinfo = None
		self._con = connection
		self.__keepalive_task = None
		self.keepalive_period = 10
		self.disconnected_evt = None
		self._sid_cache = {} #SID -> (domain, user)
		self._domainsid_cache = {} # SID -> domain
	
	async def __aenter__(self):
		return self
		
	async def __aexit__(self, exc_type, exc, traceback):
		await asyncio.wait_for(self.disconnect(), timeout = 1)
	
	async def __keepalive(self):
		try:
			while not self.disconnected_evt.is_set():
				if self._con is not None:
					ldap_filter = r'(distinguishedName=%s)' % self._tree
					async for entry, err in self.pagedsearch(ldap_filter, MSADInfo_ATTRS):
						if err is not None:
							return None, err
				await asyncio.sleep(self.keepalive_period)

		
		except asyncio.CancelledError:
			return

		except Exception as e:
			print('Keepalive exception: %s' % e)
			await self.disconnect()
	
	async def disconnect(self):
		try:
			if self.__keepalive_task is not None:
				self.__keepalive_task.cancel()
			if self._con is not None:
				await self._con.disconnect()
			
			self.disconnected_evt.set()
		
		except Exception as e:
			return False, e

	async def connect(self):
		try:
			self.disconnected_evt = asyncio.Event()
			if self._con is None:
				self._con = MSLDAPClientConnection(self.target, self.creds)
				_, err = await self._con.connect()
				if err is not None:
					raise err
				res, err = await self._con.bind()
				if err is not None:
					return False, err
			res, err = await self._con.get_serverinfo()
			if err is not None:
				raise err
			self._serverinfo = res
			self._tree = res['defaultNamingContext']
			self._ldapinfo, err = await self.get_ad_info()
			if self._con.is_anon is False:
				if err is not None:
					raise err
				self._domainsid_cache[self._ldapinfo.objectSid] = self._ldapinfo.name
			
			if self.keepalive is True:
				self.__keepalive_task = asyncio.create_task(self.__keepalive())
			return True, None
		except Exception as e:
			return False, e

	def get_server_info(self):
		return self._serverinfo

	async def pagedsearch(self, query, attributes, controls = None, tree = None):
		"""
		Performs a paged search on the AD, using the filter and attributes as a normal query does.
			!The LDAP connection MUST be active before invoking this function!

		:param query: LDAP query filter
		:type query: str
		:param attributes: List of requested attributes
		:type attributes: List[str]
		:param controls: additional controls to be passed in the query
		:type controls: dict
		:param level: Recursion level
		:type level: int

		:return: Async generator which yields (`dict`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`dict`, :class:`Exception`)]

		"""
		logger.debug('Paged search, filter: %s attributes: %s' % (query, ','.join(attributes)))
		if self._con.status != MSLDAPClientStatus.RUNNING:
			if self._con.status == MSLDAPClientStatus.ERROR:
				print('There was an error in the connection!')
				return
			elif self._con.status == MSLDAPClientStatus.ERROR:
				print('Theconnection is in stopped state!')
				return

		if tree is None:
			tree = self._tree
		if tree is None:
			raise Exception('BIND first!')
		t = []
		for x in attributes:
			t.append(x.encode())
		attributes = t

		t = []
		if controls is not None:
			for control in controls:
				t.append(Control({
					'controlType': control[0].encode(),
					'criticality': control[1],
					'controlValue': control[2]
				}))

		controls = t

		async for entry, err in self._con.pagedsearch(
			tree, 
			query, 
			attributes = attributes, 
			size_limit = self.ldap_query_page_size, 
			controls = controls,
			rate_limit=self.ldap_query_ratelimit
			):
				
				if err is not None:
					yield None, err
					return
				if entry['objectName'] == '' and entry['attributes'] == '':
					#searchresref...
					continue
				#print('et %s ' % entry)
				yield entry, None

	async def get_tree_plot(self, root_dn, level = 2):
		"""
		Returns a dictionary representing a tree starting from 'dn' containing all subtrees.

		:param root_dn: The start DN of the tree
		:type root_dn: str
		:param level: Recursion level
		:type level: int

		:return: A dictionary representing the LDAP tree
		:rtype: dict
		"""

		logger.debug('Tree, dn: %s level: %s' % (root_dn, level))
		tree = {}
		async for entry, err in self._con.pagedsearch(
			root_dn, 
			'(distinguishedName=*)', 
			attributes = [b'distinguishedName'], 
			size_limit = self.ldap_query_page_size, 
			search_scope=LEVEL, 
			controls = None, 
			rate_limit=self.ldap_query_ratelimit
			):
				if err is not None:
					raise err

				if level == 0:
					return {}
				#print(entry)
				#print(entry['attributes']['distinguishedName'])
				if 'distinguishedName' not in entry['attributes'] or entry['attributes']['distinguishedName'] is None or entry['attributes']['distinguishedName'] == []:
					continue
				subtree = await self.get_tree_plot(entry['attributes']['distinguishedName'], level = level -1)
				tree[entry['attributes']['distinguishedName']] = subtree
		return {root_dn : tree}

	async def get_all_users(self, attrs = MSADUser_ATTRS):
		"""
		Fetches all user objects available in the LDAP tree and yields them as MSADUser object.
		
		:return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]
		
		"""
		logger.debug('Polling AD for all user objects')
		ldap_filter = r'(sAMAccountType=805306368)'
		async for entry, err in self.pagedsearch(ldap_filter, attrs):
			if err is not None:
				yield None, err
				return
			yield MSADUser.from_ldap(entry, self._ldapinfo), None
		logger.debug('Finished polling for entries!')

	async def get_all_machines(self, attrs = MSADMachine_ATTRS):
		"""
		Fetches all machine objects available in the LDAP tree and yields them as MSADMachine object.

		:param attrs: Lists of attributes to request (eg. `['sAMAccountName', 'dNSHostName']`) Default: all attrs.
		:type attrs: list
		:return: Async generator which yields (`MSADMachine`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADMachine`, :class:`Exception`)]
		
		"""
		logger.debug('Polling AD for all user objects')
		ldap_filter = r'(sAMAccountType=805306369)'

		async for entry, err in self.pagedsearch(ldap_filter, attrs):
			if err is not None:
				yield None, err
				return
			yield MSADMachine.from_ldap(entry, self._ldapinfo), None
		logger.debug('Finished polling for entries!')
	
	async def get_all_gpos(self, attrs = MSADGPO_ATTRS):
		"""
		Fetches all GPOs available in the LDAP tree and yields them as MSADGPO object.
		
		:return: Async generator which yields (`MSADGPO`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADGPO`, :class:`Exception`)]
		
		"""

		ldap_filter = r'(objectCategory=groupPolicyContainer)'
		async for entry, err in self.pagedsearch(ldap_filter, attrs):
			if err is not None:
				yield None, err
				return
			yield MSADGPO.from_ldap(entry), None

	async def get_all_laps(self):
		"""
		Fetches all LAPS passwords for all machines. This functionality is only available to specific high-privileged users.

		:return: Async generator which yields (`dict`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`dict`, :class:`Exception`)]
		"""

		ldap_filter = r'(sAMAccountType=805306369)'
		attributes = ['cn','ms-mcs-AdmPwd']
		async for entry, err in self.pagedsearch(ldap_filter, attributes):
			yield entry, err

	async def get_schemaentry(self, dn):
		"""
		Fetches one Schema entriy identified by dn

		:return: (`MSADSchemaEntry`, None) tuple on success or (None, `Exception`) on error
		:rtype: (:class:`MSADSchemaEntry`, :class:`Exception`)
		"""
		logger.debug('Polling Schema entry for %s'% dn)
		
		async for entry, err in self._con.pagedsearch(
			dn, 
			r'(distinguishedName=%s)' % escape_filter_chars(dn),
			attributes = [x.encode() for x in MSADSCHEMAENTRY_ATTRS], 
			size_limit = self.ldap_query_page_size, 
			search_scope=BASE, 
			controls = None, 
			):
				if err is not None:
					raise err
		
				return MSADSchemaEntry.from_ldap(entry), None
		else:
			return None, None
		logger.debug('Finished polling for entries!')
	
	async def get_all_schemaentry(self):
		"""
		Fetches all Schema entries under CN=Schema,CN=Configuration,...

		:return: Async generator which yields (`MSADSchemaEntry`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADSchemaEntry`, :class:`Exception`)]
		"""
		res = await self.get_tree_plot('CN=Schema,CN=Configuration,' + self._tree, level = 1)		
		for x in res:
			for dn in res[x]:
				async for entry, err in self._con.pagedsearch(
					dn, 
					r'(distinguishedName=%s)' % escape_filter_chars(dn),
					attributes = [x.encode() for x in MSADSCHEMAENTRY_ATTRS], 
					size_limit = self.ldap_query_page_size, 
					search_scope=BASE, 
					controls = None,
					rate_limit=self.ldap_query_ratelimit
					):
						if err is not None:
							yield None, err
							return
									
						yield MSADSchemaEntry.from_ldap(entry), None
						break
				else:
					yield None, None
					
		logger.debug('Finished polling for entries!')

	async def get_laps(self, sAMAccountName):
		"""
		Fetches the LAPS password for a machine. This functionality is only available to specific high-privileged users.
		
		:param sAMAccountName: The username of the machine (eg. `COMP123$`).
		:type sAMAccountName: str
		:return: Laps attributes as a `dict`
		:rtype: (:class:`dict`, :class:`Exception`)
		"""

		ldap_filter = r'(&(sAMAccountType=805306369)(sAMAccountName=%s))' % sAMAccountName
		attributes = ['cn','ms-mcs-AdmPwd']
		async for entry, err in self.pagedsearch(ldap_filter, attributes):
			return entry, err

	async def get_user(self, sAMAccountName):
		"""
		Fetches one user object from the AD, based on the sAMAccountName attribute (read: username) 
		
		:param sAMAccountName: The username of the user.
		:type sAMAccountName: str
		:return: A tuple with the user as `MSADUser` and an `Exception` is there was any
		:rtype: (:class:`MSADUser`, :class:`Exception`)
		"""
		logger.debug('Polling AD for user %s'% sAMAccountName)
		ldap_filter = r'(&(objectClass=user)(sAMAccountName=%s))' % sAMAccountName
		async for entry, err in self.pagedsearch(ldap_filter, MSADUser_ATTRS):
			if err is not None:
				return None, err
			return MSADUser.from_ldap(entry, self._ldapinfo), None
		else:
			return None, None
		logger.debug('Finished polling for entries!')

	async def get_machine(self, sAMAccountName):
		"""
		Fetches one machine object from the AD, based on the sAMAccountName attribute (read: username) 
		
		:param sAMAccountName: The username of the machine.
		:type sAMAccountName: str
		:return: A tuple with the user as `MSADMachine` and an `Exception` is there was any
		:rtype: (:class:`MSADMachine`, :class:`Exception`)
		"""
		logger.debug('Polling AD for user %s'% sAMAccountName)
		ldap_filter = r'(&(sAMAccountType=805306369)(sAMAccountName=%s))' % sAMAccountName
		async for entry, err in self.pagedsearch(ldap_filter, MSADMachine_ATTRS):
			if err is not None:
				return None, err
			return MSADMachine.from_ldap(entry, self._ldapinfo), None
		else:
			return None, None
		logger.debug('Finished polling for entries!')

	async def get_ad_info(self):
		"""
		Polls for basic AD information (needed for determine password usage characteristics!)
		
		:return: A tuple with the domain information as `MSADInfo` and an `Exception` is there was any
		:rtype: (:class:`MSADInfo`, :class:`Exception`)
		"""
		logger.debug('Polling AD for basic info')
		ldap_filter = r'(distinguishedName=%s)' % self._tree
		async for entry, err in self.pagedsearch(ldap_filter, MSADInfo_ATTRS):
			if err is not None:
				return None, err
			self._ldapinfo = MSADInfo.from_ldap(entry)
			return self._ldapinfo, None

		logger.debug('Poll finished!')

	async def get_all_spn_entries(self):
		"""
		Fetches all service user objects from the AD, and returns MSADUser object.
		Service user refers to an user with SPN (servicePrincipalName) attribute set

		:param include_machine: Specifies wether machine accounts should be included in the query
		:type include_machine: bool
		:return: Async generator which yields tuples with a string in SPN format and an Exception if there was any
		:rtype: Iterator[(:class:`str`, :class:`Exception`)]
		
		"""

		logger.debug('Polling AD for all SPN entries')
		ldap_filter = r'(&(sAMAccountType=805306369))'
		attributes = ['objectSid','sAMAccountName', 'servicePrincipalName']

		async for entry, err in self.pagedsearch(ldap_filter, attributes):
			yield entry, err

	async def get_all_service_users(self, include_machine = False):
		"""
		Fetches all service user objects from the AD, and returns MSADUser object.
		Service user refers to an user with SPN (servicePrincipalName) attribute set

		:param include_machine: Specifies wether machine accounts should be included in the query
		:type include_machine: bool
		
		:return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]

		"""
		logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine)
		if include_machine == True:
			ldap_filter = r'(servicePrincipalName=*)'
		else:
			ldap_filter = r'(&(servicePrincipalName=*)(!(sAMAccountName=*$)))'

		async for entry, err in self.pagedsearch(ldap_filter, MSADUser_ATTRS):
			if err is not None:
				yield None, err
				return
			yield MSADUser.from_ldap(entry, self._ldapinfo), None
		logger.debug('Finished polling for entries!')

	async def get_all_knoreq_users(self, include_machine = False):
		"""
		Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object.
		
		:param include_machine: Specifies wether machine accounts should be included in the query
		:type include_machine: bool
		:return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]

		"""
		logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine)
		if include_machine == True:
			ldap_filter = r'(userAccountControl:1.2.840.113556.1.4.803:=4194304)'
		else:
			ldap_filter = r'(&(userAccountControl:1.2.840.113556.1.4.803:=4194304)(!(sAMAccountName=*$)))'

		async for entry, err in self.pagedsearch(ldap_filter, MSADUser_ATTRS):
			if err is not None:
				yield None, err
				return
			yield MSADUser.from_ldap(entry, self._ldapinfo), None
		logger.debug('Finished polling for entries!')
			
	async def get_objectacl_by_dn_p(self, dn, flags = SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION):
		"""
		Returns the full or partial Security Descriptor of the object specified by it's DN.
		The flags indicate which part of the security Descriptor to be returned.
		By default the full SD info is returned.

		:param object_dn: The object's DN
		:type object_dn: str
		:param flags: Flags indicate the data type to be returned.
		:type flags: :class:`SDFlagsRequest`
		:return: 
		:rtype: :class:`MSADSecurityInfo`

		"""
		
		req_flags = SDFlagsRequestValue({'Flags' : flags})
		
		ldap_filter = r'(distinguishedName=%s)' % escape_filter_chars(dn)
		attributes = MSADSecurityInfo.ATTRS
		controls = [('1.2.840.113556.1.4.801', True, req_flags.dump())]
		
		async for entry, err in self.pagedsearch(ldap_filter, attributes, controls = controls):
			if err is not None:
				yield None, err
				return
			yield MSADSecurityInfo.from_ldap(entry), None

	async def get_objectacl_by_dn(self, dn, flags = SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION):
		"""
		Returns the full or partial Security Descriptor of the object specified by it's DN.
		The flags indicate which part of the security Descriptor to be returned.
		By default the full SD info is returned.

		:param object_dn: The object's DN
		:type object_dn: str
		:param flags: Flags indicate the data type to be returned.
		:type flags: :class:`SDFlagsRequest`
		:return: nTSecurityDescriptor attribute of the object as `bytes` and an `Exception` is there was any
		:rtype: (:class:`bytes`, :class:`Exception`)

		"""
		
		req_flags = SDFlagsRequestValue({'Flags' : flags})
		
		ldap_filter = r'(distinguishedName=%s)' % escape_filter_chars(dn)
		attributes = ['nTSecurityDescriptor']
		controls = [('1.2.840.113556.1.4.801', True, req_flags.dump())]
		
		async for entry, err in self.pagedsearch(ldap_filter, attributes, controls = controls):
			if err is not None:
				return None, err
			return entry['attributes'].get('nTSecurityDescriptor'), None
		return None, None

	async def set_objectacl_by_dn(self, object_dn, data, flags = SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION):
		"""
		Updates the security descriptor of the LDAP object
		
		:param object_dn: The object's DN
		:type object_dn: str
		:param data: The actual data as bytearray to be updated in the Security Descriptor of the specified object 
		:type data: bytes
		:param flags: Flags indicate the data type to be updated.
		:type flags: :class:`SDFlagsRequest`
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: tuple

		"""
		
		req_flags = SDFlagsRequestValue({'Flags' : flags})
		controls = [
					Control({
						'controlType' : b'1.2.840.113556.1.4.801',
						'controlValue': req_flags.dump(),
						'criticality' : True,
					})
				]

		changes = {
			'nTSecurityDescriptor': [('replace', [data])]
		}
		return await self._con.modify(object_dn, changes, controls = controls)
		
	async def get_all_groups(self, attrs = MSADGroup_ATTRS):
		"""
		Yields all Groups present in the LDAP tree.  
		
		:return: Async generator which yields (`MSADGroup`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADGroup`, :class:`Exception`)]
		"""
		ldap_filter = r'(objectClass=group)'
		async for entry, err in self.pagedsearch(ldap_filter, attrs):
			if err is not None:
				yield None, err
				return
			yield MSADGroup.from_ldap(entry), None
			
	async def get_all_ous(self):
		"""
		Yields all OUs present in the LDAP tree.  

		:return: Async generator which yields (`MSADOU`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADOU`, :class:`Exception`)]
		"""
		ldap_filter = r'(objectClass=organizationalUnit)'
		async for entry, err in self.pagedsearch(ldap_filter, MSADOU_ATTRS):
			if err is not None:
				yield None, err
				return
			yield MSADOU.from_ldap(entry), None
			
	async def get_group_by_dn(self, group_dn):
		"""
		Returns an `MSADGroup` object for the group specified by group_dn

		:param group_dn: The user's DN
		:type group_dn: str
		:return: tuple of `MSADGroup` and an `Exception` is there was any
		:rtype: (:class:`MSADGroup`, :class:`Exception`)
		"""

		ldap_filter = r'(&(objectClass=group)(distinguishedName=%s))' % escape_filter_chars(group_dn)
		async for entry, err in self.pagedsearch(ldap_filter, MSADGroup_ATTRS):
			if err is not None:
				return None, err
			return MSADGroup.from_ldap(entry), None
		
		return None, Exception('Search returned no results!')
			
	async def get_user_by_dn(self, user_dn):
		"""
		Fetches the DN for an object specified by `user_dn`

		:param user_dn: The user's DN
		:type user_dn: str
		:return: The user object
		:rtype: (:class:`MSADUser`, :class:`Exception`)
		"""

		ldap_filter = r'(&(objectClass=user)(distinguishedName=%s))' % user_dn
		async for entry, err in self.pagedsearch(ldap_filter, MSADUser_ATTRS):
			if err is not None:
				return None, err
			return MSADUser.from_ldap(entry), None
			
	async def get_group_members(self, dn, recursive = False):
		"""
		Fetches the DN for an object specified by `objectsid`

		:param dn: The object's DN
		:type dn: str
		:param recursive: Indicates wether the lookup should recursively affect all groups
		:type recursive: bool
		:return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]
		"""

		group, err = await self.get_group_by_dn(dn)
		if err is not None:
			yield None, err
			return
		for member in group.member:
			async for result, err in self.get_object_by_dn(member):
				if isinstance(result, MSADGroup) and recursive:
					async for user, err in self.get_group_members(result.distinguishedName, recursive = True):
						yield user, err
				else:
					yield result, err
		
						
	async def get_dn_for_objectsid(self, objectsid):
		"""
		Fetches the DN for an object specified by `objectsid`

		:param objectsid: The object's SID
		:type objectsid: str
		:return: The distinguishedName
		:rtype: (:class:`str`, :class:`Exception`)

		"""

		ldap_filter = r'(objectSid=%s)' % str(objectsid)
		async for entry, err in self.pagedsearch(ldap_filter, ['distinguishedName']):
			if err is not None:
				return None, err
			
			return entry['attributes']['distinguishedName'], None
		
		return None, Exception('Search returned no results!')

	async def get_objectsid_for_dn(self, dn):
		"""
		Fetches the objectsid for an object specified by `dn`

		:param dn: The object's distinguishedName
		:type dn: str
		:return: The SID of the pobject
		:rtype: (:class:`str`, :class:`Exception`)

		"""

		ldap_filter = r'(distinguishedName=%s)' % escape_filter_chars(dn)
		async for entry, err in self.pagedsearch(ldap_filter, ['objectSid']):
			if err is not None:
				return None, err
			
			return entry['attributes']['objectSid'], None
		
		return None, Exception('Search returned no results!')
	
	async def get_tokengroups_user(self, samaccountname):
		ldap_filter = r'(sAMAccountName=%s)' % escape_filter_chars(samaccountname)
		user_dn = None
		async for entry, err in self.pagedsearch(ldap_filter, ['distinguishedName']):
			if err is not None:
				return None, err
			
			user_dn = entry['attributes']['distinguishedName']
		
		if user_dn is None:
			return None, Exception('User not found! %s' % samaccountname)

		tokengroup = []
		async for sids, err in self.get_tokengroups(user_dn):
			if err is not None:
				return None, err
			tokengroup.append(sids)
		
		return tokengroup, None
		
	async def get_tokengroups(self, dn):
		"""
		Yields SIDs of groups that the given DN is a member of.

		:return: Async generator which yields (`str`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`str`, :class:`Exception`)]

		"""
		ldap_filter = r'(distinguishedName=%s)' % escape_filter_chars(dn)
		attributes=[b'tokenGroups']

		async for entry, err in self._con.pagedsearch(
			dn, 
			ldap_filter, 
			attributes = attributes, 
			size_limit = self.ldap_query_page_size, 
			search_scope=BASE, 
			rate_limit=self.ldap_query_ratelimit
			):
				if err is not None:
					yield None, err
					return
				
				#print(entry['attributes'])
				if 'tokenGroups' in entry['attributes']:
					for sid_data in entry['attributes']['tokenGroups']:
						yield sid_data, None
			
	async def get_all_tokengroups(self):
		"""
		Yields all effective group membership information for all objects of the following type:
		Users, Groups, Computers

		:return: Async generator which yields (`dict`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`dict`, :class:`Exception`)]

		"""

		ldap_filter = r'(|(sAMAccountType=805306369)(objectClass=group)(sAMAccountType=805306368))'
		async for entry, err in self.pagedsearch(
			ldap_filter, 
			attributes = ['dn', 'cn', 'objectSid','objectClass', 'objectGUID']
			):				
				if err is not None:
					yield None, err
					return
				if 'objectName' in entry:
					#print(entry['objectName'])
					async for entry2, err in self._con.pagedsearch(
						entry['objectName'], 
						r'(distinguishedName=%s)' % escape_filter_chars(entry['objectName']), 
						attributes = [b'tokenGroups'], 
						size_limit = self.ldap_query_page_size, 
						search_scope=BASE, 
						rate_limit=self.ldap_query_ratelimit
						):
							
							#print(entry2)
							if err is not None:
								yield None, err
								break
							if 'tokenGroups' in entry2['attributes']:
								for token in entry2['attributes']['tokenGroups']:
									yield {
										'cn' : entry['attributes']['cn'],
										'dn' : entry['objectName'],
										'guid' : entry['attributes']['objectGUID'],
										'sid' : entry['attributes']['objectSid'],
										'type' : entry['attributes']['objectClass'][-1],
										'token' : token

									}, None

	async def get_all_objectacl(self):
		"""
		Yields the security descriptor of all objects in the LDAP tree of the following types:  
		Users, Computers, GPOs, OUs, Groups

		:return: Async generator which yields (`MSADSecurityInfo`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADSecurityInfo`, :class:`Exception`)]

		"""
		
		flags_value = SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION
		req_flags = SDFlagsRequestValue({'Flags' : flags_value})
		
		ldap_filter = r'(|(objectClass=organizationalUnit)(objectCategory=groupPolicyContainer)(sAMAccountType=805306369)(objectClass=group)(sAMAccountType=805306368))'
		async for entry, err in self.pagedsearch(ldap_filter, attributes = ['dn']):
			if err is not None:
				yield None, err
				return
			ldap_filter = r'(distinguishedName=%s)' % escape_filter_chars(entry['objectName'])
			attributes = MSADSecurityInfo.ATTRS
			controls = [('1.2.840.113556.1.4.801', True, req_flags.dump())]
			
			async for entry2, err in self.pagedsearch(ldap_filter, attributes, controls = controls):
				if err is not None:
					yield None, err
					return
				yield MSADSecurityInfo.from_ldap(entry2), None


	async def get_all_trusts(self):
		"""
		Yields all trusted domains.

		:return: Async generator which yields (`MSADDomainTrust`, None) tuple on success or (None, `Exception`) on error
		:rtype: Iterator[(:class:`MSADDomainTrust`, :class:`Exception`)]

		"""

		ldap_filter = r'(objectClass=trustedDomain)'
		async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADDomainTrust_ATTRS):
			if err is not None:
				yield None, err
				return
			yield MSADDomainTrust.from_ldap(entry), None
		
	async def create_user_dn(self, user_dn, password):
		"""
		Creates a new user object with a password and enables the user so it can be used immediately.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:param password: The password of the user
		:type password: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		try:
			sn = user_dn.split(',')[0][3:]
			domain = self._tree[3:].replace(',DC=','.')
			attributes = {
				'objectClass':  ['organizationalPerson', 'person', 'top', 'user'], 
				'sn': sn, 
				'sAMAccountName': sn,
				'displayName': sn,
				'userPrincipalName' : "{}@{}".format(sn, domain),
			}
			
			_, err = await self._con.add(user_dn, attributes)
			if err is not None:
				return False, err

			_, err = await self.change_password(user_dn, password)
			if err is not None:
				return False, err

			_, err = await self.enable_user(user_dn)
			if err is not None:
				return False, err

			return True, None
		except Exception as e:
			return False, e


	async def unlock_user(self, user_dn):
		"""
		Unlocks the user by clearing the lockoutTime attribute.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'lockoutTime': [('replace', [0])]
		}
		return await self._con.modify(user_dn, changes)

	async def enable_user(self, user_dn):
		"""
		Sets the user object to enabled by modifying the UserAccountControl attribute.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'userAccountControl': [('replace', [512])]
		}
		return await self._con.modify(user_dn, changes)
	
	async def disable_user(self, user_dn):
		"""
		Sets the user object to disabled by modifying the UserAccountControl attribute.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'userAccountControl': [('replace', [2])]
		}
		return await self._con.modify(user_dn, changes)

	async def add_user_spn(self, user_dn, spn):
		"""
		Adds an SPN record to the user object.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:param spn: The SPN to be added. It must follow the SPN string format specifications.
		:type spn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'servicePrincipalName': [('add', [spn])]
		}
		return await self._con.modify(user_dn, changes)
	
	async def del_user_spn(self, user_dn, spn):
		"""
		Adds an SPN record to the user object.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:param spn: The SPN to be added. It must follow the SPN string format specifications.
		:type spn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'servicePrincipalName': [('delete', [spn])]
		}
		return await self._con.modify(user_dn, changes)

	async def add_additional_hostname(self, user_dn, hostname):
		"""
		Adds additional hostname to the user object.
		
		:param user_dn: The user's DN
		:type user_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'msds-additionaldnshostname': [('add', [hostname])]
		}
		return await self._con.modify(user_dn, changes)
		
	
	async def delete_user(self, user_dn):
		"""
		Deletes the user.
		This action is destructive!
		
		:param user_dn: The user's DN
		:type user_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		return await self._con.delete(user_dn)

	async def change_password(self, user_dn: str, newpass: str, oldpass = None):
		"""
		Changes the password of a user.  
		If used with a high-privileged account (eg. Domain admin, Account operator...), the old password can be `None` 
		
		:param user_dn: The user's DN
		:type user_dn: str
		:param newpass: The new password
		:type newpass: str		
		:param oldpass: The current password
		:type oldpass: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)

		"""
		changes = {
			'unicodePwd': []
		}
		if oldpass is not None:
			changes['unicodePwd'].append(('delete', ['"%s"' % oldpass]))
			changes['unicodePwd'].append(('add', ['"%s"' % newpass]))
		else:
			#if you are admin...
			changes['unicodePwd'].append(('replace', ['"%s"' % newpass]))

		return await self._con.modify(user_dn, changes)

	
	async def add_user_to_group(self, user_dn: str, group_dn: str):
		"""
		Adds a user to a group

		:param user_dn: The user's DN
		:type user_dn: str
		:param group_dn: The groups's DN
		:type group_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)


		"""
		changes = {
			'member': [('add', [user_dn])]
		}
		return await self._con.modify(group_dn, changes)

	async def del_user_from_group(self, user_dn: str, group_dn: str):
		"""
		Removes user from group

		:param user_dn: The user's DN
		:type user_dn: str
		:param group_dn: The groups's DN
		:type group_dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)


		"""
		changes = {
			'member': [('delete', [user_dn])]
		}
		return await self._con.modify(group_dn, changes)
		

	async def get_object_by_dn(self, dn, expected_class = None):
		ldap_filter = r'(distinguishedName=%s)' % dn
		async for entry, err in self.pagedsearch(ldap_filter, ALL_ATTRIBUTES):
			if err is not None:
				yield None, err
				return
			temp = entry['attributes'].get('objectClass')
			if expected_class:
				yield expected_class.from_ldap(entry), None
			
			if not temp:
				yield entry, None
			elif 'user' in temp:
				yield MSADUser.from_ldap(entry), None
			elif 'group' in temp:
				yield MSADGroup.from_ldap(entry), None

	async def modify(self, dn, changes, controls = None):
		"""
		Performs the modify operation.
		
		:param dn: The DN of the object whose attributes are to be modified
		:type dn: str
		:param changes: Describes the changes to be made on the object. Must be a dictionary of the following format: {'attribute': [('change_type', [value])]}
		:type changes: dict
		:param controls: additional controls to be passed in the query
		:type controls: dict
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)
		"""
		if controls is None:
			controls = []
		controls_conv = []
		for control in controls:		
			controls_conv.append(Control(control))
		return await self._con.modify(dn, changes, controls=controls_conv)


	async def add(self, dn, attributes):
		"""
		Performs the add operation.
		
		:param dn: The DN of the object to be added
		:type dn: str
		:param attributes: Attributes to be used in the operation
		:type attributes: dict
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)
		"""
		
		return await self._con.add(dn, attributes)

	async def delete(self, dn):
		"""
		Performs the delete operation.
		
		:param dn: The DN of the object to be deleted
		:type dn: str
		:return: A tuple of (True, None) on success or (False, Exception) on error. 
		:rtype: (:class:`bool`, :class:`Exception`)
		"""

		return await self._con.delete(dn)

	async def add_priv_addmember(self, user_dn, group_dn):
		"""Adds AddMember rights to the user on the group specified by group_dn"""
		try:
			#getting SID of target dn
			user_sid, err = await self.get_objectsid_for_dn(user_dn)
			if err is not None:
				raise err
			
			res, err = await self.get_objectacl_by_dn(group_dn)
			if err is not None:
				raise err
			if res is None:
				raise Exception('Failed to get forest\'s SD')
			group_sd = SECURITY_DESCRIPTOR.from_bytes(res)

			new_sd = copy.deepcopy(group_sd)
			
			ace_1 = ACCESS_ALLOWED_OBJECT_ACE()
			ace_1.Sid = SID.from_string(user_sid)
			ace_1.ObjectType = GUID.from_string('bf9679c0-0de6-11d0-a285-00aa003049e2')
			ace_1.Mask = ADS_ACCESS_MASK.WRITE_PROP
			ace_1.AceFlags = 0

			new_sd.Dacl.aces.append(ace_1)

			changes = {
				'nTSecurityDescriptor' : [('replace', [new_sd.to_bytes()])]
			}
			_, err = await self.modify(group_dn, changes)
			if err is not None:
				raise err

			return True, None
		except Exception as e:
			return False, e

	async def add_priv_dcsync(self, user_dn, forest_dn = None):
		"""Adds DCSync rights to the given user by modifying the forest's Security Descriptor to add GetChanges and GetChangesAll ACE"""
		try:
			#getting SID of target dn
			user_sid, err = await self.get_objectsid_for_dn(user_dn)
			if err is not None:
				raise err
			
			if forest_dn is None:					
				forest_dn = self._ldapinfo.distinguishedName
			
			res, err = await self.get_objectacl_by_dn(forest_dn)
			if err is not None:
				raise err
			if res is None:
				raise Exception('Failed to get forest\'s SD')
			forest_sd = SECURITY_DESCRIPTOR.from_bytes(res)


			new_sd = copy.deepcopy(forest_sd)
			
			ace_1 = ACCESS_ALLOWED_OBJECT_ACE()
			ace_1.Sid = SID.from_string(user_sid)
			ace_1.ObjectType = GUID.from_string('1131f6aa-9c07-11d1-f79f-00c04fc2dcd2')
			ace_1.Mask = ADS_ACCESS_MASK.CONTROL_ACCESS
			ace_1.AceFlags = 0


			new_sd.Dacl.aces.append(ace_1)
			
			ace_2 = ACCESS_ALLOWED_OBJECT_ACE()
			ace_2.Sid = SID.from_string(user_sid)
			ace_2.ObjectType = GUID.from_string('1131f6ad-9c07-11d1-f79f-00c04fc2dcd2')
			ace_2.Mask = ADS_ACCESS_MASK.CONTROL_ACCESS
			ace_2.AceFlags = 0

			new_sd.Dacl.aces.append(ace_2)

			changes = {
				'nTSecurityDescriptor' : [('replace', [new_sd.to_bytes()])]
			}
			_, err = await self.modify(forest_dn, changes)
			if err is not None:
				raise err

			return True, None
		except Exception as e:
			return False, e

	async def change_priv_owner(self, new_owner_sid, target_dn, target_attribute = None):
		"""Changes the owner in a Security Descriptor to the new_owner_sid on an LDAP object or on an LDAP object's attribute identified by target_dn and target_attribute. target_attribute can be omitted to change the target_dn's SD's owner"""
		try:
			try:
				new_owner_sid = SID.from_string(new_owner_sid)
			except:
				return False, Exception('Incorrect SID')


			target_sd = None
			if target_attribute is None or target_attribute == '':
				target_attribute = 'nTSecurityDescriptor'
				res, err = await self.get_objectacl_by_dn(target_dn)
				if err is not None:
					raise err
				target_sd = SECURITY_DESCRIPTOR.from_bytes(res)
			else:
				query = '(distinguishedName=%s)' % target_dn
				async for entry, err in self.pagedsearch(query, [target_attribute]):
					if err is not None:
						raise err
					target_sd = SECURITY_DESCRIPTOR.from_bytes(entry['attributes'][target_attribute])
					break
				else:
					raise Exception('Target DN not found!')

			new_sd = copy.deepcopy(target_sd)
			new_sd.Owner = new_owner_sid

			changes = {
				target_attribute : [('replace', [new_sd.to_bytes()])]
			}
			_, err = await self.modify(target_dn, changes)
			if err is not None:
				raise err

			return True, None
		except Exception as e:
			return False, e

	async def list_root_cas(self):
		try:
			ldap_filter = "(objectClass=certificationAuthority)"
			tree = "CN=Certification Authorities,CN=Public Key Services,CN=Services,CN=Configuration,%s" % self._ldapinfo.distinguishedName
			async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADCA_ATTRS, tree = tree):
				if err is not None:
					yield None, err
					return
				yield MSADCA.from_ldap(entry, 'ROOTCA'), None

		except Exception as e:
			yield None, e
			return
	
	async def list_ntcas(self):
		try:
			ldap_filter = "(objectClass=certificationAuthority)"
			tree = "CN=NTAuthCertificates,CN=Public Key Services,CN=Services,CN=Configuration,%s" % self._ldapinfo.distinguishedName
			async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADCA_ATTRS, tree = tree):
				if err is not None:
					yield None, err
					return
				yield MSADCA.from_ldap(entry, 'NTCA'), None

		except Exception as e:
			yield None, e
			return

	async def list_aiacas(self):
		try:
			ldap_filter = "(objectClass=certificationAuthority)"
			tree = "CN=AIA,CN=Public Key Services,CN=Services,CN=Configuration,%s" % self._ldapinfo.distinguishedName
			async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADCA_ATTRS, tree = tree):
				if err is not None:
					yield None, err
					return
				yield MSADCA.from_ldap(entry, 'AIACA'), None

		except Exception as e:
			yield None, e
			return

	async def list_enrollment_services(self):
		try:
			ldap_filter = "(objectCategory=pKIEnrollmentService)"
			tree = "CN=Configuration,%s" % self._ldapinfo.distinguishedName

			async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADEnrollmentService_ATTRS, tree = tree):
				if err is not None:
					yield None, err
					return
				yield MSADEnrollmentService.from_ldap(entry), None
			
		except Exception as e:
			yield None, e
			return

	async def list_certificate_templates(self, name = None):
		try:
			req_flags = SDFlagsRequestValue({'Flags' : SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION})
			controls = [('1.2.840.113556.1.4.801', True, req_flags.dump())]

			ldap_filter = "(objectCategory=pKICertificateTemplate)"
			if name is not None:
				ldap_filter = "(&(objectCategory=pKICertificateTemplate)(name=%s))" % name
			tree = "CN=Configuration,%s" % self._ldapinfo.distinguishedName

			async for entry, err in self.pagedsearch(ldap_filter, attributes = MSADCertificateTemplate_ATTRS, controls=controls, tree = tree):
				if err is not None:
					yield None, err
					return
				yield MSADCertificateTemplate.from_ldap(entry), None
			
		except Exception as e:
			yield None, e
			return

	async def list_gmsa(self):
		try:
			ldap_filter = r'(objectClass=msDS-GroupManagedServiceAccount)'
			async for entry, err in self.pagedsearch(ldap_filter, attributes = ['sAMAccountName','msDS-GroupMSAMembership', 'msDS-ManagedPassword']):
				if err is not None:
					yield None, err
					return
				yield entry['attributes'].get('sAMAccountName'), entry['attributes'].get('msDS-GroupMSAMembership'), entry['attributes'].get('msDS-ManagedPassword'), None

		except Exception as e:
			yield None, None, None, e
			return


	async def resolv_sd(self, sd):
		"Resolves all SIDs found in security descriptor, returns lookup table"
		try:
			if isinstance(sd, bytes):
				sd = SECURITY_DESCRIPTOR.from_bytes(sd)
			
			lookup_table = {}
			sids = {}
			sids[str(sd.Owner)] = 1
			sids[str(sd.Group)] = 1
			if sd.Dacl is not None:
				for ace in sd.Dacl.aces:
					sids[str(ace.Sid)] = 1
			if sd.Sacl is not None:
				for ace in sd.Sacl.aces:
					sids[str(ace.Sid)] = 1
			
			for sid in sids:
				domain, username, err = await self.resolv_sid(sid)
				if err is not None:
					raise err
				lookup_table[sid] = (domain, username)
			
			return lookup_table, None

		except Exception as e:
			return None, e
	
	async def resolv_sid(self, sid, use_cache = True):
		"""Performs a SID lookup for object and returns the domain name and the samaccountname"""
		try:
			sid = str(sid).upper()
			if sid in KNOWN_SIDS:
				return "BUILTIN", KNOWN_SIDS[sid], None
			domain = None
			username = None
			domainsid = sid.rsplit('-',1)[0]
			if domainsid not in self._domainsid_cache:
				logger.debug('Domain SID "%s" was not found! ' % domainsid)
				return '???', '???', None
			domain = self._domainsid_cache[domainsid]
			if sid in self._sid_cache:
				username = self._sid_cache[sid]
			
			else:
				ldap_filter = r'(objectSid=%s)' % sid
				async for entry, err in self.pagedsearch(ldap_filter, attributes = ['sAMAccountName']):
					if err is not None:
						return None, None, err
					username = entry['attributes'].get('sAMAccountName')
				
				if username is None:
					return domain, '???', None
					#raise Exception('User not found! %s' % sid)
			
			if use_cache is True:
				self._sid_cache[sid] = username
			return domain, username, None
		except Exception as e:
			return None, None, e
	
	async def whoami(self):
		return await self._con.whoami()

	async def whoamifull(self):
		"""Full whoami"""
		#TODO: it can be the case that the server returns the SID of the user
		# implement that path!
		result = {}
		try:
			res, err = await self.whoami()
			if err is not None:
				raise err
			result['raw'] = res
			if res.startswith('u:') is True:
				domain, samaccountname = res[2:].split('\\', 1)
				result['domain'] = domain
				result['samaccountname'] = samaccountname
				user, err = await self.get_user(samaccountname)
				if err is not None:
					raise err
				result['sid'] = str(user.objectSid)
				result['groups'] = {}
				async for group_sid, err in self.get_tokengroups(user.distinguishedName):
					if err is not None:
						raise err
					result['groups'][group_sid] = ('NA','NA')
					domain, username, err = await self.resolv_sid(group_sid)
					if err is not None:
						raise err
					result['groups'][group_sid] = (domain, username)				
			
			return result, None
		except:
			return result, None

	#async def get_permissions_for_dn(self, dn):
	#	"""
	#	Lists all users who can modify the specified dn
	#	"""
	#	async for secinfo in self.get_objectacl_by_dn(dn):
	#		for sdec in secinfo.nTSecurityDescriptor:
	#			sids_to_lookup = {}
	#			if not sdec.Dacl:
	#				continue
	#			
	#			for ace in sdec.Dacl.aces:
	#				sids_to_lookup[str(ace.Sid)] = 1
	#			
	#			for sid in sids_to_lookup:
	#				sids_to_lookup[sid] = self.get_dn_for_objectsid(sid)
	#				
	#			print(sids_to_lookup)
	#			
	#			for ace in sdec.Dacl.aces:
	#				if not sids_to_lookup[str(ace.Sid)]:
	#					print(str(ace.Sid))
	#				#print('===== %s =====' % sids_to_lookup[str(ace.Sid)])
	#				#if 
	#				#print(str(ace))
	
	#async def get_all_tokengroups(self):
	#	"""
	#	returns the tokengroups attribute for all user and machine on the server
	#	"""
	#	dns = []
	#	
	#	ldap_filters = [r'(objectClass=user)', r'(sAMAccountType=805306369)']
	#	attributes = ['distinguishedName']
	#	
	#	for ldap_filter in ldap_filters:
	#		print(ldap_filter)
	#		for entry in self.pagedsearch(ldap_filter, attributes):
	#			print(entry['attributes']['distinguishedName'])
	#			dns.append(entry['attributes']['distinguishedName'])
	#
	#	attributes=['tokenGroups', 'sn', 'cn', 'distinguishedName','objectGUID', 'objectSid']
	#	for dn in dns:
	#		ldap_filter = r'(distinguishedName=%s)' % dn
	#		self._con.search(dn, ldap_filter, attributes=attributes, search_scope=BASE)
	#		async for entry, err in self._con.response:
	#			#yield MSADTokenGroup.from_ldap(entry)
	#			print(str(MSADTokenGroup.from_ldap(entry)))

			
	#async def get_all_objectacl(self):
	#	"""
	#	Returns all ACL info for all AD objects
	#	"""
	#	
	#	flags_value = SDFlagsRequest.DACL_SECURITY_INFORMATION|SDFlagsRequest.GROUP_SECURITY_INFORMATION|SDFlagsRequest.OWNER_SECURITY_INFORMATION
	#	req_flags = SDFlagsRequestValue({'Flags' : flags_value})
	#	
	#	ldap_filter = r'(objectClass=*)'
	#	attributes = MSADSecurityInfo.ATTRS
	#	controls = [('1.2.840.113556.1.4.801', True, req_flags.dump())]
	#	
	#	async for entry in self.pagedsearch(ldap_filter, attributes, controls = controls):
	#		yield MSADSecurityInfo.from_ldap(entry)


	#async def get_netdomain(self):
	#	def nameconvert(x):
	#		return x.split(',CN=')[1]
	#	"""
	#	gets the name of the current user's domain
	#	"""
	#	if not self._ldapinfo:
	#		self.get_ad_info()
	#	print(self._ldapinfo)
	#	dname = self._ldapinfo.distinguishedName.replace('DC','').replace('=','').replace(',','.')
	#	domain_controllers = ','.join(nameconvert(x) + '.' +dname  for x in self._ldapinfo.masteredBy)
	#	
	#	ridroleowner = nameconvert(self.get_ridroleowner()) + '.' +dname
	#	infraowner = nameconvert(self.get_infrastructureowner()) + '.' +dname
	#	pdcroleowner = nameconvert(self.get_pdcroleowner()) + '.' +dname
	#	
	#	print('name : %s' % dname)
	#	print('Domain Controllers : %s' % domain_controllers)
	#	print('DomainModeLevel : %s' % self._ldapinfo.domainmodelevel)
	#	print('PdcRoleOwner : %s' % pdcroleowner)
	#	print('RidRoleOwner : %s' % ridroleowner)
	#	print('InfrastructureRoleOwner : %s' % infraowner)
	#	
	#async def get_domaincontroller(self):
	#	ldap_filter = r'(userAccountControl:1.2.840.113556.1.4.803:=8192)'
	#	async for entry in self.pagedsearch(ldap_filter, ALL_ATTRIBUTES):
	#		print('Forest: %s' % '')
	#		print('Name: %s' % entry['attributes'].get('dNSHostName'))
	#		print('OSVersion: %s' % entry['attributes'].get('operatingSystem'))
	#		print(entry['attributes'])

	#async def get_pdcroleowner(self):
	#	#http://adcoding.com/how-to-determine-the-fsmo-role-holder-fsmoroleowner-attribute/
	#	#get adinfo -> get ridmanagerreference attr -> look up the dn of ridmanagerreference -> get fsmoroleowner attr (which is a DN)
	#	if not self._ldapinfo:
	#		self.get_ad_info()
	#	
	#	ldap_filter = r'(distinguishedName=%s)' % self._ldapinfo.rIDManagerReference
	#	async for entry in self.pagedsearch(ldap_filter, ['fSMORoleOwner']):
	#		return entry['attributes']['fSMORoleOwner']
	#	
	#async def get_infrastructureowner(self):
	#	#http://adcoding.com/how-to-determine-the-fsmo-role-holder-fsmoroleowner-attribute/
	#	#"CN=Infrastructure,DC=concorp,DC=contoso,DC=com" -l fSMORoleOwner
	#	if not self._ldapinfo:
	#		self.get_ad_info()
	#	
	#	ldap_filter = r'(distinguishedName=%s)' % ('CN=Infrastructure,' + self._ldapinfo.distinguishedName)
	#	async for entry in self.pagedsearch(ldap_filter, ['fSMORoleOwner']):
	#		return entry['attributes']['fSMORoleOwner']
	#		
	#async def get_ridroleowner(self):
	#	#http://adcoding.com/how-to-determine-the-fsmo-role-holder-fsmoroleowner-attribute/
	#	if not self._ldapinfo:
	#		self.get_ad_info()
	#	
	#	ldap_filter = r'(distinguishedName=%s)' % ('CN=RID Manager$,CN=System,' + self._ldapinfo.distinguishedName)
	#	async for entry in self.pagedsearch(ldap_filter, ['fSMORoleOwner']):
	#		return entry['attributes']['fSMORoleOwner']

	#async def get_all_user_raw(self):
	#	"""
	#	Fetches all user objects from the AD, and returns MSADUser object
	#	"""
	#	logger.debug('Polling AD for all user objects')
	#	ldap_filter = r'(sAMAccountType=805306368)'
	#
	#	return self.pagedsearch(ldap_filter, MSADUser_ATTRS)