Onion Information
Setup Caddy as a reverse proxy on NixOS (Part 2: Hardening) | Ming Di Leom's Blog
Part 2: Securing NixOS
Onion Details
Page Clicks: 0
First Seen: 04/26/2024
Last Indexed: 10/23/2024
Onion Content
Part 2: Securing NixOS Prerequisites Disable mutableUsers Disable root Hash password hashedPasswordFile Run each service as different user Enables 2FA (OTP) for login DNS-over-TLS Bind to port >1024 Unattended upgrade USBGuard (restricts new USB devices) Networking stack hardening and performance Hardened kernel Remove old, unreferenced packages Complete configuration.nix 6 Jul 2022: Updated to NixOS 22.05 syntax. In this post, I show you how I securely configure the NixOS, the server OS behind this website. This post is Part 2 of a series of articles that show you how I set up Caddy and Tor hidden service on NixOS: Part 1: Install NixOS Part 2: Configure NixOS Part 3: Configure Caddy Part 4: Configure Tor Part 5: Configure I2P Following diagram shows the architecture behind this website. Prerequisites § Before proceeding to the rest of this guide, there are some packages that you need to install. $ nix-shell -p google-authenticator p7zip usbguard wormhole-william Disable mutableUsers § In NixOS, instead of using useradd and passwd to manage users, you could also manage them from the “configuration.nix”. I prefer this approach because it fits the OS’ declarative nature and you could say it is the NixOS- way . First, I disabled useradd and passwd . users. mutableUsers = false ; Disable root § users.root. hashedPassword = "*" ; Hash password § User’s password can be configured by users. .password , obviously this means the password is stored in plain text. Even if you lock down configuration.nix with chmod 600 (which I did), “it is (still) world-readable in the Nix store”. The safer way is to store in a hashed form, users. . hashedPassword = "xxxx" ; Use mkpasswd -m yescrypt to generate the yescrypt-hashed password. mkpasswd generates it with “5” compute cost by default, you can change it using --round option with a value from 1 to 11. Increasing the value will make it more resistant to brute-force, but password verification will also be slower. To verify the output, --salt option cannot be used for yescrypt due to a bug . As a workaround, copy the output from the first $ until the forth. printf "Password: " && read -s var && mkpasswd "$var" '$y$parameter$salt$' && var="" Replace the single-quoted value '' with the copied value. It should have similar output as the previous mkpasswd. hashedPasswordFile § Note that the hash is still world-readable. A more secure option is to use users. .hashedPasswordFile . Save the hash into a file (e.g. “/etc/nixos/nixos.password”) and restricts the file to be readable by root only ( chown root:root and chmod 600 ). You might be wondering why not just hashedPasswordFile during installation. The issue is that, in the live CD environment, the “/etc/“ folder refers to the live CD’s not the actual one which is located in “/mnt/etc/“. I mean, you could try “/mnt/etc/nixos/nixos.password”, but remember to update the option after reboot otherwise you would get locked out. “./nixos.password” value doesn’t work because hashedPasswordFile option doesn’t support relative path, it must be a full path. Hence, I have to use hashedPassword during the initial setup and then switch to hashedPasswordFile . Remember to remove the hashedPassword option once you have set up hashedPasswordFile . hashedPasswordFile = "/etc/nixos/nixos.password" ; isNormalUser = true ; extraGroups = [ "wheel" ]; # Enable ‘sudo’ for the user. I enable isNormalUser which includes sane defaults (disable “isSystemUser”, create a home folder in “/home/nixos/“ and enable shell). Since root account is disabled, you definitely need to add the user to wheel group so that it can use sudo . Once you run # nixos-rebuild switch , verify the password has been set, by checking the /etc/shadow . # cat /etc/shadow | grep 'nixos' The hash in the output should be the same as the content of “/etc/nixos/nixos.password” or hashedPassword value. Only quit root shell after verify. Run each service as different user § For separation of privilege, each service is launched with different user under different group. Shell is disabled for those users. In this case, I have “caddyProxy” to run the Caddy reverse proxy for mdleom.com, “caddyTor” for the reverse proxy to be connected to Tor and “tor” for the Tor hidden service. Caddy package does create “caddy” user by default in its “caddy.nix” , but I prefer to use my own “caddy.nix” which has less permissions granted. “tor” user will be created automatically by the Tor package, but I need to import the private key and assign it to the “tor” user before I can enable the service, hence I create the user beforehand. Combining with the previous user configs, I ended up with: users = { mutableUsers = false ; users = { root = { hashedPassword = "*" ; }; nixos = { group = "nixos" ; hashedPassword = "xxxx" ; isNormalUser = true ; extraGroups = [ "wheel" ]; }; caddyProxy = { group = "caddyProxy" ; home = "/var/lib/caddyProxy" ; createHome = true ; isSystemUser = true ; group = "caddyProxy" ; }; caddyTor = { group = "caddyTor" ; home = "/var/lib/caddyTor" ; createHome = true ; isSystemUser = true ; group = "caddyTor" ; }; tor = { group = "tor" ; home = "/var/lib/tor" ; createHome = true ; isSystemUser = true ; group = "tor" ; uid = config.ids.uids.tor; }; groups = { nixos = {}; caddyProxy = {}; caddyTor = {}; tor = {}; }; Enables 2FA (OTP) for login § For extra security, I enabled 2FA for the user account via TOTP method. It can be configured using google-authenticator (available in NixOS repo). The resulting secret is stored in “~/.google authenticator”. This is also why isNormalUser is needed. google-authenticator should be run as a normal user, _not root nor sudo. $ google-authenticator Yes to time-based Import the generated QR code or secret key to an OTP app or password manager. Enter OTP Backup scratch codes Yes to saving the key to ~/.google_authenticator Yes to disallowing multiple usage No to increasing window Yes to rate-limiting login attempts Once the secret is generated, TOTP can be enabled using the following config. I configured it to require OTP as the second-factor authentication when login and ssh. There is no security benefit of enabling it on sudo because the secret key is stored in the home folder ( $HOME/.google_authenticator ) that the user can write to. services. openssh = { settings = { PermitRootLogin = "no" ; PasswordAuthentication = false ; KbdInteractiveAuthentication = true ; # https://github.com/NixOS/nixpkgs/issues/115044#issuecomment-2244953944 AuthenticationMethods = "publickey,keyboard-interactive:pam" ; }; ## Requires OTP to login & ssh security.pam. services = { login.googleAuthenticator. enable = true ; # https://github.com/NixOS/nixpkgs/issues/115044#issuecomment-2065409087 sshd. text = '' account required pam_unix.so # unix (order 10900) auth required ${pkgs.google-authenticator} /lib/security/pam_google_authenticator.so nullok no_increment_hotp # google_authenticator (order 12500) auth sufficient pam_permit.so session required pam_env.so conffile=/etc/pam/environment readenv=0 # env (order 10100) session required pam_unix.so # unix (order 10200) session required pam_loginuid.so # loginuid (order 10300) session optional ${pkgs.systemd} /lib/security/pam_systemd.so # systemd (order 12000) '' ; }; DNS-over-TLS § Since DNS is not encrypted in transit, it risks being tampered. To resolve that, I use DNS-over-TLS which as the name implies, uses TLS to encrypt the DNS traffic. I use stubby which creates a DNS resolver that listens on localhost and forward DNS query to the upstream server(s) using DoT. stubby enables DNSSEC by default to verify authenticity of the DNS response for supported domains. (This domain mdleom.com has DNSSEC enabled through a DS record) I use Cloudflare DNS (simply because I’m already using its CDN) and Quad9 as backup. Refer to stubby.yml for a full list of supported servers. For Cloudflare DNS, I opt for the malware-blocking flavour, refer to the following IPs if you prefer the default flavour. Source: https://developers.cloudflare.com/1.1.1.1/setup/ # No malware blocking 1.1.1.1.0.0.1 2606:4700:4700::1111 2606:4700:4700::1001 # Malware blocking 1.1.1.2 1.0.0.2 2606:4700:4700::1112 2606:4700:4700::1002 ## DNS-over-TLS services. stubby = { enable = true ; settings = { # ::1 cause error, use 0::1 instead listen_addresses = [ "127.0.0.1" "0::1" ]; # https://github.com/getdnsapi/stubby/blob/develop/stubby.yml.example resolution_type = "GETDNS_RESOLUTION_STUB" ; dns_transport_list = [ "GETDNS_TRANSPORT_TLS" ]; tls_authentication = "GETDNS_AUTHENTICATION_REQUIRED" ; tls_query_padding_blocksize = 128 ; idle_timeout = 10000 ; round_robin_upstreams = 1 ; tls_min_version = "GETDNS_TLS1_3" ; dnssec = "GETDNS_EXTENSION_TRUE" ; upstream_recursive_servers = [ { address_data = "1.1.1.2" ; tls_auth_name = "cloudflare-dns.com" ; } { address_data = "1.0.0.2" ; tls_auth_name = "cloudflare-dns.com" ; } { address_data = "2606:4700:4700::1112" ; tls_auth_name = "cloudflare-dns.com" ; } { address_data = "2606:4700:4700::1002" ; tls_auth_name = "cloudflare-dns.com" ; } { address_data = "9.9.9.9" ; tls_auth_name = "dns.quad9.net" ; } { address_data = "149.112.112.112" ; tls_auth_name = "dns.quad9.net" ; } { address_data = "2620:fe::fe" ; tls_auth_name = "dns.quad9.net" ; } { address_data = "2620:fe::9" ; tls_auth_name = "dns.quad9.net" ; } ]; Then I point systemd’s resolved to stubby. I do configure it to fallback to unencrypted DNS if stubby is not responsive (which does happen). Whether you need an unsecured fallback depends on your cost-benefit. For me, the cost of the site being inaccessible (due to unresponsive stubby) outweighs the benefit of having enforced encryption (my setup is opportunistic). networking. nameservers = [ "::1" "127.0.0.1" ]; services. resolved = { enable = true ; fallbackDns = [ "2606:4700:4700::1112" "2606:4700:4700::1002" "1.1.1.2" "1.0.0.2" ]; }; Execute nixos-rebuild switch and test the DNS resolver by using dig (part of “dnsutils” package): $ dig example.com Bind to port >1024 § By default, Linux program cannot bind to port 1024 and port forward 80/443 to that port. In my case, I configure iptables to port forward 443 to 4430, so any traffic that hits 443 will be redirected to 4430. Both ports need to be opened, but I do configure my dedicated firewall (separate from the web server) to allow port 443 only. ## Port forwarding networking. firewall = { enable = true ; interfaces. ens3 = { allowedTCPPorts = [ 443 4430 ]; }; extraCommands = '' ip6tables -t nat -I PREROUTING -i ens3 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 4430 '' ; }; Most probably you would need ip46tables to open ports in both IPv4 and IPv6. If the server doesn’t support IPv6 (!), just use iptables . (Edit: 20 Jun 2021) cloudflared replaced my port forwarding setup, my web server now binds to localhost and no longer needs open...