summary refs log tree commit diff
path: root/nixos/modules/services/security/tor.nix
blob: a5822c02794d9b3f84979e0a42c2ac3d4a0cf5aa (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
{ config, lib, options, pkgs, ... }:

with builtins;
with lib;

let
  cfg = config.services.tor;
  opt = options.services.tor;
  stateDir = "/var/lib/tor";
  runDir = "/run/tor";
  descriptionGeneric = option: ''
    See <link xlink:href="https://2019.www.torproject.org/docs/tor-manual.html.en#${option}">torrc manual</link>.
  '';
  bindsPrivilegedPort =
    any (p0:
      let p1 = if p0 ? "port" then p0.port else p0; in
      if p1 == "auto" then false
      else let p2 = if isInt p1 then p1 else toInt p1; in
        p1 != null && 0 < p2 && p2 < 1024)
    (flatten [
      cfg.settings.ORPort
      cfg.settings.DirPort
      cfg.settings.DNSPort
      cfg.settings.ExtORPort
      cfg.settings.HTTPTunnelPort
      cfg.settings.NATDPort
      cfg.settings.SOCKSPort
      cfg.settings.TransPort
    ]);
  optionBool = optionName: mkOption {
    type = with types; nullOr bool;
    default = null;
    description = descriptionGeneric optionName;
  };
  optionInt = optionName: mkOption {
    type = with types; nullOr int;
    default = null;
    description = descriptionGeneric optionName;
  };
  optionString = optionName: mkOption {
    type = with types; nullOr str;
    default = null;
    description = descriptionGeneric optionName;
  };
  optionStrings = optionName: mkOption {
    type = with types; listOf str;
    default = [];
    description = descriptionGeneric optionName;
  };
  optionAddress = mkOption {
    type = with types; nullOr str;
    default = null;
    example = "0.0.0.0";
    description = ''
      IPv4 or IPv6 (if between brackets) address.
    '';
  };
  optionUnix = mkOption {
    type = with types; nullOr path;
    default = null;
    description = ''
      Unix domain socket path to use.
    '';
  };
  optionPort = mkOption {
    type = with types; nullOr (oneOf [port (enum ["auto"])]);
    default = null;
  };
  optionPorts = optionName: mkOption {
    type = with types; listOf port;
    default = [];
    description = descriptionGeneric optionName;
  };
  optionIsolablePort = with types; oneOf [
    port (enum ["auto"])
    (submodule ({config, ...}: {
      options = {
        addr = optionAddress;
        port = optionPort;
        flags = optionFlags;
        SessionGroup = mkOption { type = nullOr int; default = null; };
      } // genAttrs isolateFlags (name: mkOption { type = types.bool; default = false; });
      config = {
        flags = filter (name: config.${name} == true) isolateFlags ++
                optional (config.SessionGroup != null) "SessionGroup=${toString config.SessionGroup}";
      };
    }))
  ];
  optionIsolablePorts = optionName: mkOption {
    default = [];
    type = with types; either optionIsolablePort (listOf optionIsolablePort);
    description = descriptionGeneric optionName;
  };
  isolateFlags = [
    "IsolateClientAddr"
    "IsolateClientProtocol"
    "IsolateDestAddr"
    "IsolateDestPort"
    "IsolateSOCKSAuth"
    "KeepAliveIsolateSOCKSAuth"
  ];
  optionSOCKSPort = doConfig: let
    flags = [
      "CacheDNS" "CacheIPv4DNS" "CacheIPv6DNS" "GroupWritable" "IPv6Traffic"
      "NoDNSRequest" "NoIPv4Traffic" "NoOnionTraffic" "OnionTrafficOnly"
      "PreferIPv6" "PreferIPv6Automap" "PreferSOCKSNoAuth" "UseDNSCache"
      "UseIPv4Cache" "UseIPv6Cache" "WorldWritable"
    ] ++ isolateFlags;
    in with types; oneOf [
      port (submodule ({config, ...}: {
        options = {
          unix = optionUnix;
          addr = optionAddress;
          port = optionPort;
          flags = optionFlags;
          SessionGroup = mkOption { type = nullOr int; default = null; };
        } // genAttrs flags (name: mkOption { type = types.bool; default = false; });
        config = mkIf doConfig { # Only add flags in SOCKSPort to avoid duplicates
          flags = filter (name: config.${name} == true) flags ++
                  optional (config.SessionGroup != null) "SessionGroup=${toString config.SessionGroup}";
        };
      }))
    ];
  optionFlags = mkOption {
    type = with types; listOf str;
    default = [];
  };
  optionORPort = optionName: mkOption {
    default = [];
    example = 443;
    type = with types; oneOf [port (enum ["auto"]) (listOf (oneOf [
      port
      (enum ["auto"])
      (submodule ({config, ...}:
        let flags = [ "IPv4Only" "IPv6Only" "NoAdvertise" "NoListen" ];
        in {
        options = {
          addr = optionAddress;
          port = optionPort;
          flags = optionFlags;
        } // genAttrs flags (name: mkOption { type = types.bool; default = false; });
        config = {
          flags = filter (name: config.${name} == true) flags;
        };
      }))
    ]))];
    description = descriptionGeneric optionName;
  };
  optionBandwith = optionName: mkOption {
    type = with types; nullOr (either int str);
    default = null;
    description = descriptionGeneric optionName;
  };
  optionPath = optionName: mkOption {
    type = with types; nullOr path;
    default = null;
    description = descriptionGeneric optionName;
  };

  mkValueString = k: v:
    if v == null then ""
    else if isBool v then
      (if v then "1" else "0")
    else if v ? "unix" && v.unix != null then
      "unix:"+v.unix +
      optionalString (v ? "flags") (" " + concatStringsSep " " v.flags)
    else if v ? "port" && v.port != null then
      optionalString (v ? "addr" && v.addr != null) "${v.addr}:" +
      toString v.port +
      optionalString (v ? "flags") (" " + concatStringsSep " " v.flags)
    else if k == "ServerTransportPlugin" then
      optionalString (v.transports != []) "${concatStringsSep "," v.transports} exec ${v.exec}"
    else if k == "HidServAuth" then
      v.onion + " " + v.auth
    else generators.mkValueStringDefault {} v;
  genTorrc = settings:
    generators.toKeyValue {
      listsAsDuplicateKeys = true;
      mkKeyValue = k: generators.mkKeyValueDefault { mkValueString = mkValueString k; } " " k;
    }
    (lib.mapAttrs (k: v:
      # Not necesssary, but prettier rendering
      if elem k [ "AutomapHostsSuffixes" "DirPolicy" "ExitPolicy" "SocksPolicy" ]
      && v != []
      then concatStringsSep "," v
      else v)
    (lib.filterAttrs (k: v: !(v == null || v == ""))
    settings));
  torrc = pkgs.writeText "torrc" (
    genTorrc cfg.settings +
    concatStrings (mapAttrsToList (name: onion:
      "HiddenServiceDir ${onion.path}\n" +
      genTorrc onion.settings) cfg.relay.onionServices)
  );
in
{
  imports = [
    (mkRenamedOptionModule [ "services" "tor" "client" "dns" "automapHostsSuffixes" ] [ "services" "tor" "settings" "AutomapHostsSuffixes" ])
    (mkRemovedOptionModule [ "services" "tor" "client" "dns" "isolationOptions" ] "Use services.tor.settings.DNSPort instead.")
    (mkRemovedOptionModule [ "services" "tor" "client" "dns" "listenAddress" ] "Use services.tor.settings.DNSPort instead.")
    (mkRemovedOptionModule [ "services" "tor" "client" "privoxy" "enable" ] "Use services.privoxy.enable and services.privoxy.enableTor instead.")
    (mkRemovedOptionModule [ "services" "tor" "client" "socksIsolationOptions" ] "Use services.tor.settings.SOCKSPort instead.")
    (mkRemovedOptionModule [ "services" "tor" "client" "socksListenAddressFaster" ] "Use services.tor.settings.SOCKSPort instead.")
    (mkRenamedOptionModule [ "services" "tor" "client" "socksPolicy" ] [ "services" "tor" "settings" "SocksPolicy" ])
    (mkRemovedOptionModule [ "services" "tor" "client" "transparentProxy" "isolationOptions" ] "Use services.tor.settings.TransPort instead.")
    (mkRemovedOptionModule [ "services" "tor" "client" "transparentProxy" "listenAddress" ] "Use services.tor.settings.TransPort instead.")
    (mkRenamedOptionModule [ "services" "tor" "controlPort" ] [ "services" "tor" "settings" "ControlPort" ])
    (mkRemovedOptionModule [ "services" "tor" "extraConfig" ] "Plese use services.tor.settings instead.")
    (mkRenamedOptionModule [ "services" "tor" "hiddenServices" ] [ "services" "tor" "relay" "onionServices" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "accountingMax" ] [ "services" "tor" "settings" "AccountingMax" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "accountingStart" ] [ "services" "tor" "settings" "AccountingStart" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "address" ] [ "services" "tor" "settings" "Address" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "bandwidthBurst" ] [ "services" "tor" "settings" "BandwidthBurst" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "bandwidthRate" ] [ "services" "tor" "settings" "BandwidthRate" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "bridgeTransports" ] [ "services" "tor" "settings" "ServerTransportPlugin" "transports" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "contactInfo" ] [ "services" "tor" "settings" "ContactInfo" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "exitPolicy" ] [ "services" "tor" "settings" "ExitPolicy" ])
    (mkRemovedOptionModule [ "services" "tor" "relay" "isBridge" ] "Use services.tor.relay.role instead.")
    (mkRemovedOptionModule [ "services" "tor" "relay" "isExit" ] "Use services.tor.relay.role instead.")
    (mkRenamedOptionModule [ "services" "tor" "relay" "nickname" ] [ "services" "tor" "settings" "Nickname" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "port" ] [ "services" "tor" "settings" "ORPort" ])
    (mkRenamedOptionModule [ "services" "tor" "relay" "portSpec" ] [ "services" "tor" "settings" "ORPort" ])
  ];

  options = {
    services.tor = {
      enable = mkEnableOption ''Tor daemon.
        By default, the daemon is run without
        relay, exit, bridge or client connectivity'';

      openFirewall = mkEnableOption "opening of the relay port(s) in the firewall";

      package = mkOption {
        type = types.package;
        default = pkgs.tor;
        defaultText = literalExpression "pkgs.tor";
        description = "Tor package to use.";
      };

      enableGeoIP = mkEnableOption ''use of GeoIP databases.
        Disabling this will disable by-country statistics for bridges and relays
        and some client and third-party software functionality'' // { default = true; };

      controlSocket.enable = mkEnableOption ''control socket,
        created in <literal>${runDir}/control</literal>'';

      client = {
        enable = mkEnableOption ''the routing of application connections.
          You might want to disable this if you plan running a dedicated Tor relay'';

        transparentProxy.enable = mkEnableOption "transparent proxy";
        dns.enable = mkEnableOption "DNS resolver";

        socksListenAddress = mkOption {
          type = optionSOCKSPort false;
          default = {addr = "127.0.0.1"; port = 9050; IsolateDestAddr = true;};
          example = {addr = "192.168.0.1"; port = 9090; IsolateDestAddr = true;};
          description = ''
            Bind to this address to listen for connections from
            Socks-speaking applications.
          '';
        };

        onionServices = mkOption {
          description = descriptionGeneric "HiddenServiceDir";
          default = {};
          example = {
            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" = {
              clientAuthorizations = ["/run/keys/tor/alice.prv.x25519"];
            };
          };
          type = types.attrsOf (types.submodule ({name, config, ...}: {
            options.clientAuthorizations = mkOption {
              description = ''
                Clients' authorizations for a v3 onion service,
                as a list of files containing each one private key, in the format:
                <screen>descriptor:x25519:&lt;base32-private-key&gt;</screen>
              '' + descriptionGeneric "_client_authorization";
              type = with types; listOf path;
              default = [];
              example = ["/run/keys/tor/alice.prv.x25519"];
            };
          }));
        };
      };

      relay = {
        enable = mkEnableOption ''relaying of Tor traffic for others.

          See <link xlink:href="https://www.torproject.org/docs/tor-doc-relay" />
          for details.

          Setting this to true requires setting
          <option>services.tor.relay.role</option>
          and
          <option>services.tor.settings.ORPort</option>
          options'';

        role = mkOption {
          type = types.enum [ "exit" "relay" "bridge" "private-bridge" ];
          description = ''
            Your role in Tor network. There're several options:

            <variablelist>
            <varlistentry>
              <term><literal>exit</literal></term>
              <listitem>
                <para>
                  An exit relay. This allows Tor users to access regular
                  Internet services through your public IP.
                </para>

                <important><para>
                  Running an exit relay may expose you to abuse
                  complaints. See
                  <link xlink:href="https://www.torproject.org/faq.html.en#ExitPolicies"/>
                  for more info.
                </para></important>

                <para>
                  You can specify which services Tor users may access via
                  your exit relay using <option>settings.ExitPolicy</option> option.
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term><literal>relay</literal></term>
              <listitem>
                <para>
                  Regular relay. This allows Tor users to relay onion
                  traffic to other Tor nodes, but not to public
                  Internet.
                </para>

                <important><para>
                  Note that some misconfigured and/or disrespectful
                  towards privacy sites will block you even if your
                  relay is not an exit relay. That is, just being listed
                  in a public relay directory can have unwanted
                  consequences.

                  Which means you might not want to use
                  this role if you browse public Internet from the same
                  network as your relay, unless you want to write
                  e-mails to those sites (you should!).
                </para></important>

                <para>
                  See
                  <link xlink:href="https://www.torproject.org/docs/tor-doc-relay.html.en" />
                  for more info.
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term><literal>bridge</literal></term>
              <listitem>
                <para>
                  Regular bridge. Works like a regular relay, but
                  doesn't list you in the public relay directory and
                  hides your Tor node behind obfs4proxy.
                </para>

                <para>
                  Using this option will make Tor advertise your bridge
                  to users through various mechanisms like
                  <link xlink:href="https://bridges.torproject.org/" />, though.
                </para>

                <important>
                  <para>
                    WARNING: THE FOLLOWING PARAGRAPH IS NOT LEGAL ADVICE.
                    Consult with your lawyer when in doubt.
                  </para>

                  <para>
                    This role should be safe to use in most situations
                    (unless the act of forwarding traffic for others is
                    a punishable offence under your local laws, which
                    would be pretty insane as it would make ISP illegal).
                  </para>
                </important>

                <para>
                  See <link xlink:href="https://www.torproject.org/docs/bridges.html.en" />
                  for more info.
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term><literal>private-bridge</literal></term>
              <listitem>
                <para>
                  Private bridge. Works like regular bridge, but does
                  not advertise your node in any way.
                </para>

                <para>
                  Using this role means that you won't contribute to Tor
                  network in any way unless you advertise your node
                  yourself in some way.
                </para>

                <para>
                  Use this if you want to run a private bridge, for
                  example because you'll give out your bridge addr
                  manually to your friends.
                </para>

                <para>
                  Switching to this role after measurable time in
                  "bridge" role is pretty useless as some Tor users
                  would have learned about your node already. In the
                  latter case you can still change
                  <option>port</option> option.
                </para>

                <para>
                  See <link xlink:href="https://www.torproject.org/docs/bridges.html.en" />
                  for more info.
                </para>
              </listitem>
            </varlistentry>
            </variablelist>
          '';
        };

        onionServices = mkOption {
          description = descriptionGeneric "HiddenServiceDir";
          default = {};
          example = {
            "example.org/www" = {
              map = [ 80 ];
              authorizedClients = [
                "descriptor:x25519:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
              ];
            };
          };
          type = types.attrsOf (types.submodule ({name, config, ...}: {
            options.path = mkOption {
              type = types.path;
              description = ''
                Path where to store the data files of the hidden service.
                If the <option>secretKey</option> is null
                this defaults to <literal>${stateDir}/onion/$onion</literal>,
                otherwise to <literal>${runDir}/onion/$onion</literal>.
              '';
            };
            options.secretKey = mkOption {
              type = with types; nullOr path;
              default = null;
              example = "/run/keys/tor/onion/expyuzz4wqqyqhjn/hs_ed25519_secret_key";
              description = ''
                Secret key of the onion service.
                If null, Tor reuses any preexisting secret key (in <option>path</option>)
                or generates a new one.
                The associated public key and hostname are deterministically regenerated
                from this file if they do not exist.
              '';
            };
            options.authorizeClient = mkOption {
              description = descriptionGeneric "HiddenServiceAuthorizeClient";
              default = null;
              type = types.nullOr (types.submodule ({...}: {
                options = {
                  authType = mkOption {
                    type = types.enum [ "basic" "stealth" ];
                    description = ''
                      Either <literal>"basic"</literal> for a general-purpose authorization protocol
                      or <literal>"stealth"</literal> for a less scalable protocol
                      that also hides service activity from unauthorized clients.
                    '';
                  };
                  clientNames = mkOption {
                    type = with types; nonEmptyListOf (strMatching "[A-Za-z0-9+-_]+");
                    description = ''
                      Only clients that are listed here are authorized to access the hidden service.
                      Generated authorization data can be found in <filename>${stateDir}/onion/$name/hostname</filename>.
                      Clients need to put this authorization data in their configuration file using
                      <xref linkend="opt-services.tor.settings.HidServAuth"/>.
                    '';
                  };
                };
              }));
            };
            options.authorizedClients = mkOption {
              description = ''
                Authorized clients for a v3 onion service,
                as a list of public key, in the format:
                <screen>descriptor:x25519:&lt;base32-public-key&gt;</screen>
              '' + descriptionGeneric "_client_authorization";
              type = with types; listOf str;
              default = [];
              example = ["descriptor:x25519:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
            };
            options.map = mkOption {
              description = descriptionGeneric "HiddenServicePort";
              type = with types; listOf (oneOf [
                port (submodule ({...}: {
                  options = {
                    port = optionPort;
                    target = mkOption {
                      default = null;
                      type = nullOr (submodule ({...}: {
                        options = {
                          unix = optionUnix;
                          addr = optionAddress;
                          port = optionPort;
                        };
                      }));
                    };
                  };
                }))
              ]);
              apply = map (v: if isInt v then {port=v; target=null;} else v);
            };
            options.version = mkOption {
              description = descriptionGeneric "HiddenServiceVersion";
              type = with types; nullOr (enum [2 3]);
              default = null;
            };
            options.settings = mkOption {
              description = ''
                Settings of the onion service.
              '' + descriptionGeneric "_hidden_service_options";
              default = {};
              type = types.submodule {
                freeformType = with types;
                  (attrsOf (nullOr (oneOf [str int bool (listOf str)]))) // {
                    description = "settings option";
                  };
                options.HiddenServiceAllowUnknownPorts = optionBool "HiddenServiceAllowUnknownPorts";
                options.HiddenServiceDirGroupReadable = optionBool "HiddenServiceDirGroupReadable";
                options.HiddenServiceExportCircuitID = mkOption {
                  description = descriptionGeneric "HiddenServiceExportCircuitID";
                  type = with types; nullOr (enum ["haproxy"]);
                  default = null;
                };
                options.HiddenServiceMaxStreams = mkOption {
                  description = descriptionGeneric "HiddenServiceMaxStreams";
                  type = with types; nullOr (ints.between 0 65535);
                  default = null;
                };
                options.HiddenServiceMaxStreamsCloseCircuit = optionBool "HiddenServiceMaxStreamsCloseCircuit";
                options.HiddenServiceNumIntroductionPoints = mkOption {
                  description = descriptionGeneric "HiddenServiceNumIntroductionPoints";
                  type = with types; nullOr (ints.between 0 20);
                  default = null;
                };
                options.HiddenServiceSingleHopMode = optionBool "HiddenServiceSingleHopMode";
                options.RendPostPeriod = optionString "RendPostPeriod";
              };
            };
            config = {
              path = mkDefault ((if config.secretKey == null then stateDir else runDir) + "/onion/${name}");
              settings.HiddenServiceVersion = config.version;
              settings.HiddenServiceAuthorizeClient =
                if config.authorizeClient != null then
                  config.authorizeClient.authType + " " +
                  concatStringsSep "," config.authorizeClient.clientNames
                else null;
              settings.HiddenServicePort = map (p: mkValueString "" p.port + " " + mkValueString "" p.target) config.map;
            };
          }));
        };
      };

      settings = mkOption {
        description = ''
          See <link xlink:href="https://2019.www.torproject.org/docs/tor-manual.html.en">torrc manual</link>
          for documentation.
        '';
        default = {};
        type = types.submodule {
          freeformType = with types;
            (attrsOf (nullOr (oneOf [str int bool (listOf str)]))) // {
              description = "settings option";
            };
          options.Address = optionString "Address";
          options.AssumeReachable = optionBool "AssumeReachable";
          options.AccountingMax = optionBandwith "AccountingMax";
          options.AccountingStart = optionString "AccountingStart";
          options.AuthDirHasIPv6Connectivity = optionBool "AuthDirHasIPv6Connectivity";
          options.AuthDirListBadExits = optionBool "AuthDirListBadExits";
          options.AuthDirPinKeys = optionBool "AuthDirPinKeys";
          options.AuthDirSharedRandomness = optionBool "AuthDirSharedRandomness";
          options.AuthDirTestEd25519LinkKeys = optionBool "AuthDirTestEd25519LinkKeys";
          options.AuthoritativeDirectory = optionBool "AuthoritativeDirectory";
          options.AutomapHostsOnResolve = optionBool "AutomapHostsOnResolve";
          options.AutomapHostsSuffixes = optionStrings "AutomapHostsSuffixes" // {
            default = [".onion" ".exit"];
            example = [".onion"];
          };
          options.BandwidthBurst = optionBandwith "BandwidthBurst";
          options.BandwidthRate = optionBandwith "BandwidthRate";
          options.BridgeAuthoritativeDir = optionBool "BridgeAuthoritativeDir";
          options.BridgeRecordUsageByCountry = optionBool "BridgeRecordUsageByCountry";
          options.BridgeRelay = optionBool "BridgeRelay" // { default = false; };
          options.CacheDirectory = optionPath "CacheDirectory";
          options.CacheDirectoryGroupReadable = optionBool "CacheDirectoryGroupReadable"; # default is null and like "auto"
          options.CellStatistics = optionBool "CellStatistics";
          options.ClientAutoIPv6ORPort = optionBool "ClientAutoIPv6ORPort";
          options.ClientDNSRejectInternalAddresses = optionBool "ClientDNSRejectInternalAddresses";
          options.ClientOnionAuthDir = mkOption {
            description = descriptionGeneric "ClientOnionAuthDir";
            default = null;
            type = with types; nullOr path;
          };
          options.ClientPreferIPv6DirPort = optionBool "ClientPreferIPv6DirPort"; # default is null and like "auto"
          options.ClientPreferIPv6ORPort = optionBool "ClientPreferIPv6ORPort"; # default is null and like "auto"
          options.ClientRejectInternalAddresses = optionBool "ClientRejectInternalAddresses";
          options.ClientUseIPv4 = optionBool "ClientUseIPv4";
          options.ClientUseIPv6 = optionBool "ClientUseIPv6";
          options.ConnDirectionStatistics = optionBool "ConnDirectionStatistics";
          options.ConstrainedSockets = optionBool "ConstrainedSockets";
          options.ContactInfo = optionString "ContactInfo";
          options.ControlPort = mkOption rec {
            description = descriptionGeneric "ControlPort";
            default = [];
            example = [{port = 9051;}];
            type = with types; oneOf [port (enum ["auto"]) (listOf (oneOf [
              port (enum ["auto"]) (submodule ({config, ...}: let
                flags = ["GroupWritable" "RelaxDirModeCheck" "WorldWritable"];
                in {
                options = {
                  unix = optionUnix;
                  flags = optionFlags;
                  addr = optionAddress;
                  port = optionPort;
                } // genAttrs flags (name: mkOption { type = types.bool; default = false; });
                config = {
                  flags = filter (name: config.${name} == true) flags;
                };
              }))
            ]))];
          };
          options.ControlPortFileGroupReadable= optionBool "ControlPortFileGroupReadable";
          options.ControlPortWriteToFile = optionPath "ControlPortWriteToFile";
          options.ControlSocket = optionPath "ControlSocket";
          options.ControlSocketsGroupWritable = optionBool "ControlSocketsGroupWritable";
          options.CookieAuthFile = optionPath "CookieAuthFile";
          options.CookieAuthFileGroupReadable = optionBool "CookieAuthFileGroupReadable";
          options.CookieAuthentication = optionBool "CookieAuthentication";
          options.DataDirectory = optionPath "DataDirectory" // { default = stateDir; };
          options.DataDirectoryGroupReadable = optionBool "DataDirectoryGroupReadable";
          options.DirPortFrontPage = optionPath "DirPortFrontPage";
          options.DirAllowPrivateAddresses = optionBool "DirAllowPrivateAddresses";
          options.DormantCanceledByStartup = optionBool "DormantCanceledByStartup";
          options.DormantOnFirstStartup = optionBool "DormantOnFirstStartup";
          options.DormantTimeoutDisabledByIdleStreams = optionBool "DormantTimeoutDisabledByIdleStreams";
          options.DirCache = optionBool "DirCache";
          options.DirPolicy = mkOption {
            description = descriptionGeneric "DirPolicy";
            type = with types; listOf str;
            default = [];
            example = ["accept *:*"];
          };
          options.DirPort = optionORPort "DirPort";
          options.DirReqStatistics = optionBool "DirReqStatistics";
          options.DisableAllSwap = optionBool "DisableAllSwap";
          options.DisableDebuggerAttachment = optionBool "DisableDebuggerAttachment";
          options.DisableNetwork = optionBool "DisableNetwork";
          options.DisableOOSCheck = optionBool "DisableOOSCheck";
          options.DNSPort = optionIsolablePorts "DNSPort";
          options.DoSCircuitCreationEnabled = optionBool "DoSCircuitCreationEnabled";
          options.DoSConnectionEnabled = optionBool "DoSConnectionEnabled"; # default is null and like "auto"
          options.DoSRefuseSingleHopClientRendezvous = optionBool "DoSRefuseSingleHopClientRendezvous";
          options.DownloadExtraInfo = optionBool "DownloadExtraInfo";
          options.EnforceDistinctSubnets = optionBool "EnforceDistinctSubnets";
          options.EntryStatistics = optionBool "EntryStatistics";
          options.ExitPolicy = optionStrings "ExitPolicy" // {
            default = ["reject *:*"];
            example = ["accept *:*"];
          };
          options.ExitPolicyRejectLocalInterfaces = optionBool "ExitPolicyRejectLocalInterfaces";
          options.ExitPolicyRejectPrivate = optionBool "ExitPolicyRejectPrivate";
          options.ExitPortStatistics = optionBool "ExitPortStatistics";
          options.ExitRelay = optionBool "ExitRelay"; # default is null and like "auto"
          options.ExtORPort = mkOption {
            description = descriptionGeneric "ExtORPort";
            default = null;
            type = with types; nullOr (oneOf [
              port (enum ["auto"]) (submodule ({...}: {
                options = {
                  addr = optionAddress;
                  port = optionPort;
                };
              }))
            ]);
            apply = p: if isInt p || isString p then { port = p; } else p;
          };
          options.ExtORPortCookieAuthFile = optionPath "ExtORPortCookieAuthFile";
          options.ExtORPortCookieAuthFileGroupReadable = optionBool "ExtORPortCookieAuthFileGroupReadable";
          options.ExtendAllowPrivateAddresses = optionBool "ExtendAllowPrivateAddresses";
          options.ExtraInfoStatistics = optionBool "ExtraInfoStatistics";
          options.FascistFirewall = optionBool "FascistFirewall";
          options.FetchDirInfoEarly = optionBool "FetchDirInfoEarly";
          options.FetchDirInfoExtraEarly = optionBool "FetchDirInfoExtraEarly";
          options.FetchHidServDescriptors = optionBool "FetchHidServDescriptors";
          options.FetchServerDescriptors = optionBool "FetchServerDescriptors";
          options.FetchUselessDescriptors = optionBool "FetchUselessDescriptors";
          options.ReachableAddresses = optionStrings "ReachableAddresses";
          options.ReachableDirAddresses = optionStrings "ReachableDirAddresses";
          options.ReachableORAddresses = optionStrings "ReachableORAddresses";
          options.GeoIPFile = optionPath "GeoIPFile";
          options.GeoIPv6File = optionPath "GeoIPv6File";
          options.GuardfractionFile = optionPath "GuardfractionFile";
          options.HidServAuth = mkOption {
            description = descriptionGeneric "HidServAuth";
            default = [];
            type = with types; listOf (oneOf [
              (submodule {
                options = {
                  onion = mkOption {
                    type = strMatching "[a-z2-7]{16}\\.onion";
                    description = "Onion address.";
                    example = "xxxxxxxxxxxxxxxx.onion";
                  };
                  auth = mkOption {
                    type = strMatching "[A-Za-z0-9+/]{22}";
                    description = "Authentication cookie.";
                  };
                };
              })
            ]);
            example = [
              {
                onion = "xxxxxxxxxxxxxxxx.onion";
                auth = "xxxxxxxxxxxxxxxxxxxxxx";
              }
            ];
          };
          options.HiddenServiceNonAnonymousMode = optionBool "HiddenServiceNonAnonymousMode";
          options.HiddenServiceStatistics = optionBool "HiddenServiceStatistics";
          options.HSLayer2Nodes = optionStrings "HSLayer2Nodes";
          options.HSLayer3Nodes = optionStrings "HSLayer3Nodes";
          options.HTTPTunnelPort = optionIsolablePorts "HTTPTunnelPort";
          options.IPv6Exit = optionBool "IPv6Exit";
          options.KeyDirectory = optionPath "KeyDirectory";
          options.KeyDirectoryGroupReadable = optionBool "KeyDirectoryGroupReadable";
          options.LogMessageDomains = optionBool "LogMessageDomains";
          options.LongLivedPorts = optionPorts "LongLivedPorts";
          options.MainloopStats = optionBool "MainloopStats";
          options.MaxAdvertisedBandwidth = optionBandwith "MaxAdvertisedBandwidth";
          options.MaxCircuitDirtiness = optionInt "MaxCircuitDirtiness";
          options.MaxClientCircuitsPending = optionInt "MaxClientCircuitsPending";
          options.NATDPort = optionIsolablePorts "NATDPort";
          options.NewCircuitPeriod = optionInt "NewCircuitPeriod";
          options.Nickname = optionString "Nickname";
          options.ORPort = optionORPort "ORPort";
          options.OfflineMasterKey = optionBool "OfflineMasterKey";
          options.OptimisticData = optionBool "OptimisticData"; # default is null and like "auto"
          options.PaddingStatistics = optionBool "PaddingStatistics";
          options.PerConnBWBurst = optionBandwith "PerConnBWBurst";
          options.PerConnBWRate = optionBandwith "PerConnBWRate";
          options.PidFile = optionPath "PidFile";
          options.ProtocolWarnings = optionBool "ProtocolWarnings";
          options.PublishHidServDescriptors = optionBool "PublishHidServDescriptors";
          options.PublishServerDescriptor = mkOption {
            description = descriptionGeneric "PublishServerDescriptor";
            type = with types; nullOr (enum [false true 0 1 "0" "1" "v3" "bridge"]);
            default = null;
          };
          options.ReducedExitPolicy = optionBool "ReducedExitPolicy";
          options.RefuseUnknownExits = optionBool "RefuseUnknownExits"; # default is null and like "auto"
          options.RejectPlaintextPorts = optionPorts "RejectPlaintextPorts";
          options.RelayBandwidthBurst = optionBandwith "RelayBandwidthBurst";
          options.RelayBandwidthRate = optionBandwith "RelayBandwidthRate";
          #options.RunAsDaemon
          options.Sandbox = optionBool "Sandbox";
          options.ServerDNSAllowBrokenConfig = optionBool "ServerDNSAllowBrokenConfig";
          options.ServerDNSAllowNonRFC953Hostnames = optionBool "ServerDNSAllowNonRFC953Hostnames";
          options.ServerDNSDetectHijacking = optionBool "ServerDNSDetectHijacking";
          options.ServerDNSRandomizeCase = optionBool "ServerDNSRandomizeCase";
          options.ServerDNSResolvConfFile = optionPath "ServerDNSResolvConfFile";
          options.ServerDNSSearchDomains = optionBool "ServerDNSSearchDomains";
          options.ServerTransportPlugin = mkOption {
            description = descriptionGeneric "ServerTransportPlugin";
            default = null;
            type = with types; nullOr (submodule ({...}: {
              options = {
                transports = mkOption {
                  description = "List of pluggable transports.";
                  type = listOf str;
                  example = ["obfs2" "obfs3" "obfs4" "scramblesuit"];
                };
                exec = mkOption {
                  type = types.str;
                  description = "Command of pluggable transport.";
                };
              };
            }));
          };
          options.ShutdownWaitLength = mkOption {
            type = types.int;
            default = 30;
            description = descriptionGeneric "ShutdownWaitLength";
          };
          options.SocksPolicy = optionStrings "SocksPolicy" // {
            example = ["accept *:*"];
          };
          options.SOCKSPort = mkOption {
            description = descriptionGeneric "SOCKSPort";
            default = if cfg.settings.HiddenServiceNonAnonymousMode == true then [{port = 0;}] else [];
            defaultText = literalExpression ''
              if config.${opt.settings}.HiddenServiceNonAnonymousMode == true
              then [ { port = 0; } ]
              else [ ]
            '';
            example = [{port = 9090;}];
            type = types.listOf (optionSOCKSPort true);
          };
          options.TestingTorNetwork = optionBool "TestingTorNetwork";
          options.TransPort = optionIsolablePorts "TransPort";
          options.TransProxyType = mkOption {
            description = descriptionGeneric "TransProxyType";
            type = with types; nullOr (enum ["default" "TPROXY" "ipfw" "pf-divert"]);
            default = null;
          };
          #options.TruncateLogFile
          options.UnixSocksGroupWritable = optionBool "UnixSocksGroupWritable";
          options.UseDefaultFallbackDirs = optionBool "UseDefaultFallbackDirs";
          options.UseMicrodescriptors = optionBool "UseMicrodescriptors";
          options.V3AuthUseLegacyKey = optionBool "V3AuthUseLegacyKey";
          options.V3AuthoritativeDirectory = optionBool "V3AuthoritativeDirectory";
          options.VersioningAuthoritativeDirectory = optionBool "VersioningAuthoritativeDirectory";
          options.VirtualAddrNetworkIPv4 = optionString "VirtualAddrNetworkIPv4";
          options.VirtualAddrNetworkIPv6 = optionString "VirtualAddrNetworkIPv6";
          options.WarnPlaintextPorts = optionPorts "WarnPlaintextPorts";
        };
      };
    };
  };

  config = mkIf cfg.enable {
    # Not sure if `cfg.relay.role == "private-bridge"` helps as tor
    # sends a lot of stats
    warnings = optional (cfg.settings.BridgeRelay &&
      flatten (mapAttrsToList (n: o: o.map) cfg.relay.onionServices) != [])
      ''
        Running Tor hidden services on a public relay makes the
        presence of hidden services visible through simple statistical
        analysis of publicly available data.
        See https://trac.torproject.org/projects/tor/ticket/8742

        You can safely ignore this warning if you don't intend to
        actually hide your hidden services. In either case, you can
        always create a container/VM with a separate Tor daemon instance.
      '' ++
      flatten (mapAttrsToList (n: o:
        optional (o.settings.HiddenServiceVersion == 2) [
          (optional (o.settings.HiddenServiceExportCircuitID != null) ''
            HiddenServiceExportCircuitID is used in the HiddenService: ${n}
            but this option is only for v3 hidden services.
          '')
        ] ++
        optional (o.settings.HiddenServiceVersion != 2) [
          (optional (o.settings.HiddenServiceAuthorizeClient != null) ''
            HiddenServiceAuthorizeClient is used in the HiddenService: ${n}
            but this option is only for v2 hidden services.
          '')
          (optional (o.settings.RendPostPeriod != null) ''
            RendPostPeriod is used in the HiddenService: ${n}
            but this option is only for v2 hidden services.
          '')
        ]
      ) cfg.relay.onionServices);

    users.groups.tor.gid = config.ids.gids.tor;
    users.users.tor =
      { description = "Tor Daemon User";
        createHome  = true;
        home        = stateDir;
        group       = "tor";
        uid         = config.ids.uids.tor;
      };

    services.tor.settings = mkMerge [
      (mkIf cfg.enableGeoIP {
        GeoIPFile = "${cfg.package.geoip}/share/tor/geoip";
        GeoIPv6File = "${cfg.package.geoip}/share/tor/geoip6";
      })
      (mkIf cfg.controlSocket.enable {
        ControlPort = [ { unix = runDir + "/control"; GroupWritable=true; RelaxDirModeCheck=true; } ];
      })
      (mkIf cfg.relay.enable (
        optionalAttrs (cfg.relay.role != "exit") {
          ExitPolicy = mkForce ["reject *:*"];
        } //
        optionalAttrs (elem cfg.relay.role ["bridge" "private-bridge"]) {
          BridgeRelay = true;
          ExtORPort.port = mkDefault "auto";
          ServerTransportPlugin.transports = mkDefault ["obfs4"];
          ServerTransportPlugin.exec = mkDefault "${pkgs.obfs4}/bin/obfs4proxy managed";
        } // optionalAttrs (cfg.relay.role == "private-bridge") {
          ExtraInfoStatistics = false;
          PublishServerDescriptor = false;
        }
      ))
      (mkIf (!cfg.relay.enable) {
        # Avoid surprises when leaving ORPort/DirPort configurations in cfg.settings,
        # because it would still enable Tor as a relay,
        # which can trigger all sort of problems when not carefully done,
        # like the blocklisting of the machine's IP addresses
        # by some hosting providers...
        DirPort = mkForce [];
        ORPort = mkForce [];
        PublishServerDescriptor = mkForce false;
      })
      (mkIf (!cfg.client.enable) {
        # Make sure application connections via SOCKS are disabled
        # when services.tor.client.enable is false
        SOCKSPort = mkForce [ 0 ];
      })
      (mkIf cfg.client.enable (
        { SOCKSPort = [ cfg.client.socksListenAddress ];
        } // optionalAttrs cfg.client.transparentProxy.enable {
          TransPort = [{ addr = "127.0.0.1"; port = 9040; }];
        } // optionalAttrs cfg.client.dns.enable {
          DNSPort = [{ addr = "127.0.0.1"; port = 9053; }];
          AutomapHostsOnResolve = true;
        } // optionalAttrs (flatten (mapAttrsToList (n: o: o.clientAuthorizations) cfg.client.onionServices) != []) {
          ClientOnionAuthDir = runDir + "/ClientOnionAuthDir";
        }
      ))
    ];

    networking.firewall = mkIf cfg.openFirewall {
      allowedTCPPorts =
        concatMap (o:
          if isInt o && o > 0 then [o]
          else if o ? "port" && isInt o.port && o.port > 0 then [o.port]
          else []
        ) (flatten [
          cfg.settings.ORPort
          cfg.settings.DirPort
        ]);
    };

    systemd.services.tor = {
      description = "Tor Daemon";
      path = [ pkgs.tor ];

      wantedBy = [ "multi-user.target" ];
      after    = [ "network.target" ];
      restartTriggers = [ torrc ];

      serviceConfig = {
        Type = "simple";
        User = "tor";
        Group = "tor";
        ExecStartPre = [
          "${cfg.package}/bin/tor -f ${torrc} --verify-config"
          # DOC: Appendix G of https://spec.torproject.org/rend-spec-v3
          ("+" + pkgs.writeShellScript "ExecStartPre" (concatStringsSep "\n" (flatten (["set -eu"] ++
            mapAttrsToList (name: onion:
              optional (onion.authorizedClients != []) ''
                rm -rf ${escapeShellArg onion.path}/authorized_clients
                install -d -o tor -g tor -m 0700 ${escapeShellArg onion.path} ${escapeShellArg onion.path}/authorized_clients
              '' ++
              imap0 (i: pubKey: ''
                echo ${pubKey} |
                install -o tor -g tor -m 0400 /dev/stdin ${escapeShellArg onion.path}/authorized_clients/${toString i}.auth
              '') onion.authorizedClients ++
              optional (onion.secretKey != null) ''
                install -d -o tor -g tor -m 0700 ${escapeShellArg onion.path}
                key="$(cut -f1 -d: ${escapeShellArg onion.secretKey} | head -1)"
                case "$key" in
                 ("== ed25519v"*"-secret")
                  install -o tor -g tor -m 0400 ${escapeShellArg onion.secretKey} ${escapeShellArg onion.path}/hs_ed25519_secret_key;;
                 (*) echo >&2 "NixOS does not (yet) support secret key type for onion: ${name}"; exit 1;;
                esac
              ''
            ) cfg.relay.onionServices ++
            mapAttrsToList (name: onion: imap0 (i: prvKeyPath:
              let hostname = removeSuffix ".onion" name; in ''
              printf "%s:" ${escapeShellArg hostname} | cat - ${escapeShellArg prvKeyPath} |
              install -o tor -g tor -m 0700 /dev/stdin \
               ${runDir}/ClientOnionAuthDir/${escapeShellArg hostname}.${toString i}.auth_private
            '') onion.clientAuthorizations)
            cfg.client.onionServices
          ))))
        ];
        ExecStart = "${cfg.package}/bin/tor -f ${torrc}";
        ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
        KillSignal = "SIGINT";
        TimeoutSec = cfg.settings.ShutdownWaitLength + 30; # Wait a bit longer than ShutdownWaitLength before actually timing out
        Restart = "on-failure";
        LimitNOFILE = 32768;
        RuntimeDirectory = [
          # g+x allows access to the control socket
          "tor"
          "tor/root"
          # g+x can't be removed in ExecStart=, but will be removed by Tor
          "tor/ClientOnionAuthDir"
        ];
        RuntimeDirectoryMode = "0710";
        StateDirectoryMode = "0700";
        StateDirectory = [
            "tor"
            "tor/onion"
          ] ++
          flatten (mapAttrsToList (name: onion:
            optional (onion.secretKey == null) "tor/onion/${name}"
          ) cfg.relay.onionServices);
        # The following options are only to optimize:
        # systemd-analyze security tor
        RootDirectory = runDir + "/root";
        RootDirectoryStartOnly = true;
        #InaccessiblePaths = [ "-+${runDir}/root" ];
        UMask = "0066";
        BindPaths = [ stateDir ];
        BindReadOnlyPaths = [ storeDir "/etc" ] ++
          optionals config.services.resolved.enable [
            "/run/systemd/resolve/stub-resolv.conf"
            "/run/systemd/resolve/resolv.conf"
          ];
        AmbientCapabilities   = [""] ++ lib.optional bindsPrivilegedPort "CAP_NET_BIND_SERVICE";
        CapabilityBoundingSet = [""] ++ lib.optional bindsPrivilegedPort "CAP_NET_BIND_SERVICE";
        # ProtectClock= adds DeviceAllow=char-rtc r
        DeviceAllow = "";
        LockPersonality = true;
        MemoryDenyWriteExecute = true;
        NoNewPrivileges = true;
        PrivateDevices = true;
        PrivateMounts = true;
        PrivateNetwork = mkDefault false;
        PrivateTmp = true;
        # Tor cannot currently bind privileged port when PrivateUsers=true,
        # see https://gitlab.torproject.org/legacy/trac/-/issues/20930
        PrivateUsers = !bindsPrivilegedPort;
        ProcSubset = "pid";
        ProtectClock = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectProc = "invisible";
        ProtectSystem = "strict";
        RemoveIPC = true;
        RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" "AF_NETLINK" ];
        RestrictNamespaces = true;
        RestrictRealtime = true;
        RestrictSUIDSGID = true;
        # See also the finer but experimental option settings.Sandbox
        SystemCallFilter = [
          "@system-service"
          # Groups in @system-service which do not contain a syscall listed by:
          # perf stat -x, 2>perf.log -e 'syscalls:sys_enter_*' tor
          # in tests, and seem likely not necessary for tor.
          "~@aio" "~@chown" "~@keyring" "~@memlock" "~@resources" "~@setuid" "~@timer"
        ];
        SystemCallArchitectures = "native";
        SystemCallErrorNumber = "EPERM";
      };
    };

    environment.systemPackages = [ cfg.package ];
  };

  meta.maintainers = with lib.maintainers; [ julm ];
}