Pritunl Cloud v2.2 Released

Pritunl Cloud v2.2 has been released. This release includes several features focused on managing replicated services across multiple datacenters, instance monitoring and instance disk management.

Node and Instance Security Advisories

A new security advisory system has been developed. The significant increase in nuisance CVEs creates a problem for administrators when deciding when to update systems. This new system uses AI analysis provided by Pritunl of all RHEL 8-10 and FreeBSD CVEs. These are made available at advisory.pritunl.com and provide a more realistic score of each CVE. In the first example below a CVE is upgraded in severity by the analysis due to the risk of container escape. Additionally the analysis determines when a CVE will not impact a system. In the second example below two CVEs impact specific kernel modules and when those modules are not loaded on a system they can be marked unreachable. A combination of process names, kernel modules and open ports is used to determine when a CVE is unreachable. The IMDS agent metric system provides the list of processes, kernel modules and open ports to the Pritunl Cloud host. The Pritunl Cloud host then compares those to the information provided by the advisory analysis.

Instance and Node Metrics

All instances and nodes now have historical metrics for system resources and active processes, kernel modules and open ports. This system was built from the endpoint monitoring system in Pritunl Zero. Data is collected from the instance IMDS agent and MongoDB time series collections are used to store the data.

Pod Editor Interface Improvements

Several interface improvements have been made to the pod editor. This includes moving the unit list to the sidebar to allow managing pods with large numbers of units.

Saving or discarding changes now displays a prompt showing a diff of what changes will be applied.

TUI Interface

A TUI interface has been added to control Pritunl Cloud from the terminal. The TUI can be started by running sudo pritunl-cloud tui and includes most features available in the web console. This allows managing a Pritunl Cloud system where the web console is hosted on an instance and the instance needs to be started to provide access. It is also helpful for outage recovery.

Disk Shapes

Disk shapes allow handling different disk types such as NVMe and magnetic drives. In this example nodes mount an NVMe RAID at /var/lib/pritunl-cloud and a slower magnetic RAID at /mnt/storage. Instances can then create large slower QCOW disks for data storage while also having fast NVMe disks.

Disk Partition Editor

The web console now includes a graphical partition editor that allows better management of LVM disks and resizing partitions from the web console.

DNS Improvements

Google DNS support has been added. Additionally changes to zone upstream DNS servers are now applied to all instances within 5 seconds.

MongoDB Change Streams

Change stream support has been added for the host state sync. This significantly reduces bandwidth and database queries for host state updates. The command sudo pritunl-cloud set system state_stream true will enable this feature. Below are test results from a four host cluster before and after change streams are enabled.

Metric Reduction
Find commands/sec 51.2%
Index keys scanned/sec 88.6%
Documents scanned/sec 59.6%
Documents returned/sec 84.4%
Network sent 48.3%
Network requests/sec 22.6%
GetMore operations/sec 16.2%
Metric Before After Reduction
Find commands/sec 79.36 38.70 51.2%
Index keys scanned/sec 1,262 144 88.6%
Documents scanned/sec 1,401 566 59.6%
Documents returned/sec 971 152 84.4%
Network sent per 10 seconds 14.83 MiB 7.67 MiB 48.3%
Network requests/sec 354 274 22.6%
GetMore operations/sec 47.63 39.93 16.2%

Multi Datacenter Realms

Pod realms allow defining resources across multiple datacenters allowing for complex multi-datacenter failover configurations. In the example below an nginx server is deployed to the us-west-1 and us-east-1 datacenters.

---
name: nginx
kind: instance
shape: +/shape/c2-medium
processors: 2
memory: 2048
image: +/image/almalinux10
roles:
    - instance
nodePorts:
    - protocol: tcp
      externalPort: 32120
      internalPort: 80
realms:
    - name: us-west
      datacenter: +/datacenter/us-west-1
      vpc: +/vpc/pritunl-dev
      subnet: +/subnet/primary
    - name: us-east
      datacenter: +/datacenter/us-east-1
      vpc: +/vpc/pritunl-dev
      subnet: +/subnet/primary

---
name: nginx-firewall
kind: firewall
ingress:
    - protocol: tcp
      port: 22
      source:
        - 10.20.0.0/16

---
name: nginx-logs
kind: journal
inputs:
    - key: nginx
      type: systemd
      unit: nginx

