Blame src/tests/t_mkey.py

Packit fd8b60
from k5test import *
Packit fd8b60
import random
Packit fd8b60
import re
Packit fd8b60
import struct
Packit fd8b60
Packit fd8b60
# Convenience constants for use as expected enctypes.  defetype is the
Packit fd8b60
# default enctype for master keys.
Packit fd8b60
aes256 = 'aes256-cts-hmac-sha1-96'
Packit fd8b60
aes128 = 'aes128-cts-hmac-sha1-96'
Packit fd8b60
defetype = aes256
Packit fd8b60
Packit fd8b60
realm = K5Realm(create_host=False, start_kadmind=True)
Packit fd8b60
realm.prep_kadmin()
Packit fd8b60
stash_file = os.path.join(realm.testdir, 'stash')
Packit fd8b60
Packit fd8b60
# Count the number of principals in the realm.
Packit fd8b60
nprincs = len(realm.run([kadminl, 'listprincs']).splitlines())
Packit fd8b60
Packit fd8b60
# List the currently active mkeys and compare against expected
Packit fd8b60
# results.  Each argument must be a sequence of four elements: an
Packit fd8b60
# expected kvno, an expected enctype, whether the key is expected to
Packit fd8b60
# have an activation time, and whether the key is expected to be
Packit fd8b60
# currently active.
Packit fd8b60
list_mkeys_re = re.compile(r'^KVNO: (\d+), Enctype: (\S+), '
Packit fd8b60
                           '(Active on: [^\*]+|No activate time set)( \*)?$')
Packit fd8b60
def check_mkey_list(*expected):
Packit fd8b60
    # Split the output of kdb5_util list_mkeys into lines and ignore the first.
Packit fd8b60
    outlines = realm.run([kdb5_util, 'list_mkeys']).splitlines()[1:]
Packit fd8b60
    if len(outlines) != len(expected):
Packit fd8b60
        fail('Unexpected number of list_mkeys output lines')
Packit fd8b60
    for line, ex in zip(outlines, expected):
Packit fd8b60
        m = list_mkeys_re.match(line)
Packit fd8b60
        if not m:
Packit fd8b60
            fail('Unrecognized list_mkeys output line')
Packit fd8b60
        kvno, enctype, act_time, active = m.groups()
Packit fd8b60
        exp_kvno, exp_enctype, exp_act_time_present, exp_active = ex
Packit fd8b60
        if kvno != str(exp_kvno):
Packit fd8b60
            fail('Unexpected master key version')
Packit fd8b60
        if enctype != exp_enctype:
Packit fd8b60
            fail('Unexpected master key enctype')
Packit fd8b60
        if act_time.startswith('Active on: ') != exp_act_time_present:
Packit fd8b60
            fail('Unexpected presence or absence of mkey activation time')
Packit fd8b60
        if (active == ' *') != exp_active:
Packit fd8b60
            fail('Master key unexpectedly active or inactive')
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Get the K/M principal.  Verify that it has the expected mkvno.  Each
Packit fd8b60
# remaining argment must be a sequence of two elements: an expected
Packit fd8b60
# key version and an expected enctype.
Packit fd8b60
keyline_re = re.compile(r'^Key: vno (\d+), (\S+)$')
Packit fd8b60
def check_master_dbent(expected_mkvno, *expected_keys):
Packit fd8b60
    outlines = realm.run([kadminl, 'getprinc', 'K/M']).splitlines()
Packit fd8b60
    mkeyline = [l for l in outlines if l.startswith('MKey: vno ')]
Packit fd8b60
    if len(mkeyline) != 1 or mkeyline[0] != ('MKey: vno %d' % expected_mkvno):
Packit fd8b60
        fail('Unexpected mkvno in K/M DB entry')
Packit fd8b60
    keylines = [l for l in outlines if l.startswith('Key: vno ')]
Packit fd8b60
    if len(keylines) != len(expected_keys):
Packit fd8b60
        fail('Unexpected number of key lines in K/M DB entry')
Packit fd8b60
    for line, ex in zip(keylines, expected_keys):
Packit fd8b60
        m = keyline_re.match(line)
