Commit files for public release
All checks were successful
CI / build (push) Successful in 13m53s

This commit is contained in:
Fabian Hauser 2024-10-02 16:52:04 +03:00
commit fef2377502
174 changed files with 7423 additions and 0 deletions

View file

@ -0,0 +1,8 @@
inputs: {
default =
{ config, pkgs, ... }:
{
imports = (inputs.self.lib.loadSubmodulesFrom ./.) ++ [ inputs.private.nixosModules.default ];
};
}

View file

@ -0,0 +1,109 @@
{
config,
lib,
pkgs,
...
}:
with lib;
let
cfg = config.services.qois.luks-ssh;
in
{
options.services.qois.luks-ssh = {
enable = mkEnableOption "luks-ssh service";
interface = mkOption {
type = types.str;
example = "enp0";
description = ''
Interface name.
'';
};
ip = mkOption {
type = types.str;
example = "192.168.0.1";
default = "dhcp";
description = ''
Host IP Address or "dhcp" (default).
'';
};
gateway = mkOption {
type = types.str;
default = null;
example = "192.168.0.1";
description = ''
IP of gateway. May be null if ip is aquired by dhcp.
'';
};
netmask = mkOption {
type = types.str;
default = null;
example = "192.168.0.1";
description = ''
Netmask of internal network. May be null if ip is aquired by dhcp.
'';
};
sshHostKey = mkOption {
type = types.str;
default = "/secrets/initrd_ssh_key_ed25519";
description = ''
Hostkey for ssh connection.
The key is stored in an unencrypted form,
so it is strongly advised against using the normal host key.
You can generate a host key with:
ssh-keygen -t ed25519 -N "" -f /secrets/initrd_ssh_key_ed25519
'';
};
sshPort = mkOption {
type = types.addCheck types.int (n: n > 0 && n < 65536);
default = 2222;
description = ''
SSH Port of the initrd ssh server.
Should be different from default SSH port to prevent known hosts collissions.
'';
};
};
config = mkIf cfg.enable {
boot.initrd.network = {
enable = true;
ssh = {
enable = true;
port = cfg.sshPort;
authorizedKeys =
with lib;
concatLists (
mapAttrsToList (
name: user: if elem "wheel" user.extraGroups then user.openssh.authorizedKeys.keys else [ ]
) config.users.users
);
hostKeys = [ cfg.sshHostKey ];
};
postCommands = ''
echo 'cryptsetup-askpass' >> /root/.profile
'';
};
boot.initrd.network.udhcpc.enable = cfg.ip == "dhcp";
boot.kernelParams =
if cfg.ip == "dhcp" then
[ ]
else
[
"ip=${cfg.ip}::${cfg.gateway}:${cfg.netmask}:${config.networking.hostName}:${cfg.interface}:none"
]; # See boot.initrd.network.enable
boot.initrd.postMountCommands = ''
ip link set ${cfg.interface} down
'';
};
}

View file

@ -0,0 +1,13 @@
{
config,
lib,
pkgs,
options,
...
}:
{
imports = [
./hosts.nix
./network.nix
];
}

View file

@ -0,0 +1,53 @@
{
config,
lib,
pkgs,
options,
...
}:
with lib;
let
cfg = config.qois.meta.hosts;
in
{
options.qois.meta.hosts = mkOption {
type = types.attrsOf (
types.submodule (
{ name, ... }:
{
options = {
hostName = mkOption {
type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$";
default = name;
description = "The host's name. See networking.hostName for more details.";
};
sshKey = mkOption {
type = types.nullOr (types.strMatching "^ssh-ed25519 [a-zA-Z0-9/+]{68}$");
default = null;
example = "ssh-ed25519 AAAAbcdefgh....xyz root@myhost";
description = lib.mdDoc ''
The ssh public key of ed25519 type.
May be fetched with `ssh-keyscan example.com`.
'';
};
};
}
)
);
default = { };
description = "Host configuration properties options";
};
config =
let
hostsWithSshKey = lib.filterAttrs (name: hostCfg: hostCfg.sshKey != null) cfg;
in
{
programs.ssh.knownHosts = lib.mapAttrs (name: hostCfg: {
publicKey = hostCfg.sshKey;
}) hostsWithSshKey;
};
}

View file

@ -0,0 +1,234 @@
{
config,
lib,
pkgs,
options,
...
}:
with lib;
with types;
let
cfg = config.qois.meta.network;
mkStr =
description:
(mkOption {
type = str;
inherit description;
});
mkOptStr =
description:
(mkOption {
type = nullOr str;
default = null;
inherit description;
});
mkNetworkIdOpts =
v:
assert v == 4 || v == 6;
submodule {
options = {
id = mkOption {
type = types.str;
description = ''
IPv${toString v} ID
'';
};
prefixLength = mkOption {
type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
description = ''
Subnet mask of the ip, specified as the number of
bits in the prefix (<literal>${if v == 4 then "24" else "64"}</literal>).
'';
};
gateway = mkOption {
default = null;
type = nullOr str;
description = ''
Upstream Gateway IP
'';
};
nameservers = mkOption {
default = null;
type = nullOr (listOf str);
description = "Nameserver IP";
};
};
};
mkFqdn =
host: domain:
mkOption {
type = str;
default = "${config.qois.meta.hosts.${host}.hostName}.${domain}";
description = ''
The fully qualified domain name (FYDN) of this host inside of this specific
network. Defaults to the host attribute key and net domain.
'';
};
in
{
options.qois.meta.network.physical = mkOption {
description = "Physical network configuration";
type = attrsOf (
submodule (
{ name, ... }:
let
networkName = name;
in
{
options = {
v4 = mkOption { type = (mkNetworkIdOpts 4); };
v6 = mkOption { type = nullOr (mkNetworkIdOpts 6); };
domain = mkStr "Network DNS Domain suffix";
hosts = mkOption {
type = attrsOf (
submodule (
{ name, ... }:
let
host = name;
in
{
options = {
v4 = mkOption { type = submodule { options.ip = mkStr "The V4 host IP address"; }; };
v6 = mkOption {
default = null;
type = nullOr (submodule {
options.ip = mkStr "The V6 host IP address";
});
};
fqdn = mkFqdn host cfg.physical.${networkName}.domain;
};
}
)
);
};
};
}
)
);
default = { };
};
options.qois.meta.network.virtual = mkOption {
description = "Virtual network configuration";
type = types.attrsOf (
types.submodule (
{ name, ... }:
let
networkName = name;
in
{
options = {
v4 = mkOption { type = (mkNetworkIdOpts 4); };
v6 = mkOption {
default = null;
type = nullOr (mkNetworkIdOpts 6);
};
domain = mkStr "Network DNS Domain suffix";
hosts = mkOption {
type = attrsOf (
submodule (
{ name, ... }:
let
host = name;
in
{
options = {
v4 = mkOption { type = submodule { options.ip = mkStr "The V4 host IP address"; }; };
v6 = mkOption {
default = null;
type = nullOr (submodule {
options.ip = mkStr "The V6 host IP address";
});
};
# Taken from https://github.com/NixOS/nixpkgs/blob/nixos-21.11/nixos/modules/services/networking/wireguard.nix:
publicKey = mkOption {
example = "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=";
type = str;
description = "The base64 public key of the peer.";
};
persistentKeepalive = mkOption {
default = null;
type = nullOr int;
example = 25;
description = ''
This is optional and is by default off, because most
users will not need it. It represents, in seconds, between 1 and 65535
inclusive, how often to send an authenticated empty packet to the peer,
for the purpose of keeping a stateful firewall or NAT mapping valid
persistently. For example, if the interface very rarely sends traffic,
but it might at anytime receive traffic from a peer, and it is behind
NAT, the interface might benefit from having a persistent keepalive
interval of 25 seconds; however, most users will not need this.'';
};
# Endpoint Configuration:
endpoint = mkOption {
description = ''
FQDN and port of this vpn-endpoint. This option indicates this host is a VPN
server.
'';
default = null;
type = nullOr (submodule {
options = {
fqdn = mkFqdn host cfg.virtual.${networkName}.domain;
port = mkOption {
type = types.addCheck types.int (n: n > 0 && n < 65536);
description = ''
The port on which the wireguard endpoint receives packages.
'';
};
};
});
};
};
}
)
);
};
};
}
)
);
default = { };
};
config = {
programs.ssh.knownHosts =
let
# hostname -> single network cfg attr -> ["known host's names"]
getHostNamesFromNetwork =
hostname: network:
if network.hosts ? ${hostname} && network.hosts.${hostname} != null then
let
hostCfg = network.hosts.${hostname};
in
[
"${hostname}.${network.domain}"
hostCfg.v4.ip
]
++ (if hostCfg.v6 != null then [ hostCfg.v6.ip ] else [ ])
else
[ ];
# hostname -> attr of network defs -> ["known host's names"]
getHostNamesForNetworks =
hostname: networks: lib.flatten (map (getHostNamesFromNetwork hostname) (lib.attrValues networks));
# hostname -> ["known host's names"]
getHostNames =
hostname:
(getHostNamesForNetworks hostname cfg.virtual) ++ (getHostNamesForNetworks hostname cfg.physical);
hostsWithPublicKey = lib.filterAttrs (
hostName: hostConfig: hostConfig.sshKey != null
) config.qois.meta.hosts;
in
mapAttrs (name: hostCfg: { extraHostNames = getHostNames name; }) hostsWithPublicKey;
};
}

View file