This also allows defining domains with a primary/secondary select. After including failover: primary in the instance definition domains can include select: primary to select the given address type from only the primary instance. Primary selection can be scripted from the instance using the IMDS command sudo pci set-primary or by clicking Make Primary from the deployment settings.

name: git-domain
kind: domain
records:
    - name: git
      domain: +/domain/pritunl-com
      type: public
      select: primary

Active Passive LVM Failover

Below is an example of a more complex usage of realms to create a active passive failover Forgejo deployment. This is done using the LVM support in Pritunl Cloud and lvsync, an LVM based replication tool. This functionality allows replicating complex software that has no built in replication support or any knowledge of the replication occurring.

flowchart TD
    Cloud["Pritunl Cloud Hosts"]
    DNS["DNS: git.pritunl.com"]
    Users["Git And Web Clients"]

    SelectPrimary["Select Primary"]
    AssignStandby["Assign Standby"]
    UpdateDNS["Update Primary IP"]
    Resolve["Resolve Hostname"]
    Connect["HTTPS And Git Over SSH"]
    Sync["LVSync: Freeze, Snapshot, Replicate Over SSH"]

    subgraph East["Datacenter: us-east-1"]
        Primary["Primary VM"]
        Active["Forgejo And PostgreSQL Running"]
        Source[("Forgejo And PostgreSQL LVM Volumes")]

        Primary --> Active
        Active --> Source
    end

    subgraph West["Datacenter: us-west-1"]
        Standby["Standby VM"]
        Stopped["Forgejo And PostgreSQL Stopped"]
        Replica[("Replicated LVM Volumes")]

        Standby --> Stopped
        Standby --- Replica
    end

    Cloud -.-> SelectPrimary -.-> Primary
    Cloud -.-> AssignStandby -.-> Standby
    Cloud --> UpdateDNS --> DNS

    Users -.-> Resolve -.-> DNS
    Users --> Connect --> Active

    Source ==> Sync ==> Replica

    classDef control fill:#6d28d9,stroke:#c084fc,color:#ffffff,stroke-width:2px
    classDef client fill:#1d4ed8,stroke:#60a5fa,color:#ffffff,stroke-width:2px
    classDef primary fill:#047857,stroke:#34d399,color:#ffffff,stroke-width:2px
    classDef standby fill:#b45309,stroke:#fbbf24,color:#ffffff,stroke-width:2px
    classDef action fill:#1e293b,stroke:#64748b,color:#f1f5f9,stroke-width:1px

    class Cloud,DNS control
    class Users client
    class Primary,Active,Source primary
    class Standby,Stopped,Replica standby
    class SelectPrimary,AssignStandby,UpdateDNS,Resolve,Connect,Sync action

    style East fill:#0b2420,stroke:#10b981,color:#a7f3d0,stroke-width:2px
    style West fill:#292013,stroke:#f59e0b,color:#fde68a,stroke-width:2px

    linkStyle default stroke:#94a3b8,stroke-width:2px

Below is the pod spec for this active passive failover configuration.

```yaml
name: forgejo
kind: instance
shape: +/shape/c2-large
processors: 4
memory: 4096
failover: primary
image: +/image/almalinux10
diskSize: 40
mounts:
    - name: forgejo-data
      type: disk
      path: /var/lib/forgejo
      disks:
        - +/disk/forgejo-data
    - name: forgejo-db
      type: disk
      path: /var/lib/pgsql
      disks:
        - +/disk/forgejo-db
roles:
    - instance
certificates:
    - +/certificate/git-pritunl-com
secrets:
    - +/secret/forgejo
realms:
    - name: us-east-1
      datacenter: +/datacenter/us-east-1
      vpc: +/vpc/pritunl
      subnet: +/subnet/git
    - name: us-west-1
      datacenter: +/datacenter/us-west-1
      vpc: +/vpc/pritunl
      subnet: +/subnet/git

---
name: forgejo-domain
kind: domain
records:
    - name: git
      domain: +/domain/pritunl-com
      type: public
      select: primary

---
name: forgejo-logs
kind: journal
inputs:
    - key: forgejo
      type: systemd
      unit: forgejo
    - key: postgresql
      type: systemd
      unit: postgresql
    - key: lvsync
      type: systemd
      unit: lvsync

---
name: forgejo-firewall
kind: firewall
ingress:
    - protocol: tcp
      port: 22
      source:
        - 10.20.0.0/16
        - +/unit/forgejo/private_ips
    - protocol: tcp
      port: 443
      source:
        - 0.0.0.0/0
```

## install

