about summary refs log tree commit diff
path: root/nixos/modules/services/networking/nat.nix
blob: f35b0f68e3efd44d797a04715880427edff14589 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# This module enables Network Address Translation (NAT).
# XXX: todo: support multiple upstream links
# see http://yesican.chsoft.biz/lartc/MultihomedLinuxNetworking.html

{ config, lib, pkgs, ... }:

with lib;

let

  cfg = config.networking.nat;

  dest = if cfg.externalIP == null then "-j MASQUERADE" else "-j SNAT --to-source ${cfg.externalIP}";

  externalInterfaceFilter = param:
    optionalString (cfg.externalInterface != null) "${param} ${cfg.externalInterface}";

  flushNat = ''
    iptables -w -t nat -D PREROUTING -j nixos-nat-pre 2>/dev/null|| true
    iptables -w -t nat -F nixos-nat-pre 2>/dev/null || true
    iptables -w -t nat -X nixos-nat-pre 2>/dev/null || true
    iptables -w -t nat -D POSTROUTING -j nixos-nat-post 2>/dev/null || true
    iptables -w -t nat -F nixos-nat-post 2>/dev/null || true
    iptables -w -t nat -X nixos-nat-post 2>/dev/null || true
  '';

  setupNat = ''
    # Create subchain where we store rules
    iptables -w -t nat -N nixos-nat-pre
    iptables -w -t nat -N nixos-nat-post

    # We can't match on incoming interface in POSTROUTING, so
    # mark packets coming from the external interfaces.
    ${concatMapStrings (iface: ''
      iptables -w -t nat -A nixos-nat-pre \
        -i '${iface}' -j MARK --set-mark 1
    '') cfg.internalInterfaces}

    # NAT the marked packets.
    ${optionalString (cfg.internalInterfaces != []) ''
      iptables -w -t nat -A nixos-nat-post -m mark --mark 1 \
        ${externalInterfaceFilter "-o"} ${dest}
    ''}

    # NAT packets coming from the internal IPs.
    ${concatMapStrings (range: ''
      iptables -w -t nat -A nixos-nat-post \
        -s '${range}' \! -d '${range}'
        ${externalInterfaceFilter "-o"} ${dest}
    '') cfg.internalIPs}

    # NAT from external ports to internal ports.
    ${concatMapStrings (fwd: ''
      iptables -w -t nat -A nixos-nat-pre \
        ${externalInterfaceFilter "-i"} -p tcp \
        --dport ${builtins.toString fwd.sourcePort} \
        -j DNAT --to-destination ${fwd.destination}
    '') cfg.forwardPorts}

    # Append our chains to the nat tables
    iptables -w -t nat -A PREROUTING -j nixos-nat-pre
    iptables -w -t nat -A POSTROUTING -j nixos-nat-post
  '';

in

{

  ###### interface

  options = {

    networking.nat.enable = mkOption {
      type = types.bool;
      default = false;
      description =
        ''
          Whether to enable Network Address Translation (NAT).
        '';
    };

    networking.nat.internalInterfaces = mkOption {
      type = types.listOf types.str;
      default = [];
      example = [ "eth0" ];
      description =
        ''
          The interfaces for which to perform NAT. Packets coming from
          these interface and destined for the external interface will
          be rewritten.
        '';
    };

    networking.nat.internalIPs = mkOption {
      type = types.listOf types.str;
      default = [];
      example = [ "192.168.1.0/24" ];
      description =
        ''
          The IP address ranges for which to perform NAT.  Packets
          coming from these addresses (on any interface) and destined
          for the external interface will be rewritten.
        '';
    };

    networking.nat.externalInterface = mkOption {
      type = types.nullOr types.str;
      default = null;
      example = "eth1";
      description =
        ''
          The name of the external network interface.
        '';
    };

    networking.nat.externalIP = mkOption {
      type = types.nullOr types.str;
      default = null;
      example = "203.0.113.123";
      description =
        ''
          The public IP address to which packets from the local
          network are to be rewritten.  If this is left empty, the
          IP address associated with the external interface will be
          used.
        '';
    };

    networking.nat.forwardPorts = mkOption {
      type = types.listOf types.optionSet;
      default = [];
      example = [ { sourcePort = 8080; destination = "10.0.0.1:80"; } ];
      options = {
        sourcePort = mkOption {
          type = types.int;
          example = 8080;
          description = "Source port of the external interface";
        };

        destination = mkOption {
          type = types.str;
          example = "10.0.0.1:80";
          description = "Forward tcp connection to destination ip:port";
        };
      };

      description =
        ''
          List of forwarded ports from the external interface to
          internal destinations by using DNAT.
        '';
    };

  };


  ###### implementation

  config = mkIf config.networking.nat.enable {

    environment.systemPackages = [ pkgs.iptables ];

    boot = {
      kernelModules = [ "nf_nat_ftp" ];
      kernel.sysctl = {
        "net.ipv4.conf.all.forwarding" = mkOverride 99 true;
        "net.ipv4.conf.default.forwarding" = mkOverride 99 true;
      };
    };

    networking.firewall = mkIf config.networking.firewall.enable {
      extraCommands = mkMerge [ (mkBefore flushNat) setupNat ];
      extraStopCommands = flushNat;
    };

    systemd.services = mkIf (!config.networking.firewall.enable) { nat = {
      description = "Network Address Translation";
      wantedBy = [ "network.target" ];
      after = [ "network-interfaces.target" "systemd-modules-load.service" ];
      path = [ pkgs.iptables ];
      unitConfig.ConditionCapability = "CAP_NET_ADMIN";

      serviceConfig = {
        Type = "oneshot";
        RemainAfterExit = true;
      };

      script = flushNat + setupNat;

      postStop = flushNat;
    }; };
  };
}