1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 sysctlOption = mkOptionType {
8 name = "sysctl option value";
9 check = val:
10 let
11 checkType = x: isBool x || isString x || isInt x || isNull x;
12 in
13 checkType val || (val._type or "" == "override" && checkType val.content);
14 merge = loc: defs: mergeOneOption loc (filterOverrides defs);
15 };
16
17in
18
19{
20
21 options = {
22
23 boot.kernel.sysctl = mkOption {
24 default = {};
25 example = {
26 "net.ipv4.tcp_syncookies" = false;
27 "vm.swappiness" = 60;
28 };
29 type = types.attrsOf sysctlOption;
30 description = ''
31 Runtime parameters of the Linux kernel, as set by
32 <citerefentry><refentrytitle>sysctl</refentrytitle>
33 <manvolnum>8</manvolnum></citerefentry>. Note that sysctl
34 parameters names must be enclosed in quotes
35 (e.g. <literal>"vm.swappiness"</literal> instead of
36 <literal>vm.swappiness</literal>). The value of each
37 parameter may be a string, integer, boolean, or null
38 (signifying the option will not appear at all).
39 '';
40 };
41
42 };
43
44 config = {
45
46 environment.etc."sysctl.d/nixos.conf".text =
47 concatStrings (mapAttrsToList (n: v:
48 optionalString (v != null) "${n}=${if v == false then "0" else toString v}\n"
49 ) config.boot.kernel.sysctl);
50
51 systemd.services.systemd-sysctl =
52 { wantedBy = [ "multi-user.target" ];
53 restartTriggers = [ config.environment.etc."sysctl.d/nixos.conf".source ];
54 };
55
56 # Enable hardlink and symlink restrictions. See
57 # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7
58 # for details.
59 boot.kernel.sysctl."fs.protected_hardlinks" = true;
60 boot.kernel.sysctl."fs.protected_symlinks" = true;
61
62 # Hide kernel pointers (e.g. in /proc/modules) for unprivileged
63 # users as these make it easier to exploit kernel vulnerabilities.
64 #
65 # Removed under grsecurity.
66 boot.kernel.sysctl."kernel.kptr_restrict" =
67 if (config.boot.kernelPackages.kernel.features.grsecurity or false) then null else 1;
68 };
69}