```shell
timedatectl set-timezone America/New_York

dnf -y update

dnf -y install dnf-automatic git git-lfs wget rsync postgresql-server
sed -i 's/^upgrade_type =.*/upgrade_type = default/g' /etc/dnf/automatic.conf
sed -i 's/^download_updates =.*/download_updates = yes/g' /etc/dnf/automatic.conf
sed -i 's/^apply_updates =.*/apply_updates = yes/g' /etc/dnf/automatic.conf
systemctl enable --now dnf-automatic.timer

wget https://codeberg.org/forgejo/forgejo/releases/download/v17.0.1/forgejo-17.0.1-linux-amd64
echo "51a8cdf4a1252e79f4b3855d7a7891af6c6635105420768c460e2f0690385d6f  forgejo-17.0.1-linux-amd64" | sha256sum -c - && install -m 755 forgejo-17.0.1-linux-amd64 /usr/bin/forgejo
rm -f forgejo-17.0.1-linux-amd64

getent group git > /dev/null || groupadd --system --gid 600 git
id git &>/dev/null || useradd --system --uid 600 --gid 600 --create-home --home-dir /home/git --shell /bin/bash git
mkdir -p /home/git/.ssh
chmod 700 /home/git/.ssh
chown -R git:git /home/git
restorecon -R /home/git
mkdir -p /var/lib/forgejo/{custom,data,log}
chown -R git:git /var/lib/forgejo
chmod 750 /var/lib/forgejo

chown postgres:postgres /var/lib/pgsql
chmod 700 /var/lib/pgsql
restorecon -R /var/lib/pgsql
```

## configure

```shell
set -e
cd /

SECRET_KEY=$(pci get +/secret/forgejo/data.secret_key)
INTERNAL_TOKEN=$(pci get +/secret/forgejo/data.internal_token)
JWT_SECRET=$(pci get +/secret/forgejo/data.jwt_secret)
LFS_JWT_SECRET=$(pci get +/secret/forgejo/data.lfs_jwt_secret)
DB_PASSWORD=$(pci get +/secret/forgejo/data.db_password)
ADMIN_PASSWORD=$(pci get +/secret/forgejo/data.admin_password)
SSH_HOST_KEY=$(pci get +/secret/forgejo/data.ssh_host_key)

for VAL in "$SECRET_KEY" "$INTERNAL_TOKEN" "$JWT_SECRET" "$LFS_JWT_SECRET" "$DB_PASSWORD" "$ADMIN_PASSWORD" "$SSH_HOST_KEY"; do
    if [[ -z "$VAL" ]]; then
        echo "Missing required configure values"
        exit 1
    fi
done

install -m 600 -o root -g root /dev/null /etc/ssh/ssh_host_ed25519_key
printf '%s' "$SSH_HOST_KEY" | base64 -d > /etc/ssh/ssh_host_ed25519_key
ssh-keygen -y -f /etc/ssh/ssh_host_ed25519_key > /etc/ssh/ssh_host_ed25519_key.pub
chmod 644 /etc/ssh/ssh_host_ed25519_key.pub
restorecon /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_ed25519_key.pub
tee /etc/ssh/sshd_config.d/01-hostkey.conf << EOF
HostKey /etc/ssh/ssh_host_ed25519_key
EOF
sshd -t
systemctl reload sshd

if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
    PGSETUP_INITDB_OPTIONS="--auth-local=peer --auth-host=scram-sha-256" postgresql-setup --initdb
fi
systemctl enable --now postgresql

sudo -u postgres psql -v ON_ERROR_STOP=1 -v pw="$DB_PASSWORD" > /dev/null << 'EOF'
SELECT 'CREATE ROLE forgejo LOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'forgejo')\gexec
ALTER ROLE forgejo PASSWORD :'pw';
SELECT 'CREATE DATABASE forgejo OWNER forgejo TEMPLATE template0 ENCODING ''UTF8''' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'forgejo')\gexec
EOF

mkdir -p /etc/forgejo/certs
chown root:git /etc/forgejo
chmod 750 /etc/forgejo
chown git:git /etc/forgejo/certs
chmod 700 /etc/forgejo/certs

install -m 640 -o root -g git /dev/null /etc/forgejo/app.ini
tee /etc/forgejo/app.ini > /dev/null << EOF
APP_NAME = Forgejo
RUN_USER = git
RUN_MODE = prod
WORK_PATH = /var/lib/forgejo

[server]
PROTOCOL = https
DOMAIN = git.pritunl.com
HTTP_ADDR = 0.0.0.0
HTTP_PORT = 443
SSL_MIN_VERSION = tlsv1.2
SSL_MAX_VERSION = tlsv1.3
ROOT_URL = https://git.pritunl.com/
CERT_FILE = /etc/forgejo/certs/cert.pem
KEY_FILE = /etc/forgejo/certs/key.pem
START_SSH_SERVER = false
SSH_DOMAIN = git.pritunl.com
SSH_PORT = 22
LFS_START_SERVER = true
LFS_JWT_SECRET = ${LFS_JWT_SECRET}
OFFLINE_MODE = true

[database]
DB_TYPE = postgres
HOST = 127.0.0.1:5432
NAME = forgejo
USER = forgejo
PASSWD = ${DB_PASSWORD}
SSL_MODE = disable

[repository]
ROOT = /var/lib/forgejo/data/forgejo-repositories

[security]
INSTALL_LOCK = true
SECRET_KEY = ${SECRET_KEY}
INTERNAL_TOKEN = ${INTERNAL_TOKEN}

[oauth2]
JWT_SECRET = ${JWT_SECRET}

[service]
DISABLE_REGISTRATION = true

[time]
DEFAULT_UI_LOCATION = America/New_York

[ssh.minimum_key_sizes]
RSA = 2048

[log]
MODE = console
LEVEL = warn
EOF

tee /etc/systemd/system/forgejo.service << EOF
[Unit]
Description=Forgejo
Wants=network-online.target postgresql.service
After=network-online.target postgresql.service

[Service]
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/forgejo
Environment=USER=git HOME=/home/git FORGEJO_WORK_DIR=/var/lib/forgejo
ExecStart=/usr/bin/forgejo web --config /etc/forgejo/app.ini
Restart=always
RestartSec=2s
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
LimitNOFILE=524288

[Install]
WantedBy=multi-user.target
EOF

FORGEJO="sudo -u git /usr/bin/forgejo -w /var/lib/forgejo -c /etc/forgejo/app.ini"
$FORGEJO migrate
$FORGEJO admin regenerate keys
$FORGEJO admin regenerate hooks
$FORGEJO admin user list | grep -qw pritunl || \
    $FORGEJO admin user create --admin --username pritunl --email demo@pritunl.com --password "$ADMIN_PASSWORD" --must-change-password=false

systemctl daemon-reload
systemctl enable forgejo
```

