set_ipa_pwpolicies.py 2.39 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
   Set the password expiration dates to a (very relaxed) value set via the 
   global variable `EXPIRE`.

   :Authors: Julian Gethmann
   :Contact: phd@gethmann.org
   :Date: 2018-01-08
   :Version: 0.1

   For general IPA usage see get_ipa_users.py
"""
15
from contextlib import suppress
16 17
from ipalib import api, cli
from pprint import pprint
18 19 20
from subprocess import run, PIPE
from typing import Dict
import ansible.utils
21
import datetime
22
import ipalib
23 24 25 26 27 28 29 30 31 32 33 34
import yaml

def bootstrap():
     """
     Bootstrap the script.
     I hope that all of this stuff is re-entrant.
     Also, api is defined in __init__.py.
     """
     api.bootstrap_with_global_options(context='cli')
     api.finalize()
     api.Backend.rpcclient.connect()

35 36 37
def decrypt(filename: str) -> Dict[str, str]:
    return yaml.load(run(["ansible-vault", "view", filename], stdout=PIPE).stdout)

38 39
def main():
    EXPIRE = 5 * 52  # weeks
40
    IPA_USER_CONFIG = "./group_vars/all/vault.yml"
41 42 43 44 45 46 47 48 49 50 51

    bootstrap()
    pw = api.Command.pwpolicy_find(u"global_policy")["result"]
    prev_lifetime = int(pw[0]["krbmaxpwdlife"][0])
    print("Set new default password expiration time")
    with suppress(ipalib.errors.EmptyModlist):
        api.Command.pwpolicy_mod(u"global_policy", krbmaxpwdlife="0")

    print("Set password expiration time for all users")
    new_expiretime = datetime.datetime.now() + datetime.timedelta(weeks=EXPIRE)

52 53 54 55
    # TODO: This NEEDS TO BE modified when using ansible vault!
    # with open(IPA_USER_CONFIG, "r") as fobj:
    #     ipa_config = yaml.load(fobj)
    ipa_config = decrypt(IPA_USER_CONFIG)
56

57
    for user in ipa_config["vault_ipa_users"]:
58 59 60 61 62 63
        if user["state"] not in ("enabled",):
            continue
        user = user["name"]

        prev_expire = api.Command.user_show(user, all=True)["result"].get("krbpasswordexpiration",
            (datetime.datetime(1970, 1, 1),))[0]
64 65
        print(f"Set password expiration time for {user} from
                {prev_expire:%Y-%m-%dT%H:%M:%S} to {new_expiretime:%Y-%m-%d}")
66 67 68 69 70 71 72 73 74 75 76 77 78
        with suppress(ipalib.errors.EmptyModlist):
            api.Command.user_mod(
                user,
                setattr=f"krbPasswordExpiration={new_expiretime:%Y%m%d%H%M%S}Z",
            )

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        print(__doc__)
        sys.exit(0)
    main()
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4