@ -0,0 +1,83 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.nixpkgs-cache;
in
with lib;
{
options.qois.nixpkgs-cache = {
enable = mkEnableOption ''Enable nixpkgs cache server.'';
hostname = mkOption {
type = types.str;
example = "mycache.myhost.org";
description = "Hostname, under which the cache is served";
};
timeout = mkOption {
type = types.str;
default = "90d";
description = "Timespan after which cache entries should be removed.";
};
size = mkOption {
type = types.int;
default = 50;
description = "in GB; maximum size of the cache on disk.";
};
dnsResolvers = mkOption {
type = types.listOf types.str;
example = [ "8.8.8.8" ];
description = ''
List of DNS resolvers to use for upstream cache hostname resolution.
Note: IPv6 is not supported currently.
'';
};
};
config = mkIf cfg.enable {
networking.hosts."127.0.0.1" = [ cfg.hostname ];
services.nginx = {
enable = true;
resolver.ipv6 = false; # TODO(6): Support IPv6
resolver.addresses = cfg.dnsResolvers;
proxyCachePath.nixpkgs-cache = {
enable = true;
keysZoneName = "nixpkgs_cache";
maxSize = "${builtins.toString cfg.size}G";
keysZoneSize = "${builtins.toString (cfg.size * 3)}M"; # Assumes 3MB keys storage per GB
inactive = cfg.timeout;
};
virtualHosts.${cfg.hostname} = {
kTLS = true;
forceSSL = true;
enableACME = true;
locations."/" = {
proxyPass = "https://cache.nixos.org";
recommendedProxySettings = false;
extraConfig = ''
proxy_cache nixpkgs_cache;
proxy_cache_valid ${cfg.timeout};
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_504 http_403 http_404 http_429;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie; # Files are immutable so just keep them
proxy_cache_lock on;
proxy_ssl_server_name on;
proxy_ssl_session_reuse off;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
proxy_set_header Host cache.nixos.org;
'';
};
};
};
};
}

View file

@ -0,0 +1,47 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.outgoing-server-mail;
in
with lib;
{
options.qois.outgoing-server-mail = {
enable = mkEnableOption ''Enable outgoing emails for server.'';
};
config = mkIf cfg.enable {
sops.secrets."msmtp/password" = {
owner = "root";
group = config.users.groups.postdrop.name;
mode = "0440";
};
users.groups.postdrop = { };
programs.msmtp = {
enable = true;
defaults = {
aliases = pkgs.writeText "aliases" ''
root: sysadmin@qo.is
'';
port = 465;
tls = true;
tls_starttls = "off";
};
accounts.default = {
auth = true;
host = "mail.cyon.ch";
user = "system@qo.is";
from = "no-reply@qo.is";
passwordeval = "${pkgs.busybox}/bin/cat ${config.sops.secrets."msmtp/password".path}";
};
};
};
}

View file

@ -0,0 +1,22 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.postgresql;
in
with lib;
{
options.qois.postgresql = {
enable = mkEnableOption ''Enable postgresql services with defaults'';
};
config = mkIf cfg.enable {
services.postgresql.enable = true;
services.postgresqlBackup.enable = true;
qois.backup-client.includePaths = [ config.services.postgresqlBackup.location ];
};
}

View file

@ -0,0 +1,6 @@
# Backup Module
This module creates a host-based backup job `system-${target-hostname}` (currently with borg).
The module has sensible defaults for a whole system, note however that individual services/paths must be included or excluded added manually.
Target hosts should use the [Backup Server Module](../backup-server).

View file

@ -0,0 +1,103 @@
{
config,
lib,
options,
pkgs,
self,
...
}:
let
cfg = config.qois.backup-client;
defaultIncludePaths = [
"/etc"
"/home"
"/root"
];
defaultExcludePaths = [
"/root/.cache"
"/root/.config/borg"
];
defaultSopsPasswordFile = "system/backup/password";
in
with lib;
{
options.qois.backup-client =
let
pathsType = with types; listOf str;
in
{
enable = mkEnableOption "Enable this host to execute backups.";
targets = mkOption {
type = with types; listOf (enum (attrNames config.qois.meta.hosts));
default = [
"cyprianspitz"
];
description = "Target hosts to make backups to. Must be configured to receive backups in the backplane network.";
};
includePaths = mkOption {
type = pathsType;
default = [ ];
description = "Paths that are included in backup. The backup module always includes: ${concatStringsSep ", " defaultIncludePaths}";
};
excludePaths = mkOption {
type = pathsType;
default = [ ];
description = "Paths that are excluded in backup. The backup module always excludes: ${concatStringsSep ", " defaultExcludePaths}";
};
passwordFile = mkOption {
type = with types; nullOr str;
default = null;
example = "config.sops.secrets.${defaultSopsPasswordFile}.path";
description = "Path to password file. Taken from sops host secret ${defaultSopsPasswordFile} by default, must be randomly generated per host.";
};
networkName = mkOption {
type = types.enum (attrNames config.qois.meta.network.virtual);
default = "backplane";
description = "Name of virtual network through which the backups should be done";
};
};
config.services.borgbackup.jobs = mkIf cfg.enable (
builtins.listToAttrs (
map (backupHost: {
name = "system-${backupHost}";
value = {
repo = "borg@${config.qois.meta.network.virtual.${cfg.networkName}.hosts.${backupHost}.v4.ip}:.";
environment.BORG_RSH = "ssh -i /etc/ssh/ssh_host_ed25519_key";
paths = defaultIncludePaths ++ cfg.includePaths;
exclude = defaultExcludePaths ++ cfg.excludePaths;
doInit = true;
encryption = {
mode = "repokey";
passCommand =
let
passFile =
if cfg.passwordFile != null then
cfg.passwordFile
else
config.sops.secrets.${defaultSopsPasswordFile}.path;
in
"cat ${passFile}";
};
startAt = "07:06";
persistentTimer = true;
};
}) cfg.targets
)
);
config.sops.secrets = mkIf (cfg.enable && cfg.passwordFile == null) {
${defaultSopsPasswordFile} = {
restartUnits = map (target: "borgbackup-job-system-${target}.service") cfg.targets;
};
};
}

View file

@ -0,0 +1,3 @@
# Backup Server Module
This backup module creates borg repositories for all the hosts configured with hosts.

View file

@ -0,0 +1,53 @@
{
config,
lib,
options,
pkgs,
self,
...
}:
let
cfg = config.qois.backup-server or { };
in
with lib;
{
options.qois.backup-server = {
enable = mkEnableOption "Enable backup hosting";
backupStorageRoot = mkOption {
type = with types; nullOr str;
default = "/mnt/backup";
example = "/mnt/nas/backup";
description = "Path where backups are stored if this host is used as a backup target.";
};
hosts = options.qois.meta.hosts // {
default = config.qois.meta.hosts;
};
};
config = lib.mkIf cfg.enable {
services.borgbackup.repos =
let
hasSshKey = hostName: cfg.hosts.${hostName}.sshKey != null;
mkRepo =
hostName:
(
let
name = "system-${hostName}";
in
{
inherit name;
value = {
path = "${cfg.backupStorageRoot}/${name}";
authorizedKeys = [ cfg.hosts.${hostName}.sshKey ];
};
}
);
hostsWithSshKeys = lib.filter hasSshKey (lib.attrNames cfg.hosts);
in
lib.listToAttrs (map mkRepo hostsWithSshKeys);
};
}

View file

@ -0,0 +1,10 @@
{
config,
pkgs,
inputs,
...
}:
{
imports = inputs.self.lib.loadSubmodulesFrom ./.;
}

View file