Packit fd8b60
        if not m:
Packit fd8b60
            fail('Unrecognized key line in K/M DB entry')
Packit fd8b60
        kvno, enctype = m.groups()
Packit fd8b60
        exp_kvno, exp_enctype = ex
Packit fd8b60
        if kvno != str(exp_kvno):
Packit fd8b60
            fail('Unexpected key version in K/M DB entry')
Packit fd8b60
        if enctype != exp_enctype:
Packit fd8b60
            fail('Unexpected enctype in K/M DB entry')
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Check the stash file.  Each argument must be a sequence of two
Packit fd8b60
# elements: an expected key version and an expected enctype.
Packit fd8b60
klist_re = re.compile(r'^\s*(\d+) K/M@KRBTEST.COM \((\S+)\)')
Packit fd8b60
def check_stash(*expected):
Packit fd8b60
    # Split the output of klist -e -k into lines and ignore the first three.
Packit fd8b60
    outlines = realm.run([klist, '-e', '-k', stash_file]).splitlines()[3:]
Packit fd8b60
    if len(outlines) != len(expected):
Packit fd8b60
        fail('Unexpected number of lines in stash file klist')
Packit fd8b60
    for line, ex in zip(outlines, expected):
Packit fd8b60
        m = klist_re.match(line)
Packit fd8b60
        if not m:
Packit fd8b60
            fail('Unrecognized stash file klist line')
Packit fd8b60
        kvno, enctype = m.groups()
Packit fd8b60
        exp_kvno, exp_enctype = ex
Packit fd8b60
        if kvno != str(exp_kvno):
Packit fd8b60
            fail('Unexpected stash file klist kvno')
Packit fd8b60
        if enctype != exp_enctype:
Packit fd8b60
            fail('Unexpected stash file klist enctype')
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Verify that the user principal has the expected mkvno.
Packit fd8b60
def check_mkvno(princ, expected_mkvno):
Packit fd8b60
    msg = 'MKey: vno %d\n' % expected_mkvno
Packit fd8b60
    realm.run([kadminl, 'getprinc', princ], expected_msg=msg)
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Change the password using either kadmin.local or kadmin, then check
Packit fd8b60
# the mkvno of the principal against expected_mkvno and verify that
Packit fd8b60
# the running KDC can access the new key.
Packit fd8b60
def change_password_check_mkvno(local, princ, password, expected_mkvno):
Packit fd8b60
    cmd = ['cpw', '-pw', password, princ]
Packit fd8b60
    if local:
Packit fd8b60
        realm.run([kadminl] + cmd)
Packit fd8b60
    else:
Packit fd8b60
        realm.run_kadmin(cmd)
Packit fd8b60
    check_mkvno(princ, expected_mkvno)
Packit fd8b60
    realm.kinit(princ, password)
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Add a master key with the specified options and a random password.
Packit fd8b60
def add_mkey(options):
Packit fd8b60
    pw = ''.join(random.choice(string.ascii_uppercase) for x in range(5))
