288 lines
14 KiB
Python
288 lines
14 KiB
Python
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the .env of the repository, the
|
|
persistent state in .lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
|
|
secrets to an instance through it, and the TOTP tokens of the users of a VM, kept in the Vault's TOTP engine.
|
|
|
|
A secret never reaches an instance as a command-line argument or on standard input. Each instance has an AppRole of
|
|
its own (enrol_instance): its role ID and the helper lm-dev-vault (tests/remote/lm-dev-vault) are pushed into it, and
|
|
its secret ID with a response-wrapping token, which the helper unwraps once into /etc/vault. The instance then logs in
|
|
and reads what the Mac stored for it under kv/<instance>/, whole files that hold a secret (hand_over), and creates its
|
|
own TOTP keys (enrol_otp).
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
# The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in.
|
|
TESTS = ROOT / 'tests' / 'remote'
|
|
# The project of the manual tests, which lm-dev-lxd-project.py makes.
|
|
PROJECT = 'lm-dev'
|
|
# The state of the scripts that outlives a clean-up of tmp/: project and Vault states, keys and secrets; 0700.
|
|
CONFIG = ROOT / '.lm-dev-config'
|
|
|
|
# The Vault: its port, the KV v2 and TOTP mounts, the lifetimes of a wrapping token and of an instance's token.
|
|
VAULT_PORT = 8200
|
|
VAULT_MOUNT = 'kv'
|
|
TOTP_MOUNT = 'totp'
|
|
WRAP_TTL = '120s'
|
|
TOKEN_TTL = '5m'
|
|
# In an instance: the helper, its directory of the Vault's URL and the AppRole's IDs, and the directory of files a
|
|
# secret passes through.
|
|
HELPER = '/usr/local/sbin/lm-dev-vault'
|
|
ETC_VAULT = '/etc/vault'
|
|
HANDOVER_DIR = '/run/lm-dev'
|
|
|
|
# Run in the VM as python3 -c CODE USER FILE: enrol the secret of the otpauth URI in FILE for USER with its current
|
|
# code, then remove the file.
|
|
OTP_ENROL = ("import os, sys, urllib.parse; sys.path.insert(0, '/usr/lib/linux-manager')\n"
|
|
"import linuxmanager_users as users\n"
|
|
"user, path = sys.argv[1:3]\n"
|
|
"try:\n"
|
|
" with open(path, encoding='utf-8') as handle: url = handle.read().strip()\n"
|
|
"finally:\n"
|
|
" os.unlink(path)\n"
|
|
"secret = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)['secret'][0]\n"
|
|
"with users.session() as connection:\n"
|
|
" users.otp_enrol(connection, user, secret, users.totp(secret).now())")
|
|
|
|
|
|
def lxc_exec(remote, project, instance, *command, input=None):
|
|
"""Run the command in the instance as root with the input, and return its CompletedProcess."""
|
|
return subprocess.run(['lxc', 'exec', f'{remote}:{instance}', '--project', project, '-T', '--', *command],
|
|
input=input, capture_output=True, text=True)
|
|
|
|
|
|
def lxc_push(remote, project, instance, source, path, mode):
|
|
"""Copy the local file to the path in the instance with the mode; True when it was copied."""
|
|
return subprocess.run(['lxc', 'file', 'push', str(source), f'{remote}:{instance}{path}', '--mode', mode,
|
|
'--project', project], capture_output=True, text=True).returncode == 0
|
|
|
|
|
|
def set_dotenv(values):
|
|
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines."""
|
|
dotenv = ROOT / '.env'
|
|
lines = dotenv.read_text(encoding='utf-8').splitlines() if dotenv.is_file() else []
|
|
kept = [line for line in lines if line.split('=', 1)[0] not in values]
|
|
dotenv.touch(mode=0o600)
|
|
dotenv.chmod(0o600)
|
|
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]),
|
|
encoding='utf-8')
|
|
|
|
|
|
def newest_deb():
|
|
"""The package built last, release or dev build, by modification time among out/ and out/dev/; None without
|
|
one."""
|
|
debs = [*(ROOT / 'out').glob('linux-manager_*_all.deb'), *(ROOT / 'out' / 'dev').glob('linux-manager_*_all.deb')]
|
|
return max(debs, key=lambda path: path.stat().st_mtime, default=None)
|
|
|
|
|
|
def config_path(name):
|
|
"""The path of a file in CONFIG, which is made with mode 0700 when it is missing."""
|
|
CONFIG.mkdir(mode=0o700, exist_ok=True)
|
|
CONFIG.chmod(0o700)
|
|
return CONFIG / name
|
|
|
|
|
|
def write_private(path, text):
|
|
"""Write the text to the file, readable by its owner only."""
|
|
path = pathlib.Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.touch(mode=0o600)
|
|
path.chmod(0o600)
|
|
path.write_text(text, encoding='utf-8')
|
|
|
|
|
|
def host_address(remote):
|
|
"""The IPv4 address of the host of the remote's lxc URL, or None."""
|
|
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True,
|
|
text=True, check=True).stdout)
|
|
host = urllib.parse.urlsplit(remotes.get(remote, {}).get('Addr', '')).hostname
|
|
try:
|
|
return socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None
|
|
except socket.gaierror:
|
|
return None
|
|
|
|
|
|
class VaultError(Exception):
|
|
"""A Vault request that failed."""
|
|
|
|
|
|
def vault_call(url, method, path, body=None, token=None, wrap=None):
|
|
"""Send the request to the Vault at url; the JSON answer, {} for none. wrap asks for a wrapped answer."""
|
|
headers = {'Content-Type': 'application/json'}
|
|
if token:
|
|
headers['X-Vault-Token'] = token
|
|
if wrap:
|
|
headers['X-Vault-Wrap-TTL'] = wrap
|
|
request = urllib.request.Request(url.rstrip('/') + path, json.dumps(body).encode() if body is not None else None,
|
|
headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=30) as response:
|
|
data = response.read()
|
|
except urllib.error.HTTPError as error:
|
|
raise VaultError(f'{method} {path}: {error.code} {error.read().decode(errors="replace").strip()}')
|
|
except (urllib.error.URLError, OSError) as error:
|
|
raise VaultError(f'{method} {path}: {url} cannot be reached: {error}')
|
|
return json.loads(data) if data else {}
|
|
|
|
|
|
def vault_state(project):
|
|
"""The Vault state of the project: {url, internal_url, key, root_token}, None when it has no Vault."""
|
|
path = config_path(f'vault-{project}.json')
|
|
return json.loads(path.read_text(encoding='utf-8')) if path.is_file() else None
|
|
|
|
|
|
def vault_initialise(project, url, internal_url):
|
|
"""Initialise the Vault at url with one key share, unseal it, mount KV v2 and TOTP, enable AppRole and keep its
|
|
state; the state."""
|
|
for _ in range(60):
|
|
try:
|
|
if 'initialized' in vault_call(url, 'GET', '/v1/sys/init'):
|
|
break
|
|
except VaultError:
|
|
pass
|
|
time.sleep(2)
|
|
else:
|
|
raise VaultError(f'{url} does not answer')
|
|
answer = vault_call(url, 'POST', '/v1/sys/init', {'secret_shares': 1, 'secret_threshold': 1})
|
|
state = {'url': url, 'internal_url': internal_url, 'key': answer['keys_base64'][0],
|
|
'root_token': answer['root_token']}
|
|
write_private(config_path(f'vault-{project}.json'), json.dumps(state, indent=2) + '\n')
|
|
vault_unseal(state)
|
|
vault_call(url, 'POST', f'/v1/sys/mounts/{VAULT_MOUNT}', {'type': 'kv', 'options': {'version': '2'}},
|
|
token=state['root_token'])
|
|
vault_call(url, 'POST', f'/v1/sys/mounts/{TOTP_MOUNT}', {'type': 'totp'}, token=state['root_token'])
|
|
vault_call(url, 'POST', '/v1/sys/auth/approle', {'type': 'approle'}, token=state['root_token'])
|
|
return state
|
|
|
|
|
|
def vault_unseal(state):
|
|
"""Unseal the Vault of the state with its key; it is left as it is when it is unsealed."""
|
|
answer = vault_call(state['url'], 'POST', '/v1/sys/unseal', {'key': state['key']})
|
|
if answer.get('sealed'):
|
|
raise VaultError(f'{state["url"]} is still sealed')
|
|
|
|
|
|
def store_secret(state, path, values):
|
|
"""Write the values, a dict of strings, as the KV v2 secret at path."""
|
|
vault_call(state['url'], 'POST', f'/v1/{VAULT_MOUNT}/data/{path}', {'data': values}, token=state['root_token'])
|
|
|
|
|
|
def enrol_instance(remote, project, instance, state):
|
|
"""Give the instance an AppRole of its own, named after it, whose policy reads kv/<instance>/ and creates the TOTP
|
|
keys <instance>-*, and set up /etc/vault in it; the problem, or None.
|
|
|
|
The instance receives the helper, the Vault's URL, the role ID and a wrapping token of a new secret ID, each as a
|
|
file; the helper unwraps the token once, after checking that it wraps the role's secret-id request.
|
|
"""
|
|
policy = (f'path "{VAULT_MOUNT}/data/{instance}/*" {{ capabilities = ["read"] }}\n'
|
|
f'path "{TOTP_MOUNT}/keys/{instance}-*" {{ capabilities = ["create", "update"] }}\n')
|
|
role = f'/v1/auth/approle/role/{instance}'
|
|
try:
|
|
vault_call(state['url'], 'POST', f'/v1/sys/policies/acl/instance-{instance}', {'policy': policy},
|
|
token=state['root_token'])
|
|
vault_call(state['url'], 'POST', role, {'token_policies': [f'instance-{instance}'], 'token_type': 'batch',
|
|
'token_ttl': TOKEN_TTL, 'secret_id_ttl': 0, 'secret_id_num_uses': 0},
|
|
token=state['root_token'])
|
|
role_id = vault_call(state['url'], 'GET', f'{role}/role-id', token=state['root_token'])['data']['role_id']
|
|
token = vault_call(state['url'], 'POST', f'{role}/secret-id', {}, token=state['root_token'],
|
|
wrap=WRAP_TTL)['wrap_info']['token']
|
|
except (VaultError, KeyError) as error:
|
|
return f'the AppRole of {instance} cannot be made: {error}'
|
|
prepared = lxc_exec(remote, project, instance, 'install', '-d', '-m', '0700', ETC_VAULT)
|
|
if prepared.returncode != 0:
|
|
return f'{ETC_VAULT} cannot be made in {instance}: {prepared.stderr.strip()}'
|
|
with tempfile.TemporaryDirectory(dir=ROOT / 'tmp' if (ROOT / 'tmp').is_dir() else None) as folder:
|
|
local = pathlib.Path(folder)
|
|
os.chmod(local, 0o700)
|
|
write_private(local / 'url', state['internal_url'] + '\n')
|
|
write_private(local / 'role-id', role_id + '\n')
|
|
write_private(local / 'wrapped', token + '\n')
|
|
files = ((TESTS / 'lm-dev-vault', HELPER, '0755'), (local / 'url', f'{ETC_VAULT}/url', '0644'),
|
|
(local / 'role-id', f'{ETC_VAULT}/role-id', '0600'),
|
|
(local / 'wrapped', f'{ETC_VAULT}/secret-id.wrapped', '0600'))
|
|
for source, target, mode in files:
|
|
if not lxc_push(remote, project, instance, source, target, mode):
|
|
return f'{target} cannot be copied into {instance}'
|
|
result = lxc_exec(remote, project, instance, HELPER, 'init', instance)
|
|
if result.returncode != 0:
|
|
return f'{instance} did not take its secret ID: {result.stderr.strip()}'
|
|
return None
|
|
|
|
|
|
def forget_instance(state, instance):
|
|
"""Delete the instance's AppRole, its policy, its secrets under kv/<instance>/ and its TOTP keys."""
|
|
url, token = state['url'], state['root_token']
|
|
|
|
def listed(path):
|
|
try:
|
|
return vault_call(url, 'LIST', path, token=token)['data']['keys']
|
|
except VaultError:
|
|
return []
|
|
|
|
vault_call(url, 'DELETE', f'/v1/auth/approle/role/{instance}', token=token)
|
|
vault_call(url, 'DELETE', f'/v1/sys/policies/acl/instance-{instance}', token=token)
|
|
for name in listed(f'/v1/{VAULT_MOUNT}/metadata/{instance}'):
|
|
vault_call(url, 'DELETE', f'/v1/{VAULT_MOUNT}/metadata/{instance}/{name}', token=token)
|
|
for key in listed(f'/v1/{TOTP_MOUNT}/keys'):
|
|
if key.startswith(f'{instance}-'):
|
|
vault_call(url, 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=token)
|
|
|
|
|
|
def hand_over(remote, project, instance, state, name, content, destination, mode):
|
|
"""Store the content, a file that holds a secret, as kv/<instance>/<name>, and have the instance write it to
|
|
destination with the mode, reading it with its AppRole; the problem, or None."""
|
|
try:
|
|
store_secret(state, f'{instance}/{name}', {'content': content})
|
|
except VaultError as error:
|
|
return f'the secret {instance}/{name} cannot be stored: {error}'
|
|
result = lxc_exec(remote, project, instance, HELPER, 'get', f'{instance}/{name}', 'content', destination, mode)
|
|
if result.returncode != 0:
|
|
return f'{instance}/{name} was not handed over to {instance}: {result.stderr.strip()}'
|
|
return None
|
|
|
|
|
|
def totp_key(instance, user):
|
|
"""The name of the TOTP key of the user of the instance in the Vault's TOTP engine."""
|
|
return f'{instance}-{user}'
|
|
|
|
|
|
def enrol_otp(remote, project, instance, user):
|
|
"""Enrol a new TOTP token for the user of the VM, replacing one the user had; the problem, or None.
|
|
|
|
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the secret is
|
|
held by the Vault and the VM only, and the codes are read from the Vault (otp_code).
|
|
"""
|
|
state = vault_state(project)
|
|
if state is None:
|
|
return f'project {project} has no Vault; make it with lm-dev-lxd-project.py vault create'
|
|
key = totp_key(instance, user)
|
|
try:
|
|
vault_call(state['url'], 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=state['root_token'])
|
|
except VaultError as error:
|
|
return f'the TOTP key {key} cannot be replaced: {error}'
|
|
target = f'{HANDOVER_DIR}/otp-url'
|
|
for command in (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
|
|
('python3', '-c', OTP_ENROL, user, target)):
|
|
result = lxc_exec(remote, project, instance, *command)
|
|
if result.returncode != 0:
|
|
return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}'
|
|
return None
|
|
|
|
|
|
def otp_code(project, instance, user):
|
|
"""The current TOTP code of the user of the instance, from the project's Vault."""
|
|
state = vault_state(project)
|
|
if state is None:
|
|
raise VaultError(f'project {project} has no Vault')
|
|
return vault_call(state['url'], 'GET', f'/v1/{TOTP_MOUNT}/code/{totp_key(instance, user)}',
|
|
token=state['root_token'])['data']['code']
|