## reload

```shell {phase=reload}
set -e

if [[ -f /etc/forgejo/certs/key.pem ]]; then
    OLD_KEY_HASH=$(md5sum /etc/forgejo/certs/key.pem | awk '{print $1}')
else
    OLD_KEY_HASH=""
fi
if [[ -f /etc/forgejo/certs/cert.pem ]]; then
    OLD_CERT_HASH=$(md5sum /etc/forgejo/certs/cert.pem | awk '{print $1}')
else
    OLD_CERT_HASH=""
fi

pci get +/certificate/git-pritunl-com/key > /etc/forgejo/certs/key.pem
chmod 600 /etc/forgejo/certs/key.pem
chown git:git /etc/forgejo/certs/key.pem
pci get +/certificate/git-pritunl-com/certificate > /etc/forgejo/certs/cert.pem
chmod 644 /etc/forgejo/certs/cert.pem
chown git:git /etc/forgejo/certs/cert.pem

NEW_KEY_HASH=$(md5sum /etc/forgejo/certs/key.pem | awk '{print $1}')
NEW_CERT_HASH=$(md5sum /etc/forgejo/certs/cert.pem | awk '{print $1}')

if [[ "$OLD_KEY_HASH" != "$NEW_KEY_HASH" ]] || [[ "$OLD_CERT_HASH" != "$NEW_CERT_HASH" ]]; then
    echo "Certificate updated, restarting forgejo..."
    systemctl try-restart forgejo
fi
```

## replication