@ -0,0 +1,8 @@
# Git CI Runner
Runner for the [Forgejo git instance](../git/README.md).
Currently registers a default runner with ubuntu OS.
## Create Secret Token
To create a new token for registration, follow the steps outlined in the [Forgejo documentation](https://forgejo.org/docs/latest/user/actions/#forgejo-runner).

View file

@ -0,0 +1,52 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.git-ci-runner;
defaultInstanceName = "default";
in
with lib;
{
options.qois.git-ci-runner = {
enable = mkEnableOption "Enable qois git ci-runner service";
domain = mkOption {
type = types.str;
default = "git.qo.is";
description = "Domain, under which the service is served.";
};
};
config = mkIf cfg.enable {
sops.secrets."forgejo/runner-token/${defaultInstanceName}".restartUnits = [
"gitea-runner-${defaultInstanceName}.service"
];
services.gitea-actions-runner = {
package = pkgs.forgejo-runner;
instances.${defaultInstanceName} = {
enable = true;
name = "${config.networking.hostName}-${defaultInstanceName}";
url = "https://${cfg.domain}";
tokenFile = config.sops.secrets."forgejo/runner-token/${defaultInstanceName}".path;
labels = [
"ubuntu-latest:docker://gitea/runner-images:ubuntu-latest"
"ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04"
"docker:docker://code.forgejo.org/oci/alpine:3.20"
];
settings = {
log.level = "warn";
runner = {
capacity = 30;
};
cache.enable = true; # TODO: This should probably be a central cache server?
};
};
};
};
}

View file

@ -0,0 +1,44 @@
# Git
## Configuration for Git Clients
### Authentication
To use oauth authentication, your git configuration should have something like:
```ini
[credential]
helper = "libsecret"
helper = "cache --timeout 21600"
helper = "/usr/bin/git-credential-oauth" # See https://github.com/hickford/git-credential-oauth
```
On NixOS with HomeManager, this can be achieved by following home-manager config:
```nix
programs.git.extraConfig.credential.helper = [ "libsecret" "cache --timeout 21600" ];
programs.git-credential-oauth.enable = true;
```
## Administration
### Create Accounts
Accounts can be created by an admin in the [administrator area](https://git.qo.is/admin).
- use their full `firstname.lastname@qo.is` email so users may be connected to a LDAP database in the future
- Username should be in form of "firstnamelastname" (Forgejo doesn't support usernames with dots)
To create a new admin user from the commandline, run:
```bash
sudo -u forgejo 'nix run nixpkgs#forgejo -- admin user create --config ~custom/conf/app.ini --admin --email "xy.z@qo.is" --username firstnamelastname --password Chur7000'
```
## Backup / Restore
1. `systemctl stop forgejo.service`
2. Import Postgresql Database Backup
3. Restore `/var/lib/forgejo`
4. `systemctl start forgejo.service`

View file

@ -0,0 +1,81 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.git;
in
with lib;
{
options.qois.git = {
enable = mkEnableOption "Enable qois git service";
domain = mkOption {
type = types.str;
default = "git.qo.is";
description = "Domain, under which the service is served.";
};
};
config = mkIf cfg.enable {
qois.postgresql.enable = true;
services.forgejo = {
enable = true;
database.type = "postgres";
lfs.enable = true;
settings = {
DEFAULT.APP_NAME = cfg.domain;
server = {
DOMAIN = cfg.domain;
ROOT_URL = "https://${cfg.domain}";
PROTOCOL = "http+unix";
DISABLE_SSH = true;
};
"ssh.minimum_key_sizes".RSA = 2047;
session.COOKIE_SECURE = true;
service.DISABLE_REGISTRATION = true;
mailer = {
ENABLED = true;
PROTOCOL = "sendmail";
FROM = "git@qo.is";
SENDMAIL_PATH = "${pkgs.msmtp}/bin/sendmail";
# Note: The sendmail passwordeval has to use the coreutil cat (that is in the services path)
# instead of the busybox one due to filtered syscalls.
SENDMAIL_ARGS = "--passwordeval 'cat ${config.sops.secrets."msmtp/password".path}'";
};
log.LEVEL = "Warn";
};
};
qois.backup-client.includePaths = [ config.services.forgejo.stateDir ];
users.users.forgejo.extraGroups = [ "postdrop" ];
systemd.services.forgejo.serviceConfig.ReadOnlyPaths = [
config.sops.secrets."msmtp/password".path
];
networking.hosts."127.0.0.1" = [ cfg.domain ];
services.nginx = {
enable = true;
virtualHosts.${cfg.domain} = {
kTLS = true;
forceSSL = true;
enableACME = true;
extraConfig = ''
client_max_body_size 512M;
'';
locations."/" = {
proxyPass = "http://unix:${config.services.forgejo.settings.server.HTTP_ADDR}";
proxyWebsockets = true;
};
};
};
};
}

View file

@ -0,0 +1,169 @@
{
config,
pkgs,
lib,
...
}:
with lib;
let
# We assume that all static pages are hosted on lindberg-webapps
staticPages = pipe config.qois.static-page.pages [
(mapAttrsToList (name: { domain, domainAliases, ... }: [ domain ] ++ domainAliases))
flatten
(map (name: {
inherit name;
value = "lindberg-webapps";
}))
listToAttrs
];
defaultDomains = staticPages // {
"cloud.qo.is" = "lindberg-nextcloud";
"build.qo.is" = "lindberg-build";
"gitlab-runner.qo.is" = "lindberg-build";
"nixpkgs-cache.qo.is" = "lindberg-build";
"attic.qo.is" = "lindberg-build";
"vault.qo.is" = "lindberg-webapps";
"git.qo.is" = "lindberg-webapps";
"kokus.raphael.li" = "lindberg-rzimmermann";
"auth.raphael.li" = "lindberg-rzimmermann";
"toolia.raphael.li" = "lindberg-rzimmermann";
"ha.raphael.li" = "lindberg-rzimmermann";
"www.raphael.li" = "lindberg-rzimmermann";
"vpn.qo.is" = "cyprianspitz-headscale";
};
getBackplaneIp = hostname: config.qois.meta.network.virtual.backplane.hosts.${hostname}.v4.ip;
defaultHostmap =
lib.pipe
[
"lindberg-nextcloud"
"lindberg-build"
"lindberg-webapps"
]
[
(map (name: {
inherit name;
value = getBackplaneIp name;
}))
lib.listToAttrs
];
defaultExtraConfig =
let
headscalePort = toString 46084;
rzimmermannIp = "10.247.0.113";
in
''
# lindberg-rzimmermann (uses send-proxy-v2)
backend lindberg-rzimmermann-https
mode tcp
server s1 ${rzimmermannIp}:443 send-proxy-v2
backend lindberg-rzimmermann-http
mode http
server s1 ${rzimmermannIp}:80
# cyprianspitz headscale
backend cyprianspitz-headscale-http
mode http
server s1 ${getBackplaneIp "cyprianspitz"}:${headscalePort}
backend cyprianspitz-headscale-https
mode tcp
server s1 ${getBackplaneIp "cyprianspitz"}:${headscalePort}
'';
cfg = config.qois.loadbalancer;
in
{
options.qois.loadbalancer = with lib; {
enable = mkEnableOption "Enable services http+s loadbalancing";
domains = mkOption {
description = "Domain to hostname mappings";
type = with lib.types; attrsOf str;
default = defaultDomains;
};
hostmap = mkOption {
description = "Hostname to IP mappings for TLS-TCP and http forwarding";
type = with lib.types; attrsOf str;
default = defaultHostmap;
};
extraConfig = mkOption {
description = "Additional haproxy mapping configs. Amended to services.haproxy.config. Make sure indentations are correct.";
type = types.nullOr types.lines;
default = defaultExtraConfig;
};
};
config =
with lib;
mkIf cfg.enable {
networking.firewall.allowedTCPPorts = [
80
443
];
services.haproxy =
let
domainMappingFile = pipe cfg.domains [
(mapAttrsToList (host: backend: "${host} ${backend}"))
concatLines
(pkgs.writeText "haproxy_backend_map")
];
genHttpBackend = hostName: ip: ''
# Mapping for ${hostName}
backend ${hostName}-https
mode tcp
server s1 ${ip}:443
backend ${hostName}-http
mode http
server s1 ${ip}:80
'';
httpBackends = pipe cfg.hostmap [
(mapAttrsToList genHttpBackend)
concatLines
];
in
{
enable = true;
config = ''
defaults
mode http
retries 3
maxconn 2000
timeout connect 5000
timeout client 50000
timeout server 50000
frontend http
mode http
bind *:80
use_backend %[req.hdr(host),lower,map_dom(${domainMappingFile})]-http
frontend https
bind *:443
mode tcp
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
use_backend %[req.ssl_sni,lower,map_dom(${domainMappingFile})]-https
## Generated Backends:
${httpBackends}
## extraConfig
${cfg.extraConfig}
'';
};
};
}

View file

@ -0,0 +1,6 @@
# Static Pages
This module enables static nginx sites, with data served from "/var/lib/nginx/$domain/root".
To deploy the site, a user `nginx-$domain` is added, of which a `root` profile in the home folder can be deployed, e.g. with deploy-rs.

View file

@ -0,0 +1,26 @@
{
config,
pkgs,
lib,
...
}:
{
qois.static-page.pages = {
"fabianhauser.ch" = {
domainAliases = [
"www.fabianhauser.ch"
"fabianhauser.nl"
"www.fabianhauser.nl"
"www.fh2.ch"
"fh2.ch"
];
authorizedKeys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFsSCoClNpgW7x6YngP/CEFbyR8GEJ3V8NdUFvZ/6lj6 ci@git.qo.is"
];
};
"docs-ops.qo.is".authorizedKeys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBS65v7n5ozOUjYGuO/dgLC9C5MUGL5kTnQnvWAYP5B3 ci@git.qo.is"
];
};
}

View file

@ -0,0 +1,145 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.static-page;
in
with lib;
{
imports = [ ./default-pages.nix ];
options.qois.static-page =
let
pageType =
{ name, ... }:
{
options = {
domain = mkOption {
type = types.str;
default = name;
description = ''
Primary domain, under which the site is served.
Only ASCII Domains are supported at this time.
Note that changing this changes the root folder of the vhost in /var/lib/nginx-$domain/root and the ssh user to "nginx-$domain".
'';
};
domainAliases = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain aliases which are forwarded to the primary domain";
};
authorizedKeys = mkOption {
type = types.listOf types.str;
default = [ ];
description = "SSH keys for deployment";
};
};
}
;
in
{
enable = mkEnableOption "Enable static-page hosting";
pages = mkOption {
type = types.attrsOf (types.submodule (pageType));
};
};
config = mkIf cfg.enable (
let
pageConfigs = concatMapAttrs (
name: page:
let
home = "/var/lib/nginx-${page.domain}";
in
{
"${page.domain}" = page // {
inherit home;
user = "${config.services.nginx.user}-${page.domain}";
root = "${home}/root";
};
}
) cfg.pages;
in
{
networking.hosts."127.0.0.1" = pipe pageConfigs [
attrValues
(map (page: [ page.domain ] ++ page.domainAliases))
flatten
];
users = {
groups = concatMapAttrs (
name:
{ user, ... }:
{
"${user}" = { };
}
) pageConfigs;
users =
{
${config.services.nginx.user}.extraGroups = mapAttrsToList (domain: getAttr "user") pageConfigs;
}
// (concatMapAttrs (
name:
{
user,
home,
authorizedKeys,
...
}:
{
${user} = {
inherit home;
isSystemUser = true;
useDefaultShell = true;
homeMode = "750";
createHome = true;
group = user;
openssh.authorizedKeys.keys = authorizedKeys;
};
}
) pageConfigs);
};
services.nginx = {
enable = true;
virtualHosts =
let
defaultVhostConfig = {
enableACME = true;
forceSSL = true;
kTLS = true;
};
mkVhost =
{ root, ... }:
defaultVhostConfig
// {
inherit root;
};
mkAliasVhost =
{ domainAliases, domain, ... }:
if (domainAliases == [ ]) then
{ }
else
({
"${head domainAliases}" = defaultVhostConfig // {
serverAliases = tail domainAliases;
globalRedirect = domain;
};
});
aliasVhosts = concatMapAttrs (name: mkAliasVhost) pageConfigs;
in
aliasVhosts // (mapAttrs (name: mkVhost) pageConfigs);
};
}
);
}

View file

