feature: the VPN, the router, the name server and WebDAV are components switched on the System tab and installed on demand, Caddy from the Ubuntu archive is a dependency and serves every HTTP and HTTPS port, HTTPS is chosen at install, its certificate is of the Servers Issuing CA or self-signed by default, of ACME or of another CA, the issuing CAs are in one tab, a locked account is unlocked again, the name of a CA is fixed once the CA exists, and a run of setup is no longer cut short by a change.
Release / release (push) Failing after 8s
Release / release (push) Failing after 8s
This commit is contained in:
1 parent
a649331aa2
commit
a7bfabcb89
97 files changed
+4498
-1834
No files matched your search
+117
-40
@@ -3,20 +3,26 @@
|
||||
The scripts are in `bin/` of the repository; this directory holds their data: `scenarios/`,
|
||||
`configs/`, `cloud-init/`, `repo/` and the files copied into instances.
|
||||
|
||||
`bin/lm-dev-run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD
|
||||
remote and checks the router and VPN components in three scenarios:
|
||||
`bin/lm-dev-run.py` installs the package built last, a release in `out/` or a dev build in
|
||||
`out/dev/`, or the one `--deb` names, into instances of an LXD remote and checks the server in four
|
||||
scenarios:
|
||||
|
||||
- `core`: one interface, router and VPN off;
|
||||
- `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through
|
||||
NAT, then the VPN is switched off;
|
||||
- `s2s`: router and VPN on, two sites with two interfaces each, a site-to-site connection with a
|
||||
pre-shared key, and a routed WireGuard client; the router is then switched off while
|
||||
`site_to_site` is set, which setup refuses.
|
||||
`site_to_site` is set, which setup refuses;
|
||||
- `oidc`: HTTPS with a certificate of the Servers CA and the OpenID Provider on; the scenario's
|
||||
Vault, a relying party with its `auth/oidc` method, signs the user alice in with the
|
||||
authorization code flow and PKCE, her password and a TOTP code of the Vault, driven in a client
|
||||
by `oidc_login.py` as a browser would, and a wrong code is refused.
|
||||
|
||||
Servers are virtual machines, clients and LAN hosts containers, all from `ubuntu:26.04`. Each
|
||||
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`.
|
||||
`wireguard_peer.py` and `echo.py` are copied into the instances: the first gives the test user a
|
||||
WireGuard peer on the server, the second answers HTTP with the client's address.
|
||||
`wireguard_peer.py`, `echo.py` and `oidc_login.py` are copied into the instances: the first gives
|
||||
the test user a WireGuard peer on the server, the second answers HTTP with the client's address,
|
||||
and the third signs a user in at the server's OpenID Provider.
|
||||
|
||||
```sh
|
||||
export LXD_REMOTE=...
|
||||
@@ -41,32 +47,75 @@ Options:
|
||||
| `--project` | `LXD_TEST_PROJECT` | `lm-test` | The project the instances live in; it must not exist |
|
||||
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of every instance |
|
||||
| `--keep` | | off | Leaves the project and the networks in place; run one scenario then |
|
||||
| `--deb` | | the package built last | The package to test |
|
||||
|
||||
Each scenario creates the project and its networks (`lmt-<scenario>-<net>`) and removes them at
|
||||
its end. The administrator password and the pre-shared key are generated per run. The
|
||||
administrator's name and password are set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
|
||||
repository's `.env`, keeping its other lines, and the key is written to `tmp/remote-test.env`.
|
||||
its end. Its first instance is its Vault, `lm-vault` on the bridge `lmt-vault` (`10.99.99.0/24`),
|
||||
reached by the Mac and the instances on the LXD host's address, port 8200, through a proxy
|
||||
device; every secret reaches an instance through it (see Secrets). The administrator password and
|
||||
the pre-shared key are generated per run and kept in the scenario's Vault, as `<server>/admin` and
|
||||
`<server>/config`; with `--keep` they stay there. The run leaves `.env` as it is.
|
||||
The run prints PASS, FAIL or SKIP per check and exits non-zero on a failure; WireGuard is skipped
|
||||
when the host kernel has no WireGuard module.
|
||||
|
||||
The configurations in `configs/` have placeholders that are filled in for each server:
|
||||
|
||||
- `@PSK@`: the pre-shared key;
|
||||
- `@PSK@`: the pre-shared key, filled in on the Mac; the file reaches the server through the Vault;
|
||||
- `@ETH0@` and `@ETH1@`: the names of its interfaces;
|
||||
- `@CIDR0@`: the network of its first address.
|
||||
|
||||
## Secrets
|
||||
|
||||
A secret never reaches an instance as a command-line argument or on standard input, where `ps`,
|
||||
`/proc/<pid>/cmdline` or a log would show it. The scripts keep it in the project's Vault, HashiCorp
|
||||
Vault with file storage and a plain HTTP listener, which `lm_dev.py` initialises with one key share
|
||||
and unseals over its API, with KV v2 at `kv`, the TOTP engine at `totp` and AppRole enabled.
|
||||
|
||||
Every instance the scripts launch, apart from the Vault and the hosts of the lab's isolated LANs,
|
||||
which have no route to it, gets an AppRole of its own, named after it, once it has booted:
|
||||
|
||||
1. The Mac makes the policy `instance-<name>`, which reads `kv/data/<name>/*` and creates the TOTP
|
||||
keys `totp/keys/<name>-*`, and the role `<name>`, which gives batch tokens of 5 minutes and secret
|
||||
IDs that do not expire.
|
||||
2. The helper `lm-dev-vault` goes to `/usr/local/sbin`, and the Vault's URL, the role ID and a
|
||||
wrapping token of a new secret ID, single-use and living 120 seconds, to `/etc/vault` (0700), the
|
||||
IDs readable by root only.
|
||||
3. `lm-dev-vault init` removes the token, refuses it unless it wraps the role's `secret-id`
|
||||
request, unwraps it and keeps the secret ID in `/etc/vault/secret-id`.
|
||||
|
||||
From then on the instance logs in with its AppRole. A file that holds a secret is stored whole by
|
||||
the Mac as `kv/<name>/<file>`, and `lm-dev-vault get` writes it in the instance with the mode asked
|
||||
for; a program that reads the secret on standard input reads that file, which is removed right
|
||||
after. The debconf preseed with the admin password, `linux-manager.json` with the pre-shared key,
|
||||
and alice's password and OpenVPN profile take this way; the admin password is also kept as
|
||||
`<name>/admin`. A WireGuard client's private key is made in the client and never leaves it.
|
||||
|
||||
A user's TOTP token is the key `<vm>-<user>` of the TOTP engine. The VM has the Vault generate it
|
||||
with `lm-dev-vault totp` and enrols its secret with its current code; the secret is never on the
|
||||
Mac and cannot be read back from the Vault, which gives the codes (`totp/code/<vm>-<user>`).
|
||||
`lm-dev-vm.py remove` deletes the VM's role, policy, secrets and TOTP keys.
|
||||
|
||||
The Vault's web UI is at `/ui` of its address, `http://<vault-address>:8200/ui`; it signs in with
|
||||
the root token of `vault-<project>.json`.
|
||||
|
||||
The state the scripts keep across clean-ups of `tmp/` is in `.lm-dev-config/` at the repository's
|
||||
root, mode 0700, its files 0600, ignored by git: the project's state and repository key, the
|
||||
Vault's address, unseal key and root token (`vault-<project>.json`). `tmp/` holds
|
||||
only what can go: logs and files removed right after use.
|
||||
|
||||
## A VM to work with
|
||||
|
||||
`lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves
|
||||
it running. The VM is created in a project, the test project `lm-dev` by default, with that
|
||||
project's default profile, and takes its address from DHCP. It gets the package with the
|
||||
administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
|
||||
repository's `.env`, and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the
|
||||
interface of the VM's default route.
|
||||
repository's `.env`, a TOTP token for `admin` in the project's Vault unless `--no-otp` is given,
|
||||
and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the interface of the VM's
|
||||
default route.
|
||||
|
||||
In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's
|
||||
repository, so later dev builds reach it as updates; in another project it installs the newest
|
||||
`out/linux-manager_*_all.deb`. The leased address is pinned on the VM's NIC, and these ports lead
|
||||
repository, so later dev builds reach it as updates; in another project it installs `--deb`, or
|
||||
else the package built last, in `out/` or `out/dev/`. The leased address is pinned on the VM's NIC, and these ports lead
|
||||
to the VM:
|
||||
|
||||
- `7080` to the Manager;
|
||||
@@ -74,13 +123,13 @@ to the VM:
|
||||
- `2222` to SSH, port `22`.
|
||||
|
||||
In a test project they lead through a network forward on the project's `wan`, whose listen address
|
||||
LXD allocates from the uplink's `--routes`, as LXD refuses NAT proxy devices in a project with
|
||||
networks of its own. In another project NAT proxy devices listen on the LXD host address
|
||||
`--listen`, by default the IPv4 address of the host in the remote's URL (`lxc remote list`), which
|
||||
must be an address of the LXD host itself.
|
||||
is `--forward-address`, or else one LXD allocates from the uplink's `--routes`, as LXD refuses
|
||||
NAT proxy devices in a project with networks of its own. In another project NAT proxy devices
|
||||
listen on the LXD host address `--listen`, by default the IPv4 address of the host in the remote's
|
||||
URL (`lxc remote list`), which must be an address of the LXD host itself.
|
||||
|
||||
The script prints the VM's address, the administrator's password, the URLs, the command of a
|
||||
shell in it and the command that removes it.
|
||||
The script prints the VM's address, where the administrator's password is kept, the URLs, the
|
||||
command of a shell in it and the command that removes it; it never prints the password.
|
||||
|
||||
```sh
|
||||
bin/lm-dev-vm.py create
|
||||
@@ -90,8 +139,10 @@ bin/lm-dev-vm.py create
|
||||
bin/lm-dev-vm.py remove
|
||||
```
|
||||
|
||||
`remove` deletes the VM, its forward and `tmp/vm-<vm>.env`, its pre-shared key; `.env` is left as
|
||||
it is. Options:
|
||||
`create` needs the project's Vault (`lm-dev-lxd-project.py vault create`): the VM gets its
|
||||
AppRole there, and reads the preseed and the configuration, kept as `<vm>/preseed` and
|
||||
`<vm>/config`, and creates the TOTP key `<vm>-admin` with it. `remove` deletes the VM, its forward
|
||||
and what the Vault keeps for it; `.env` is left as it is. Options:
|
||||
|
||||
| Option | Variable | Default | Meaning |
|
||||
|---|---|---|---|
|
||||
@@ -101,6 +152,9 @@ it is. Options:
|
||||
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM |
|
||||
| `--config` | | `core.json` | The configuration from `configs/` |
|
||||
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
|
||||
| `--forward-address` | `LXD_FORWARD_ADDRESS` | allocated | In a test project, the forward's listen address, one of the uplink's routes, so a recreated VM keeps it |
|
||||
| `--no-otp` | | off | With `create`, enrol no TOTP token for `admin` |
|
||||
| `--deb` | | the package built last | Outside a test project, the package to install |
|
||||
|
||||
## A test project with dev builds
|
||||
|
||||
@@ -114,11 +168,21 @@ project has:
|
||||
gateway;
|
||||
- a default profile with a root disk on the pool and `eth0` on `wan`;
|
||||
- the container `repo`, whose nginx serves a signed apt repository of the dev builds,
|
||||
`resolute main` for amd64 and arm64, at its pinned address.
|
||||
`resolute main` for amd64 and arm64, at its pinned address;
|
||||
- the container `vault`, the project's Vault (see Secrets), reached by the Mac through a forward
|
||||
of port 8200 on `wan` at `--vault-address` (`LXD_VAULT_ADDRESS`), or an allocated address, and
|
||||
by the instances on its pinned address.
|
||||
|
||||
What the other scripts need, the repository's URL among it, is written to
|
||||
`tmp/lxd-project-<project>.json`, and the repository's key to `tmp/lxd-project-<project>.gpg`.
|
||||
`remove` deletes the project's instances, its networks, the project and those files.
|
||||
`.lm-dev-config/lxd-project-<project>.json`, and the repository's key to
|
||||
`.lm-dev-config/lxd-project-<project>.gpg`. `remove` deletes the project's instances, its networks,
|
||||
the project and those files.
|
||||
|
||||
```sh
|
||||
bin/lm-dev-lxd-project.py vault create # the Vault of an existing project
|
||||
bin/lm-dev-lxd-project.py vault unseal # after a restart of the vault container
|
||||
bin/lm-dev-lxd-project.py vault remove
|
||||
```
|
||||
|
||||
The remote needs OVN, set up as LXD's standalone OVN guide describes, and a host bridge on the
|
||||
LAN, whose host address stays on the bridge. `uplink setup` creates on it, once per remote, the
|
||||
@@ -156,6 +220,7 @@ bin/lm-dev-lxd-project.py remove
|
||||
| `--pool` | `LXD_POOL` | required by `create` | The storage pool of the project's root disks |
|
||||
| `--project` | `LXD_PROJECT` | `lm-dev` | The project |
|
||||
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the repository container |
|
||||
| `--vault-address` | `LXD_VAULT_ADDRESS` | allocated | The listen address of the Vault's forward, one of the uplink's routes |
|
||||
| `--uplink` | `LXD_UPLINK` | `uplink` | The physical uplink network of the OVN networks |
|
||||
| `--parent` | `LXD_UPLINK_PARENT` | required by `uplink setup` | The host bridge on the LAN |
|
||||
| `--gateway` | `LXD_UPLINK_GATEWAY` | required by `uplink setup` | The LAN's gateway, address/prefix |
|
||||
@@ -167,8 +232,8 @@ bin/lm-dev-lxd-project.py remove
|
||||
entry's with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release
|
||||
of that entry is newer than its dev builds. `N` is that of the last dev build, kept in
|
||||
`.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and
|
||||
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the
|
||||
environment; the build is moved to `out/dev/`, copied into the repository and published there. A
|
||||
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh`
|
||||
builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the environment; the build is moved to `out/dev/`, copied into the repository and published there. A
|
||||
VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update`
|
||||
and `apt-get upgrade`.
|
||||
|
||||
@@ -182,36 +247,39 @@ read from its state file, so the script takes no `--remote`.
|
||||
## A TOTP token for a user of a test VM
|
||||
|
||||
`bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by
|
||||
default, through `lxc exec`: in the VM, as root, the package's `linuxmanager_users` makes a new
|
||||
secret and stores it once a code the script computes from it verifies, replacing a token the user
|
||||
had. The secret, base32, is then written to the file `--secret-file` or `OTP_FILE` names,
|
||||
readable by its owner only; `otp.py code` prints its codes (see below).
|
||||
default, replacing a token the user had. The project's Vault generates the key `<vm>-<user>` in its
|
||||
TOTP engine and hands it to the VM (see Secrets), where the package's `linuxmanager_users` stores
|
||||
it. `bin/lm-dev-otp-code.py` prints the user's current code, read from the Vault, for the Manager's
|
||||
sign-in, SSH or `sudo`.
|
||||
|
||||
```sh
|
||||
export OTP_FILE=tmp/admin.otp
|
||||
bin/lm-dev-otp-register.py
|
||||
```
|
||||
|
||||
```sh
|
||||
bin/lm-dev-otp-code.py
|
||||
```
|
||||
|
||||
| Option | Variable | Default | Meaning |
|
||||
|---|---|---|---|
|
||||
| `--secret-file` | `OTP_FILE` | required | The file the secret is written to |
|
||||
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
|
||||
| `--remote` | `LXD_REMOTE` | required by `lm-dev-otp-register.py` | The `lxc` remote |
|
||||
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
|
||||
| `--vm` | | `lm-dev` | The name of the VM |
|
||||
| `--user` | | `admin` | The user to enrol |
|
||||
| `--user` | | `admin` | The user |
|
||||
|
||||
## A command-line authenticator app
|
||||
|
||||
`bin/otp.py` is an authenticator app on the command line, in place of one on a phone, not tied to
|
||||
Linux Manager or LXD. It keeps a base32 secret in the file `--secret-file` or `OTP_FILE` names,
|
||||
readable by its owner only. The codes are
|
||||
RFC 6238's, SHA-1, 6 digits and 30 seconds by default.
|
||||
Linux Manager or LXD. It keeps a secret in the file `--secret-file` or `OTP_FILE` names, readable
|
||||
by its owner only: the base32 secret alone, or with `--url` its `otpauth://` URI, without a line
|
||||
end, so Vault's TOTP engine imports the file as it is. The codes are RFC 6238's, SHA-1, 6 digits
|
||||
and 30 seconds by default; a file holding a URI gives the URI's.
|
||||
|
||||
Options of both actions:
|
||||
|
||||
| Option | Variable | Default | Meaning |
|
||||
|---|---|---|---|
|
||||
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret |
|
||||
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret or its `otpauth://` URI |
|
||||
| `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` |
|
||||
| `--digits` | | `6` | The digits of a code, 6 to 10 |
|
||||
| `--period` | | `30` | The seconds a code is valid |
|
||||
@@ -223,9 +291,18 @@ algorithm, digits and period, for a server or an app that enrols a given secret:
|
||||
bin/otp.py new --account admin --issuer lm-dev
|
||||
```
|
||||
|
||||
Either file is a key of Vault's TOTP engine, the secret with its settings, or the URI with all of
|
||||
them:
|
||||
|
||||
```sh
|
||||
vault write totp/keys/admin key=@secret-file issuer=lm-dev account_name=admin
|
||||
vault write totp/keys/admin url=@otpauth-file
|
||||
```
|
||||
|
||||
| Option | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `--account`, `--issuer` | none | The label of the URI |
|
||||
| `--url` | off | Store the `otpauth://` URI instead of the secret alone |
|
||||
| `--force` | off | Replace an existing secret |
|
||||
|
||||
`code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`:
|
||||
@@ -240,5 +317,5 @@ bin/otp.py code
|
||||
|
||||
## Scope of the tests
|
||||
|
||||
Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID
|
||||
Provider and passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules.
|
||||
Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, passkeys,
|
||||
PowerDNS answering from outside, and the Azure and GCP platform modules.
|
||||
@@ -0,0 +1,24 @@
|
||||
#cloud-config
|
||||
# The Vault of a test project: HashiCorp's vault package from its apt repository, file storage and a plain HTTP
|
||||
# listener; lm_dev.vault_initialise initialises and unseals it over its API.
|
||||
write_files:
|
||||
- path: /root/vault.hcl
|
||||
permissions: '0644'
|
||||
content: |
|
||||
storage "file" {
|
||||
path = "/opt/vault/data"
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_disable = "true"
|
||||
}
|
||||
disable_mlock = true
|
||||
ui = true
|
||||
runcmd:
|
||||
- wget -O - https://apt.releases.hashicorp.com/gpg | gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
|
||||
- echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" > /etc/apt/sources.list.d/hashicorp.list
|
||||
- apt-get update
|
||||
- DEBIAN_FRONTEND=noninteractive apt-get install -y vault
|
||||
- install -d -o vault -g vault -m 0700 /opt/vault/data
|
||||
- install -m 0644 /root/vault.hcl /etc/vault.d/vault.hcl
|
||||
- systemctl enable --now vault
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": false},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-oidc.test"},
|
||||
"https": {"enabled": true, "certificate": "ca"},
|
||||
"oidc": {"enabled": true}
|
||||
}
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/python3
|
||||
"""The test project's Vault seen from an instance, which logs in with its own AppRole: lm-dev-vault init|get|totp.
|
||||
|
||||
lm-dev-vault init ROLE
|
||||
lm-dev-vault get PATH FIELD OUTPUT MODE
|
||||
lm-dev-vault totp KEY ISSUER ACCOUNT OUTPUT MODE
|
||||
|
||||
/etc/vault (0700) holds the Vault's URL (url), the role ID of the instance's AppRole (role-id) and its secret ID
|
||||
(secret-id), both 0600. init takes the secret ID from the wrapping token in secret-id.wrapped, which is removed: the
|
||||
token's creation path must be the secret-id request of the role ROLE, and it is unwrapped once. get logs in and writes
|
||||
the field FIELD of the KV v2 secret PATH to OUTPUT with MODE, octal. totp logs in, has the Vault generate the TOTP key
|
||||
KEY for ACCOUNT of ISSUER, SHA1, 6 digits and 30 seconds, and writes its otpauth URI to OUTPUT with MODE. No argument
|
||||
is a secret.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ETC = pathlib.Path('/etc/vault')
|
||||
KV_MOUNT = 'kv'
|
||||
TOTP_MOUNT = 'totp'
|
||||
|
||||
|
||||
def call(path, body=None, token=None, method='POST'):
|
||||
"""Send the request to the Vault; the JSON answer."""
|
||||
url = (ETC / 'url').read_text(encoding='utf-8').strip()
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
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:
|
||||
return json.loads(response.read() or b'{}')
|
||||
except urllib.error.HTTPError as error:
|
||||
sys.exit(f'lm-dev-vault: {method} {path}: {error.code}')
|
||||
except (urllib.error.URLError, OSError) as error:
|
||||
sys.exit(f'lm-dev-vault: {url} cannot be reached: {error}')
|
||||
|
||||
|
||||
def write(output, text, mode):
|
||||
"""Write the text to the regular file output with the octal mode."""
|
||||
descriptor = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, int(mode, 8))
|
||||
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
|
||||
os.close(descriptor)
|
||||
sys.exit(f'lm-dev-vault: {output} is not a regular file')
|
||||
os.ftruncate(descriptor, 0)
|
||||
os.fchmod(descriptor, int(mode, 8))
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
|
||||
handle.write(text)
|
||||
|
||||
|
||||
def login():
|
||||
"""A token of the instance's AppRole."""
|
||||
answer = call('/v1/auth/approle/login', {'role_id': (ETC / 'role-id').read_text(encoding='utf-8').strip(),
|
||||
'secret_id': (ETC / 'secret-id').read_text(encoding='utf-8').strip()})
|
||||
return answer['auth']['client_token']
|
||||
|
||||
|
||||
def main():
|
||||
action, arguments = (sys.argv[1], sys.argv[2:]) if len(sys.argv) > 1 else (None, [])
|
||||
if action == 'init' and len(arguments) == 1:
|
||||
wrapped = ETC / 'secret-id.wrapped'
|
||||
try:
|
||||
token = wrapped.read_text(encoding='utf-8').strip()
|
||||
finally:
|
||||
wrapped.unlink(missing_ok=True)
|
||||
expected = f'auth/approle/role/{arguments[0]}/secret-id'
|
||||
created = call('/v1/sys/wrapping/lookup', {'token': token}).get('data', {}).get('creation_path')
|
||||
if created != expected:
|
||||
sys.exit(f'lm-dev-vault: the token wraps {created}, not {expected}')
|
||||
write(ETC / 'secret-id', call('/v1/sys/wrapping/unwrap', token=token)['data']['secret_id'] + '\n', '0600')
|
||||
elif action == 'get' and len(arguments) == 4:
|
||||
path, field, output, mode = arguments
|
||||
values = call(f'/v1/{KV_MOUNT}/data/{path}', token=login(), method='GET')['data']['data']
|
||||
if field not in values:
|
||||
sys.exit(f'lm-dev-vault: {path} has no {field}')
|
||||
write(output, values[field], mode)
|
||||
elif action == 'totp' and len(arguments) == 5:
|
||||
key, issuer, account, output, mode = arguments
|
||||
answer = call(f'/v1/{TOTP_MOUNT}/keys/{key}',
|
||||
{'generate': True, 'exported': True, 'qr_size': 0, 'issuer': issuer, 'account_name': account,
|
||||
'algorithm': 'SHA1', 'digits': 6, 'period': 30}, token=login())
|
||||
write(output, answer['data']['url'] + '\n', mode)
|
||||
else:
|
||||
sys.exit('usage: lm-dev-vault init ROLE | get PATH FIELD OUTPUT MODE | totp KEY ISSUER ACCOUNT OUTPUT MODE')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Sign a user in at the server's OpenID Provider as a browser would, in the client of the oidc scenario.
|
||||
|
||||
It reads the authorization URL a relying party made from /run/lm-dev/oidc-url, the user's name, password and TOTP code
|
||||
from /run/lm-dev/oidc-name, /run/lm-dev/oidc-password and /run/lm-dev/oidc-code, and removes the password and the code,
|
||||
trusts the server's root CA in /root/oidc-root.pem, opens the URL, which answers the sign-in page, and posts the page's
|
||||
form to /oidc/login without following the redirect. It prints {"page", "status", "location"} as JSON: whether the
|
||||
sign-in page came, the status of the sign-in, and the Location of its redirect, null without one.
|
||||
|
||||
python3 oidc_login.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
HANDOVER = '/run/lm-dev'
|
||||
ROOT_PEM = '/root/oidc-root.pem'
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""A redirect is answered as it is, not followed."""
|
||||
|
||||
def redirect_request(self, request, fp, code, message, headers, new_url):
|
||||
return None
|
||||
|
||||
|
||||
def read(name, remove=False):
|
||||
path = os.path.join(HANDOVER, name)
|
||||
with open(path, encoding='utf-8') as handle:
|
||||
value = handle.read().strip()
|
||||
if remove:
|
||||
os.remove(path)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
url = read('oidc-url')
|
||||
name = read('oidc-name')
|
||||
password = read('oidc-password', remove=True)
|
||||
code = read('oidc-code', remove=True)
|
||||
context = ssl.create_default_context(cafile=ROOT_PEM)
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context), NoRedirect())
|
||||
with opener.open(url, timeout=30) as response:
|
||||
page = response.status == 200 and 'name="password"' in response.read().decode(errors='replace')
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
form = urllib.parse.urlencode({'request': parts.query, 'name': name, 'password': password, 'code': code}).encode()
|
||||
request = urllib.request.Request(f'{parts.scheme}://{parts.netloc}/oidc/login', data=form, method='POST',
|
||||
headers={'Content-Type': 'application/x-www-form-urlencoded'})
|
||||
try:
|
||||
with opener.open(request, timeout=30) as response:
|
||||
status, location = response.status, response.headers.get('Location')
|
||||
except urllib.error.HTTPError as error:
|
||||
status, location = error.code, error.headers.get('Location')
|
||||
print(json.dumps({'page': page, 'status': status, 'location': location}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -19,13 +19,15 @@ def run(lab):
|
||||
'lm-core', 'cat', '/etc/ufw/before.rules')
|
||||
for unit in ('strongswan', 'wg-quick@wg0', 'openvpn-server@linux-manager', 'linux-manager-resolver'):
|
||||
lab.refuse(f'core: {unit} inactive', r'^active', 'lm-core', 'systemctl', 'is-active', unit)
|
||||
lab.refuse('core: no VPN or router package installed', r'(?m)^installed$', 'lm-core', 'sh', '-c',
|
||||
"dpkg-query -W -f='${db:Status-Status}\\n' strongswan-swanctl openvpn 2>/dev/null")
|
||||
lab.expect('core: schema under the PEN arc', r"1\.3\.6\.1\.4\.1\.67380\.10\.1\.2\.2\.1 NAME 'linuxManagerAccount'",
|
||||
'lm-core', 'slapcat', '-n', '0', '-o', 'ldif-wrap=no')
|
||||
lab.expect('core: base DN dc=linux-manager,dc=local', r'^dn: dc=linux-manager,dc=local$',
|
||||
'lm-core', 'slapcat', '-b', 'dc=linux-manager,dc=local', '-o', 'ldif-wrap=no')
|
||||
status = lab.json_of('lm-core', 'linux-manager-ca', '--json', 'status') or {}
|
||||
states = {authority.get('name'): authority.get('state') for authority in status.get('authorities', [])}
|
||||
lab.result('core: p2s and s2s CAs missing', states.get('p2s') == 'missing' and states.get('s2s') == 'missing')
|
||||
lab.result('core: p2s and s2s CAs off', states.get('p2s') == 'off' and states.get('s2s') == 'off')
|
||||
lab.result('core: VPN user added', lab.vpn_user('lm-core'))
|
||||
user = lab.alice('lm-core')
|
||||
lab.result('core: VPN user has no certificate', user is not None and not user.get('certificate'))
|
||||
|
||||
@@ -47,8 +47,8 @@ def run(lab):
|
||||
lab.skip('nat: WireGuard (no wireguard module on the host)')
|
||||
|
||||
profile = (lab.json_of('lm-nat', 'linux-manager-user', '--json', 'profile', 'alice') or {}).get('profile', '')
|
||||
lab.push_text(profile, 'lm-nat-client', '/root/alice.ovpn', '0600')
|
||||
lab.push_text(f'alice\n{lab.admin_password}\n', 'lm-nat-client', '/root/alice.pass', '0600')
|
||||
lab.hand_over('lm-nat-client', 'openvpn-profile', profile, '/root/alice.ovpn')
|
||||
lab.hand_over('lm-nat-client', 'alice', f'alice\n{lab.admin_password}\n', '/root/alice.pass')
|
||||
lab.on('lm-nat-client', 'sh', '-c', f'echo "{server} lm-nat.test" >>/etc/hosts')
|
||||
lab.on('lm-nat-client', 'openvpn', '--config', '/root/alice.ovpn', '--auth-user-pass', '/root/alice.pass',
|
||||
'--route-nopull', '--disable-dco', '--route', target, '255.255.255.255',
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""OpenID Provider: the lab's Vault signs the user alice in through the server's provider, as a relying party
|
||||
(auth/oidc) with the authorization code flow and PKCE, the sign-in driven in a client as a browser would."""
|
||||
|
||||
import secrets
|
||||
import urllib.parse
|
||||
|
||||
from lm_dev import TESTS, VaultError, enrol_otp, otp_code, store_secret, vault_call
|
||||
|
||||
#: The FQDN of the server, the host of its issuer.
|
||||
FQDN = 'lm-oidc.test'
|
||||
|
||||
#: The server's OpenID Provider, the HTTPS site of its web service.
|
||||
ISSUER = f'https://{FQDN}:7444'
|
||||
|
||||
#: The redirect URI of Vault's CLI convention, registered on both sides; the driver reads it, nothing follows it.
|
||||
REDIRECT = 'http://localhost:8250/oidc/callback'
|
||||
|
||||
#: The server's root CA, which the server trusts and publishes.
|
||||
ROOT_PEM = '/usr/local/share/ca-certificates/linux-manager-ca.crt'
|
||||
|
||||
|
||||
def vault(lab, method, path, body=None, token=None):
|
||||
"""A call to the lab's Vault with the root token, or the token given; the answer, or None with the problem printed."""
|
||||
try:
|
||||
return vault_call(lab.vault['url'], method, path, body, token or lab.vault['root_token'])
|
||||
except VaultError as error:
|
||||
print(f'oidc: {error}')
|
||||
return None
|
||||
|
||||
|
||||
def sign_in(lab, url, code):
|
||||
"""Hand the client the authorization URL, alice's password and the code, and run the driver; its answer or {}."""
|
||||
ok = (lab.push_text(url, 'lm-oidc-client', '/run/lm-dev/oidc-url') and
|
||||
lab.push_text('alice', 'lm-oidc-client', '/run/lm-dev/oidc-name') and
|
||||
lab.hand_over('lm-oidc-client', 'oidc-password', lab.admin_password, '/run/lm-dev/oidc-password') and
|
||||
lab.hand_over('lm-oidc-client', 'oidc-code', code, '/run/lm-dev/oidc-code'))
|
||||
return (lab.json_of('lm-oidc-client', 'python3', '/root/oidc_login.py') or {}) if ok else {}
|
||||
|
||||
|
||||
def run(lab):
|
||||
lab.network('lmt-oidc-ext', '172.31.12.1/24')
|
||||
lab.instance('lm-oidc', 'vm', 'server.yaml', ('lmt-oidc-ext', '00:16:3e:4c:12:10', '172.31.12.10/24', '172.31.12.1'))
|
||||
lab.instance('lm-oidc-client', 'container', 'client.yaml',
|
||||
('lmt-oidc-ext', '00:16:3e:4c:12:30', '172.31.12.30/24', '172.31.12.1'))
|
||||
if not lab.ready('lm-oidc', 'lm-oidc-client'):
|
||||
lab.result('oidc: instances ready', False)
|
||||
lab.result('oidc: package installed and configured', lab.server('lm-oidc', 'oidc.json'))
|
||||
server = str(lab.address('lm-oidc').ip)
|
||||
lab.result('oidc: user alice added', lab.vpn_user('lm-oidc'))
|
||||
lab.result('oidc: TOTP token of alice enrolled', enrol_otp(lab.remote, lab.project, 'lm-oidc', 'alice') is None)
|
||||
|
||||
# The client: a service account with the redirect URI, its secret handed over as a file and kept in the Vault.
|
||||
secret = secrets.token_urlsafe(24)
|
||||
store_secret(lab.vault, 'lm-oidc/vault-client', {'secret': secret})
|
||||
file = '/run/lm-dev/vault-client.secret'
|
||||
registered = lab.hand_over('lm-oidc', 'vault-client', f'{secret}\n', file) and lab.on(
|
||||
'lm-oidc', 'sh', '-c', f'linux-manager-user --json add vault --service --display-name Vault --redirect-uri '
|
||||
f'{REDIRECT} < {file}; status=$?; rm -f {file}; exit $status').returncode == 0
|
||||
lab.result('oidc: client vault registered', registered)
|
||||
|
||||
root = lab.on('lm-oidc', 'cat', ROOT_PEM).stdout
|
||||
hosts = f'echo "{server} {FQDN}" >>/etc/hosts'
|
||||
lab.on('lm-oidc-client', 'sh', '-c', hosts)
|
||||
lab.push_text(root, 'lm-oidc-client', '/root/oidc-root.pem')
|
||||
lab.push(TESTS / 'oidc_login.py', 'lm-oidc-client', '/root/oidc_login.py')
|
||||
lab.expect('oidc: discovery answers over HTTPS with the server CA', rf'"issuer": ?"{ISSUER}"',
|
||||
'lm-oidc-client', 'curl', '-s', '--cacert', '/root/oidc-root.pem',
|
||||
f'{ISSUER}/.well-known/openid-configuration')
|
||||
|
||||
# Vault, a relying party of the server, configured with the root token.
|
||||
lab.on('lm-vault', 'sh', '-c', hosts)
|
||||
vault(lab, 'POST', '/v1/sys/auth/oidc', {'type': 'oidc'})
|
||||
configured = vault(lab, 'POST', '/v1/auth/oidc/config', {
|
||||
'oidc_discovery_url': ISSUER, 'oidc_discovery_ca_pem': root, 'oidc_client_id': 'vault',
|
||||
'oidc_client_secret': secret, 'default_role': 'lab'})
|
||||
lab.result('oidc: Vault reads the discovery document', configured is not None)
|
||||
role = vault(lab, 'POST', '/v1/auth/oidc/role/lab', {
|
||||
'role_type': 'oidc', 'user_claim': 'preferred_username', 'groups_claim': 'groups',
|
||||
'oidc_scopes': ['profile', 'email', 'groups'], 'allowed_redirect_uris': [REDIRECT],
|
||||
'claim_mappings': {'email': 'email'}, 'token_policies': ['default']})
|
||||
lab.result('oidc: Vault role lab written', role is not None)
|
||||
|
||||
# The authorization code flow: Vault's URL, the sign-in in the client, the code back to Vault.
|
||||
url = ((vault(lab, 'POST', '/v1/auth/oidc/oidc/auth_url', {'role': 'lab', 'redirect_uri': REDIRECT}) or {})
|
||||
.get('data') or {}).get('auth_url') or ''
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)
|
||||
lab.result('oidc: authorization URL asks for PKCE S256', query.get('code_challenge_method') == ['S256'])
|
||||
answer = sign_in(lab, url, otp_code(lab.project, 'lm-oidc', 'alice')) if url else {}
|
||||
lab.result('oidc: sign-in page shown', answer.get('page') is True)
|
||||
location = urllib.parse.parse_qs(urllib.parse.urlsplit(answer.get('location') or '').query)
|
||||
lab.result('oidc: sign-in redirects with a code and the state',
|
||||
answer.get('status') == 302 and bool(location.get('code')) and location.get('state') == query.get('state'))
|
||||
login = vault(lab, 'GET', '/v1/auth/oidc/oidc/callback?' + urllib.parse.urlencode({
|
||||
'state': (location.get('state') or [''])[0], 'code': (location.get('code') or [''])[0],
|
||||
'nonce': (query.get('nonce') or [''])[0]})) if location.get('code') else None
|
||||
token = ((login or {}).get('auth') or {}).get('client_token')
|
||||
lab.result('oidc: Vault issues a token for alice', bool(token))
|
||||
looked = vault(lab, 'GET', '/v1/auth/token/lookup-self', token=token) if token else None
|
||||
entity = (looked or {}).get('data', {}).get('entity_id')
|
||||
aliases = ((vault(lab, 'GET', f'/v1/identity/entity/id/{entity}') or {}).get('data') or {}).get('aliases', []) \
|
||||
if entity else []
|
||||
alias = next((item for item in aliases if item.get('name') == 'alice'), {})
|
||||
lab.result('oidc: the token is of the entity alias alice', bool(alias))
|
||||
lab.result('oidc: the email claim is mapped', (alias.get('metadata') or {}).get('email') == 'alice@example.org')
|
||||
|
||||
# A wrong code: the sign-in page again, no redirect.
|
||||
url = ((vault(lab, 'POST', '/v1/auth/oidc/oidc/auth_url', {'role': 'lab', 'redirect_uri': REDIRECT}) or {})
|
||||
.get('data') or {}).get('auth_url') or ''
|
||||
wrong = f'{(int(otp_code(lab.project, "lm-oidc", "alice")) + 1) % 1000000:06d}'
|
||||
answer = sign_in(lab, url, wrong) if url else {}
|
||||
lab.result('oidc: a wrong code is refused without a redirect', answer.get('status') == 401 and not answer.get('location'))
|
||||
Reference in new issue
Block a user