Packit fd8b60
    realm.run([kdb5_util, 'add_mkey'] + options, input=(pw + '\n' + pw + '\n'))
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Run kdb5_util update_princ_encryption (with the dry-run option if
Packit fd8b60
# specified) and verify the output against the expected mkvno, number
Packit fd8b60
# of updated principals, and number of already-current principals.
Packit fd8b60
mkvno_re = {False: re.compile(r'^Principals whose keys are being re-encrypted '
Packit fd8b60
                              'to master key vno (\d+) if necessary:$'),
Packit fd8b60
            True: re.compile(r'^Principals whose keys WOULD BE re-encrypted '
Packit fd8b60
                             'to master key vno (\d+):$')}
Packit fd8b60
count_re = {False: re.compile(r'^(\d+) principals processed: (\d+) updated, '
Packit fd8b60
                              '(\d+) already current$'),
Packit fd8b60
            True: re.compile(r'^(\d+) principals processed: (\d+) would be '
Packit fd8b60
                             'updated, (\d+) already current$')}
Packit fd8b60
def update_princ_encryption(dry_run, expected_mkvno, expected_updated,
Packit fd8b60
                            expected_current):
Packit fd8b60
    opts = ['-f', '-v']
Packit fd8b60
    if dry_run:
Packit fd8b60
        opts += ['-n']
Packit fd8b60
    out = realm.run([kdb5_util, 'update_princ_encryption'] + opts)
Packit fd8b60
    lines = out.splitlines()
Packit fd8b60
    # Parse the first line to get the target mkvno.
Packit fd8b60
    m = mkvno_re[dry_run].match(lines[0])
Packit fd8b60
    if not m:
Packit fd8b60
        fail('Unexpected first line of update_princ_encryption output')
Packit fd8b60
    if m.group(1) != str(expected_mkvno):
Packit fd8b60
        fail('Unexpected master key version in update_princ_encryption output')
Packit fd8b60
    # Parse the last line to get the principal counts.
Packit fd8b60
    m = count_re[dry_run].match(lines[-1])
Packit fd8b60
    if not m:
Packit fd8b60
        fail('Unexpected last line of update_princ_encryption output')
Packit fd8b60
    total, updated, current = m.groups()
Packit fd8b60
    if (total != str(expected_updated + expected_current) or
Packit fd8b60
        updated != str(expected_updated) or current != str(expected_current)):
Packit fd8b60
        fail('Unexpected counts from update_princ_encryption')
Packit fd8b60
Packit fd8b60
Packit fd8b60
# Check the initial state of the realm.
Packit fd8b60
mark('initial state')
Packit fd8b60
check_mkey_list((1, defetype, True, True))
Packit fd8b60
check_master_dbent(1, (1, defetype))
Packit fd8b60
check_stash((1, defetype))
Packit fd8b60
check_mkvno(realm.user_princ, 1)
Packit fd8b60
Packit fd8b60
# Check that stash will fail if a temp stash file is already present.
Packit fd8b60
mark('temp stash collision')
Packit fd8b60
collisionfile = os.path.join(realm.testdir, 'stash_tmp')
Packit fd8b60
f = open(collisionfile, 'w')
Packit fd8b60
f.close()
Packit fd8b60
realm.run([kdb5_util, 'stash'], expected_code=1,
Packit fd8b60
          expected_msg='Temporary stash file already exists')
Packit fd8b60
os.unlink(collisionfile)
Packit fd8b60
Packit fd8b60
# Add a new master key with no options.  Verify that:
Packit fd8b60
# 1. The new key appears in list_mkeys but has no activation time and
Packit fd8b60
#    is not active.
Packit fd8b60
# 2. The new key appears in the K/M DB entry and is the current key to
Packit fd8b60
#    encrypt that entry.
Packit fd8b60
# 3. The stash file is not modified (since we did not pass -s).
Packit fd8b60
# 4. The old key is used for password changes.
Packit fd8b60
mark('add_mkey (second master key)')
Packit fd8b60
add_mkey([])
Packit fd8b60
check_mkey_list((2, defetype, False, False), (1, defetype, True, True))
Packit fd8b60
check_master_dbent(2, (2, defetype), (1, defetype))
Packit fd8b60
change_password_check_mkvno(True, realm.user_princ, 'abcd', 1)
Packit fd8b60
change_password_check_mkvno(False, realm.user_princ, 'user', 1)
Packit fd8b60
Packit fd8b60
# Verify that use_mkey won't make all master keys inactive.
Packit fd8b60
mark('use_mkey (no active keys)')
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '1', 'now+1day'], expected_code=1,
Packit fd8b60
          expected_msg='there must be one master key currently active')
Packit fd8b60
check_mkey_list((2, defetype, False, False), (1, defetype, True, True))
Packit fd8b60
Packit fd8b60
# Make the new master key active.  Verify that:
Packit fd8b60
# 1. The new key has an activation time in list_mkeys and is active.
Packit fd8b60
# 2. The new key is used for password changes.
Packit fd8b60
# 3. The running KDC can access the new key.
Packit fd8b60
mark('use_mkey')
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '2', 'now-1day'])
Packit fd8b60
check_mkey_list((2, defetype, True, True), (1, defetype, True, False))
Packit fd8b60
change_password_check_mkvno(True, realm.user_princ, 'abcd', 2)
Packit fd8b60
change_password_check_mkvno(False, realm.user_princ, 'user', 2)
Packit fd8b60
Packit fd8b60
# Check purge_mkeys behavior with both master keys still in use.
Packit fd8b60
mark('purge_mkeys (nothing to purge)')
Packit fd8b60
realm.run([kdb5_util, 'purge_mkeys', '-f', '-v'],
Packit fd8b60
          expected_msg='All keys in use, nothing purged.')
