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
|
# Tests for source4/libnet/py_net_dckeytab.c
#
# Copyright (C) David Mulder <dmulder@suse.com> 2018
#
# 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 subprocess
import time
from samba.net import Net
from samba import enable_net_export_keytab
from samba import credentials, dsdb, ntstatus, NTSTATUSError
from samba.dcerpc import krb5ccache, security
from samba.dsdb import UF_WORKSTATION_TRUST_ACCOUNT
from samba.ndr import ndr_unpack, ndr_pack
from samba.param import LoadParm
from samba.samdb import SamDB
from samba.tests import TestCaseInTempDir, delete_force
from ldb import SCOPE_BASE
enable_net_export_keytab()
def keytab_as_set(keytab_bytes):
def entry_to_tuple(entry):
principal = '/'.join(entry.principal.components) + f"@{entry.principal.realm}"
enctype = entry.enctype
kvno = entry.key_version
key = bytes(entry.key.data)
return (principal, enctype, kvno, key)
keytab = ndr_unpack(krb5ccache.KEYTAB, keytab_bytes)
entry = keytab.entry
keytab_set = set()
entry_as_tuple = entry_to_tuple(entry)
keytab_set.add(entry_as_tuple)
keytab_bytes = keytab.further_entry
while keytab_bytes:
multiple_entry = ndr_unpack(krb5ccache.MULTIPLE_KEYTAB_ENTRIES, keytab_bytes)
entry = multiple_entry.entry
entry_as_tuple = entry_to_tuple(entry)
if entry_as_tuple in keytab_set:
raise AssertionError('entry found multiple times in keytab')
keytab_set.add(entry_as_tuple)
keytab_bytes = multiple_entry.further_entry
return keytab_set
class DCKeytabTests(TestCaseInTempDir):
def setUp(self):
super().setUp()
self.lp = LoadParm()
self.lp.load_default()
self.creds = self.insta_creds(template=self.get_credentials())
self.samdb = SamDB(url=f"ldap://{os.environ.get('SERVER')}",
credentials=self.creds,
lp=self.lp)
self.ktfile = os.path.join(self.tempdir, 'test.keytab')
self.principal = self.creds.get_principal()
def tearDown(self):
super().tearDown()
def test_export_keytab(self):
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=self.principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
# confirm only this principal was exported
for entry in keytab_as_set(keytab_bytes):
(principal, enctype, kvno, key) = entry
self.assertEqual(principal, self.principal)
def test_export_keytab_all(self):
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
# Parse the keytab
keytab_set = keytab_as_set(keytab_bytes)
# confirm many principals were exported
self.assertGreater(len(keytab_set), 10)
def test_export_keytab_all_keep_stale(self):
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile)
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net.export_keytab(keytab=self.ktfile, keep_stale_entries=True)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
# confirm many principals were exported
# keytab_as_set() will also check we only got it
# each entry once
keytab_set = keytab_as_set(keytab_bytes)
self.assertGreater(len(keytab_set), 10)
# Look for the new principal, showing this was updated
found = False
for entry in keytab_set:
(principal, enctype, kvno, key) = entry
if principal == new_principal:
found = True
self.assertTrue(found)
def test_export_keytab_nochange_update(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
ktfile1 = self.ktfile + ".1"
self.addCleanup(self.rm_files, ktfile1, allow_missing=True)
ktfile2 = self.ktfile + ".2"
self.addCleanup(self.rm_files, ktfile2, allow_missing=True)
# The export includes the current timestamp
# so we better do both exports within the
# same second.
#
# First we sleep until we reach the next second
now = time.time()
next = float(int(now)+1)
sleep = next-now
time.sleep(sleep)
start = time.time()
net.export_keytab(keytab=ktfile1, principal=new_principal)
net.export_keytab(keytab=ktfile2, principal=new_principal)
end = time.time()
self.assertTrue(os.path.exists(ktfile1), 'keytab1 was not created')
self.assertTrue(os.path.exists(ktfile2), 'keytab2 was not created')
print("now: %f" % now)
print("next: %f" % next)
print("sleep: %f" % sleep)
print("start: %f" % start)
print("end: %f" % end)
self.assertEqual(int(end), int(start))
# The output may contain the file name
# so we have to use self.ktfile...
os.rename(ktfile1, self.ktfile)
cmd = ['klist', '-K', '-C', '-t', '-k', self.ktfile]
keytab_orig_content = subprocess.Popen(
cmd,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
).communicate()[0]
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
# The output may contain the file name
# so we have to use self.ktfile...
os.rename(ktfile2, self.ktfile)
cmd = ['klist', '-K', '-C', '-t', '-k', self.ktfile]
keytab_content = subprocess.Popen(
cmd,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
).communicate()[0]
self.maxDiff = None # No maximum length of diffs.
self.assertMultiLineEqual(keytab_orig_content.decode(),
keytab_content.decode())
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
self.assertEqual(keytab_orig_bytes, keytab_bytes)
# confirm only this principal was exported.
# keytab_as_set() will also check we only got it
# once
for entry in keytab_as_set(keytab_bytes):
(principal, enctype, kvno, key) = entry
self.assertEqual(principal, new_principal)
def test_export_keytab_change_update(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=new_principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "5rfvBGT%")
net.export_keytab(keytab=self.ktfile, principal=new_principal)
with open(self.ktfile, 'rb') as bytes_kt:
keytab_change_bytes = bytes_kt.read()
self.assertNotEqual(keytab_orig_bytes, keytab_change_bytes)
# We can't parse it as the parser is simple and doesn't
# understand holes in the file.
def test_export_keytab_change2_update(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=new_principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
# intended to trigger the pruning code for old keys
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "5rfvBGT%")
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "6rfvBGT%")
net.export_keytab(keytab=self.ktfile, principal=new_principal)
with open(self.ktfile, 'rb') as bytes_kt:
keytab_change_bytes = bytes_kt.read()
self.assertNotEqual(keytab_orig_bytes, keytab_change_bytes)
# We can't parse it as the parser is simple and doesn't
# understand holes in the file.
def test_export_keytab_change3_update_keep(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=new_principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
# By changing the password three times, we allow Samba to fill
# out current, old, older from supplementalCredentials and
# still have one password that must still be from the original
# keytab
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "5rfvBGT%")
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "6rfvBGT%")
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "7rfvBGT%")
net.export_keytab(keytab=self.ktfile, principal=new_principal, keep_stale_entries=True)
with open(self.ktfile, 'rb') as bytes_kt:
keytab_change_bytes = bytes_kt.read()
self.assertNotEqual(keytab_orig_bytes, keytab_change_bytes)
# keytab_as_set() will also check we got each entry
# exactly once
keytab_set = keytab_as_set(keytab_change_bytes)
# Look for the new principal, showing this was updated but the old kept
found = 0
for entry in keytab_set:
(principal, enctype, kvno, key) = entry
if principal == new_principal and enctype == credentials.ENCTYPE_AES128_CTS_HMAC_SHA1_96:
found += 1
# We exported the previous keys into the keytab...
self.assertEqual(found, 4)
# confirm at least 12 keys (4 changes, 1 in orig export and 3
# history in 2nd export, 3 enctypes) were exported
self.assertGreaterEqual(len(keytab_set), 12)
def test_export_keytab_change3_update_only_current_keep(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=new_principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
# By changing the password three times, we allow Samba to fill
# out current, old, older from supplementalCredentials and
# still have one password that must still be from the original
# keytab
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "5rfvBGT%")
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "6rfvBGT%")
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "7rfvBGT%")
net.export_keytab(keytab=self.ktfile,
principal=new_principal,
keep_stale_entries=True,
only_current_keys=True)
with open(self.ktfile, 'rb') as bytes_kt:
keytab_change_bytes = bytes_kt.read()
self.assertNotEqual(keytab_orig_bytes, keytab_change_bytes)
# keytab_as_set() will also check we got each entry
# exactly once
keytab_set = keytab_as_set(keytab_change_bytes)
# Look for the new principal, showing this was updated but the old kept
found = 0
for entry in keytab_set:
(principal, enctype, kvno, key) = entry
if principal == new_principal and enctype == credentials.ENCTYPE_AES128_CTS_HMAC_SHA1_96:
found += 1
# By default previous keys are not exported into the keytab.
self.assertEqual(found, 2)
# confirm at least 6 keys (1 change, 1 in orig export
# both with 3 enctypes) were exported
self.assertGreaterEqual(len(keytab_set), 6)
def test_export_keytab_change2_export2_update_keep(self):
new_principal=f"keytab_testuser@{self.creds.get_realm()}"
self.samdb.newuser("keytab_testuser", "4rfvBGT%")
self.addCleanup(self.samdb.deleteuser, "keytab_testuser")
net = Net(None, self.lp)
self.addCleanup(self.rm_files, self.ktfile)
net.export_keytab(keytab=self.ktfile, principal=new_principal)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_orig_bytes = bytes_kt.read()
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "5rfvBGT%")
net.export_keytab(keytab=self.ktfile, principal=new_principal, keep_stale_entries=True)
self.samdb.setpassword(f"(userPrincipalName={new_principal})", "6rfvBGT%")
net.export_keytab(keytab=self.ktfile, principal=new_principal, keep_stale_entries=True)
with open(self.ktfile, 'rb') as bytes_kt:
keytab_change_bytes = bytes_kt.read()
self.assertNotEqual(keytab_orig_bytes, keytab_change_bytes)
# keytab_as_set() will also check we got each entry
# exactly once
keytab_set = keytab_as_set(keytab_change_bytes)
# Look for the new principal, showing this was updated but the old kept
found = 0
for entry in keytab_set:
(principal, enctype, kvno, key) = entry
if principal == new_principal and enctype == credentials.ENCTYPE_AES128_CTS_HMAC_SHA1_96:
found += 1
# This covers the simple case, one export per password change
self.assertEqual(found, 3)
# confirm at least 9 keys (3 exports, 3 enctypes) were exported
self.assertGreaterEqual(len(keytab_set), 9)
def test_export_keytab_not_a_dir(self):
net = Net(None, self.lp)
with open(self.ktfile, mode='w') as f:
f.write("NOT A KEYTAB")
self.addCleanup(self.rm_files, self.ktfile)
try:
net.export_keytab(keytab=self.ktfile + "/f")
self.fail("Expected failure to write to an existing file")
except NTSTATUSError as err:
num, _ = err.args
self.assertEqual(num, ntstatus.NT_STATUS_NOT_A_DIRECTORY)
def test_export_keytab_existing(self):
net = Net(None, self.lp)
with open(self.ktfile, mode='w') as f:
f.write("NOT A KEYTAB")
self.addCleanup(self.rm_files, self.ktfile)
try:
net.export_keytab(keytab=self.ktfile)
self.fail(f"Expected failure to write to an existing file {self.ktfile}")
except NTSTATUSError as err:
num, _ = err.args
self.assertEqual(num, ntstatus.NT_STATUS_OBJECT_NAME_EXISTS)
def test_export_keytab_gmsa(self):
# Create gMSA account
gmsa_username = "GMSA_K5KeytabTest$"
gmsa_principal = f"{gmsa_username}@{self.samdb.domain_dns_name().upper()}"
gmsa_base_dn = self.samdb.get_wellknown_dn(
self.samdb.get_default_basedn(),
dsdb.DS_GUID_MANAGED_SERVICE_ACCOUNTS_CONTAINER,
)
gmsa_user_dn = f"CN={gmsa_username},{gmsa_base_dn}"
msg = self.samdb.search(base="", scope=SCOPE_BASE, attrs=["tokenGroups"])[0]
connecting_user_sid = str(ndr_unpack(security.dom_sid, msg["tokenGroups"][0]))
domain_sid = security.dom_sid(self.samdb.get_domain_sid())
allow_sddl = f"O:SYD:(A;;RP;;;{connecting_user_sid})"
allow_sd = ndr_pack(security.descriptor.from_sddl(allow_sddl, domain_sid))
details = {
"dn": str(gmsa_user_dn),
"objectClass": "msDS-GroupManagedServiceAccount",
"msDS-ManagedPasswordInterval": "1",
"msDS-GroupMSAMembership": allow_sd,
"sAMAccountName": gmsa_username,
"userAccountControl": str(UF_WORKSTATION_TRUST_ACCOUNT),
}
delete_force(self.samdb, gmsa_user_dn)
self.samdb.add(details)
self.addCleanup(delete_force, self.samdb, gmsa_user_dn)
# Export keytab of gMSA account remotely
net = Net(None, self.lp)
try:
net.export_keytab(samdb=self.samdb, keytab=self.ktfile, principal=gmsa_principal)
except RuntimeError as e:
self.fail(e)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
remote_keytab = ndr_unpack(krb5ccache.KEYTAB, keytab_bytes)
self.rm_files('test.keytab')
# Export keytab of gMSA account locally
try:
net.export_keytab(keytab=self.ktfile, principal=gmsa_principal)
except RuntimeError as e:
self.fail(e)
self.assertTrue(os.path.exists(self.ktfile), 'keytab was not created')
# Parse the first entry in the keytab
with open(self.ktfile, 'rb') as bytes_kt:
keytab_bytes = bytes_kt.read()
self.rm_files('test.keytab')
local_keytab = ndr_unpack(krb5ccache.KEYTAB, keytab_bytes)
# Confirm that the principal is as expected
principal_parts = gmsa_principal.split('@')
self.assertEqual(local_keytab.entry.principal.component_count, 1)
self.assertEqual(local_keytab.entry.principal.realm, principal_parts[1])
self.assertEqual(local_keytab.entry.principal.components[0], principal_parts[0])
self.assertEqual(remote_keytab.entry.principal.component_count, 1)
self.assertEqual(remote_keytab.entry.principal.realm, principal_parts[1])
self.assertEqual(remote_keytab.entry.principal.components[0], principal_parts[0])
# Put all keys from each into a dictionary, and confirm all remote keys are in local keytab
remote_keys = {}
while True:
remote_keys[remote_keytab.entry.enctype] = bytes(remote_keytab.entry.key.data)
keytab_bytes = remote_keytab.further_entry
if not keytab_bytes:
break
remote_keytab = ndr_unpack(krb5ccache.MULTIPLE_KEYTAB_ENTRIES, keytab_bytes)
local_keys = {}
while True:
local_keys[local_keytab.entry.enctype] = bytes(local_keytab.entry.key.data)
keytab_bytes = local_keytab.further_entry
if not keytab_bytes:
break
local_keytab = ndr_unpack(krb5ccache.MULTIPLE_KEYTAB_ENTRIES, keytab_bytes)
# Check that the gMSA keys are in the local keys
remote_enctypes = set(remote_keys.keys())
# Check that at least the AES keys were generated
self.assertLessEqual({credentials.ENCTYPE_AES256_CTS_HMAC_SHA1_96,
credentials.ENCTYPE_AES128_CTS_HMAC_SHA1_96},
remote_enctypes)
local_enctypes = set(local_keys.keys())
self.assertLessEqual(remote_enctypes, local_enctypes)
common_enctypes = remote_enctypes & local_enctypes
for enctype in common_enctypes:
self.assertEqual(remote_keys[enctype], local_keys[enctype])
|