1 { config, options, lib, pkgs, utils, ... }:
8 cfg = config.networking;
9 opt = options.networking;
10 interfaces = attrValues cfg.interfaces;
11 hasVirtuals = any (i: i.virtual) interfaces;
12 hasSits = cfg.sits != { };
13 hasGres = cfg.greTunnels != { };
14 hasBonds = cfg.bonds != { };
15 hasFous = cfg.fooOverUDP != { }
16 || filterAttrs (_: s: s.encapsulation != null) cfg.sits != { };
18 slaves = concatMap (i: i.interfaces) (attrValues cfg.bonds)
19 ++ concatMap (i: i.interfaces) (attrValues cfg.bridges)
20 ++ concatMap (i: attrNames (filterAttrs (name: config: ! (config.type == "internal" || hasAttr name cfg.interfaces)) i.interfaces)) (attrValues cfg.vswitches);
22 slaveIfs = map (i: cfg.interfaces.${i}) (filter (i: cfg.interfaces ? ${i}) slaves);
24 rstpBridges = flip filterAttrs cfg.bridges (_: { rstp, ... }: rstp);
26 needsMstpd = rstpBridges != { };
28 bridgeStp = optional needsMstpd (pkgs.writeTextFile {
31 destination = "/bin/bridge-stp";
33 #!${pkgs.runtimeShell} -e
34 export PATH="${pkgs.mstpd}/bin"
36 BRIDGES=(${concatStringsSep " " (attrNames rstpBridges)})
37 for BRIDGE in $BRIDGES; do
38 if [ "$BRIDGE" = "$1" ]; then
39 if [ "$2" = "start" ]; then
40 mstpctl addbridge "$BRIDGE"
42 elif [ "$2" = "stop" ]; then
43 mstpctl delbridge "$BRIDGE"
53 # We must escape interfaces due to the systemd interpretation
54 subsystemDevice = interface:
55 "sys-subsystem-net-devices-${escapeSystemdPath interface}.device";
58 assert v == 4 || v == 6;
63 IPv${toString v} address of the interface. Leave empty to configure the
68 prefixLength = mkOption {
69 type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
71 Subnet mask of the interface, specified as the number of
72 bits in the prefix (`${if v == 4 then "24" else "64"}`).
82 description = "IPv${toString v} address of the network.";
85 prefixLength = mkOption {
86 type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
88 Subnet mask of the network, specified as the number of
89 bits in the prefix (`${if v == 4 then "24" else "64"}`).
94 type = types.nullOr (types.enum [
95 "unicast" "local" "broadcast" "multicast"
99 Type of the route. See the `Route types` section
100 in the `ip-route(8)` manual page for the details.
102 Note that `prohibit`, `blackhole`,
103 `unreachable`, and `throw` cannot
104 be configured per device, so they are not available here. Similarly,
105 `nat` hasn't been supported since kernel 2.6.
110 type = types.nullOr types.str;
112 description = "IPv${toString v} address of the next hop.";
116 type = types.attrsOf types.str;
118 example = { mtu = "1492"; window = "524288"; };
120 Other route options. See the symbol `OPTIONS`
121 in the `ip-route(8)` manual page for the details.
122 You may also specify `metric`,
125 and `table`, which are technically
126 not route options, in the sense used in the manual.
133 gatewayCoerce = address: { inherit address; };
135 gatewayOpts = { ... }: {
141 description = "The default gateway address.";
144 interface = mkOption {
145 type = types.nullOr types.str;
148 description = "The default gateway interface.";
152 type = types.nullOr types.int;
155 description = "The default gateway metric/preference.";
162 interfaceOpts = { name, ... }: {
168 description = "Name of the interface.";
171 tempAddress = mkOption {
172 type = types.enum (lib.attrNames tempaddrValues);
173 default = cfg.tempAddresses;
174 defaultText = literalExpression ''config.networking.tempAddresses'';
176 When IPv6 is enabled with SLAAC, this option controls the use of
177 temporary address (aka privacy extensions) on this
178 interface. This is used to reduce tracking.
180 See also the global option
181 [](#opt-networking.tempAddresses), which
182 applies to all interfaces where this is not set.
190 type = types.nullOr types.bool;
193 Whether this interface should be configured with DHCP. Overrides the
194 default set by {option}`networking.useDHCP`. If `null` (the default),
195 DHCP is enabled if the interface has no IPv4 addresses configured
196 with {option}`networking.interfaces.<name>.ipv4.addresses`, and
201 ipv4.addresses = mkOption {
204 { address = "10.0.0.1"; prefixLength = 16; }
205 { address = "192.168.1.1"; prefixLength = 24; }
207 type = with types; listOf (submodule (addrOpts 4));
209 List of IPv4 addresses that will be statically assigned to the interface.
213 ipv6.addresses = mkOption {
216 { address = "fdfd:b3f0:482::1"; prefixLength = 48; }
217 { address = "2001:1470:fffd:2098::e006"; prefixLength = 64; }
219 type = with types; listOf (submodule (addrOpts 6));
221 List of IPv6 addresses that will be statically assigned to the interface.
225 ipv4.routes = mkOption {
228 { address = "10.0.0.0"; prefixLength = 16; }
229 { address = "192.168.2.0"; prefixLength = 24; via = "192.168.1.1"; }
231 type = with types; listOf (submodule (routeOpts 4));
233 List of extra IPv4 static routes that will be assigned to the interface.
236 If the route type is the default `unicast`, then the scope
237 is set differently depending on the value of {option}`networking.useNetworkd`:
238 the script-based backend sets it to `link`, while networkd sets
242 If you want consistency between the two implementations,
243 set the scope of the route manually with
244 `networking.interfaces.eth0.ipv4.routes = [{ options.scope = "global"; }]`
249 ipv6.routes = mkOption {
252 { address = "fdfd:b3f0::"; prefixLength = 48; }
253 { address = "2001:1470:fffd:2098::"; prefixLength = 64; via = "fdfd:b3f0::1"; }
255 type = with types; listOf (submodule (routeOpts 6));
257 List of extra IPv6 static routes that will be assigned to the interface.
261 macAddress = mkOption {
263 example = "00:11:22:33:44:55";
264 type = types.nullOr (types.str);
266 MAC address of the interface. Leave empty to use the default.
273 type = types.nullOr types.int;
275 MTU size for packets leaving the interface. Leave empty to use the default.
283 Whether this interface is virtual and should be created by tunctl.
284 This is mainly useful for creating bridges between a host and a virtual
285 network such as VPN or a virtual machine.
289 virtualOwner = mkOption {
293 In case of a virtual device, the user who owns it.
297 virtualType = mkOption {
298 default = if hasPrefix "tun" name then "tun" else "tap";
299 defaultText = literalExpression ''if hasPrefix "tun" name then "tun" else "tap"'';
300 type = with types; enum [ "tun" "tap" ];
302 The type of interface to create.
303 The default is TUN for an interface name starting
304 with "tun", otherwise TAP.
308 proxyARP = mkOption {
312 Turn on proxy_arp for this device.
313 This is mainly useful for creating pseudo-bridges between a real
314 interface and a virtual network such as VPN or a virtual machine for
315 interfaces that don't support real bridging (most wlan interfaces).
316 As ARP proxying acts slightly above the link-layer, below-ip traffic
317 isn't bridged, so things like DHCP won't work. The advantage above
318 using NAT lies in the fact that no IP addresses are shared, so all
319 hosts are reachable/routeable.
321 WARNING: turns on ip-routing, so if you have multiple interfaces, you
322 should think of the consequence and setup firewall rules to limit this.
330 description = "Whether to enable wol on this interface.";
333 type = with types; listOf (
334 enum ["phy" "unicast" "multicast" "broadcast" "arp" "magic" "secureon"]
338 The [Wake-on-LAN policy](https://www.freedesktop.org/software/systemd/man/systemd.link.html#WakeOnLan=)
339 to set for the device.
342 - `phy`: Wake on PHY activity
343 - `unicast`: Wake on unicast messages
344 - `multicast`: Wake on multicast messages
345 - `broadcast`: Wake on broadcast messages
347 - `magic`: Wake on receipt of a magic packet
354 name = mkDefault name;
357 # Renamed or removed options
360 defined = x: x != "_mkMergedOptionModule";
362 (mkChangedOptionModule [ "preferTempAddress" ] [ "tempAddress" ]
364 let bool = getAttrFromPath [ "preferTempAddress" ] config;
365 in if bool then "default" else "enabled"
367 (mkRenamedOptionModule [ "ip4" ] [ "ipv4" "addresses"])
368 (mkRenamedOptionModule [ "ip6" ] [ "ipv6" "addresses"])
369 (mkRemovedOptionModule [ "subnetMask" ] ''
370 Supply a prefix length instead; use option
371 networking.interfaces.<name>.ipv{4,6}.addresses'')
372 (mkMergedOptionModule
373 [ [ "ipAddress" ] [ "prefixLength" ] ]
374 [ "ipv4" "addresses" ]
376 optional (defined ipAddress && defined prefixLength)
377 { address = ipAddress; prefixLength = prefixLength; }))
378 (mkMergedOptionModule
379 [ [ "ipv6Address" ] [ "ipv6PrefixLength" ] ]
380 [ "ipv6" "addresses" ]
382 optional (defined ipv6Address && defined ipv6PrefixLength)
383 { address = ipv6Address; prefixLength = ipv6PrefixLength; }))
385 ({ options.warnings = options.warnings; options.assertions = options.assertions; })
390 vswitchInterfaceOpts = {name, ...}: {
395 description = "Name of the interface";
401 description = "Vlan tag to apply to interface";
403 type = types.nullOr types.int;
408 description = "Openvswitch type to assign to interface";
409 example = "internal";
410 type = types.nullOr types.str;
416 hexChars = stringToCharacters "0123456789abcdef";
418 isHexString = s: all (c: elem c hexChars) (stringToCharacters (toLower s));
423 description = "completely disable IPv6 temporary addresses";
427 description = "generate IPv6 temporary addresses but still use EUI-64 addresses as source addresses";
431 description = "generate IPv6 temporary addresses and use these as source addresses in routing";
434 tempaddrDoc = concatStringsSep "\n"
436 (name: { description, ... }: ''- `"${name}"` to ${description};'')
439 hostidFile = pkgs.runCommand "gen-hostid" { preferLocalBuild = true; } ''
441 ${if pkgs.stdenv.hostPlatform.isBigEndian then ''
442 echo -ne "\x''${hi:0:2}\x''${hi:2:2}\x''${hi:4:2}\x''${hi:6:2}" > $out
444 echo -ne "\x''${hi:6:2}\x''${hi:4:2}\x''${hi:2:2}\x''${hi:0:2}" > $out
456 networking.hostName = mkOption {
457 default = config.system.nixos.distroId;
458 defaultText = literalExpression "config.system.nixos.distroId";
459 # Only allow hostnames without the domain name part (i.e. no FQDNs, see
460 # e.g. "man 5 hostname") and require valid DNS labels (recommended
461 # syntax). Note: We also allow underscores for compatibility/legacy
462 # reasons (as undocumented feature):
463 type = types.strMatching
464 "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$";
466 The name of the machine. Leave it empty if you want to obtain it from a
467 DHCP server (if using DHCP). The hostname must be a valid DNS label (see
468 RFC 1035 section 2.3.1: "Preferred name syntax", RFC 1123 section 2.1:
469 "Host Names and Numbers") and as such must not contain the domain part.
470 This means that the hostname must start with a letter or digit,
471 end with a letter or digit, and have as interior characters only
472 letters, digits, and hyphen. The maximum length is 63 characters.
473 Additionally it is recommended to only use lower-case characters.
474 If (e.g. for legacy reasons) a FQDN is required as the Linux kernel
475 network node hostname (uname --nodename) the option
476 boot.kernel.sysctl."kernel.hostname" can be used as a workaround (but
477 the 64 character limit still applies).
479 WARNING: Do not use underscores (_) or you may run into unexpected issues.
481 # warning until the issues in https://github.com/NixOS/nixpkgs/pull/138978
485 networking.fqdn = mkOption {
488 default = if (cfg.hostName != "" && cfg.domain != null)
489 then "${cfg.hostName}.${cfg.domain}"
491 The FQDN is required but cannot be determined. Please make sure that
492 both networking.hostName and networking.domain are set properly.
494 defaultText = literalExpression ''"''${networking.hostName}.''${networking.domain}"'';
496 The fully qualified domain name (FQDN) of this host. It is the result
497 of combining `networking.hostName` and `networking.domain.` Using this
498 option will result in an evaluation error if the hostname is empty or
499 no domain is specified.
501 Modules that accept a mere `networking.hostName` but prefer a fully qualified
502 domain name may use `networking.fqdnOrHostName` instead.
506 networking.fqdnOrHostName = mkOption {
509 default = if cfg.domain == null then cfg.hostName else cfg.fqdn;
510 defaultText = literalExpression ''
511 if cfg.domain == null then cfg.hostName else cfg.fqdn
514 Either the fully qualified domain name (FQDN), or just the host name if
517 This is a convenience option for modules to read instead of `fqdn` when
518 a mere `hostName` is also an acceptable value; this option does not
519 throw an error when `domain` is unset.
523 networking.hostId = mkOption {
525 example = "4e98920d";
526 type = types.nullOr types.str;
528 The 32-bit host ID of the machine, formatted as 8 hexadecimal characters.
530 You should try to make this ID unique among your machines. You can
531 generate a random 32-bit ID using the following commands:
533 `head -c 8 /etc/machine-id`
535 (this derives it from the machine-id that systemd generates) or
537 `head -c4 /dev/urandom | od -A none -t x4`
539 The primary use case is to ensure when using ZFS that a pool isn't imported
540 accidentally on a wrong machine.
544 networking.enableIPv6 = mkOption {
548 Whether to enable support for IPv6.
552 networking.defaultGateway = mkOption {
555 address = "131.211.84.1";
556 interface = "enp3s0";
558 type = types.nullOr (types.coercedTo types.str gatewayCoerce (types.submodule gatewayOpts));
560 The default gateway. It can be left empty if it is auto-detected through DHCP.
561 It can be specified as a string or an option set along with a network interface.
565 networking.defaultGateway6 = mkOption {
568 address = "2001:4d0:1e04:895::1";
569 interface = "enp3s0";
571 type = types.nullOr (types.coercedTo types.str gatewayCoerce (types.submodule gatewayOpts));
573 The default ipv6 gateway. It can be left empty if it is auto-detected through DHCP.
574 It can be specified as a string or an option set along with a network interface.
578 networking.defaultGatewayWindowSize = mkOption {
581 type = types.nullOr types.int;
583 The window size of the default gateway. It limits maximal data bursts that TCP peers
584 are allowed to send to us.
588 networking.nameservers = mkOption {
589 type = types.listOf types.str;
591 example = ["130.161.158.4" "130.161.33.17"];
593 The list of nameservers. It can be left empty if it is auto-detected through DHCP.
597 networking.search = mkOption {
599 example = [ "example.com" "home.arpa" ];
600 type = types.listOf types.str;
602 The list of search paths used when resolving domain names.
606 networking.domain = mkOption {
608 example = "home.arpa";
609 type = types.nullOr types.str;
611 The domain. It can be left empty if it is auto-detected through DHCP.
615 networking.useHostResolvConf = mkOption {
619 In containers, whether to use the
620 {file}`resolv.conf` supplied by the host.
624 networking.localCommands = mkOption {
627 example = "text=anything; echo You can put $text here.";
629 Shell commands to be executed at the end of the
630 `network-setup` systemd service. Note that if
631 you are using DHCP to obtain the network configuration,
632 interfaces may not be fully configured yet.
636 networking.interfaces = mkOption {
639 { eth0.ipv4.addresses = [ {
640 address = "131.211.84.78";
645 The configuration for each network interface.
647 Please note that {option}`systemd.network.netdevs` has more features
648 and is better maintained. When building new things, it is advised to
651 type = with types; attrsOf (submodule interfaceOpts);
654 networking.vswitches = mkOption {
657 { vs0.interfaces = { eth0 = { }; lo1 = { type="internal"; }; };
658 vs1.interfaces = [ { name = "eth2"; } { name = "lo2"; type="internal"; } ];
661 This option allows you to define Open vSwitches that connect
662 physical networks together. The value of this option is an
663 attribute set. Each attribute specifies a vswitch, with the
664 attribute name specifying the name of the vswitch's network
668 type = with types; attrsOf (submodule {
672 interfaces = mkOption {
673 description = "The physical network interfaces connected by the vSwitch.";
674 type = with types; attrsOf (submodule vswitchInterfaceOpts);
677 controllers = mkOption {
678 type = types.listOf types.str;
680 example = [ "ptcp:6653:[::1]" ];
682 Specify the controller targets. For the allowed options see `man 8 ovs-vsctl`.
686 openFlowRules = mkOption {
693 OpenFlow rules to insert into the Open vSwitch. All `openFlowRules` are
694 loaded with `ovs-ofctl` within one atomic operation.
698 # TODO: custom "openflow version" type, with list from existing openflow protocols
699 supportedOpenFlowVersions = mkOption {
700 type = types.listOf types.str;
701 example = [ "OpenFlow10" "OpenFlow13" "OpenFlow14" ];
702 default = [ "OpenFlow13" ];
704 Supported versions to enable on this switch.
708 # TODO: use same type as elements from supportedOpenFlowVersions
709 openFlowVersion = mkOption {
711 default = "OpenFlow13";
713 Version of OpenFlow protocol to use when communicating with the switch internally (e.g. with `openFlowRules`).
717 extraOvsctlCmds = mkOption {
721 set-fail-mode <switch_name> secure
722 set Bridge <switch_name> stp_enable=true
725 Commands to manipulate the Open vSwitch database. Every line executed with `ovs-vsctl`.
726 All commands are bundled together with the operations for adding the interfaces
727 into one atomic operation.
737 networking.bridges = mkOption {
740 { br0.interfaces = [ "eth0" "eth1" ];
741 br1.interfaces = [ "eth2" "wlan0" ];
744 This option allows you to define Ethernet bridge devices
745 that connect physical networks together. The value of this
746 option is an attribute set. Each attribute specifies a
747 bridge, with the attribute name specifying the name of the
748 bridge's network interface.
751 type = with types; attrsOf (submodule {
755 interfaces = mkOption {
756 example = [ "eth0" "eth1" ];
757 type = types.listOf types.str;
758 description = "The physical network interfaces connected by the bridge.";
764 description = "Whether the bridge interface should enable rstp.";
775 driverOptionsExample = ''
778 mode = "active-backup";
783 example = literalExpression ''
786 interfaces = [ "eth0" "wlan0" ];
787 driverOptions = ${driverOptionsExample};
789 anotherBond.interfaces = [ "enp4s0f0" "enp4s0f1" "enp5s0f0" "enp5s0f1" ];
793 This option allows you to define bond devices that aggregate multiple,
794 underlying networking interfaces together. The value of this option is
795 an attribute set. Each attribute specifies a bond, with the attribute
796 name specifying the name of the bond's network interface
799 type = with types; attrsOf (submodule {
803 interfaces = mkOption {
804 example = [ "enp4s0f0" "enp4s0f1" "wlan0" ];
805 type = types.listOf types.str;
806 description = "The interfaces to bond together";
809 driverOptions = mkOption {
810 type = types.attrsOf types.str;
812 example = literalExpression driverOptionsExample;
814 Options for the bonding driver.
815 Documentation can be found in
816 <https://www.kernel.org/doc/Documentation/networking/bonding.txt>
821 lacp_rate = mkOption {
824 type = types.nullOr types.str;
826 DEPRECATED, use `driverOptions`.
827 Option specifying the rate in which we'll ask our link partner
828 to transmit LACPDU packets in 802.3ad mode.
835 type = types.nullOr types.int;
837 DEPRECATED, use `driverOptions`.
838 Miimon is the number of millisecond in between each round of polling
839 by the device driver for failed links. By default polling is not
840 enabled and the driver is trusted to properly detect and handle
847 example = "active-backup";
848 type = types.nullOr types.str;
850 DEPRECATED, use `driverOptions`.
851 The mode which the bond will be running. The default mode for
852 the bonding driver is balance-rr, optimizing for throughput.
853 More information about valid modes can be found at
854 https://www.kernel.org/doc/Documentation/networking/bonding.txt
858 xmit_hash_policy = mkOption {
860 example = "layer2+3";
861 type = types.nullOr types.str;
863 DEPRECATED, use `driverOptions`.
864 Selects the transmit hash policy to use for slave selection in
865 balance-xor, 802.3ad, and tlb modes.
874 networking.macvlans = mkOption {
876 example = literalExpression ''
879 interface = "enp2s0";
885 This option allows you to define macvlan interfaces which should
886 be automatically created.
888 type = with types; attrsOf (submodule {
891 interface = mkOption {
894 description = "The interface the macvlan will transmit packets through.";
899 type = types.nullOr types.str;
901 description = "The mode of the macvlan device.";
909 networking.fooOverUDP = mkOption {
913 primary = { port = 9001; local = { address = "192.0.2.1"; dev = "eth0"; }; };
914 backup = { port = 9002; };
917 This option allows you to configure Foo Over UDP and Generic UDP Encapsulation
918 endpoints. See {manpage}`ip-fou(8)` for details.
920 type = with types; attrsOf (submodule {
925 Local port of the encapsulation UDP socket.
929 protocol = mkOption {
930 type = nullOr (ints.between 1 255);
933 Protocol number of the encapsulated packets. Specifying `null`
934 (the default) creates a GUE endpoint, specifying a protocol number will create
940 type = nullOr (submodule {
945 Local address to bind to. The address must be available when the FOU
946 endpoint is created, using the scripted network setup this can be achieved
947 either by setting `dev` or adding dependency information to
948 `systemd.services.<name>-fou-encap`; it isn't supported
958 Network device to bind to.
964 example = { address = "203.0.113.22"; };
966 Local address (and optionally device) to bind to using the given port.
973 networking.sits = mkOption {
975 example = literalExpression ''
983 remote = "192.168.0.1";
990 This option allows you to define 6-to-4 interfaces which should be automatically created.
992 type = with types; attrsOf (submodule {
996 type = types.nullOr types.str;
998 example = "10.0.0.1";
1000 The address of the remote endpoint to forward traffic over.
1005 type = types.nullOr types.str;
1007 example = "10.0.0.22";
1009 The address of the local endpoint which the remote
1010 side should send packets to.
1015 type = types.nullOr types.int;
1019 The time-to-live of the connection to the remote tunnel endpoint.
1024 type = types.nullOr types.str;
1026 example = "enp4s0f0";
1028 The underlying network device on which the tunnel resides.
1032 encapsulation = with types; mkOption {
1033 type = nullOr (submodule {
1036 type = enum [ "fou" "gue" ];
1038 Selects encapsulation type. See
1039 {manpage}`ip-link(8)` for details.
1047 Destination port for encapsulated packets.
1051 sourcePort = mkOption {
1052 type = nullOr types.port;
1056 Source port for encapsulated packets. Will be chosen automatically by
1057 the kernel if unset.
1063 example = { type = "fou"; port = 9001; };
1065 Configures encapsulation in UDP packets.
1074 networking.greTunnels = mkOption {
1076 example = literalExpression ''
1079 remote = "10.0.0.1";
1080 local = "10.0.0.22";
1086 remote = "fd7a:5634::1";
1087 local = "fd7a:5634::2";
1095 This option allows you to define Generic Routing Encapsulation (GRE) tunnels.
1097 type = with types; attrsOf (submodule {
1101 type = types.nullOr types.str;
1103 example = "10.0.0.1";
1105 The address of the remote endpoint to forward traffic over.
1110 type = types.nullOr types.str;
1112 example = "10.0.0.22";
1114 The address of the local endpoint which the remote
1115 side should send packets to.
1120 type = types.nullOr types.str;
1122 example = "enp4s0f0";
1124 The underlying network device on which the tunnel resides.
1129 type = types.nullOr types.int;
1133 The time-to-live/hoplimit of the connection to the remote tunnel endpoint.
1138 type = with types; enum [ "tun" "tap" "tun6" "tap6" ];
1148 Whether the tunnel routes layer 2 (tap) or layer 3 (tun) traffic.
1155 networking.vlans = mkOption {
1157 example = literalExpression ''
1161 interface = "enp3s0";
1165 interface = "wlan0";
1170 This option allows you to define vlan devices that tag packets
1171 on top of a physical interface. The value of this option is an
1172 attribute set. Each attribute specifies a vlan, with the name
1173 specifying the name of the vlan interface.
1176 type = with types; attrsOf (submodule {
1183 description = "The vlan identifier";
1186 interface = mkOption {
1189 description = "The interface the vlan will transmit packets through.";
1198 networking.wlanInterfaces = mkOption {
1200 example = literalExpression ''
1208 mac = "02:00:00:00:00:01";
1212 mac = "02:00:00:00:00:02";
1216 mac = "02:00:00:00:00:03";
1221 Creating multiple WLAN interfaces on top of one physical WLAN device (NIC).
1223 The name of the WLAN interface corresponds to the name of the attribute.
1224 A NIC is referenced by the persistent device name of the WLAN interface that
1225 `udev` assigns to a NIC by default.
1226 If a NIC supports multiple WLAN interfaces, then the one NIC can be used as
1227 `device` for multiple WLAN interfaces.
1228 If a NIC is used for creating WLAN interfaces, then the default WLAN interface
1229 with a persistent device name form `udev` is not created.
1230 A WLAN interface with the persistent name assigned from `udev`
1231 would have to be created explicitly.
1234 type = with types; attrsOf (submodule {
1241 description = "The name of the underlying hardware WLAN device as assigned by `udev`.";
1245 type = types.enum [ "managed" "ibss" "monitor" "mesh" "wds" ];
1246 default = "managed";
1249 The type of the WLAN interface.
1250 The type has to be supported by the underlying hardware of the device.
1255 type = types.nullOr types.str;
1257 description = "MeshID of interface with type `mesh`.";
1261 type = with types; nullOr (enum [ "none" "fcsfail" "control" "otherbss" "cook" "active" ]);
1263 example = "control";
1265 Flags for interface of type `monitor`.
1269 fourAddr = mkOption {
1270 type = types.nullOr types.bool;
1272 description = "Whether to enable `4-address mode` with type `managed`.";
1276 type = types.nullOr types.str;
1278 example = "02:00:00:00:00:01";
1280 MAC address to use for the device. If `null`, then the MAC of the
1281 underlying hardware WLAN device is used.
1283 INFO: Locally administered MAC addresses are of the form:
1297 networking.useDHCP = mkOption {
1301 Whether to use DHCP to obtain an IP address and other
1302 configuration for all network interfaces that do not have any manually
1303 configured IPv4 addresses.
1307 networking.useNetworkd = mkOption {
1311 Whether we should use networkd as the network configuration backend or
1312 the legacy script based system. Note that this option is experimental,
1313 enable at your own risk.
1317 networking.tempAddresses = mkOption {
1318 default = if cfg.enableIPv6 then "default" else "disabled";
1319 defaultText = literalExpression ''
1320 if ''${config.${opt.enableIPv6}} then "default" else "disabled"
1322 type = types.enum (lib.attrNames tempaddrValues);
1324 Whether to enable IPv6 Privacy Extensions for interfaces not
1325 configured explicitly in
1326 [](#opt-networking.interfaces._name_.tempAddress).
1328 This sets the ipv6.conf.*.use_tempaddr sysctl for all
1329 interfaces. Possible values are:
1338 ###### implementation
1342 warnings = (concatMap (i: i.warnings) interfaces) ++ (lib.optional
1343 (config.systemd.network.enable && cfg.useDHCP && !cfg.useNetworkd) ''
1344 The combination of `systemd.network.enable = true`, `networking.useDHCP = true` and `networking.useNetworkd = false` can cause both networkd and dhcpcd to manage the same interfaces. This can lead to loss of networking. It is recommended you choose only one of networkd (by also enabling `networking.useNetworkd`) or scripting (by disabling `systemd.network.enable`)
1348 (forEach interfaces (i: {
1349 # With the linux kernel, interface name length is limited by IFNAMSIZ
1350 # to 16 bytes, including the trailing null byte.
1351 # See include/linux/if.h in the kernel sources
1352 assertion = stringLength i.name < 16;
1354 The name of networking.interfaces."${i.name}" is too long, it needs to be less than 16 characters.
1356 })) ++ (forEach slaveIfs (i: {
1357 assertion = i.ipv4.addresses == [ ] && i.ipv6.addresses == [ ];
1359 The networking.interfaces."${i.name}" must not have any defined ips when it is a slave.
1361 })) ++ (forEach interfaces (i: {
1362 assertion = i.tempAddress != "disabled" -> cfg.enableIPv6;
1364 Temporary addresses are only needed when IPv6 is enabled.
1366 })) ++ (forEach interfaces (i: {
1367 assertion = (i.virtual && i.virtualType == "tun") -> i.macAddress == null;
1369 Setting a MAC Address for tun device ${i.name} isn't supported.
1373 assertion = cfg.hostId == null || (stringLength cfg.hostId == 8 && isHexString cfg.hostId);
1374 message = "Invalid value given to the networking.hostId option.";
1378 boot.kernelModules = [ ]
1379 ++ optional hasVirtuals "tun"
1380 ++ optional hasSits "sit"
1381 ++ optional hasGres "gre"
1382 ++ optional hasBonds "bonding"
1383 ++ optional hasFous "fou";
1385 boot.extraModprobeConfig =
1386 # This setting is intentional as it prevents default bond devices
1387 # from being created.
1388 optionalString hasBonds "options bonding max_bonds=0";
1390 boot.kernel.sysctl = {
1391 "net.ipv4.conf.all.forwarding" = mkDefault (any (i: i.proxyARP) interfaces);
1392 "net.ipv6.conf.all.disable_ipv6" = mkDefault (!cfg.enableIPv6);
1393 "net.ipv6.conf.default.disable_ipv6" = mkDefault (!cfg.enableIPv6);
1394 # allow all users to do ICMP echo requests (ping)
1395 "net.ipv4.ping_group_range" = mkDefault "0 2147483647";
1396 # networkmanager falls back to "/proc/sys/net/ipv6/conf/default/use_tempaddr"
1397 "net.ipv6.conf.default.use_tempaddr" = tempaddrValues.${cfg.tempAddresses}.sysctl;
1398 } // listToAttrs (forEach interfaces
1399 (i: nameValuePair "net.ipv4.conf.${replaceStrings ["."] ["/"] i.name}.proxy_arp" i.proxyARP))
1400 // listToAttrs (forEach interfaces
1402 opt = i.tempAddress;
1403 val = tempaddrValues.${opt}.sysctl;
1404 in nameValuePair "net.ipv6.conf.${replaceStrings ["."] ["/"] i.name}.use_tempaddr" val));
1406 systemd.services.domainname = lib.mkIf (cfg.domain != null) {
1407 wantedBy = [ "sysinit.target" ];
1408 before = [ "sysinit.target" "shutdown.target" ];
1409 conflicts = [ "shutdown.target" ];
1410 unitConfig.DefaultDependencies = false;
1411 serviceConfig.ExecStart = ''${pkgs.nettools}/bin/domainname "${cfg.domain}"'';
1412 serviceConfig.Type = "oneshot";
1415 environment.etc.hostid = mkIf (cfg.hostId != null) { source = hostidFile; };
1416 boot.initrd.systemd.contents."/etc/hostid" = mkIf (cfg.hostId != null) { source = hostidFile; };
1418 # static hostname configuration needed for hostnamectl and the
1419 # org.freedesktop.hostname1 dbus service (both provided by systemd)
1420 environment.etc.hostname = mkIf (cfg.hostName != "")
1422 text = cfg.hostName + "\n";
1425 environment.systemPackages =
1431 ++ optionals config.networking.wireless.enable [
1432 pkgs.wirelesstools # FIXME: obsolete?
1437 # Wake-on-LAN configuration is shared by the scripted and networkd backends.
1438 systemd.network.links = pipe interfaces [
1439 (filter (i: i.wakeOnLan.enable))
1440 (map (i: nameValuePair "40-${i.name}" {
1441 matchConfig.OriginalName = i.name;
1442 linkConfig.WakeOnLan = concatStringsSep " " i.wakeOnLan.policy;
1447 systemd.services = {
1448 network-local-commands = {
1449 description = "Extra networking commands.";
1450 before = [ "network.target" ];
1451 wantedBy = [ "network.target" ];
1452 after = [ "network-pre.target" ];
1453 unitConfig.ConditionCapability = "CAP_NET_ADMIN";
1454 path = [ pkgs.iproute2 ];
1455 serviceConfig.Type = "oneshot";
1456 serviceConfig.RemainAfterExit = true;
1458 # Run any user-specified commands.
1459 ${cfg.localCommands}
1463 services.mstpd = mkIf needsMstpd { enable = true; };
1465 virtualisation.vswitch = mkIf (cfg.vswitches != { }) { enable = true; };
1467 services.udev.packages = [
1468 (pkgs.writeTextFile rec {
1469 name = "ipv6-privacy-extensions.rules";
1470 destination = "/etc/udev/rules.d/98-${name}";
1472 sysctl-value = tempaddrValues.${cfg.tempAddresses}.sysctl;
1474 # enable and prefer IPv6 privacy addresses by default
1475 ACTION=="add", SUBSYSTEM=="net", RUN+="${pkgs.bash}/bin/sh -c 'echo ${sysctl-value} > /proc/sys/net/ipv6/conf/$name/use_tempaddr'"
1478 (pkgs.writeTextFile rec {
1479 name = "ipv6-privacy-extensions.rules";
1480 destination = "/etc/udev/rules.d/99-${name}";
1481 text = concatMapStrings (i:
1483 opt = i.tempAddress;
1484 val = tempaddrValues.${opt}.sysctl;
1485 msg = tempaddrValues.${opt}.description;
1488 # override to ${msg} for ${i.name}
1489 ACTION=="add", SUBSYSTEM=="net", NAME=="${i.name}", RUN+="${pkgs.procps}/bin/sysctl net.ipv6.conf.${replaceStrings ["."] ["/"] i.name}.use_tempaddr=${val}"
1490 '') (filter (i: i.tempAddress != cfg.tempAddresses) interfaces);
1492 ] ++ lib.optional (cfg.wlanInterfaces != {})
1493 (pkgs.writeTextFile {
1494 name = "99-zzz-40-wlanInterfaces.rules";
1495 destination = "/etc/udev/rules.d/99-zzz-40-wlanInterfaces.rules";
1498 # Collect all interfaces that are defined for a device
1499 # as device:interface key:value pairs.
1500 wlanDeviceInterfaces =
1502 allDevices = unique (mapAttrsToList (_: v: v.device) cfg.wlanInterfaces);
1503 interfacesOfDevice = d: filterAttrs (_: v: v.device == d) cfg.wlanInterfaces;
1505 genAttrs allDevices (d: interfacesOfDevice d);
1507 # Convert device:interface key:value pairs into a list, and if it exists,
1508 # place the interface which is named after the device at the beginning.
1509 wlanListDeviceFirst = device: interfaces:
1510 if hasAttr device interfaces
1511 then mapAttrsToList (n: v: v//{_iName=n;}) (filterAttrs (n: _: n==device) interfaces) ++ mapAttrsToList (n: v: v//{_iName=n;}) (filterAttrs (n: _: n!=device) interfaces)
1512 else mapAttrsToList (n: v: v // {_iName = n;}) interfaces;
1514 # Udev script to execute for the default WLAN interface with the persistend udev name.
1515 # The script creates the required, new WLAN interfaces interfaces and configures the
1516 # existing, default interface.
1517 curInterfaceScript = device: current: new: pkgs.writeScript "udev-run-script-wlan-interfaces-${device}.sh" ''
1518 #!${pkgs.runtimeShell}
1519 # Change the wireless phy device to a predictable name.
1520 ${pkgs.iw}/bin/iw phy `${pkgs.coreutils}/bin/cat /sys/class/net/$INTERFACE/phy80211/name` set name ${device}
1522 # Add new WLAN interfaces
1523 ${flip concatMapStrings new (i: ''
1524 ${pkgs.iw}/bin/iw phy ${device} interface add ${i._iName} type managed
1527 # Configure the current interface
1528 ${pkgs.iw}/bin/iw dev ${device} set type ${current.type}
1529 ${optionalString (current.type == "mesh" && current.meshID!=null) "${pkgs.iw}/bin/iw dev ${device} set meshid ${current.meshID}"}
1530 ${optionalString (current.type == "monitor" && current.flags!=null) "${pkgs.iw}/bin/iw dev ${device} set monitor ${current.flags}"}
1531 ${optionalString (current.type == "managed" && current.fourAddr!=null) "${pkgs.iw}/bin/iw dev ${device} set 4addr ${if current.fourAddr then "on" else "off"}"}
1532 ${optionalString (current.mac != null) "${pkgs.iproute2}/bin/ip link set dev ${device} address ${current.mac}"}
1535 # Udev script to execute for a new WLAN interface. The script configures the new WLAN interface.
1536 newInterfaceScript = new: pkgs.writeScript "udev-run-script-wlan-interfaces-${new._iName}.sh" ''
1537 #!${pkgs.runtimeShell}
1538 # Configure the new interface
1539 ${pkgs.iw}/bin/iw dev ${new._iName} set type ${new.type}
1540 ${optionalString (new.type == "mesh" && new.meshID!=null) "${pkgs.iw}/bin/iw dev ${new._iName} set meshid ${new.meshID}"}
1541 ${optionalString (new.type == "monitor" && new.flags!=null) "${pkgs.iw}/bin/iw dev ${new._iName} set monitor ${new.flags}"}
1542 ${optionalString (new.type == "managed" && new.fourAddr!=null) "${pkgs.iw}/bin/iw dev ${new._iName} set 4addr ${if new.fourAddr then "on" else "off"}"}
1543 ${optionalString (new.mac != null) "${pkgs.iproute2}/bin/ip link set dev ${new._iName} address ${new.mac}"}
1546 # Udev attributes for systemd to name the device and to create a .device target.
1547 systemdAttrs = n: ''NAME:="${n}", ENV{INTERFACE}="${n}", ENV{SYSTEMD_ALIAS}="/sys/subsystem/net/devices/${n}", TAG+="systemd"'';
1549 flip (concatMapStringsSep "\n") (attrNames wlanDeviceInterfaces) (device:
1551 interfaces = wlanListDeviceFirst device wlanDeviceInterfaces.${device};
1552 curInterface = elemAt interfaces 0;
1553 newInterfaces = drop 1 interfaces;
1555 # It is important to have that rule first as overwriting the NAME attribute also prevents the
1556 # next rules from matching.
1557 ${flip (concatMapStringsSep "\n") (wlanListDeviceFirst device wlanDeviceInterfaces.${device}) (interface:
1558 ''ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", ENV{INTERFACE}=="${interface._iName}", ${systemdAttrs interface._iName}, RUN+="${newInterfaceScript interface}"'')}
1560 # Add the required, new WLAN interfaces to the default WLAN interface with the
1561 # persistent, default name as assigned by udev.
1562 ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", NAME=="${device}", ${systemdAttrs curInterface._iName}, RUN+="${curInterfaceScript device curInterface newInterfaces}"
1563 # Generate the same systemd events for both 'add' and 'move' udev events.
1564 ACTION=="move", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", NAME=="${device}", ${systemdAttrs curInterface._iName}