Packit fd8b60
Packit fd8b60
# Do an update_princ_encryption dry run and for real.  Verify that:
Packit fd8b60
# 1. The target master key is 2 (the active mkvno).
Packit fd8b60
# 2. nprincs - 2 principals were updated and one principal was
Packit fd8b60
#    skipped (K/M is not included in the output and user was updated
Packit fd8b60
#    above).
Packit fd8b60
# 3. The dry run doesn't change user/admin's mkvno but the real update
Packit fd8b60
#    does.
Packit fd8b60
# 4. The old stashed master key is sufficient to access the DB (via
Packit fd8b60
#    MKEY_AUX tl-data which keeps the current master key encrypted in
Packit fd8b60
#    each of the old master keys).
Packit fd8b60
mark('update_princ_encryption')
Packit fd8b60
update_princ_encryption(True, 2, nprincs - 2, 1)
Packit fd8b60
check_mkvno(realm.admin_princ, 1)
Packit fd8b60
update_princ_encryption(False, 2, nprincs - 2, 1)
Packit fd8b60
check_mkvno(realm.admin_princ, 2)
Packit fd8b60
realm.stop_kdc()
Packit fd8b60
realm.start_kdc()
Packit fd8b60
realm.kinit(realm.user_princ, 'user')
Packit fd8b60
Packit fd8b60
# Update all principals back to mkvno 1 and to mkvno 2 again, to
Packit fd8b60
# verify that update_princ_encryption targets the active master key.
Packit fd8b60
mark('update_princ_encryption (back and forth)')
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '2', 'now+1day'])
Packit fd8b60
update_princ_encryption(False, 1, nprincs - 1, 0)
Packit fd8b60
check_mkvno(realm.user_princ, 1)
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '2', 'now-1day'])
Packit fd8b60
update_princ_encryption(False, 2, nprincs - 1, 0)
Packit fd8b60
check_mkvno(realm.user_princ, 2)
Packit fd8b60
Packit fd8b60
# Test the safety check for purging with an outdated stash file.
Packit fd8b60
mark('purge_mkeys (outdated stash file)')
Packit fd8b60
realm.run([kdb5_util, 'purge_mkeys', '-f'], expected_code=1,
Packit fd8b60
          expected_msg='stash file needs updating')
Packit fd8b60
Packit fd8b60
# Update the master stash file and check it.  Save a copy of the old
Packit fd8b60
# one for a later test.
Packit fd8b60
mark('update stash file')
Packit fd8b60
shutil.copy(stash_file, stash_file + '.old')
Packit fd8b60
realm.run([kdb5_util, 'stash'])
Packit fd8b60
check_stash((2, defetype), (1, defetype))
Packit fd8b60
Packit fd8b60
# Do a purge_mkeys dry run and for real.  Verify that:
Packit fd8b60
# 1. Master key 1 is purged.
Packit fd8b60
# 2. The dry run doesn't remove mkvno 1 but the real one does.
Packit fd8b60
# 3. The old stash file is no longer sufficient to access the DB.
Packit fd8b60
# 4. If the stash file is updated, it no longer contains mkvno 1.
Packit fd8b60
# 5. use_mkey now gives an error if we refer to mkvno 1.
Packit fd8b60
# 6. A second purge_mkeys gives the right message.
Packit fd8b60
mark('purge_mkeys')
Packit fd8b60
out = realm.run([kdb5_util, 'purge_mkeys', '-v', '-n', '-f'])
Packit fd8b60
if 'KVNO: 1' not in out or '1 key(s) would be purged' not in out:
Packit fd8b60
    fail('Unexpected output from purge_mkeys dry-run')
