You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

network-interfaces.nix 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. { config, options, lib, pkgs, utils, ... }:
  2. with lib;
  3. with utils;
  4. let
  5. cfg = config.networking;
  6. interfaces = attrValues cfg.interfaces;
  7. hasVirtuals = any (i: i.virtual) interfaces;
  8. hasSits = cfg.sits != { };
  9. hasBonds = cfg.bonds != { };
  10. slaves = concatMap (i: i.interfaces) (attrValues cfg.bonds)
  11. ++ concatMap (i: i.interfaces) (attrValues cfg.bridges)
  12. ++ concatMap (i: i.interfaces) (attrValues cfg.vswitches);
  13. slaveIfs = map (i: cfg.interfaces.${i}) (filter (i: cfg.interfaces ? ${i}) slaves);
  14. rstpBridges = flip filterAttrs cfg.bridges (_: { rstp, ... }: rstp);
  15. needsMstpd = rstpBridges != { };
  16. bridgeStp = optional needsMstpd (pkgs.writeTextFile {
  17. name = "bridge-stp";
  18. executable = true;
  19. destination = "/bin/bridge-stp";
  20. text = ''
  21. #!${pkgs.runtimeShell} -e
  22. export PATH="${pkgs.mstpd}/bin"
  23. BRIDGES=(${concatStringsSep " " (attrNames rstpBridges)})
  24. for BRIDGE in $BRIDGES; do
  25. if [ "$BRIDGE" = "$1" ]; then
  26. if [ "$2" = "start" ]; then
  27. mstpctl addbridge "$BRIDGE"
  28. exit 0
  29. elif [ "$2" = "stop" ]; then
  30. mstpctl delbridge "$BRIDGE"
  31. exit 0
  32. fi
  33. exit 1
  34. fi
  35. done
  36. exit 1
  37. '';
  38. });
  39. # We must escape interfaces due to the systemd interpretation
  40. subsystemDevice = interface:
  41. "sys-subsystem-net-devices-${escapeSystemdPath interface}.device";
  42. addrOpts = v:
  43. assert v == 4 || v == 6;
  44. { options = {
  45. address = mkOption {
  46. type = types.str;
  47. description = ''
  48. IPv${toString v} address of the interface. Leave empty to configure the
  49. interface using DHCP.
  50. '';
  51. };
  52. prefixLength = mkOption {
  53. type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
  54. description = ''
  55. Subnet mask of the interface, specified as the number of
  56. bits in the prefix (<literal>${if v == 4 then "24" else "64"}</literal>).
  57. '';
  58. };
  59. };
  60. };
  61. routeOpts = v:
  62. { options = {
  63. address = mkOption {
  64. type = types.str;
  65. description = "IPv${toString v} address of the network.";
  66. };
  67. prefixLength = mkOption {
  68. type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
  69. description = ''
  70. Subnet mask of the network, specified as the number of
  71. bits in the prefix (<literal>${if v == 4 then "24" else "64"}</literal>).
  72. '';
  73. };
  74. via = mkOption {
  75. type = types.nullOr types.str;
  76. default = null;
  77. description = "IPv${toString v} address of the next hop.";
  78. };
  79. options = mkOption {
  80. type = types.attrsOf types.str;
  81. default = { };
  82. example = { mtu = "1492"; window = "524288"; };
  83. description = ''
  84. Other route options. See the symbol <literal>OPTIONS</literal>
  85. in the <literal>ip-route(8)</literal> manual page for the details.
  86. '';
  87. };
  88. };
  89. };
  90. gatewayCoerce = address: { inherit address; };
  91. gatewayOpts = { ... }: {
  92. options = {
  93. address = mkOption {
  94. type = types.str;
  95. description = "The default gateway address.";
  96. };
  97. interface = mkOption {
  98. type = types.nullOr types.str;
  99. default = null;
  100. example = "enp0s3";
  101. description = "The default gateway interface.";
  102. };
  103. metric = mkOption {
  104. type = types.nullOr types.int;
  105. default = null;
  106. example = 42;
  107. description = "The default gateway metric/preference.";
  108. };
  109. };
  110. };
  111. interfaceOpts = { name, ... }: {
  112. options = {
  113. name = mkOption {
  114. example = "eth0";
  115. type = types.str;
  116. description = "Name of the interface.";
  117. };
  118. preferTempAddress = mkOption {
  119. type = types.bool;
  120. default = cfg.enableIPv6;
  121. defaultText = literalExample "config.networking.enableIPv6";
  122. description = ''
  123. When using SLAAC prefer a temporary (IPv6) address over the EUI-64
  124. address for originating connections. This is used to reduce tracking.
  125. '';
  126. };
  127. useDHCP = mkOption {
  128. type = types.nullOr types.bool;
  129. default = null;
  130. description = ''
  131. Whether this interface should be configured with dhcp.
  132. Null implies the old behavior which depends on whether ip addresses
  133. are specified or not.
  134. '';
  135. };
  136. ipv4.addresses = mkOption {
  137. default = [ ];
  138. example = [
  139. { address = "10.0.0.1"; prefixLength = 16; }
  140. { address = "192.168.1.1"; prefixLength = 24; }
  141. ];
  142. type = with types; listOf (submodule (addrOpts 4));
  143. description = ''
  144. List of IPv4 addresses that will be statically assigned to the interface.
  145. '';
  146. };
  147. ipv6.addresses = mkOption {
  148. default = [ ];
  149. example = [
  150. { address = "fdfd:b3f0:482::1"; prefixLength = 48; }
  151. { address = "2001:1470:fffd:2098::e006"; prefixLength = 64; }
  152. ];
  153. type = with types; listOf (submodule (addrOpts 6));
  154. description = ''
  155. List of IPv6 addresses that will be statically assigned to the interface.
  156. '';
  157. };
  158. ipv4.routes = mkOption {
  159. default = [];
  160. example = [
  161. { address = "10.0.0.0"; prefixLength = 16; }
  162. { address = "192.168.2.0"; prefixLength = 24; via = "192.168.1.1"; }
  163. ];
  164. type = with types; listOf (submodule (routeOpts 4));
  165. description = ''
  166. List of extra IPv4 static routes that will be assigned to the interface.
  167. '';
  168. };
  169. ipv6.routes = mkOption {
  170. default = [];
  171. example = [
  172. { address = "fdfd:b3f0::"; prefixLength = 48; }
  173. { address = "2001:1470:fffd:2098::"; prefixLength = 64; via = "fdfd:b3f0::1"; }
  174. ];
  175. type = with types; listOf (submodule (routeOpts 6));
  176. description = ''
  177. List of extra IPv6 static routes that will be assigned to the interface.
  178. '';
  179. };
  180. macAddress = mkOption {
  181. default = null;
  182. example = "00:11:22:33:44:55";
  183. type = types.nullOr (types.str);
  184. description = ''
  185. MAC address of the interface. Leave empty to use the default.
  186. '';
  187. };
  188. mtu = mkOption {
  189. default = null;
  190. example = 9000;
  191. type = types.nullOr types.int;
  192. description = ''
  193. MTU size for packets leaving the interface. Leave empty to use the default.
  194. '';
  195. };
  196. virtual = mkOption {
  197. default = false;
  198. type = types.bool;
  199. description = ''
  200. Whether this interface is virtual and should be created by tunctl.
  201. This is mainly useful for creating bridges between a host and a virtual
  202. network such as VPN or a virtual machine.
  203. '';
  204. };
  205. virtualOwner = mkOption {
  206. default = "root";
  207. type = types.str;
  208. description = ''
  209. In case of a virtual device, the user who owns it.
  210. '';
  211. };
  212. virtualType = mkOption {
  213. default = if hasPrefix "tun" name then "tun" else "tap";
  214. defaultText = literalExample ''if hasPrefix "tun" name then "tun" else "tap"'';
  215. type = with types; enum [ "tun" "tap" ];
  216. description = ''
  217. The type of interface to create.
  218. The default is TUN for an interface name starting
  219. with "tun", otherwise TAP.
  220. '';
  221. };
  222. proxyARP = mkOption {
  223. default = false;
  224. type = types.bool;
  225. description = ''
  226. Turn on proxy_arp for this device (and proxy_ndp for ipv6).
  227. This is mainly useful for creating pseudo-bridges between a real
  228. interface and a virtual network such as VPN or a virtual machine for
  229. interfaces that don't support real bridging (most wlan interfaces).
  230. As ARP proxying acts slightly above the link-layer, below-ip traffic
  231. isn't bridged, so things like DHCP won't work. The advantage above
  232. using NAT lies in the fact that no IP addresses are shared, so all
  233. hosts are reachable/routeable.
  234. WARNING: turns on ip-routing, so if you have multiple interfaces, you
  235. should think of the consequence and setup firewall rules to limit this.
  236. '';
  237. };
  238. };
  239. config = {
  240. name = mkDefault name;
  241. };
  242. # Renamed or removed options
  243. imports =
  244. let
  245. defined = x: x != "_mkMergedOptionModule";
  246. in [
  247. (mkRenamedOptionModule [ "ip4" ] [ "ipv4" "addresses"])
  248. (mkRenamedOptionModule [ "ip6" ] [ "ipv6" "addresses"])
  249. (mkRemovedOptionModule [ "subnetMask" ] ''
  250. Supply a prefix length instead; use option
  251. networking.interfaces.<name>.ipv{4,6}.addresses'')
  252. (mkMergedOptionModule
  253. [ [ "ipAddress" ] [ "prefixLength" ] ]
  254. [ "ipv4" "addresses" ]
  255. (cfg: with cfg;
  256. optional (defined ipAddress && defined prefixLength)
  257. { address = ipAddress; prefixLength = prefixLength; }))
  258. (mkMergedOptionModule
  259. [ [ "ipv6Address" ] [ "ipv6PrefixLength" ] ]
  260. [ "ipv6" "addresses" ]
  261. (cfg: with cfg;
  262. optional (defined ipv6Address && defined ipv6PrefixLength)
  263. { address = ipv6Address; prefixLength = ipv6PrefixLength; }))
  264. ({ options.warnings = options.warnings; options.assertions = options.assertions; })
  265. ];
  266. };
  267. hexChars = stringToCharacters "0123456789abcdef";
  268. isHexString = s: all (c: elem c hexChars) (stringToCharacters (toLower s));
  269. in
  270. {
  271. ###### interface
  272. options = {
  273. networking.hostName = mkOption {
  274. default = "nixos";
  275. type = types.str;
  276. description = ''
  277. The name of the machine. Leave it empty if you want to obtain
  278. it from a DHCP server (if using DHCP).
  279. '';
  280. };
  281. networking.hostId = mkOption {
  282. default = null;
  283. example = "4e98920d";
  284. type = types.nullOr types.str;
  285. description = ''
  286. The 32-bit host ID of the machine, formatted as 8 hexadecimal characters.
  287. You should try to make this ID unique among your machines. You can
  288. generate a random 32-bit ID using the following commands:
  289. <literal>head -c 8 /etc/machine-id</literal>
  290. (this derives it from the machine-id that systemd generates) or
  291. <literal>head -c4 /dev/urandom | od -A none -t x4</literal>
  292. '';
  293. };
  294. networking.enableIPv6 = mkOption {
  295. default = true;
  296. type = types.bool;
  297. description = ''
  298. Whether to enable support for IPv6.
  299. '';
  300. };
  301. networking.defaultGateway = mkOption {
  302. default = null;
  303. example = {
  304. address = "131.211.84.1";
  305. interface = "enp3s0";
  306. };
  307. type = types.nullOr (types.coercedTo types.str gatewayCoerce (types.submodule gatewayOpts));
  308. description = ''
  309. The default gateway. It can be left empty if it is auto-detected through DHCP.
  310. It can be specified as a string or an option set along with a network interface.
  311. '';
  312. };
  313. networking.defaultGateway6 = mkOption {
  314. default = null;
  315. example = {
  316. address = "2001:4d0:1e04:895::1";
  317. interface = "enp3s0";
  318. };
  319. type = types.nullOr (types.coercedTo types.str gatewayCoerce (types.submodule gatewayOpts));
  320. description = ''
  321. The default ipv6 gateway. It can be left empty if it is auto-detected through DHCP.
  322. It can be specified as a string or an option set along with a network interface.
  323. '';
  324. };
  325. networking.defaultGatewayWindowSize = mkOption {
  326. default = null;
  327. example = 524288;
  328. type = types.nullOr types.int;
  329. description = ''
  330. The window size of the default gateway. It limits maximal data bursts that TCP peers
  331. are allowed to send to us.
  332. '';
  333. };
  334. networking.nameservers = mkOption {
  335. type = types.listOf types.str;
  336. default = [];
  337. example = ["130.161.158.4" "130.161.33.17"];
  338. description = ''
  339. The list of nameservers. It can be left empty if it is auto-detected through DHCP.
  340. '';
  341. };
  342. networking.search = mkOption {
  343. default = [];
  344. example = [ "example.com" "local.domain" ];
  345. type = types.listOf types.str;
  346. description = ''
  347. The list of search paths used when resolving domain names.
  348. '';
  349. };
  350. networking.domain = mkOption {
  351. default = null;
  352. example = "home";
  353. type = types.nullOr types.str;
  354. description = ''
  355. The domain. It can be left empty if it is auto-detected through DHCP.
  356. '';
  357. };
  358. networking.useHostResolvConf = mkOption {
  359. type = types.bool;
  360. default = false;
  361. description = ''
  362. In containers, whether to use the
  363. <filename>resolv.conf</filename> supplied by the host.
  364. '';
  365. };
  366. networking.localCommands = mkOption {
  367. type = types.lines;
  368. default = "";
  369. example = "text=anything; echo You can put $text here.";
  370. description = ''
  371. Shell commands to be executed at the end of the
  372. <literal>network-setup</literal> systemd service. Note that if
  373. you are using DHCP to obtain the network configuration,
  374. interfaces may not be fully configured yet.
  375. '';
  376. };
  377. networking.interfaces = mkOption {
  378. default = {};
  379. example =
  380. { eth0.ipv4.addresses = [ {
  381. address = "131.211.84.78";
  382. prefixLength = 25;
  383. } ];
  384. };
  385. description = ''
  386. The configuration for each network interface. If
  387. <option>networking.useDHCP</option> is true, then every
  388. interface not listed here will be configured using DHCP.
  389. '';
  390. type = with types; loaOf (submodule interfaceOpts);
  391. };
  392. networking.vswitches = mkOption {
  393. default = { };
  394. example =
  395. { vs0.interfaces = [ "eth0" "eth1" ];
  396. vs1.interfaces = [ "eth2" "wlan0" ];
  397. };
  398. description =
  399. ''
  400. This option allows you to define Open vSwitches that connect
  401. physical networks together. The value of this option is an
  402. attribute set. Each attribute specifies a vswitch, with the
  403. attribute name specifying the name of the vswitch's network
  404. interface.
  405. '';
  406. type = with types; attrsOf (submodule {
  407. options = {
  408. interfaces = mkOption {
  409. example = [ "eth0" "eth1" ];
  410. type = types.listOf types.str;
  411. description =
  412. "The physical network interfaces connected by the vSwitch.";
  413. };
  414. controllers = mkOption {
  415. type = types.listOf types.str;
  416. default = [];
  417. example = [ "ptcp:6653:[::1]" ];
  418. description = ''
  419. Specify the controller targets. For the allowed options see <literal>man 8 ovs-vsctl</literal>.
  420. '';
  421. };
  422. openFlowRules = mkOption {
  423. type = types.lines;
  424. default = "";
  425. example = ''
  426. actions=normal
  427. '';
  428. description = ''
  429. OpenFlow rules to insert into the Open vSwitch. All <literal>openFlowRules</literal> are
  430. loaded with <literal>ovs-ofctl</literal> within one atomic operation.
  431. '';
  432. };
  433. extraOvsctlCmds = mkOption {
  434. type = types.lines;
  435. default = "";
  436. example = ''
  437. set-fail-mode <switch_name> secure
  438. set Bridge <switch_name> stp_enable=true
  439. '';
  440. description = ''
  441. Commands to manipulate the Open vSwitch database. Every line executed with <literal>ovs-vsctl</literal>.
  442. All commands are bundled together with the operations for adding the interfaces
  443. into one atomic operation.
  444. '';
  445. };
  446. };
  447. });
  448. };
  449. networking.bridges = mkOption {
  450. default = { };
  451. example =
  452. { br0.interfaces = [ "eth0" "eth1" ];
  453. br1.interfaces = [ "eth2" "wlan0" ];
  454. };
  455. description =
  456. ''
  457. This option allows you to define Ethernet bridge devices
  458. that connect physical networks together. The value of this
  459. option is an attribute set. Each attribute specifies a
  460. bridge, with the attribute name specifying the name of the
  461. bridge's network interface.
  462. '';
  463. type = with types; attrsOf (submodule {
  464. options = {
  465. interfaces = mkOption {
  466. example = [ "eth0" "eth1" ];
  467. type = types.listOf types.str;
  468. description =
  469. "The physical network interfaces connected by the bridge.";
  470. };
  471. rstp = mkOption {
  472. default = false;
  473. type = types.bool;
  474. description = "Whether the bridge interface should enable rstp.";
  475. };
  476. };
  477. });
  478. };
  479. networking.bonds =
  480. let
  481. driverOptionsExample = {
  482. miimon = "100";
  483. mode = "active-backup";
  484. };
  485. in mkOption {
  486. default = { };
  487. example = literalExample {
  488. bond0 = {
  489. interfaces = [ "eth0" "wlan0" ];
  490. driverOptions = driverOptionsExample;
  491. };
  492. anotherBond.interfaces = [ "enp4s0f0" "enp4s0f1" "enp5s0f0" "enp5s0f1" ];
  493. };
  494. description = ''
  495. This option allows you to define bond devices that aggregate multiple,
  496. underlying networking interfaces together. The value of this option is
  497. an attribute set. Each attribute specifies a bond, with the attribute
  498. name specifying the name of the bond's network interface
  499. '';
  500. type = with types; attrsOf (submodule {
  501. options = {
  502. interfaces = mkOption {
  503. example = [ "enp4s0f0" "enp4s0f1" "wlan0" ];
  504. type = types.listOf types.str;
  505. description = "The interfaces to bond together";
  506. };
  507. driverOptions = mkOption {
  508. type = types.attrsOf types.str;
  509. default = {};
  510. example = literalExample driverOptionsExample;
  511. description = ''
  512. Options for the bonding driver.
  513. Documentation can be found in
  514. <link xlink:href="https://www.kernel.org/doc/Documentation/networking/bonding.txt" />
  515. '';
  516. };
  517. lacp_rate = mkOption {
  518. default = null;
  519. example = "fast";
  520. type = types.nullOr types.str;
  521. description = ''
  522. DEPRECATED, use `driverOptions`.
  523. Option specifying the rate in which we'll ask our link partner
  524. to transmit LACPDU packets in 802.3ad mode.
  525. '';
  526. };
  527. miimon = mkOption {
  528. default = null;
  529. example = 100;
  530. type = types.nullOr types.int;
  531. description = ''
  532. DEPRECATED, use `driverOptions`.
  533. Miimon is the number of millisecond in between each round of polling
  534. by the device driver for failed links. By default polling is not
  535. enabled and the driver is trusted to properly detect and handle
  536. failure scenarios.
  537. '';
  538. };
  539. mode = mkOption {
  540. default = null;
  541. example = "active-backup";
  542. type = types.nullOr types.str;
  543. description = ''
  544. DEPRECATED, use `driverOptions`.
  545. The mode which the bond will be running. The default mode for
  546. the bonding driver is balance-rr, optimizing for throughput.
  547. More information about valid modes can be found at
  548. https://www.kernel.org/doc/Documentation/networking/bonding.txt
  549. '';
  550. };
  551. xmit_hash_policy = mkOption {
  552. default = null;
  553. example = "layer2+3";
  554. type = types.nullOr types.str;
  555. description = ''
  556. DEPRECATED, use `driverOptions`.
  557. Selects the transmit hash policy to use for slave selection in
  558. balance-xor, 802.3ad, and tlb modes.
  559. '';
  560. };
  561. };
  562. });
  563. };
  564. networking.macvlans = mkOption {
  565. default = { };
  566. example = literalExample {
  567. wan = {
  568. interface = "enp2s0";
  569. mode = "vepa";
  570. };
  571. };
  572. description = ''
  573. This option allows you to define macvlan interfaces which should
  574. be automatically created.
  575. '';
  576. type = with types; attrsOf (submodule {
  577. options = {
  578. interface = mkOption {
  579. example = "enp4s0";
  580. type = types.str;
  581. description = "The interface the macvlan will transmit packets through.";
  582. };
  583. mode = mkOption {
  584. default = null;
  585. type = types.nullOr types.str;
  586. example = "vepa";
  587. description = "The mode of the macvlan device.";
  588. };
  589. };
  590. });
  591. };
  592. networking.sits = mkOption {
  593. default = { };
  594. example = literalExample {
  595. hurricane = {
  596. remote = "10.0.0.1";
  597. local = "10.0.0.22";
  598. ttl = 255;
  599. };
  600. msipv6 = {
  601. remote = "192.168.0.1";
  602. dev = "enp3s0";
  603. ttl = 127;
  604. };
  605. };
  606. description = ''
  607. This option allows you to define 6-to-4 interfaces which should be automatically created.
  608. '';
  609. type = with types; attrsOf (submodule {
  610. options = {
  611. remote = mkOption {
  612. type = types.nullOr types.str;
  613. default = null;
  614. example = "10.0.0.1";
  615. description = ''
  616. The address of the remote endpoint to forward traffic over.
  617. '';
  618. };
  619. local = mkOption {
  620. type = types.nullOr types.str;
  621. default = null;
  622. example = "10.0.0.22";
  623. description = ''
  624. The address of the local endpoint which the remote
  625. side should send packets to.
  626. '';
  627. };
  628. ttl = mkOption {
  629. type = types.nullOr types.int;
  630. default = null;
  631. example = 255;
  632. description = ''
  633. The time-to-live of the connection to the remote tunnel endpoint.
  634. '';
  635. };
  636. dev = mkOption {
  637. type = types.nullOr types.str;
  638. default = null;
  639. example = "enp4s0f0";
  640. description = ''
  641. The underlying network device on which the tunnel resides.
  642. '';
  643. };
  644. };
  645. });
  646. };
  647. networking.vlans = mkOption {
  648. default = { };
  649. example = literalExample {
  650. vlan0 = {
  651. id = 3;
  652. interface = "enp3s0";
  653. };
  654. vlan1 = {
  655. id = 1;
  656. interface = "wlan0";
  657. };
  658. };
  659. description =
  660. ''
  661. This option allows you to define vlan devices that tag packets
  662. on top of a physical interface. The value of this option is an
  663. attribute set. Each attribute specifies a vlan, with the name
  664. specifying the name of the vlan interface.
  665. '';
  666. type = with types; attrsOf (submodule {
  667. options = {
  668. id = mkOption {
  669. example = 1;
  670. type = types.int;
  671. description = "The vlan identifier";
  672. };
  673. interface = mkOption {
  674. example = "enp4s0";
  675. type = types.str;
  676. description = "The interface the vlan will transmit packets through.";
  677. };
  678. };
  679. });
  680. };
  681. networking.wlanInterfaces = mkOption {
  682. default = { };
  683. example = literalExample {
  684. wlan-station0 = {
  685. device = "wlp6s0";
  686. };
  687. wlan-adhoc0 = {
  688. type = "ibss";
  689. device = "wlp6s0";
  690. mac = "02:00:00:00:00:01";
  691. };
  692. wlan-p2p0 = {
  693. device = "wlp6s0";
  694. mac = "02:00:00:00:00:02";
  695. };
  696. wlan-ap0 = {
  697. device = "wlp6s0";
  698. mac = "02:00:00:00:00:03";
  699. };
  700. };
  701. description =
  702. ''
  703. Creating multiple WLAN interfaces on top of one physical WLAN device (NIC).
  704. The name of the WLAN interface corresponds to the name of the attribute.
  705. A NIC is referenced by the persistent device name of the WLAN interface that
  706. <literal>udev</literal> assigns to a NIC by default.
  707. If a NIC supports multiple WLAN interfaces, then the one NIC can be used as
  708. <literal>device</literal> for multiple WLAN interfaces.
  709. If a NIC is used for creating WLAN interfaces, then the default WLAN interface
  710. with a persistent device name form <literal>udev</literal> is not created.
  711. A WLAN interface with the persistent name assigned from <literal>udev</literal>
  712. would have to be created explicitly.
  713. '';
  714. type = with types; attrsOf (submodule {
  715. options = {
  716. device = mkOption {
  717. type = types.str;
  718. example = "wlp6s0";
  719. description = "The name of the underlying hardware WLAN device as assigned by <literal>udev</literal>.";
  720. };
  721. type = mkOption {
  722. type = types.enum [ "managed" "ibss" "monitor" "mesh" "wds" ];
  723. default = "managed";
  724. example = "ibss";
  725. description = ''
  726. The type of the WLAN interface.
  727. The type has to be supported by the underlying hardware of the device.
  728. '';
  729. };
  730. meshID = mkOption {
  731. type = types.nullOr types.str;
  732. default = null;
  733. description = "MeshID of interface with type <literal>mesh</literal>.";
  734. };
  735. flags = mkOption {
  736. type = with types; nullOr (enum [ "none" "fcsfail" "control" "otherbss" "cook" "active" ]);
  737. default = null;
  738. example = "control";
  739. description = ''
  740. Flags for interface of type <literal>monitor</literal>.
  741. '';
  742. };
  743. fourAddr = mkOption {
  744. type = types.nullOr types.bool;
  745. default = null;
  746. description = "Whether to enable <literal>4-address mode</literal> with type <literal>managed</literal>.";
  747. };
  748. mac = mkOption {
  749. type = types.nullOr types.str;
  750. default = null;
  751. example = "02:00:00:00:00:01";
  752. description = ''
  753. MAC address to use for the device. If <literal>null</literal>, then the MAC of the
  754. underlying hardware WLAN device is used.
  755. INFO: Locally administered MAC addresses are of the form:
  756. <itemizedlist>
  757. <listitem><para>x2:xx:xx:xx:xx:xx</para></listitem>
  758. <listitem><para>x6:xx:xx:xx:xx:xx</para></listitem>
  759. <listitem><para>xA:xx:xx:xx:xx:xx</para></listitem>
  760. <listitem><para>xE:xx:xx:xx:xx:xx</para></listitem>
  761. </itemizedlist>
  762. '';
  763. };
  764. };
  765. });
  766. };
  767. networking.useDHCP = mkOption {
  768. type = types.bool;
  769. default = true;
  770. description = ''
  771. Whether to use DHCP to obtain an IP address and other
  772. configuration for all network interfaces that are not manually
  773. configured.
  774. Using this option is highly discouraged and also incompatible with
  775. <option>networking.useNetworkd</option>. Please use
  776. <option>networking.interfaces.&lt;name&gt;.useDHCP</option> instead
  777. and set this to false.
  778. '';
  779. };
  780. networking.useNetworkd = mkOption {
  781. default = false;
  782. type = types.bool;
  783. description = ''
  784. Whether we should use networkd as the network configuration backend or
  785. the legacy script based system. Note that this option is experimental,
  786. enable at your own risk.
  787. '';
  788. };
  789. };
  790. ###### implementation
  791. config = {
  792. warnings = concatMap (i: i.warnings) interfaces;
  793. assertions =
  794. (forEach interfaces (i: {
  795. # With the linux kernel, interface name length is limited by IFNAMSIZ
  796. # to 16 bytes, including the trailing null byte.
  797. # See include/linux/if.h in the kernel sources
  798. assertion = stringLength i.name < 16;
  799. message = ''
  800. The name of networking.interfaces."${i.name}" is too long, it needs to be less than 16 characters.
  801. '';
  802. })) ++ (forEach slaveIfs (i: {
  803. assertion = i.ipv4.addresses == [ ] && i.ipv6.addresses == [ ];
  804. message = ''
  805. The networking.interfaces."${i.name}" must not have any defined ips when it is a slave.
  806. '';
  807. })) ++ (forEach interfaces (i: {
  808. assertion = i.preferTempAddress -> cfg.enableIPv6;
  809. message = ''
  810. Temporary addresses are only needed when IPv6 is enabled.
  811. '';
  812. })) ++ [
  813. {
  814. assertion = cfg.hostId == null || (stringLength cfg.hostId == 8 && isHexString cfg.hostId);
  815. message = "Invalid value given to the networking.hostId option.";
  816. }
  817. ];
  818. boot.kernelModules = [ ]
  819. ++ optional cfg.enableIPv6 "ipv6"
  820. ++ optional hasVirtuals "tun"
  821. ++ optional hasSits "sit"
  822. ++ optional hasBonds "bonding";
  823. boot.extraModprobeConfig =
  824. # This setting is intentional as it prevents default bond devices
  825. # from being created.
  826. optionalString hasBonds "options bonding max_bonds=0";
  827. boot.kernel.sysctl = {
  828. "net.ipv6.conf.all.disable_ipv6" = mkDefault (!cfg.enableIPv6);
  829. "net.ipv6.conf.default.disable_ipv6" = mkDefault (!cfg.enableIPv6);
  830. "net.ipv6.conf.all.forwarding" = mkDefault (any (i: i.proxyARP) interfaces);
  831. } // listToAttrs (flip concatMap (filter (i: i.proxyARP) interfaces)
  832. (i: forEach [ "4" "6" ] (v: nameValuePair "net.ipv${v}.conf.${replaceChars ["."] ["/"] i.name}.proxy_arp" true)))
  833. // listToAttrs (forEach (filter (i: i.preferTempAddress) interfaces)
  834. (i: nameValuePair "net.ipv6.conf.${replaceChars ["."] ["/"] i.name}.use_tempaddr" 2));
  835. # Capabilities won't work unless we have at-least a 4.3 Linux
  836. # kernel because we need the ambient capability
  837. security.wrappers = if (versionAtLeast (getVersion config.boot.kernelPackages.kernel) "4.3") then {
  838. ping = {
  839. source = "${pkgs.iputils.out}/bin/ping";
  840. capabilities = "cap_net_raw+p";
  841. };
  842. } else {
  843. ping.source = "${pkgs.iputils.out}/bin/ping";
  844. };
  845. # Set the host and domain names in the activation script. Don't
  846. # clear it if it's not configured in the NixOS configuration,
  847. # since it may have been set by dhcpcd in the meantime.
  848. system.activationScripts.hostname =
  849. optionalString (cfg.hostName != "") ''
  850. hostname "${cfg.hostName}"
  851. '';
  852. system.activationScripts.domain =
  853. optionalString (cfg.domain != null) ''
  854. domainname "${cfg.domain}"
  855. '';
  856. environment.etc.hostid = mkIf (cfg.hostId != null)
  857. { source = pkgs.runCommand "gen-hostid" { preferLocalBuild = true; } ''
  858. hi="${cfg.hostId}"
  859. ${if pkgs.stdenv.isBigEndian then ''
  860. echo -ne "\x''${hi:0:2}\x''${hi:2:2}\x''${hi:4:2}\x''${hi:6:2}" > $out
  861. '' else ''
  862. echo -ne "\x''${hi:6:2}\x''${hi:4:2}\x''${hi:2:2}\x''${hi:0:2}" > $out
  863. ''}
  864. '';
  865. };
  866. # static hostname configuration needed for hostnamectl and the
  867. # org.freedesktop.hostname1 dbus service (both provided by systemd)
  868. environment.etc.hostname = mkIf (cfg.hostName != "")
  869. {
  870. text = cfg.hostName + "\n";
  871. };
  872. environment.systemPackages =
  873. [ pkgs.host
  874. pkgs.iproute
  875. pkgs.iputils
  876. pkgs.nettools
  877. ]
  878. ++ optionals config.networking.wireless.enable [
  879. pkgs.wirelesstools # FIXME: obsolete?
  880. pkgs.iw
  881. pkgs.rfkill
  882. ]
  883. ++ bridgeStp;
  884. # The network-interfaces target is kept for backwards compatibility.
  885. # New modules must NOT use it.
  886. systemd.targets.network-interfaces =
  887. { description = "All Network Interfaces (deprecated)";
  888. wantedBy = [ "network.target" ];
  889. before = [ "network.target" ];
  890. after = [ "network-pre.target" ];
  891. unitConfig.X-StopOnReconfiguration = true;
  892. };
  893. systemd.services = {
  894. network-local-commands = {
  895. description = "Extra networking commands.";
  896. before = [ "network.target" ];
  897. wantedBy = [ "network.target" ];
  898. after = [ "network-pre.target" ];
  899. unitConfig.ConditionCapability = "CAP_NET_ADMIN";
  900. path = [ pkgs.iproute ];
  901. serviceConfig.Type = "oneshot";
  902. serviceConfig.RemainAfterExit = true;
  903. script = ''
  904. # Run any user-specified commands.
  905. ${cfg.localCommands}
  906. '';
  907. };
  908. } // (listToAttrs (forEach interfaces (i:
  909. let
  910. deviceDependency = if (config.boot.isContainer || i.name == "lo")
  911. then []
  912. else [ (subsystemDevice i.name) ];
  913. in
  914. nameValuePair "network-link-${i.name}"
  915. { description = "Link configuration of ${i.name}";
  916. wantedBy = [ "network-interfaces.target" ];
  917. before = [ "network-interfaces.target" ];
  918. bindsTo = deviceDependency;
  919. after = [ "network-pre.target" ] ++ deviceDependency;
  920. path = [ pkgs.iproute ];
  921. serviceConfig = {
  922. Type = "oneshot";
  923. RemainAfterExit = true;
  924. };
  925. script =
  926. ''
  927. echo "Configuring link..."
  928. '' + optionalString (i.macAddress != null) ''
  929. echo "setting MAC address to ${i.macAddress}..."
  930. ip link set "${i.name}" address "${i.macAddress}"
  931. '' + optionalString (i.mtu != null) ''
  932. echo "setting MTU to ${toString i.mtu}..."
  933. ip link set "${i.name}" mtu "${toString i.mtu}"
  934. '' + ''
  935. echo -n "bringing up interface... "
  936. ip link set "${i.name}" up && echo "done" || (echo "failed"; exit 1)
  937. '';
  938. })));
  939. services.mstpd = mkIf needsMstpd { enable = true; };
  940. virtualisation.vswitch = mkIf (cfg.vswitches != { }) { enable = true; };
  941. services.udev.packages = [
  942. (pkgs.writeTextFile rec {
  943. name = "ipv6-privacy-extensions.rules";
  944. destination = "/etc/udev/rules.d/98-${name}";
  945. text = ''
  946. # enable and prefer IPv6 privacy addresses by default
  947. ACTION=="add", SUBSYSTEM=="net", RUN+="${pkgs.bash}/bin/sh -c 'echo 2 > /proc/sys/net/ipv6/conf/%k/use_tempaddr'"
  948. '';
  949. })
  950. (pkgs.writeTextFile rec {
  951. name = "ipv6-privacy-extensions.rules";
  952. destination = "/etc/udev/rules.d/99-${name}";
  953. text = concatMapStrings (i: ''
  954. # enable IPv6 privacy addresses but prefer EUI-64 addresses for ${i.name}
  955. ACTION=="add", SUBSYSTEM=="net", RUN+="${pkgs.procps}/bin/sysctl net.ipv6.conf.${replaceChars ["."] ["/"] i.name}.use_tempaddr=1"
  956. '') (filter (i: !i.preferTempAddress) interfaces);
  957. })
  958. ] ++ lib.optional (cfg.wlanInterfaces != {})
  959. (pkgs.writeTextFile {
  960. name = "99-zzz-40-wlanInterfaces.rules";
  961. destination = "/etc/udev/rules.d/99-zzz-40-wlanInterfaces.rules";
  962. text =
  963. let
  964. # Collect all interfaces that are defined for a device
  965. # as device:interface key:value pairs.
  966. wlanDeviceInterfaces =
  967. let
  968. allDevices = unique (mapAttrsToList (_: v: v.device) cfg.wlanInterfaces);
  969. interfacesOfDevice = d: filterAttrs (_: v: v.device == d) cfg.wlanInterfaces;
  970. in
  971. genAttrs allDevices (d: interfacesOfDevice d);
  972. # Convert device:interface key:value pairs into a list, and if it exists,
  973. # place the interface which is named after the device at the beginning.
  974. wlanListDeviceFirst = device: interfaces:
  975. if hasAttr device interfaces
  976. then mapAttrsToList (n: v: v//{_iName=n;}) (filterAttrs (n: _: n==device) interfaces) ++ mapAttrsToList (n: v: v//{_iName=n;}) (filterAttrs (n: _: n!=device) interfaces)
  977. else mapAttrsToList (n: v: v // {_iName = n;}) interfaces;
  978. # Udev script to execute for the default WLAN interface with the persistend udev name.
  979. # The script creates the required, new WLAN interfaces interfaces and configures the
  980. # existing, default interface.
  981. curInterfaceScript = device: current: new: pkgs.writeScript "udev-run-script-wlan-interfaces-${device}.sh" ''
  982. #!${pkgs.runtimeShell}
  983. # Change the wireless phy device to a predictable name.
  984. ${pkgs.iw}/bin/iw phy `${pkgs.coreutils}/bin/cat /sys/class/net/$INTERFACE/phy80211/name` set name ${device}
  985. # Add new WLAN interfaces
  986. ${flip concatMapStrings new (i: ''
  987. ${pkgs.iw}/bin/iw phy ${device} interface add ${i._iName} type managed
  988. '')}
  989. # Configure the current interface
  990. ${pkgs.iw}/bin/iw dev ${device} set type ${current.type}
  991. ${optionalString (current.type == "mesh" && current.meshID!=null) "${pkgs.iw}/bin/iw dev ${device} set meshid ${current.meshID}"}
  992. ${optionalString (current.type == "monitor" && current.flags!=null) "${pkgs.iw}/bin/iw dev ${device} set monitor ${current.flags}"}
  993. ${optionalString (current.type == "managed" && current.fourAddr!=null) "${pkgs.iw}/bin/iw dev ${device} set 4addr ${if current.fourAddr then "on" else "off"}"}
  994. ${optionalString (current.mac != null) "${pkgs.iproute}/bin/ip link set dev ${device} address ${current.mac}"}
  995. '';
  996. # Udev script to execute for a new WLAN interface. The script configures the new WLAN interface.
  997. newInterfaceScript = device: new: pkgs.writeScript "udev-run-script-wlan-interfaces-${new._iName}.sh" ''
  998. #!${pkgs.runtimeShell}
  999. # Configure the new interface
  1000. ${pkgs.iw}/bin/iw dev ${new._iName} set type ${new.type}
  1001. ${optionalString (new.type == "mesh" && new.meshID!=null) "${pkgs.iw}/bin/iw dev ${device} set meshid ${new.meshID}"}
  1002. ${optionalString (new.type == "monitor" && new.flags!=null) "${pkgs.iw}/bin/iw dev ${device} set monitor ${new.flags}"}
  1003. ${optionalString (new.type == "managed" && new.fourAddr!=null) "${pkgs.iw}/bin/iw dev ${device} set 4addr ${if new.fourAddr then "on" else "off"}"}
  1004. ${optionalString (new.mac != null) "${pkgs.iproute}/bin/ip link set dev ${device} address ${new.mac}"}
  1005. '';
  1006. # Udev attributes for systemd to name the device and to create a .device target.
  1007. systemdAttrs = n: ''NAME:="${n}", ENV{INTERFACE}:="${n}", ENV{SYSTEMD_ALIAS}:="/sys/subsystem/net/devices/${n}", TAG+="systemd"'';
  1008. in
  1009. flip (concatMapStringsSep "\n") (attrNames wlanDeviceInterfaces) (device:
  1010. let
  1011. interfaces = wlanListDeviceFirst device wlanDeviceInterfaces.${device};
  1012. curInterface = elemAt interfaces 0;
  1013. newInterfaces = drop 1 interfaces;
  1014. in ''
  1015. # It is important to have that rule first as overwriting the NAME attribute also prevents the
  1016. # next rules from matching.
  1017. ${flip (concatMapStringsSep "\n") (wlanListDeviceFirst device wlanDeviceInterfaces.${device}) (interface:
  1018. ''ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", ENV{INTERFACE}=="${interface._iName}", ${systemdAttrs interface._iName}, RUN+="${newInterfaceScript device interface}"'')}
  1019. # Add the required, new WLAN interfaces to the default WLAN interface with the
  1020. # persistent, default name as assigned by udev.
  1021. ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", NAME=="${device}", ${systemdAttrs curInterface._iName}, RUN+="${curInterfaceScript device curInterface newInterfaces}"
  1022. # Generate the same systemd events for both 'add' and 'move' udev events.
  1023. ACTION=="move", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", NAME=="${device}", ${systemdAttrs curInterface._iName}
  1024. '');
  1025. });
  1026. };
  1027. }