@ -0,0 +1,136 @@
{
config,
pkgs,
lib,
...
}:
with lib;
let
cfg = config.qois.vpn-server;
cfgLoadbalancer = config.qois.loadbalancer;
defaultDnsRecords = mapAttrs (
name: value: mkIf (cfgLoadbalancer.hostmap ? ${value}) cfgLoadbalancer.hostmap.${value}
) cfgLoadbalancer.domains;
in
{
options.qois.vpn-server = {
enable = mkEnableOption "Enable vpn server services";
dnsRecords = mkOption {
description = "DNS records to add to Hosts";
type = with types; attrsOf str;
default = defaultDnsRecords;
};
wheelUsers = mkOption {
description = "Usernames that can change configurations";
type = with types; listOf str;
default = [ ];
};
};
config = mkIf cfg.enable ({
environment.systemPackages = [ pkgs.headscale ];
qois.backup-client.includePaths =
with config.services.headscale.settings;
(
[
db_path
private_key_path
noise.private_key_path
]
++ derp.paths
);
networking.firewall.checkReversePath = "loose";
networking.firewall.allowedUDPPorts = [
41641
];
services.headscale =
let
vnet = config.qois.meta.network.virtual;
vpnNet = vnet.vpn;
vpnNetPrefix = "${vpnNet.v4.id}/${builtins.toString vpnNet.v4.prefixLength}";
backplaneNetPrefix = "${vnet.backplane.v4.id}/${builtins.toString vnet.backplane.v4.prefixLength}";
in
{
enable = true;
address = vnet.backplane.hosts.cyprianspitz.v4.ip;
port = 46084;
settings = {
server_url = "https://${vpnNet.domain}:443";
tls_letsencrypt_challenge_type = "TLS-ALPN-01";
tls_letsencrypt_hostname = vpnNet.domain;
dns_config = {
nameservers = [ vnet.backplane.hosts.calanda.v4.ip ];
domains = [
vpnNet.domain
vnet.backplane.domain
];
magic_dns = true;
base_domain = vpnNet.domain;
extra_records = pipe cfg.dnsRecords [
attrsToList
(map (val: val // { type = "A"; }))
];
};
ip_prefixes = [ vpnNetPrefix ];
acl_policy_path = pkgs.writeTextFile {
name = "acls";
text = builtins.toJSON {
hosts = {
"clients" = vpnNetPrefix;
};
groups = {
"group:wheel" = cfg.wheelUsers;
};
tagOwners = {
"tag:srv" = [ "srv" ]; # srv tag ist owned by srv user
};
autoApprovers = {
exitNode = [
"tag:srv"
"group:wheel"
];
routes = {
${backplaneNetPrefix} = [ "tag:srv" ];
};
};
acls = [
# Allow all communication from and to srv tagged hosts
{
action = "accept";
src = [
"tag:srv"
"srv"
];
dst = [ "*:*" ];
}
{
action = "accept";
src = [ "*" ];
dst = [
"tag:srv:*"
"srv:*"
];
}
# Allow access to all connected hosts for wheels
{
action = "accept";
src = [ "group:wheel" ];
dst = [ "*:*" ];
}
];
};
};
};
};
});
}

View file

@ -0,0 +1,670 @@
{
config,
lib,
pkgs,
...
}:
with lib;
let
routerCfg = config.services.qois.router;
cfg = config.services.qois.router.dhcp;
in
{
options.services.qois.router.dhcp = {
enable = mkEnableOption "router dhcp service";
localDomain = mkOption {
type = types.str;
example = "example.com";
description = ''
DNS-Domain of local network
'';
};
dhcpRange = mkOption {
type = types.str;
example = "192.168.0.2,192.168.0.128";
description = ''
Range of IP-adresses to distribute via dhcp in dnsmasq format.
'';
};
localDnsPort = mkOption {
type = types.addCheck types.int (n: n >= 0 && n <= 65535);
example = "router";
default = 5553;
description = ''
Port to expose dns to. Note that, if you use the <literal>recursiveDns</literal> role,
the recursive DNS server should use the default DNS port (<literal>53</literal>).
'';
};
};
config = mkIf cfg.enable {
services.dnsmasq.enable = true;
services.dnsmasq.extraConfig = ''
# Listen on this specific port instead of the standard DNS port
# (53). Setting this to zero completely disables DNS function,
# leaving only DHCP and/or TFTP.
port=${toString cfg.localDnsPort}
# The following two options make you a better netizen, since they
# tell dnsmasq to filter out queries which the public DNS cannot
# answer, and which load the servers (especially the root servers)
# unnecessarily. If you have a dial-on-demand link they also stop
# these requests from bringing up the link unnecessarily.
# Never forward plain names (without a dot or domain part)
domain-needed
# Never forward addresses in the non-routed address spaces.
bogus-priv
# Uncomment this to filter useless windows-originated DNS requests
# which can trigger dial-on-demand links needlessly.
# Note that (amongst other things) this blocks all SRV requests,
# so don't use it if you use eg Kerberos, SIP, XMMP or Google-talk.
# This option only affects forwarding, SRV records originating for
# dnsmasq (via srv-host= lines) are not suppressed by it.
#filterwin2k
# Change this line if you want dns to get its upstream servers from
# somewhere other that /etc/resolv.conf
#resolv-file=
# By default, dnsmasq will send queries to any of the upstream
# servers it knows about and tries to favour servers to are known
# to be up. Uncommenting this forces dnsmasq to try each query
# with each server strictly in the order they appear in
# /etc/resolv.conf
#strict-order
# If you don't want dnsmasq to read /etc/resolv.conf or any other
# file, getting its servers from this file instead (see below), then
# uncomment this.
#no-resolv
# If you don't want dnsmasq to poll /etc/resolv.conf or other resolv
# files for changes and re-read them then uncomment this.
no-poll
# Add other name servers here, with domain specs if they are for
# non-public domains.
#server=/localnet/192.168.0.1
# Example of routing PTR queries to nameservers: this will send all
# address->name queries for 192.168.3/24 to nameserver 10.1.2.3
#server=/3.168.192.in-addr.arpa/10.1.2.3
# Add local-only domains here, queries in these domains are answered
# from /etc/hosts or DHCP only.
local=/${config.networking.hostName}/
# Add domains which you want to force to an IP address here.
# The example below send any host in double-click.net to a local
# web-server.
#address=/double-click.net/127.0.0.1
address=/${config.networking.hostName}.${cfg.localDomain}/${routerCfg.internalRouterIP}
# --address (and --server) work with IPv6 addresses too.
#address=/www.thekelleys.org.uk/fe80::20d:60ff:fe36:f83
# You can control how dnsmasq talks to a server: this forces
# queries to 10.1.2.3 to be routed via eth1
# server=10.1.2.3@eth1
# and this sets the source (ie local) address used to talk to
# 10.1.2.3 to 192.168.1.1 port 55 (there must be a interface with that
# IP on the machine, obviously).
# server=10.1.2.3@192.168.1.1#55
# If you want dnsmasq to change uid and gid to something other
# than the default, edit the following lines.
#user=
#group=
# If you want dnsmasq to listen for DHCP and DNS requests only on
# specified interfaces (and the loopback) give the name of the
# interface (eg eth0) here.
# Repeat the line for more than one interface.
interface=${routerCfg.internalBridgeInterfaceName}
interface=lo
# Or you can specify which interface _not_ to listen on
#except-interface=
# Or which to listen on by address (remember to include 127.0.0.1 if
# you use this.)
#listen-address=
# If you want dnsmasq to provide only DNS service on an interface,
# configure it as shown above, and then use the following line to
# disable DHCP and TFTP on it.
no-dhcp-interface=lo
# On systems which support it, dnsmasq binds the wildcard address,
# even when it is listening on only some interfaces. It then discards
# requests that it shouldn't reply to. This has the advantage of
# working even when interfaces come and go and change address. If you
# want dnsmasq to really bind only the interfaces it is listening on,
# uncomment this option. About the only time you may need this is when
# running another nameserver on the same machine.
bind-interfaces
# If you don't want dnsmasq to read /etc/hosts, uncomment the
# following line.
no-hosts
# or if you want it to read another file, as well as /etc/hosts, use
# this.
#addn-hosts=/etc/banner_add_hosts
# Set this (and domain: see below) if you want to have a domain
# automatically added to simple names in a hosts-file.
expand-hosts
# Set the domain for dnsmasq. this is optional, but if it is set, it
# does the following things.
# 1) Allows DHCP hosts to have fully qualified domain names, as long
# as the domain part matches this setting.
# 2) Sets the "domain" DHCP option thereby potentially setting the
# domain of all systems configured by DHCP
# 3) Provides the domain part for "expand-hosts"
domain=${cfg.localDomain}
# Set a different domain for a particular subnet
#domain=wireless.thekelleys.org.uk,192.168.2.0/24
# Same idea, but range rather then subnet
#domain=reserved.thekelleys.org.uk,192.68.3.100,192.168.3.200
# Uncomment this to enable the integrated DHCP server, you need
# to supply the range of addresses available for lease and optionally
# a lease time. If you have more than one network, you will need to
# repeat this for each network on which you want to supply DHCP
# service.
dhcp-range=${cfg.dhcpRange},48h
# This is an example of a DHCP range where the netmask is given. This
# is needed for networks we reach the dnsmasq DHCP server via a relay
# agent. If you don't know what a DHCP relay agent is, you probably
# don't need to worry about this.
#dhcp-range=192.168.0.50,192.168.0.150,255.255.255.0,12h
# This is an example of a DHCP range which sets a tag, so that
# some DHCP options may be set only for this network.
#dhcp-range=set:red,192.168.0.50,192.168.0.150
# Use this DHCP range only when the tag "green" is set.
#dhcp-range=tag:green,192.168.0.50,192.168.0.150,12h
# Specify a subnet which can't be used for dynamic address allocation,
# is available for hosts with matching --dhcp-host lines. Note that
# dhcp-host declarations will be ignored unless there is a dhcp-range
# of some type for the subnet in question.
# In this case the netmask is implied (it comes from the network
# configuration on the machine running dnsmasq) it is possible to give
# an explicit netmask instead.
#dhcp-range=192.168.0.0,static
# Enable DHCPv6. Note that the prefix-length does not need to be specified
# and defaults to 64 if missing/
#dhcp-range=1234::2, 1234::500, 64, 12h
# Do Router Advertisements, BUT NOT DHCP for this subnet.
#dhcp-range=1234::, ra-only
# Do Router Advertisements, BUT NOT DHCP for this subnet, also try and
# add names to the DNS for the IPv6 address of SLAAC-configured dual-stack
# hosts. Use the DHCPv4 lease to derive the name, network segment and
# MAC address and assume that the host will also have an
# IPv6 address calculated using the SLAAC alogrithm.
#dhcp-range=1234::, ra-names
# Do Router Advertisements, BUT NOT DHCP for this subnet.
# Set the lifetime to 46 hours. (Note: minimum lifetime is 2 hours.)
#dhcp-range=1234::, ra-only, 48h
# Do DHCP and Router Advertisements for this subnet. Set the A bit in the RA
# so that clients can use SLAAC addresses as well as DHCP ones.
#dhcp-range=1234::2, 1234::500, slaac
# Do Router Advertisements and stateless DHCP for this subnet. Clients will
# not get addresses from DHCP, but they will get other configuration information.
# They will use SLAAC for addresses.
#dhcp-range=1234::, ra-stateless
# Do stateless DHCP, SLAAC, and generate DNS names for SLAAC addresses
# from DHCPv4 leases.
#dhcp-range=1234::, ra-stateless, ra-names
# Do router advertisements for all subnets where we're doing DHCPv6
# Unless overriden by ra-stateless, ra-names, et al, the router
# advertisements will have the M and O bits set, so that the clients
# get addresses and configuration from DHCPv6, and the A bit reset, so the
# clients don't use SLAAC addresses.
#enable-ra
# Supply parameters for specified hosts using DHCP. There are lots
# of valid alternatives, so we will give examples of each. Note that
# IP addresses DO NOT have to be in the range given above, they just
# need to be on the same network. The order of the parameters in these
# do not matter, it's permissible to give name, address and MAC in any
# order.
# Always allocate the host with Ethernet address 11:22:33:44:55:66
# The IP address 192.168.0.60
#dhcp-host=11:22:33:44:55:66,192.168.0.60
# Always set the name of the host with hardware address
# 11:22:33:44:55:66 to be "fred"
#dhcp-host=11:22:33:44:55:66,fred
# Always give the host with Ethernet address 11:22:33:44:55:66
# the name fred and IP address 192.168.0.60 and lease time 45 minutes
#dhcp-host=11:22:33:44:55:66,fred,192.168.0.60,45m
# Give a host with Ethernet address 11:22:33:44:55:66 or
# 12:34:56:78:90:12 the IP address 192.168.0.60. Dnsmasq will assume
# that these two Ethernet interfaces will never be in use at the same
# time, and give the IP address to the second, even if it is already
# in use by the first. Useful for laptops with wired and wireless
# addresses.
#dhcp-host=11:22:33:44:55:66,12:34:56:78:90:12,192.168.0.60
# Give the machine which says its name is "bert" IP address
# 192.168.0.70 and an infinite lease
#dhcp-host=bert,192.168.0.70,infinite
# Always give the host with client identifier 01:02:02:04
# the IP address 192.168.0.60
#dhcp-host=id:01:02:02:04,192.168.0.60
# Always give the host with client identifier "marjorie"
# the IP address 192.168.0.60
#dhcp-host=id:marjorie,192.168.0.60
# Enable the address given for "judge" in /etc/hosts
# to be given to a machine presenting the name "judge" when
# it asks for a DHCP lease.
#dhcp-host=judge
# Never offer DHCP service to a machine whose Ethernet
# address is 11:22:33:44:55:66
#dhcp-host=11:22:33:44:55:66,ignore
# Ignore any client-id presented by the machine with Ethernet
# address 11:22:33:44:55:66. This is useful to prevent a machine
# being treated differently when running under different OS's or
# between PXE boot and OS boot.
#dhcp-host=11:22:33:44:55:66,id:*
# Send extra options which are tagged as "red" to
# the machine with Ethernet address 11:22:33:44:55:66
#dhcp-host=11:22:33:44:55:66,set:red
# Send extra options which are tagged as "red" to
# any machine with Ethernet address starting 11:22:33:
#dhcp-host=11:22:33:*:*:*,set:red
# Give a fixed IPv6 address and name to client with
# DUID 00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2
# Note the MAC addresses CANNOT be used to identify DHCPv6 clients.
# Note also the they [] around the IPv6 address are obilgatory.
#dhcp-host=id:00:01:00:01:16:d2:83:fc:92:d4:19:e2:d8:b2, fred, [1234::5]
# Ignore any clients which are not specified in dhcp-host lines
# or /etc/ethers. Equivalent to ISC "deny unknown-clients".
# This relies on the special "known" tag which is set when
# a host is matched.
#dhcp-ignore=tag:!known
# Send extra options which are tagged as "red" to any machine whose
# DHCP vendorclass string includes the substring "Linux"
#dhcp-vendorclass=set:red,Linux
# Send extra options which are tagged as "red" to any machine one
# of whose DHCP userclass strings includes the substring "accounts"
#dhcp-userclass=set:red,accounts
# Send extra options which are tagged as "red" to any machine whose
# MAC address matches the pattern.
#dhcp-mac=set:red,00:60:8C:*:*:*
# If this line is uncommented, dnsmasq will read /etc/ethers and act
# on the ethernet-address/IP pairs found there just as if they had
# been given as --dhcp-host options. Useful if you keep
# MAC-address/host mappings there for other purposes.
#read-ethers
# Send options to hosts which ask for a DHCP lease.
# See RFC 2132 for details of available options.
# Common options can be given to dnsmasq by name:
# run "dnsmasq --help dhcp" to get a list.
# Note that all the common settings, such as netmask and
# broadcast address, DNS server and default route, are given
# sane defaults by dnsmasq. You very likely will not need
# any dhcp-options. If you use Windows clients and Samba, there
# are some options which are recommended, they are detailed at the
# end of this section.
# Override the default route supplied by dnsmasq, which assumes the
# router is the same machine as the one running dnsmasq.
#dhcp-option=3,1.2.3.4
dhcp-option=6,${routerCfg.internalRouterIP}
# Do the same thing, but using the option name
#dhcp-option=option:router,1.2.3.4
# Override the default route supplied by dnsmasq and send no default
# route at all. Note that this only works for the options sent by
# default (1, 3, 6, 12, 28) the same line will send a zero-length option
# for all other option numbers.
#dhcp-option=3
# Set the NTP time server addresses to 192.168.0.4 and 10.10.0.5
#dhcp-option=option:ntp-server,192.168.0.4,10.10.0.5
# Send DHCPv6 option. Note [] around IPv6 addresses.
#dhcp-option=option6:dns-server,[1234::77],[1234::88]
# Send DHCPv6 option for namservers as the machine running
# dnsmasq and another.
#dhcp-option=option6:dns-server,[::],[1234::88]
# Set the NTP time server address to be the same machine as
# is running dnsmasq
#dhcp-option=42,0.0.0.0
# Set the NIS domain name to "welly"
#dhcp-option=40,welly
# Set the default time-to-live to 50
#dhcp-option=23,50
# Set the "all subnets are local" flag
#dhcp-option=27,1
# Send the etherboot magic flag and then etherboot options (a string).
#dhcp-option=128,e4:45:74:68:00:00
#dhcp-option=129,NIC=eepro100
# Specify an option which will only be sent to the "red" network
# (see dhcp-range for the declaration of the "red" network)
# Note that the tag: part must precede the option: part.
#dhcp-option = tag:red, option:ntp-server, 192.168.1.1
# The following DHCP options set up dnsmasq in the same way as is specified
# for the ISC dhcpcd in
# http://www.samba.org/samba/ftp/docs/textdocs/DHCP-Server-Configuration.txt
# adapted for a typical dnsmasq installation where the host running
# dnsmasq is also the host running samba.
# you may want to uncomment some or all of them if you use
# Windows clients and Samba.
#dhcp-option=19,0 # option ip-forwarding off
#dhcp-option=44,0.0.0.0 # set netbios-over-TCP/IP nameserver(s) aka WINS server(s)
#dhcp-option=45,0.0.0.0 # netbios datagram distribution server
#dhcp-option=46,8 # netbios node type
# Send an empty WPAD option. This may be REQUIRED to get windows 7 to behave.
#dhcp-option=252,"\n"
# Send RFC-3397 DNS domain search DHCP option. WARNING: Your DHCP client
# probably doesn't support this......
dhcp-option=option:domain-search,${cfg.localDomain}
# Send RFC-3442 classless static routes (note the netmask encoding)
#dhcp-option=121,192.168.1.0/24,1.2.3.4,10.0.0.0/8,5.6.7.8
# Send vendor-class specific options encapsulated in DHCP option 43.
# The meaning of the options is defined by the vendor-class so
# options are sent only when the client supplied vendor class
# matches the class given here. (A substring match is OK, so "MSFT"
# matches "MSFT" and "MSFT 5.0"). This example sets the
# mtftp address to 0.0.0.0 for PXEClients.
#dhcp-option=vendor:PXEClient,1,0.0.0.0
# Send microsoft-specific option to tell windows to release the DHCP lease
# when it shuts down. Note the "i" flag, to tell dnsmasq to send the
# value as a four-byte integer - that's what microsoft wants. See
# http://technet2.microsoft.com/WindowsServer/en/library/a70f1bb7-d2d4-49f0-96d6-4b7414ecfaae1033.mspx?mfr=true
#dhcp-option=vendor:MSFT,2,1i
# Send the Encapsulated-vendor-class ID needed by some configurations of
# Etherboot to allow is to recognise the DHCP server.
#dhcp-option=vendor:Etherboot,60,"Etherboot"
# Send options to PXELinux. Note that we need to send the options even
# though they don't appear in the parameter request list, so we need
# to use dhcp-option-force here.
# See http://syslinux.zytor.com/pxe.php#special for details.
# Magic number - needed before anything else is recognised
#dhcp-option-force=208,f1:00:74:7e
# Configuration file name
#dhcp-option-force=209,configs/common
# Path prefix
#dhcp-option-force=210,/tftpboot/pxelinux/files/
# Reboot time. (Note 'i' to send 32-bit value)
#dhcp-option-force=211,30i
# Set the boot filename for netboot/PXE. You will only need
# this is you want to boot machines over the network and you will need
# a TFTP server; either dnsmasq's built in TFTP server or an
# external one. (See below for how to enable the TFTP server.)
#dhcp-boot=pxelinux.0
# The same as above, but use custom tftp-server instead machine running dnsmasq
#dhcp-boot=pxelinux,server.name,192.168.1.100
# Boot for Etherboot gPXE. The idea is to send two different
# filenames, the first loads gPXE, and the second tells gPXE what to
# load. The dhcp-match sets the gpxe tag for requests from gPXE.
#dhcp-match=set:gpxe,175 # gPXE sends a 175 option.
#dhcp-boot=tag:!gpxe,undionly.kpxe
#dhcp-boot=mybootimage
# Encapsulated options for Etherboot gPXE. All the options are
# encapsulated within option 175
#dhcp-option=encap:175, 1, 5b # priority code
#dhcp-option=encap:175, 176, 1b # no-proxydhcp
#dhcp-option=encap:175, 177, string # bus-id
#dhcp-option=encap:175, 189, 1b # BIOS drive code
#dhcp-option=encap:175, 190, user # iSCSI username
#dhcp-option=encap:175, 191, pass # iSCSI password
# Test for the architecture of a netboot client. PXE clients are
# supposed to send their architecture as option 93. (See RFC 4578)
#dhcp-match=peecees, option:client-arch, 0 #x86-32
#dhcp-match=itanics, option:client-arch, 2 #IA64
#dhcp-match=hammers, option:client-arch, 6 #x86-64
#dhcp-match=mactels, option:client-arch, 7 #EFI x86-64
# Do real PXE, rather than just booting a single file, this is an
# alternative to dhcp-boot.
#pxe-prompt="What system shall I netboot?"
# or with timeout before first available action is taken:
#pxe-prompt="Press F8 for menu.", 60
# Available boot services. for PXE.
#pxe-service=x86PC, "Boot from local disk"
# Loads <tftp-root>/pxelinux.0 from dnsmasq TFTP server.
#pxe-service=x86PC, "Install Linux", pxelinux
# Loads <tftp-root>/pxelinux.0 from TFTP server at 1.2.3.4.
# Beware this fails on old PXE ROMS.
#pxe-service=x86PC, "Install Linux", pxelinux, 1.2.3.4
# Use bootserver on network, found my multicast or broadcast.
#pxe-service=x86PC, "Install windows from RIS server", 1
# Use bootserver at a known IP address.
#pxe-service=x86PC, "Install windows from RIS server", 1, 1.2.3.4
# If you have multicast-FTP available,
# information for that can be passed in a similar way using options 1
# to 5. See page 19 of
# http://download.intel.com/design/archives/wfm/downloads/pxespec.pdf
# Enable dnsmasq's built-in TFTP server
#enable-tftp
# Set the root directory for files available via FTP.
#tftp-root=/var/ftpd
# Make the TFTP server more secure: with this set, only files owned by
# the user dnsmasq is running as will be send over the net.
#tftp-secure
# This option stops dnsmasq from negotiating a larger blocksize for TFTP
# transfers. It will slow things down, but may rescue some broken TFTP
# clients.
#tftp-no-blocksize
# Set the boot file name only when the "red" tag is set.
#dhcp-boot=net:red,pxelinux.red-net
# An example of dhcp-boot with an external TFTP server: the name and IP
# address of the server are given after the filename.
# Can fail with old PXE ROMS. Overridden by --pxe-service.
#dhcp-boot=/var/ftpd/pxelinux.0,boothost,192.168.0.3
# If there are multiple external tftp servers having a same name
# (using /etc/hosts) then that name can be specified as the
# tftp_servername (the third option to dhcp-boot) and in that
# case dnsmasq resolves this name and returns the resultant IP
# addresses in round robin fasion. This facility can be used to
# load balance the tftp load among a set of servers.
#dhcp-boot=/var/ftpd/pxelinux.0,boothost,tftp_server_name
# Set the limit on DHCP leases, the default is 150
#dhcp-lease-max=150
# The DHCP server needs somewhere on disk to keep its lease database.
# This defaults to a sane location, but if you want to change it, use
# the line below.
#dhcp-leasefile=/var/lib/misc/dnsmasq.leases
# Set the DHCP server to authoritative mode. In this mode it will barge in
# and take over the lease for any client which broadcasts on the network,
# whether it has a record of the lease or not. This avoids long timeouts
# when a machine wakes up on a new network. DO NOT enable this if there's
# the slightest chance that you might end up accidentally configuring a DHCP
# server for your campus/company accidentally. The ISC server uses
# the same option, and this URL provides more information:
# http://www.isc.org/files/auth.html
dhcp-authoritative
# Run an executable when a DHCP lease is created or destroyed.
# The arguments sent to the script are "add" or "del",
# then the MAC address, the IP address and finally the hostname
# if there is one.
#dhcp-script=/bin/echo
# Set the cachesize here.
#cache-size=150
# If you want to disable negative caching, uncomment this.
#no-negcache
# Normally responses which come form /etc/hosts and the DHCP lease
# file have Time-To-Live set as zero, which conventionally means
# do not cache further. If you are happy to trade lower load on the
# server for potentially stale date, you can set a time-to-live (in
# seconds) here.
#local-ttl=
# If you want dnsmasq to detect attempts by Verisign to send queries
# to unregistered .com and .net hosts to its sitefinder service and
# have dnsmasq instead return the correct NXDOMAIN response, uncomment
# this line. You can add similar lines to do the same for other
# registries which have implemented wildcard A records.
#bogus-nxdomain=64.94.110.11
# If you want to fix up DNS results from upstream servers, use the
# alias option. This only works for IPv4.
# This alias makes a result of 1.2.3.4 appear as 5.6.7.8
#alias=1.2.3.4,5.6.7.8
# and this maps 1.2.3.x to 5.6.7.x
#alias=1.2.3.0,5.6.7.0,255.255.255.0
# and this maps 192.168.0.10->192.168.0.40 to 10.0.0.10->10.0.0.40
#alias=192.168.0.10-192.168.0.40,10.0.0.0,255.255.255.0
# Change these lines if you want dnsmasq to serve MX records.
# Return an MX record named "maildomain.com" with target
# servermachine.com and preference 50
#mx-host=maildomain.com,servermachine.com,50
# Set the default target for MX records created using the localmx option.
#mx-target=servermachine.com
# Return an MX record pointing to the mx-target for all local
# machines.
#localmx
# Return an MX record pointing to itself for all local machines.
#selfmx
# Change the following lines if you want dnsmasq to serve SRV
# records. These are useful if you want to serve ldap requests for
# Active Directory and other windows-originated DNS requests.
# See RFC 2782.
# You may add multiple srv-host lines.
# The fields are <name>,<target>,<port>,<priority>,<weight>
# If the domain part if missing from the name (so that is just has the
# service and protocol sections) then the domain given by the domain=
# config option is used. (Note that expand-hosts does not need to be
# set for this to work.)
# A SRV record sending LDAP for the example.com domain to
# ldapserver.example.com port 389
#srv-host=_ldap._tcp.example.com,ldapserver.example.com,389
# A SRV record sending LDAP for the example.com domain to
# ldapserver.example.com port 389 (using domain=)
#domain=example.com
#srv-host=_ldap._tcp,ldapserver.example.com,389
# Two SRV records for LDAP, each with different priorities
#srv-host=_ldap._tcp.example.com,ldapserver.example.com,389,1
#srv-host=_ldap._tcp.example.com,ldapserver.example.com,389,2
# A SRV record indicating that there is no LDAP server for the domain
# example.com
#srv-host=_ldap._tcp.example.com
# The following line shows how to make dnsmasq serve an arbitrary PTR
# record. This is useful for DNS-SD. (Note that the
# domain-name expansion done for SRV records _does_not
# occur for PTR records.)
#ptr-record=_http._tcp.dns-sd-services,"New Employee Page._http._tcp.dns-sd-services"
# Change the following lines to enable dnsmasq to serve TXT records.
# These are used for things like SPF and zeroconf. (Note that the
# domain-name expansion done for SRV records _does_not
# occur for TXT records.)
#Example SPF.
#txt-record=example.com,"v=spf1 a -all"
#Example zeroconf
#txt-record=_http._tcp.example.com,name=value,paper=A4
# Provide an alias for a "local" DNS name. Note that this _only_ works
# for targets which are names from DHCP or /etc/hosts. Give host
# "bert" another name, bertrand
#cname=bertand,bert
# For debugging purposes, log each DNS query as it passes through
# dnsmasq.
#log-queries
# Log lots of extra information about DHCP transactions.
#log-dhcp
'';
systemd.services.dnsmasq = {
bindsTo = [ "network-addresses-${routerCfg.internalBridgeInterfaceName}.service" ];
};
};
}

View file

@ -0,0 +1,70 @@
{
config,
lib,
pkgs,
...
}:
with lib;
let
routerCfg = config.services.qois.router;
dhcpCfg = config.services.qois.router.dhcp;
cfg = config.services.qois.router.recursiveDns;
in
{
options.services.qois.router.recursiveDns = {
enable = mkEnableOption "router recursive dns service";
networkIdIp = mkOption {
type = types.str;
example = "192.168.0.0";
description = ''
Network ID IP of local network.
'';
};
};
config = mkIf cfg.enable {
services.unbound =
let
revIpDomain = concatStringsSep "." (reverseList (take 3 (splitString "." cfg.networkIdIp)));
in
{
enable = true;
settings = {
server = {
interface = [
"127.0.0.1"
routerCfg.internalRouterIP
];
access-control = [
''"127.0.0.0/24" allow''
''"${cfg.networkIdIp}/${toString routerCfg.internalPrefixLength}" allow''
];
do-not-query-localhost = "no";
private-domain = [
"${dhcpCfg.localDomain}."
"${revIpDomain}.in-addr.arpa."
];
domain-insecure = [
"${dhcpCfg.localDomain}."
"${revIpDomain}.in-addr.arpa."
];
local-zone = ''"${revIpDomain}.in-addr.arpa" transparent'';
};
forward-zone = [
{
name = "${dhcpCfg.localDomain}.";
forward-addr = "127.0.0.1@${toString dhcpCfg.localDnsPort}";
}
{
name = "${revIpDomain}.in-addr.arpa.";
forward-addr = "127.0.0.1@${toString dhcpCfg.localDnsPort}";
}
];
};
};
};
}

View file

@ -0,0 +1,107 @@
{
config,
lib,
pkgs,
...
}:
with lib;
let
routerCfg = config.services.qois.router;
cfg = config.services.qois.router.wireless;
in
{
options.services.qois.router.wireless = {
enable = mkEnableOption "router wireless service";
wleInterface24Ghz = mkOption {
type = with types; nullOr str;
default = null;
example = "wlp1";
description = ''
Wireless interface name for 2.4 GHz wireless band.
'';
};
ssid = mkOption {
type = types.str;
example = "MyNetwork";
description = ''
Wireless network SSID.
'';
};
passphrase = mkOption {
type = types.str;
description = ''
Passphrase of wireless network. May be encrypted with <literal>wpa_passphrase &lt;wleSSID&gt; &lt;passphrase&gt;</literal>.
'';
};
regulatoryCountryCode = mkOption {
type = types.str;
default = "US";
description = ''
Regulatory wireless country code.
'';
};
};
config =
let
wle24GhzEnabled = cfg.wleInterface24Ghz != null;
in
mkIf cfg.enable {
boot.extraModprobeConfig = ''
options cfg80211 ieee80211_regdom=${cfg.regulatoryCountryCode}
'';
systemd.services.hostapd.after = [ "lan-netdev.service" ];
services.hostapd = {
enable = wle24GhzEnabled;
radios.${cfg.wleInterface24Ghz} = {
wifi4.enable = true;
wifi4.capabilities = [
"HT40-"
"HT40+"
"SHORT-GI-40"
"TX-STBC"
"RX-STBC1"
"DSSS_CCK-40"
];
wifi5.enable = false;
networks.${cfg.wleInterface24Ghz} = {
# hostapd requires bss to have names with the interface.
ssid = cfg.ssid;
authentication = {
mode = "wpa2-sha256";
enableRecommendedPairwiseCiphers = true;
wpaPasswordFile = /secrets/wifi_${cfg.ssid};
};
settings = {
wme_enabled = 1;
ieee80211w = 0;
sae_require_mfp = 0;
wpa_key_mgmt = lib.mkForce "WPA-PSK";
wpa_pairwise = lib.mkForce "CCMP";
rsn_pairwise = lib.mkForce "CCMP";
bridge = "lan";
};
};
settings = {
wme_enabled = 1;
ieee80211w = 0;
sae_require_mfp = 0;
wpa = 2;
wpa_key_mgmt = lib.mkForce "WPA-PSK";
wpa_pairwise = lib.mkForce "CCMP";
rsn_pairwise = lib.mkForce "CCMP";
};
};
};
};
}

View file

@ -0,0 +1,12 @@
# Router Role {#_router_role}
The `router` role set is applied on hosts which serve the rule of a SOHO
router.
Features:
- NAT and basic Firewalling (`router`)
- Recursive DNS with `unbound` (DNSSEC validated) (`router-dns`)
- Local DHCP and local DNS hostname resolution with `dnsmasq`
(`router-dhcp`)
- Wireless with `hostapd` (`router-wireless-ap`)

View file

@ -0,0 +1,103 @@
{
config,
lib,
pkgs,
...
}:
with lib;
let
cfg = config.services.qois.router;
in
{
options.services.qois.router = {
enable = mkEnableOption "router service";
wanInterface = mkOption {
type = with types; nullOr str;
example = "enp0";
default = null;
description = ''
WAN interface name.
'';
};
wirelessInterfaces = mkOption {
type = types.listOf types.str;
example = [
"wlp1"
"wlp2"
];
default = [ ];
description = ''
Wireless interfaces names.
'';
};
lanInterfaces = mkOption {
type = types.listOf types.str;
example = [
"enp1"
"enp2"
];
default = [ ];
description = ''
LAN interfaces names.
'';
};
internalRouterIP = mkOption {
type = types.str;
example = "192.168.0.1";
description = ''
Internal IP of router.
'';
};
internalPrefixLength = mkOption {
type = types.addCheck types.int (n: n >= 0 && n <= 32);
default = 24;
description = ''
Subnet mask of the network, specified as the number of
bits in the prefix (<literal>24</literal>).
'';
};
internalBridgeInterfaceName = mkOption {
type = types.str;
default = "lan";
description = ''
Name of the virtual internal interface.
'';
};
};
config = mkIf cfg.enable {
networking = {
enableIPv6 = false; # TODO
nat =
if cfg.wanInterface == null then
{ }
else
{
enable = true;
externalInterface = cfg.wanInterface;
internalInterfaces = [ cfg.internalBridgeInterfaceName ];
};
bridges.${cfg.internalBridgeInterfaceName}.interfaces = cfg.lanInterfaces; # Note: The wlp interface is added by hostapd.
interfaces.${cfg.internalBridgeInterfaceName} = {
ipv4 = {
addresses = [
{
address = cfg.internalRouterIP;
prefixLength = cfg.internalPrefixLength;
}
];
};
};
firewall.trustedInterfaces = [ cfg.internalBridgeInterfaceName ];
};
};
}

View file

@ -0,0 +1,37 @@
# Vaultwarden / Bitwarden
To use our Vaultwarden instance, you can use the regular
[Bitwarden apps](https://bitwarden.com/download/) with our custom server when logging in:
Username: `first.lastname@qo.is`
Server Name: `https://vault.qo.is`
## Create Accounts
We currently [allow signups](https://vault.qo.is/#/register) for `@qo.is` email addresses.
Please instruct users to:
- use their full `firstname.lastname@qo.is` email so users may be connected to a LDAP database in the future
- remember that the login password is used to encrypt the password database and should therefor be good.
- the password cannot be reset without loosing all the passwords.
Use of [Emergency Contacts](https://bitwarden.com/help/emergency-access/) or Organizations may be advisable.
## Administration
An admin panel is available under [vault.qo.is/admin](https://vault.qo.is/admin).
The password is saved in the pass database under `vaultwarden-admin`.
In the administration panel, users and organizations may be managed.
Instance settings should be changed with the nixos module in the infrastructure repository only.
## Backup / Restore
1. `systemctl stop vaultwarden.service`
2. Import Postgresql Database Backup
3. Restore `/var/lib/bitwarden_rs`
4. `systemctl start vaultwarden.service`
5. Click `Force clients to resync` in the [Administration interface under _Users_](https://vault.qo.is/admin/users/overview)

View file

@ -0,0 +1,90 @@
{
config,
pkgs,
lib,
...
}:
let
cfg = config.qois.vault;
in
with lib;
{
options.qois.vault = {
enable = mkEnableOption "Enable qois vault service";
domain = mkOption {
type = types.str;
default = "vault.qo.is";
description = "Domain, under which the service is served.";
};
};
config = mkIf cfg.enable {
services.vaultwarden = {
enable = true;
dbBackend = "postgresql";
environmentFile = config.sops.secrets."vaultwarden/environment-file".path;
config = {
DATA_FOLDER = "/var/lib/bitwarden_rs";
DATABASE_URL = "postgresql:///vaultwarden";
DOMAIN = "https://${cfg.domain}";
ROCKET_PORT = 8222;
USE_SENDMAIL = true;
SMTP_FROM = "vault@qo.is";
SMTP_FROM_NAME = cfg.domain;
SIGNUPS_ALLOWED = false;
INVITATIONS_ALLOWED = false;
SIGNUPS_DOMAINS_WHITELIST = "qo.is";
SIGNUPS_VERIFY = true;
EXPERIMENTAL_CLIENT_FEATURE_FLAGS = "fido2-vault-credentials";
SHOW_PASSWORD_HINT = false;
TRASH_AUTO_DELETE_DAYS = 30;
};
};
qois.postgresql.enable = true;
qois.backup-client.includePaths = [ config.services.vaultwarden.config.DATA_FOLDER ];
services.postgresql =
let
name = config.users.users.vaultwarden.name;
in
{
ensureUsers = [
{
inherit name;
ensureDBOwnership = true;
}
];
ensureDatabases = [ name ];
};
# See https://search.nixos.org/options?channel=unstable&show=services.vaultwarden.environmentFile
sops.secrets."vaultwarden/environment-file".restartUnits = [ "vaultwarden.service" ];
systemd.services.vaultwarden.path = [ pkgs.msmtp ];
users.users.vaultwarden.extraGroups = [ "postdrop" ];
networking.hosts."127.0.0.1" = [ cfg.domain ];
services.nginx = {
enable = true;
virtualHosts.${cfg.domain} = {
kTLS = true;
forceSSL = true;
enableACME = true;
locations."/" = {
proxyPass = "http://localhost:${toString config.services.vaultwarden.config.ROCKET_PORT}";
proxyWebsockets = true;
};
};
};
};
}

View file

@ -0,0 +1,11 @@
# WWAN Module {#_wwan_module}
This module configures WWAN adapters that support MBIM
## Current limitations {#_current_limitations}
- IPv4 tested only
- Currently, it is not simple to get network failures or address
updates via a hook or so.
- A systemd timer to update the configuration is executed every 2
minutes to prevent longer downtimes.

View file

@ -0,0 +1,145 @@
# Based on https://github.com/jgillich/nixos/blob/master/services/ppp.nix
# Tipps and tricks under https://www.hackster.io/munoz0raul/how-to-use-gsm-3g-4g-in-embedded-linux-systems-9047cf#toc-configuring-the-ppp-files-5
{
config,
lib,
pkgs,
...
}:
with lib;
let
cfg = config.services.qois.wwan;
mbim-ip-configured = pkgs.writeScriptBin "mbim-ip-configured" (
''
#!${pkgs.stdenv.shell}
MBIM_INTERFACE=${cfg.mbimInterface}
''
+ (readFile ./mbim-ip.bash)
);
mbim-check-status = pkgs.writeScriptBin "mbim-check-status" ''
#!${pkgs.stdenv.shell}
if ! systemctl is-active --quiet wwan.service; then
# Skip check if wwan is not running
exit 0
fi
if ! mbim-network ${cfg.mbimInterface} status | grep -q "Status: activated"; then
echo "WWAN device is currently in disabled state, triggering restart."
systemctl restart wwan.service
fi
'';
in
{
options.services.qois.wwan = {
enable = mkEnableOption "wwan client service";
apn = mkOption {
type = types.str;
description = ''
APN domain of provider.
'';
};
apnUser = mkOption {
type = types.str;
default = "";
description = ''
APN username (optional).
'';
};
apnPass = mkOption {
type = types.str;
default = "";
description = ''
APN password (optional).
'';
};
apnAuth = mkOption {
type = types.enum [
"PAP"
"CHAP"
"MSCHAPV2"
""
];
default = "";
description = ''
APN authentication type, one of ${concatMapStringsSep ", " show values} (optional).
'';
};
mbimProxy = mkOption {
type = types.bool;
default = true;
description = ''
Whether to use the mbim proxy or not.
'';
};
mbimInterface = mkOption {
type = types.str;
default = "/dev/cdc-wdm0";
description = ''
MBIM Interface which the connection will use.
'';
};
networkInterface = mkOption {
type = types.str;
description = "Name of the WWAN network interface";
};
};
config = mkIf cfg.enable {
systemd.services = {
"wwan" = {
description = "WWAN connectivity";
wantedBy = [ "network.target" ];
bindsTo = [ "network-addresses-${cfg.networkInterface}.service" ];
path = with pkgs; [
libmbim
iproute
];
serviceConfig = {
ExecStart = "${mbim-ip-configured}/bin/mbim-ip-configured start ${cfg.networkInterface}";
ExecStop = "${mbim-ip-configured}/bin/mbim-ip-configured stop ${cfg.networkInterface}";
RemainAfterExit = true;
};
};
"wwan-check" = {
description = "Check WWAN connectivity and restart if disabled";
path = with pkgs; [ libmbim ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${mbim-check-status}/bin/mbim-check-status";
};
};
};
systemd.timers."wwan-check" = {
description = "WWAN connectivity check";
wantedBy = [ "timers.target" ];
timerConfig = {
Unit = "wwan-check";
OnBootSec = "2m";
OnUnitActiveSec = "1m";
};
};
environment.etc."mbim-network.conf".text = ''
APN=${cfg.apn}
APN_USER=${cfg.apnUser}
APN_PASS=${cfg.apnPass}
APN_AUTH=${cfg.apnAuth}
PROXY=${optionalString cfg.mbimProxy "yes"}
'';
networking.interfaces.${cfg.networkInterface}.useDHCP = false;
};
}

View file

@ -0,0 +1,329 @@
#!/usr/bin/env bash
###############################################################################
# Configuration
###############################################################################
MODE=$1
DEV=$2
if [ "$DEBUG" == "" ]; then
DEBUG="false"
fi
if [ "$MBIM_INTERFACE" == "" ]; then
MBIM_INTERFACE="/dev/cdc-wdm0"
fi
###############################################################################
# Global Variables
###############################################################################
previous_state="none"
state="none"
skip_line=0
ipv4_addresses=()
ipv4_gateway=""
ipv4_dns=()
ipv4_mtu=""
ipv6_addresses=()
ipv6_gateway=""
ipv6_dns=()
ipv6_mtu=""
export previous_state state skip_line \
ipv4_addresses ipv4_gateway ipv4_dns ipv4_mtu \
ipv6_addresses ipv6_gateway ipv6_dns ipv6_mtu
###############################################################################
# Function
###############################################################################
function print_debug {
if [ "$DEBUG" != "false" ]; then
echo "[State: $state] $1" >&2
fi
}
function print_full_configuration {
if [[ "${#ipv4_addresses[@]}" > 0 ]]; then
printf "IPv4: "
printf '%s, ' "${ipv4_addresses[@]}"
printf "\n"
printf "GW: $ipv4_gateway\n"
printf "DNS: "
printf '%s, ' "${ipv4_dns[@]}"
printf "\n"
printf "MTU: $ipv4_mtu\n"
fi
if [[ "${#ipv6_addresses[@]}" > 0 ]]; then
echo
printf "IPv6: "
printf '%s, ' "${ipv6_addresses[@]}"
printf "\n"
printf "GW: $ipv6_gateway\n"
printf "DNS: "
printf '%s, ' "${ipv6_dns[@]}"
printf "\n"
printf "MTU: $ipv6_mtu\n"
fi
}
function next_state {
previous_state="$state"
state="$1"
}
function parse_ip {
# IP [0]: '10.134.203.177/30'
local line_re="IP \[([0-9]+)\]: '(.+)'"
local input=$1
if [[ $input =~ $line_re ]]; then
local ip_cnt=${BASH_REMATCH[1]}
local ip=${BASH_REMATCH[2]}
fi
echo "$ip"
}
function parse_dns {
# IP [0]: '10.134.203.177/30'
local line_re="DNS \[([0-9]+)\]: '(.+)'"
local input=$1
if [[ $input =~ $line_re ]]; then
local dns_cnt=${BASH_REMATCH[1]}
local dns=${BASH_REMATCH[2]}
fi
echo "$dns"
}
function parse_gateway {
# Gateway: '10.134.203.178'
local line_re="Gateway: '(.+)'"
local input=$1
if [[ $input =~ $line_re ]]; then
local gw=${BASH_REMATCH[1]}
fi
echo "$gw"
}
function parse_mtu {
# MTU: '1500'
local line_re="MTU: '([0-9]+)'"
local input=$1
if [[ $input =~ $line_re ]]; then
local mtu=${BASH_REMATCH[1]}
fi
echo "$mtu"
}
function parse_input_state_machine {
state="start"
while true; do
if [[ "$skip_line" == 0 ]]; then
read line || break # TODO: Clean up
else
skip_line=0
fi
case "$state" in
"start")
read line || break # first line is empty, read a new one #TODO: This is not very clean...
case "$line" in
*"configuration available: 'none'"*)
# Skip none state
# TODO: This is a workaround of the original parser's shortcomming
continue
;;
*"IPv4 configuration available"*)
next_state "ipv4_ip"
continue
;;
*"IPv6 configuration available"*)
next_state "ipv6_ip"
continue
;;
*)
next_state "exit"
continue
;;
esac
;;
"error")
echo "Error in pattern matchin of state $previous_state. Exiting." >&2
exit 2
;;
"exit")
break
;;
"ipv4_ip")
ipv4=$(parse_ip "$line")
if [ -z "$ipv4" ]; then
if [[ "${#ipv4_addresses[@]}" < 1 ]]; then
next_state "error"
continue
else
next_state "ipv4_gateway"
skip_line=1
continue
fi
fi
print_debug "$ipv4"
ipv4_addresses+=("$ipv4")
;;
"ipv4_gateway")
gw=$(parse_gateway "$line")
if [ -z "$gw" ]; then
next_state "error"
continue
fi
print_debug "$gw"
ipv4_gateway="$gw"
next_state "ipv4_dns"
;;
"ipv4_dns")
ipv4=$(parse_dns "$line")
if [ -z "$ipv4" ]; then
if [[ "${#ipv4_dns[@]}" < 1 ]]; then
next_state "error"
continue
else
next_state "ipv4_mtu"
skip_line=1
continue
fi
fi
print_debug "$ipv4"
ipv4_dns+=("$ipv4")
;;
"ipv4_mtu")
mtu=$(parse_mtu "$line")
if [ -z "$mtu" ]; then
next_state "error"
continue
fi
print_debug "$mtu"
ipv4_mtu="$mtu"
next_state "start"
;;
"ipv6_ip")
ipv6=$(parse_ip "$line")
if [ -z "$ipv6" ]; then
if [[ "${#ipv6_addresses[@]}" < 1 ]]; then
next_state "error"
continue
else
next_state "ipv6_gateway"
skip_line=1
continue
fi
fi
print_debug "$ipv6"
ipv6_addresses+=("$ipv6")
;;
"ipv6_gateway")
gw=$(parse_gateway "$line")
if [ -z "$gw" ]; then
next_state "error"
continue
fi
print_debug "$gw"
ipv6_gateway="$gw"
next_state "ipv6_dns"
;;
"ipv6_dns")
ipv6=$(parse_dns "$line")
if [ -z "$ipv6" ]; then
if [[ "${#ipv6_dns[@]}" < 1 ]]; then
next_state "error"
continue
else
next_state "ipv6_mtu"
skip_line=1
continue
fi
fi
print_debug "$ipv6"
ipv6_dns+=("$ipv6")
;;
"ipv6_mtu")
mtu=$(parse_mtu "$line")
if [ -z "$mtu" ]; then
next_state "error"
continue
fi
print_debug "$mtu"
ipv6_mtu="$mtu"
next_state "start"
;;
*)
print_debug "Invalid state (came from $previous_state). Exiting."
exit 0
;;
esac
done
}
interface_stop(){
ip addr flush dev $DEV
ip route flush dev $DEV
ip -6 addr flush dev $DEV
ip -6 route flush dev $DEV
#TODO: Nameserver?
}
interface_start() {
ip link set $DEV up
if [[ "${#ipv4_addresses[@]}" > 0 ]]; then
ip addr add ${ipv4_addresses[@]} dev $DEV broadcast + #TODO: Works for multiple addresses?
ip link set $DEV mtu $ipv4_mtu
ip route add default via $ipv4_gateway dev $DEV
#TODO: nameserver ${ipv4_dns[@]}
else
echo "No IPv4 address, skipping v4 configuration..."
fi
if [[ "${#ipv6_addresses[@]}" > 0 ]]; then
ip -6 addr add ${ipv6_addresses[@]} dev $DEV #TODO: Works for multiple addresses?
ip -6 route add default via $ipv6_gateway dev $DEV
ip -6 link set $DEV mtu $ipv6_mtu
#TODO: nameserver ${ipv6_dns[@]}"
else
echo "No IPv6 address, skipping v6 configuration..."
fi
}
###############################################################################
# Execution
###############################################################################
set -x
set -e
echo "NOTE: This script does not yet support nameserver configuration."
case "$MODE" in
"start")
mbim-network $MBIM_INTERFACE start
sleep 1
mbimcli -d $MBIM_INTERFACE -p --query-ip-configuration=0 | {
parse_input_state_machine
print_full_configuration
interface_stop
interface_start
}
;;
"stop")
mbim-network $MBIM_INTERFACE stop
interface_stop
;;
*)
echo "USAGE: $0 start|stop INTERFACE" >&2
echo "You can set an env variable DEBUG to gather debugging output." >&2
exit 1
;;
esac