Packit fd8b60
check_mkey_list((2, defetype, True, True), (1, defetype, True, False))
Packit fd8b60
check_master_dbent(2, (2, defetype), (1, defetype))
Packit fd8b60
out = realm.run([kdb5_util, 'purge_mkeys', '-v', '-f'])
Packit fd8b60
check_mkey_list((2, defetype, True, True))
Packit fd8b60
check_master_dbent(2, (2, defetype))
Packit fd8b60
os.rename(stash_file, stash_file + '.save')
Packit fd8b60
os.rename(stash_file + '.old', stash_file)
Packit fd8b60
realm.run([kadminl, 'getprinc', 'user'], expected_code=1,
Packit fd8b60
          expected_msg='Unable to decrypt latest master key')
Packit fd8b60
os.rename(stash_file + '.save', stash_file)
Packit fd8b60
realm.run([kdb5_util, 'stash'])
Packit fd8b60
check_stash((2, defetype))
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '1'], expected_code=1,
Packit fd8b60
          expected_msg='1 is an invalid KVNO value')
Packit fd8b60
realm.run([kdb5_util, 'purge_mkeys', '-f', '-v'],
Packit fd8b60
          expected_msg='There is only one master key which can not be purged.')
Packit fd8b60
Packit fd8b60
# Add a third master key with a specified enctype.  Verify that:
Packit fd8b60
# 1. The new master key receives the correct number.
Packit fd8b60
# 2. The enctype argument is respected.
Packit fd8b60
# 3. The new master key is stashed (by itself, at the moment).
Packit fd8b60
# 4. We can roll over to the new master key and use it.
Packit fd8b60
mark('add_mkey and update_princ_encryption (third master key)')
Packit fd8b60
add_mkey(['-s', '-e', aes128])
Packit fd8b60
check_mkey_list((3, aes128, False, False), (2, defetype, True, True))
Packit fd8b60
check_master_dbent(3, (3, aes128), (2, defetype))
Packit fd8b60
check_stash((3, aes128))
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '3', 'now-1day'])
Packit fd8b60
update_princ_encryption(False, 3, nprincs - 1, 0)
Packit fd8b60
check_mkey_list((3, aes128, True, True), (2, defetype, True, False))
Packit fd8b60
check_mkvno(realm.user_princ, 3)
Packit fd8b60
Packit fd8b60
# Regression test for #7994 (randkey does not update principal mkvno)
Packit fd8b60
# and #7995 (-keepold does not re-encrypt old keys).
Packit fd8b60
mark('#7994 and #7995 regression test')
Packit fd8b60
add_mkey(['-s'])
Packit fd8b60
realm.run([kdb5_util, 'use_mkey', '4', 'now-1day'])
Packit fd8b60
realm.run([kadminl, 'cpw', '-randkey', '-keepold', realm.user_princ])
Packit fd8b60
# With #7994 unfixed, mkvno of user will still be 3.
Packit fd8b60
check_mkvno(realm.user_princ, 4)
Packit fd8b60
# With #7995 unfixed, old keys are still encrypted with mkvno 3.
Packit fd8b60
update_princ_encryption(False, 4, nprincs - 2, 1)
Packit fd8b60
realm.run([kdb5_util, 'purge_mkeys', '-f'])
Packit fd8b60
out = realm.run([kadminl, 'xst', '-norandkey', realm.user_princ])
Packit fd8b60
if 'Decrypt integrity check failed' in out or 'added to keytab' not in out:
Packit fd8b60
    fail('Preserved old key data not updated to new master key')
Packit fd8b60
Packit fd8b60
realm.stop()
Packit fd8b60
Packit fd8b60
# Regression test for #8395.  Purge the master key and verify that a
Packit fd8b60
# master key fetch does not segfault.
Packit fd8b60
mark('#8395 regression test')
Packit fd8b60
realm.run([kadminl, 'purgekeys', '-all', 'K/M'])
Packit fd8b60
realm.run([kadminl, 'getprinc', realm.user_princ], expected_code=1,
Packit fd8b60
          expected_msg='Cannot find master key record in database')
Packit fd8b60
Packit fd8b60
success('Master key rollover tests')