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_.
User's password can be configured by `users.<name>.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,
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](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1003151). As a workaround, copy the output from the first `$` until the forth.
Note that the hash is still world-readable. A more secure option is to use `users.<name>.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`.
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`.
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.
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"](https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/web-servers/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:
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.
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.
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](https://quad9.net/) as backup. Refer to [stubby.yml](https://github.com/getdnsapi/stubby/blob/develop/stubby.yml.example) 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.
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).
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 for security reason. If a program needs it, you need to explicitly grant CAP_NET_BIND_SERVICE capability. An alternative approach is to bind the program 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.
(Edit: 20 Jun 2021) {% post_link cloudflare-argo-nixos 'cloudflared' %} replaced my port forwarding setup, my web server now binds to localhost and no longer needs open inbound port.
Unattended upgrade can be enabled through the following config. Once enabled, NixOS will automatically check and install the updates. If you enable `allowReboot`, it will also reboot if required (especially after kernel upgrade). Unattended upgrade is also a cost-benefit thing. The benefit is timely fix for vulnerability and reduce maintenance effort, the cost is potential incompatibility issue that can arise after update. In my use case, the cost is deemed to be minimal because I find the issue to be rare.
In the config, you can also specify the time that the server will reboot. I recommend to only enable it after everything is up and running, especially when setting a web server; you wouldn't want the server to reboot itself in the middle of your tinkering.
I use USBGuard utility to allow or deny USB devices. In a virtual server environment, I only need to use the virtualised USB keyboard. Configuration is easy and straightforward. First, I generate a policy (with root privilege) to allow all currently connected devices:
TCP Fast Open ([TFO](https://en.wikipedia.org/wiki/Tcp_fast_open)) is enabled by default (`tcp_fastopen = 1`) for outgoing connection since 3.13. As of writing, TFO has limited server support; Caddy, Tor and I2Pd don't support it yet, so enabling it for incoming and outgoing connections (`3`) has no effect.
Since my web server has limited disk space, it needs to run [garbage collector](https://nixos.org/nixos/manual/index.html#sec-nix-gc) from time to time.
Since [unattended upgrade](#unattended-upgrade) is executed on 00:00, I delay garbage collection to 01:00 to avoid time conflict. The order doesn't matter, but there should be at least 15 minutes buffer.