feat: rebranded from vpn-router to linux-manager.
This commit is contained in:
1 parent
8efe21bfa6
commit
85a1ffa21f
238 files changed
+5010
-3761
No files matched your search
@@ -0,0 +1,378 @@
|
||||
"""The server's user directory in the local slapd.
|
||||
|
||||
The package keeps its own database, dc=linux-manager,dc=local in /var/lib/ldap/linux-manager,
|
||||
next to the one slapd's installation creates. Root manages it through the local socket
|
||||
with SASL EXTERNAL: the database's root DN is root's peer-credential DN, so there is no
|
||||
administrator password. Users and groups are changed by the user-manager service account,
|
||||
which the ACLs allow to write ou=users and ou=groups and to set, never read, passwords and
|
||||
TOTP secrets.
|
||||
|
||||
The password policy locks an account for LOCKOUT_SECONDS after LOCKOUT_FAILURES failed binds;
|
||||
a successful bind clears the count. slapd's otp overlay is configured on the database, so a
|
||||
bind of a user with a TOTP token takes the password followed by a current code.
|
||||
cn=totp,ou=policies holds the TOTP parameters the token of every user points to.
|
||||
|
||||
A user with console login on its own account is also a posixAccount, with a uidNumber from
|
||||
CONSOLE_UID_MIN and the gidNumber of the local group CONSOLE_GROUP; nslcd serves those with
|
||||
linuxManagerConsoleLogin TRUE to the system over the local socket.
|
||||
|
||||
ou=pki holds the server's PKI (linuxmanager_pki): an entry per CA, and under it an entry per
|
||||
certificate the CA issued. Private keys are readable by root alone, the database's root DN.
|
||||
|
||||
ou=roles holds the roles of the resources of the OpenID Provider: an entry per role,
|
||||
cn=<resource>:<role>, whose members are the groups, users and service accounts it is assigned to.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import pwd
|
||||
import re
|
||||
import secrets
|
||||
|
||||
import ldap
|
||||
import ldap.modlist
|
||||
import ldap.sasl
|
||||
|
||||
URI = 'ldapi:///'
|
||||
#: The local socket ldapi:/// names, which slapd listens on.
|
||||
SLAPD_SOCKET = '/var/run/slapd/ldapi'
|
||||
BASE = 'dc=linux-manager,dc=local'
|
||||
USERS = f'ou=users,{BASE}'
|
||||
GROUPS = f'ou=groups,{BASE}'
|
||||
SERVICES = f'ou=services,{BASE}'
|
||||
POLICIES = f'ou=policies,{BASE}'
|
||||
PKI = f'ou=pki,{BASE}'
|
||||
ROLES = f'ou=roles,{BASE}'
|
||||
DEFAULT_POLICY = f'cn=default,{POLICIES}'
|
||||
TOTP_PARAMS = f'cn=totp,{POLICIES}'
|
||||
MANAGER = f'cn=user-manager,{SERVICES}'
|
||||
ROOT = 'gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth'
|
||||
|
||||
DB_DIRECTORY = pathlib.Path('/var/lib/ldap/linux-manager')
|
||||
SECRET_DIR = pathlib.Path('/etc/linux-manager/ldap')
|
||||
MANAGER_SECRET = SECRET_DIR / 'user-manager.secret'
|
||||
SLAPD_DEFAULTS = pathlib.Path('/etc/default/slapd')
|
||||
SLAPD_SERVICES = 'SLAPD_SERVICES="ldapi:///"'
|
||||
|
||||
MODULES = ('argon2', 'ppolicy', 'otp')
|
||||
PASSWORD_HASH = '{ARGON2}'
|
||||
|
||||
#: Failed binds that lock an account, within LOCKOUT_SECONDS, and the seconds it stays locked.
|
||||
LOCKOUT_FAILURES = 5
|
||||
LOCKOUT_SECONDS = 900
|
||||
|
||||
#: The overlays of the database, in the order they are configured.
|
||||
OVERLAYS = ('ppolicy', 'otp')
|
||||
|
||||
#: The package's own schema, under the LDAP arc of the Linux Manager OID arc (OID-REGISTRY.txt):
|
||||
#: attribute types under .1 and object classes under .2. linuxManagerAccount, auxiliary, adds properties of the
|
||||
#: package to a user of either kind: mail, for a Manager-only account, linuxManagerScope,
|
||||
#: authorization scopes, of which service marks a service account, displayName and
|
||||
#: description, the labels of a service account, and linuxManagerConsoleLogin and
|
||||
#: linuxManagerConsoleAccount, whether the user may use a console and the local account it runs as,
|
||||
#: without which it runs as the user's own posixAccount, and linuxManagerWireGuardPeer, each a
|
||||
#: WireGuard peer of the user as "<public key> <IP>[,<IP>...]", and linuxManagerPasskey, each a
|
||||
#: passkey of the user as JSON (linuxmanager_passkeys). A service account with linuxManagerRedirectUri
|
||||
#: is a client of the OpenID Provider (linuxmanager_oidc): the URIs it is sent back to after a sign-in
|
||||
#: and, linuxManagerPostLogoutRedirectUri, after a sign-out, and linuxManagerAllowedGroup, the DNs of the
|
||||
#: groups whose members may sign in to it; linuxManagerGrantType, the further grants it may use,
|
||||
#: linuxManagerPublicClient, whether it has no secret, and linuxManagerClientScope, the scopes of
|
||||
#: resources it may ask for, as <resource>:<scope>. A service account with linuxManagerResourceScope
|
||||
#: is a resource of the OpenID Provider with those scopes. linuxManagerRole is a role of a resource,
|
||||
#: named cn=<resource>:<role>, with the DNs of the groups and accounts it is assigned to in
|
||||
#: member. linuxManagerAuthority is a CA of the PKI: its
|
||||
#: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the
|
||||
#: CSR it waits with for the offline root, the number of its last CRL, where the CRL came from,
|
||||
#: and when it was retired. linuxManagerCertificate is a certificate a CA issued, named by its
|
||||
#: serial number: the certificate, the key the server keeps for its own and the users'
|
||||
#: certificates, its kind, template, names and expiry, and its revocation.
|
||||
SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2'
|
||||
SCHEMA_NAME = 'linux-manager'
|
||||
_STRING = 'EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE'
|
||||
_TIME = 'EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE'
|
||||
_OCTETS = 'EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE'
|
||||
SCHEMA_ATTRIBUTE_TYPES = (
|
||||
f"( {SCHEMA_OID}.1.1 NAME 'linuxManagerScope' DESC 'Linux Manager: an authorization scope of the account' "
|
||||
"EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
|
||||
f"( {SCHEMA_OID}.1.2 NAME 'linuxManagerPrivateKey' DESC 'Linux Manager: a private key, PEM' {_OCTETS} )",
|
||||
f"( {SCHEMA_OID}.1.3 NAME 'linuxManagerCertificateRequest' DESC 'Linux Manager: the CSR of a CA, PEM' {_OCTETS} )",
|
||||
f"( {SCHEMA_OID}.1.4 NAME 'linuxManagerCRLNumber' DESC 'Linux Manager: the number of the last CRL of a CA' "
|
||||
"EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )",
|
||||
f"( {SCHEMA_OID}.1.5 NAME 'linuxManagerCRLSource' DESC 'Linux Manager: signed or uploaded, where the CRL of a CA came from' {_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.6 NAME 'linuxManagerRetired' DESC 'Linux Manager: when a CA was retired' {_TIME} )",
|
||||
f"( {SCHEMA_OID}.1.7 NAME 'linuxManagerKind' DESC 'Linux Manager: ca, router, user or external, the kind of a certificate' {_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.8 NAME 'linuxManagerTemplate' DESC 'Linux Manager: the template of a certificate' {_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.9 NAME 'linuxManagerSubjectAltName' DESC 'Linux Manager: a subject alternative name of a certificate' "
|
||||
"EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
|
||||
f"( {SCHEMA_OID}.1.10 NAME 'linuxManagerNotAfter' DESC 'Linux Manager: when a certificate expires' {_TIME} )",
|
||||
f"( {SCHEMA_OID}.1.11 NAME 'linuxManagerRevoked' DESC 'Linux Manager: when a certificate was revoked' {_TIME} )",
|
||||
f"( {SCHEMA_OID}.1.12 NAME 'linuxManagerRevocationReason' DESC 'Linux Manager: why a certificate was revoked' {_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.13 NAME 'linuxManagerConsoleLogin' DESC 'Linux Manager: whether the user may use a console' "
|
||||
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
|
||||
f"( {SCHEMA_OID}.1.14 NAME 'linuxManagerConsoleAccount' DESC 'Linux Manager: the local account the console of the user runs as' "
|
||||
f"{_STRING} )",
|
||||
f"( {SCHEMA_OID}.1.15 NAME 'linuxManagerWireGuardPeer' DESC 'Linux Manager: a WireGuard peer of the user, its public key and IPs' "
|
||||
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
|
||||
f"( {SCHEMA_OID}.1.16 NAME 'linuxManagerPasskey' DESC 'Linux Manager: a passkey of the user, its credential as JSON' "
|
||||
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{4096} )",
|
||||
f"( {SCHEMA_OID}.1.17 NAME 'linuxManagerRedirectUri' DESC 'Linux Manager: a redirect URI of an OpenID Connect client' "
|
||||
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
|
||||
f"( {SCHEMA_OID}.1.18 NAME 'linuxManagerPostLogoutRedirectUri' DESC 'Linux Manager: a post-logout redirect URI of an "
|
||||
"OpenID Connect client' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
|
||||
f"( {SCHEMA_OID}.1.19 NAME 'linuxManagerAllowedGroup' DESC 'Linux Manager: a group whose members may sign in to an "
|
||||
"OpenID Connect client' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )",
|
||||
f"( {SCHEMA_OID}.1.20 NAME 'linuxManagerGrantType' DESC 'Linux Manager: a grant an OpenID Connect client may use besides "
|
||||
"the authorization code' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
|
||||
f"( {SCHEMA_OID}.1.21 NAME 'linuxManagerPublicClient' DESC 'Linux Manager: whether an OpenID Connect client has no secret' "
|
||||
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
|
||||
f"( {SCHEMA_OID}.1.22 NAME 'linuxManagerClientScope' DESC 'Linux Manager: a scope of a resource an OpenID Connect client "
|
||||
"may ask for' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )",
|
||||
f"( {SCHEMA_OID}.1.23 NAME 'linuxManagerResourceScope' DESC 'Linux Manager: a scope of a resource of the OpenID Provider' "
|
||||
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
|
||||
)
|
||||
SCHEMA_OBJECT_CLASSES = (
|
||||
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
|
||||
"SUP top AUXILIARY MAY ( mail $ linuxManagerScope $ displayName $ description $ linuxManagerConsoleLogin $ "
|
||||
"linuxManagerConsoleAccount $ linuxManagerWireGuardPeer $ linuxManagerPasskey $ linuxManagerRedirectUri $ "
|
||||
"linuxManagerPostLogoutRedirectUri $ linuxManagerAllowedGroup $ linuxManagerGrantType $ linuxManagerPublicClient $ "
|
||||
"linuxManagerClientScope $ linuxManagerResourceScope ) )",
|
||||
f"( {SCHEMA_OID}.2.2 NAME 'linuxManagerAuthority' DESC 'Linux Manager: a CA of the PKI' SUP top STRUCTURAL MUST cn "
|
||||
"MAY ( cACertificate $ certificateRevocationList $ linuxManagerPrivateKey $ linuxManagerCertificateRequest $ "
|
||||
"linuxManagerCRLNumber $ linuxManagerCRLSource $ linuxManagerRetired ) )",
|
||||
f"( {SCHEMA_OID}.2.3 NAME 'linuxManagerCertificate' DESC 'Linux Manager: a certificate a CA of the PKI issued' SUP top "
|
||||
"STRUCTURAL MUST serialNumber MAY ( cn $ userCertificate $ linuxManagerPrivateKey $ linuxManagerKind $ linuxManagerTemplate $ "
|
||||
"linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $ linuxManagerRevocationReason ) )",
|
||||
f"( {SCHEMA_OID}.2.4 NAME 'linuxManagerRole' DESC 'Linux Manager: a role of a resource of the OpenID Provider' SUP top "
|
||||
"STRUCTURAL MUST cn MAY ( description $ member ) )",
|
||||
)
|
||||
|
||||
#: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now.
|
||||
TOTP_DIGITS = 6
|
||||
TOTP_ALGORITHM = '1.2.840.113549.2.7'
|
||||
TOTP_PERIOD = 30
|
||||
TOTP_WINDOW = 1
|
||||
|
||||
#: The value of pwdAccountLockedTime that disables a user until it is enabled again.
|
||||
DISABLED = '000001010000Z'
|
||||
|
||||
#: The indexes of the database.
|
||||
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq')
|
||||
|
||||
#: The POSIX accounts of console login (linuxmanager_users.console): the lowest uidNumber, which nslcd's nss_min_uid
|
||||
#: matches, the local group that is their primary group and grants sudo, the shell and the parent of their homes.
|
||||
CONSOLE_UID_MIN = 20000
|
||||
CONSOLE_GROUP = 'linux-manager-console'
|
||||
CONSOLE_SHELL = '/bin/bash'
|
||||
CONSOLE_HOMES = '/home'
|
||||
|
||||
#: The ACLs of the database, in order.
|
||||
ACCESS = (
|
||||
'to attrs=linuxManagerPrivateKey by * none',
|
||||
f'to attrs=userPassword by dn.exact="{MANAGER}" =wx by self =wx by anonymous auth by * none',
|
||||
f'to attrs=oathSecret by dn.exact="{MANAGER}" =w by * none',
|
||||
f'to dn.subtree="{USERS}" by dn.exact="{MANAGER}" manage by * read',
|
||||
f'to dn.subtree="{GROUPS}" by dn.exact="{MANAGER}" manage by * read',
|
||||
f'to dn.subtree="{ROLES}" by dn.exact="{MANAGER}" manage by * read',
|
||||
'to * by * read',
|
||||
)
|
||||
|
||||
#: The index of an ordered cn=config value: {0}, {1}, ...
|
||||
ORDER = re.compile(rb'^\{\d+\}')
|
||||
|
||||
|
||||
def unordered(values):
|
||||
"""Values of an ordered cn=config attribute without their {n} prefixes."""
|
||||
return [ORDER.sub(b'', value).decode() for value in values]
|
||||
|
||||
|
||||
def root():
|
||||
"""A connection to slapd as root, through the local socket."""
|
||||
connection = ldap.initialize(URI)
|
||||
connection.sasl_interactive_bind_s('', ldap.sasl.external())
|
||||
return connection
|
||||
|
||||
|
||||
def manager():
|
||||
"""A connection to slapd as the user-manager service account."""
|
||||
connection = ldap.initialize(URI)
|
||||
connection.simple_bind_s(MANAGER, MANAGER_SECRET.read_text(encoding='utf-8'))
|
||||
return connection
|
||||
|
||||
|
||||
def ensure_services():
|
||||
"""Make slapd listen on the local socket only. Returns True when the setting changed."""
|
||||
text = SLAPD_DEFAULTS.read_text(encoding='utf-8')
|
||||
lines = text.splitlines(keepends=True)
|
||||
updated = ''.join(SLAPD_SERVICES + '\n' if line.startswith('SLAPD_SERVICES=') else line for line in lines)
|
||||
if not any(line.startswith('SLAPD_SERVICES=') for line in lines):
|
||||
updated = text.rstrip('\n') + '\n' + SLAPD_SERVICES + '\n'
|
||||
if updated == text:
|
||||
return False
|
||||
SLAPD_DEFAULTS.write_text(updated, encoding='utf-8')
|
||||
return True
|
||||
|
||||
|
||||
def _ensure_modules(connection):
|
||||
dn, attributes = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, '(objectClass=olcModuleList)', ['olcModuleLoad'])[0]
|
||||
loaded = unordered(attributes.get('olcModuleLoad', []))
|
||||
missing = [name for name in MODULES if name not in loaded and f'{name}.la' not in loaded]
|
||||
if missing:
|
||||
connection.modify_s(dn, [(ldap.MOD_ADD, 'olcModuleLoad', [name.encode() for name in missing])])
|
||||
|
||||
|
||||
def _ensure_schema(connection):
|
||||
"""Add the package's schema to cn=config when missing, else add the definitions it lacks; a definition that differs
|
||||
from the one of the same OID replaces the whole list of its kind."""
|
||||
found = connection.search_s('cn=schema,cn=config', ldap.SCOPE_ONELEVEL, f'(cn=*{SCHEMA_NAME})',
|
||||
['olcAttributeTypes', 'olcObjectClasses'])
|
||||
attributes = {'olcAttributeTypes': list(SCHEMA_ATTRIBUTE_TYPES), 'olcObjectClasses': list(SCHEMA_OBJECT_CLASSES)}
|
||||
if not found:
|
||||
connection.add_s(f'cn={SCHEMA_NAME},cn=schema,cn=config', ldap.modlist.addModlist(
|
||||
dict({name: [value.encode() for value in values] for name, values in attributes.items()},
|
||||
objectClass=[b'olcSchemaConfig'], cn=[SCHEMA_NAME.encode()])))
|
||||
return
|
||||
dn, current = found[0]
|
||||
for name, wanted in attributes.items():
|
||||
present = unordered(current.get(name, []))
|
||||
oids = {value.split()[1] for value in present}
|
||||
missing = [value for value in wanted if value not in present]
|
||||
if not missing:
|
||||
continue
|
||||
if any(value.split()[1] in oids for value in missing):
|
||||
connection.modify_s(dn, [(ldap.MOD_REPLACE, name, [value.encode() for value in wanted])])
|
||||
else:
|
||||
connection.modify_s(dn, [(ldap.MOD_ADD, name, [value.encode() for value in missing])])
|
||||
|
||||
|
||||
def _ensure_password_hash(connection):
|
||||
dn = 'olcDatabase={-1}frontend,cn=config'
|
||||
current = connection.search_s(dn, ldap.SCOPE_BASE, attrlist=['olcPasswordHash'])[0][1].get('olcPasswordHash', [])
|
||||
if current != [PASSWORD_HASH.encode()]:
|
||||
connection.modify_s(dn, [(ldap.MOD_REPLACE, 'olcPasswordHash', [PASSWORD_HASH.encode()])])
|
||||
|
||||
|
||||
def _ensure_database(connection):
|
||||
"""The DN of the package's database in cn=config, created when missing; its ACLs are kept as ACCESS, and the
|
||||
indexes of INDEXES it lacks are added, which slapd builds online."""
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', ['olcAccess', 'olcDbIndex'])
|
||||
if not found:
|
||||
DB_DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
openldap = pwd.getpwnam('openldap')
|
||||
os.chown(DB_DIRECTORY, openldap.pw_uid, openldap.pw_gid)
|
||||
connection.add_s('olcDatabase=mdb,cn=config', ldap.modlist.addModlist({
|
||||
'objectClass': [b'olcDatabaseConfig', b'olcMdbConfig'],
|
||||
'olcDatabase': [b'mdb'],
|
||||
'olcSuffix': [BASE.encode()],
|
||||
'olcDbDirectory': [str(DB_DIRECTORY).encode()],
|
||||
'olcRootDN': [ROOT.encode()],
|
||||
'olcDbIndex': [index.encode() for index in INDEXES],
|
||||
'olcAccess': [f'{{{index}}}{rule}'.encode() for index, rule in enumerate(ACCESS)],
|
||||
}))
|
||||
found = connection.search_s('cn=config', ldap.SCOPE_ONELEVEL, f'(olcSuffix={BASE})', ['olcAccess', 'olcDbIndex'])
|
||||
dn, attributes = found[0]
|
||||
if unordered(attributes.get('olcAccess', [])) != list(ACCESS):
|
||||
connection.modify_s(dn, [(ldap.MOD_REPLACE, 'olcAccess', [f'{{{index}}}{rule}'.encode() for index, rule in enumerate(ACCESS)])])
|
||||
present = [value.decode() for value in attributes.get('olcDbIndex', [])]
|
||||
missing = [index for index in INDEXES if index not in present]
|
||||
if missing:
|
||||
connection.modify_s(dn, [(ldap.MOD_ADD, 'olcDbIndex', [index.encode() for index in missing])])
|
||||
return dn
|
||||
|
||||
|
||||
def _ensure_overlays(connection, database):
|
||||
"""Add the overlays of OVERLAYS the database lacks; the otp overlay has no settings of its own."""
|
||||
found = connection.search_s(database, ldap.SCOPE_ONELEVEL, '(objectClass=olcOverlayConfig)', ['olcOverlay'])
|
||||
present = {ORDER.sub(b'', attributes['olcOverlay'][0]).decode() for _, attributes in found}
|
||||
for name in OVERLAYS:
|
||||
if name in present:
|
||||
continue
|
||||
record = {'objectClass': [b'olcOverlayConfig'], 'olcOverlay': [name.encode()]}
|
||||
if name == 'ppolicy':
|
||||
record = {'objectClass': [b'olcOverlayConfig', b'olcPPolicyConfig'], 'olcOverlay': [b'ppolicy'],
|
||||
'olcPPolicyDefault': [DEFAULT_POLICY.encode()]}
|
||||
connection.add_s(f'olcOverlay={name},{database}', ldap.modlist.addModlist(record))
|
||||
|
||||
|
||||
def _ensure_entry(connection, dn, attributes):
|
||||
"""Add the entry when it is missing, else set the given attributes that differ."""
|
||||
try:
|
||||
current = connection.search_s(dn, ldap.SCOPE_BASE, attrlist=list(attributes))[0][1]
|
||||
except ldap.NO_SUCH_OBJECT:
|
||||
connection.add_s(dn, ldap.modlist.addModlist(attributes))
|
||||
return
|
||||
changes = [(ldap.MOD_REPLACE, name, values) for name, values in attributes.items()
|
||||
if name != 'objectClass' and sorted(current.get(name, [])) != sorted(values)]
|
||||
if changes:
|
||||
connection.modify_s(dn, changes)
|
||||
|
||||
|
||||
def _ensure_manager(connection):
|
||||
SECRET_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chmod(SECRET_DIR, 0o700)
|
||||
created = False
|
||||
try:
|
||||
connection.search_s(MANAGER, ldap.SCOPE_BASE, attrlist=['1.1'])
|
||||
except ldap.NO_SUCH_OBJECT:
|
||||
connection.add_s(MANAGER, ldap.modlist.addModlist({
|
||||
'objectClass': [b'organizationalRole', b'simpleSecurityObject'],
|
||||
'cn': [b'user-manager'],
|
||||
'userPassword': [b'{CRYPT}!'],
|
||||
}))
|
||||
created = True
|
||||
if created or not MANAGER_SECRET.is_file():
|
||||
password = secrets.token_urlsafe(32)
|
||||
connection.passwd_s(MANAGER, None, password)
|
||||
MANAGER_SECRET.touch(mode=0o600)
|
||||
MANAGER_SECRET.chmod(0o600)
|
||||
MANAGER_SECRET.write_text(password, encoding='utf-8')
|
||||
|
||||
|
||||
def wireguard_peers():
|
||||
"""The WireGuard peers of the users who are not disabled, read as root: [(user, public key, [IP, ...])], sorted."""
|
||||
connection = root()
|
||||
try:
|
||||
found = connection.search_s(USERS, ldap.SCOPE_ONELEVEL,
|
||||
f'(&(linuxManagerWireGuardPeer=*)(!(pwdAccountLockedTime={DISABLED})))',
|
||||
['uid', 'linuxManagerWireGuardPeer'])
|
||||
finally:
|
||||
connection.unbind_s()
|
||||
peers = []
|
||||
for _, attributes in found:
|
||||
for value in attributes['linuxManagerWireGuardPeer']:
|
||||
key, _, ips = value.decode().partition(' ')
|
||||
peers.append((attributes['uid'][0].decode(), key, ips.split(',')))
|
||||
return sorted(peers)
|
||||
|
||||
|
||||
def provision():
|
||||
"""Create or bring up to date the modules, the package's schema, database, ACLs, password policy, entries and service account."""
|
||||
connection = root()
|
||||
try:
|
||||
_ensure_modules(connection)
|
||||
_ensure_schema(connection)
|
||||
_ensure_password_hash(connection)
|
||||
database = _ensure_database(connection)
|
||||
_ensure_overlays(connection, database)
|
||||
_ensure_entry(connection, BASE, {'objectClass': [b'dcObject', b'organization'], 'dc': [b'linux-manager'], 'o': [b'linux-manager']})
|
||||
for unit in (USERS, GROUPS, SERVICES, POLICIES, PKI, ROLES):
|
||||
_ensure_entry(connection, unit, {'objectClass': [b'organizationalUnit'], 'ou': [unit.split(',')[0][3:].encode()]})
|
||||
_ensure_entry(connection, DEFAULT_POLICY, {
|
||||
'objectClass': [b'organizationalRole', b'pwdPolicy'],
|
||||
'cn': [b'default'],
|
||||
'pwdAttribute': [b'userPassword'],
|
||||
'pwdLockout': [b'TRUE'],
|
||||
'pwdMaxFailure': [str(LOCKOUT_FAILURES).encode()],
|
||||
'pwdLockoutDuration': [str(LOCKOUT_SECONDS).encode()],
|
||||
'pwdFailureCountInterval': [str(LOCKOUT_SECONDS).encode()],
|
||||
})
|
||||
_ensure_entry(connection, TOTP_PARAMS, {
|
||||
'objectClass': [b'organizationalRole', b'oathTOTPParams'],
|
||||
'cn': [b'totp'],
|
||||
'oathOTPLength': [str(TOTP_DIGITS).encode()],
|
||||
'oathHMACAlgorithm': [TOTP_ALGORITHM.encode()],
|
||||
'oathTOTPTimeStepPeriod': [str(TOTP_PERIOD).encode()],
|
||||
'oathTOTPTimeStepWindow': [str(TOTP_WINDOW).encode()],
|
||||
})
|
||||
_ensure_manager(connection)
|
||||
finally:
|
||||
connection.unbind_s()
|
||||
Reference in new issue
Block a user