```shell
set -e

wget -O lvsync https://raw.githubusercontent.com/pritunl/toolbox/23ab797d5bf5a5e8cd9700f3ec7bc5a394713941/lvsync/lvsync.py
echo "764f899227e618f1fbacf84a51d118c40ce43f536454dc3d8ba8a175d5fa1215  lvsync" | sha256sum -c - && install -m 755 lvsync /usr/bin/lvsync
rm -f lvsync

SSH_DEPLOYMENT_KEY=$(pci get +/secret/forgejo/data.ssh_deployment_key)
mkdir -p /root/.ssh
chmod 700 /root/.ssh
install -m 600 -o root -g root /dev/null /root/.ssh/deployment_key
printf '%s' "$SSH_DEPLOYMENT_KEY" | base64 -d > /root/.ssh/deployment_key
ssh-keygen -y -f /root/.ssh/deployment_key > /root/.ssh/deployment_key.pub
echo "forgejo-peer $(cut -d' ' -f1,2 /etc/ssh/ssh_host_ed25519_key.pub)" > /root/.ssh/deployment_known_hosts

tee /etc/ssh/sshd_config.d/10-deployment.conf << EOF
Match User root
    PermitRootLogin prohibit-password
    AuthorizedKeysFile .ssh/authorized_keys /etc/ssh/deployment_authorized_keys
Match all
EOF
sshd -t
systemctl reload sshd

mkdir -p /etc/systemd/system/postgresql.service.d
tee /etc/systemd/system/postgresql.service.d/lvsync.conf << EOF
[Unit]
Wants=network-online.target
After=network-online.target
RequiresMountsFor=/var/lib/forgejo /var/lib/pgsql

[Service]
ExecCondition=+/usr/bin/pci is-primary
EOF

mkdir -p /etc/systemd/system/forgejo.service.d
tee /etc/systemd/system/forgejo.service.d/lvsync.conf << EOF
[Unit]
Wants=network-online.target
After=network-online.target
RequiresMountsFor=/var/lib/forgejo /var/lib/pgsql

[Service]
ExecCondition=+/usr/bin/pci is-primary
EOF

tee /usr/bin/forgejo-start << 'EOF'
#!/bin/bash
set -e
cd /
systemctl start postgresql
if ! systemctl is-active --quiet forgejo; then
    sudo -u git /usr/bin/forgejo -w /var/lib/forgejo -c /etc/forgejo/app.ini admin regenerate keys
    systemctl start forgejo
fi
EOF
chmod 755 /usr/bin/forgejo-start

tee /usr/bin/forgejo-stop << 'EOF'
#!/bin/bash
systemctl stop forgejo postgresql
EOF
chmod 755 /usr/bin/forgejo-stop

systemctl daemon-reload
systemctl enable postgresql forgejo

lvsync set-source /var/lib/forgejo /var/lib/pgsql
lvsync set-snap-size 8G
lvsync set-hook stop /usr/bin/forgejo-stop
lvsync set-hook start /usr/bin/forgejo-start
lvsync set-timer 5
```

```shell {phase=reload}
set -e

SELF_IPS=$(pci get +/instance/self/private_ips | \
    tr -s '[:space:],' ',' | \
    sed 's/^,//; s/,$//')
DEPLOY_IPS=$(pci get +/unit/forgejo/private_ips | \
    tr -s '[:space:],' ',' | \
    sed 's/^,//; s/,$//')
PEER_IP=$(tr ',' '\n' <<< "$DEPLOY_IPS" | \
    grep -Fvx -f <(tr ',' '\n' <<< "$SELF_IPS") | \
    head -n 1)

for VAL in "$SELF_IPS" "$DEPLOY_IPS"; do
    if [[ ! "$VAL" =~ ^[0-9a-fA-F:.,]+$ ]]; then
        echo "Missing required replication values"
        exit 1
    fi
done

tee /etc/ssh/ssh_config.d/10-deployment.conf << EOF
Host ${DEPLOY_IPS//,/ }
    User root
    IdentityFile /root/.ssh/deployment_key
    IdentitiesOnly yes
    HostKeyAlias forgejo-peer
    UserKnownHostsFile /root/.ssh/deployment_known_hosts
    StrictHostKeyChecking yes
EOF

printf 'from="%s",restrict %s forgejo-deployment\n' \
    "$DEPLOY_IPS" "$(cut -d' ' -f1,2 /root/.ssh/deployment_key.pub)" \
    > /etc/ssh/deployment_authorized_keys
chmod 600 /etc/ssh/deployment_authorized_keys

if [[ -n "$PEER_IP" ]]; then
    lvsync set-remote "root@$PEER_IP"
fi

PRIMARY=$(pci get +/deployment/self/primary) || PRIMARY=""
if [[ "$PRIMARY" == "true" ]]; then
    lvsync set-primary --force
elif [[ "$PRIMARY" == "false" ]]; then
    /usr/bin/forgejo-stop
fi
```