@@ -3,120 +3,116 @@
33with lib;
44
55let
6−
7− inherit (pkgs) tor privoxy;
8−
9− stateDir = "/var/lib/tor";
10− privoxyDir = stateDir+"/privoxy";
11−
126 cfg = config.services.tor;
13−
14− torUser = "tor";
15−
16− opt = name: value: if value != "" then "${name} ${value}" else "";
17− optint = name: value: if value != 0 then "${name} ${toString value}" else "";
18−
7+ torDirectory = "/var/lib/tor";
8+
9+ opt = name: value: optionalString (value != null) "${name} ${value}";
10+ optint = name: value: optionalString (value != 0) "${name} ${toString value}";
11+
12+ torRc = ''
13+ User tor
14+ DataDirectory ${torDirectory}
15+
16+ ${optint "ControlPort" cfg.controlPort}
17+ ''
18+ # Client connection config
19+ + optionalString cfg.client.enable ''
20+ SOCKSPort ${cfg.client.socksListenAddress}
21+ ${opt "SocksPolicy" cfg.client.socksPolicy}
22+ ''
23+ # Relay config
24+ + optionalString cfg.relay.enable ''
25+ ORPort ${cfg.relay.portSpec}
26+ ${opt "Nickname" cfg.relay.nickname}
27+ ${opt "ContactInfo" cfg.relay.contactInfo}
28+
29+ ${optint "RelayBandwidthRate" cfg.relay.bandwidthRate}
30+ ${optint "RelayBandwidthBurst" cfg.relay.bandwidthBurst}
31+ ${opt "AccountingMax" cfg.relay.accountingMax}
32+ ${opt "AccountingStart" cfg.relay.accountingStart}
33+
34+ ${if cfg.relay.isExit then
35+ opt "ExitPolicy" cfg.relay.exitPolicy
36+ else
37+ "ExitPolicy reject *:*"}
38+
39+ ${optionalString cfg.relay.isBridge ''
40+ BridgeRelay 1
41+ ServerTransportPlugin obfs2,obfs3 exec ${pkgs.pythonPackages.obfsproxy}/bin/obfsproxy managed
42+ ''}
43+ ''
44+ + cfg.extraConfig;
45+
46+ torRcFile = pkgs.writeText "torrc" torRc;
1947in
20−
2148{
22−
23− ###### interface
24−
2549 options = {
26−
2750 services.tor = {
51+ enable = mkOption {
52+ type = types.bool;
53+ default = false;
54+ description = ''
55+ Enable the Tor daemon. By default, the daemon is run without
56+ relay, exit, bridge or client connectivity.
57+ '';
58+ };
2859
29− config = mkOption {
60+ extraConfig = mkOption {
61+ type = types.str;
3062 default = "";
3163 description = ''
3264 Extra configuration. Contents will be added verbatim to the
33− configuration file.
65+ configuration file at the end.
3466 '';
3567 };
3668
37− client = {
69+ controlPort = mkOption {
70+ type = types.int;
71+ default = 0;
72+ example = 9051;
73+ description = ''
74+ If set, Tor will accept connections on the specified port
75+ and allow them to control the tor process.
76+ '';
77+ };
3878
79+ client = {
3980 enable = mkOption {
81+ type = types.bool;
4082 default = false;
4183 description = ''
42− Whether to enable Tor daemon to route application connections.
43− You might want to disable this if you plan running a dedicated Tor relay.
84+ Whether to enable Tor daemon to route application
85+ connections. You might want to disable this if you plan
86+ running a dedicated Tor relay.
4487 '';
4588 };
4689
4790 socksListenAddress = mkOption {
91+ type = types.str;
4892 default = "127.0.0.1:9050";
4993 example = "192.168.0.1:9100";
5094 description = ''
51− Bind to this address to listen for connections from Socks-speaking
52− applications.
53− '';
54− };
55−
56− socksListenAddressFaster = mkOption {
57− default = "127.0.0.1:9063";
58− description = ''
59− Same as socksListenAddress but uses weaker circuit isolation to provide
60− performance suitable for a web browser.
95+ Bind to this address to listen for connections from
96+ Socks-speaking applications.
6197 '';
6298 };
6399
64100 socksPolicy = mkOption {
65− default = "";
101+ type = types.nullOr types.str;
102+ default = null;
66103 example = "accept 192.168.0.0/16, reject *";
67104 description = ''
68− Entry policies to allow/deny SOCKS requests based on IP address.
69− First entry that matches wins. If no SocksPolicy is set, we accept
70− all (and only) requests from SocksListenAddress.
105+ Entry policies to allow/deny SOCKS requests based on IP
106+ address. First entry that matches wins. If no SocksPolicy
107+ is set, we accept all (and only) requests from
108+ SocksListenAddress.
71109 '';
72110 };
73−
74− privoxy = {
75−
76− enable = mkOption {
77− default = true;
78− description = ''
79− Whether to enable a special instance of privoxy dedicated to Tor.
80− To have anonymity, protocols need to be scrubbed of identifying
81− information.
82− Most people using Tor want to anonymize their web traffic, so by
83− default we enable an special instance of privoxy specifically for
84− Tor.
85− However, if you are only going to use Tor only for other kinds of
86− traffic then you can disable this option.
87− '';
88− };
89−
90− listenAddress = mkOption {
91− default = "127.0.0.1:8118";
92− description = ''
93− Address that Tor's instance of privoxy is listening to.
94− *This does not configure the standard NixOS instance of privoxy.*
95− This is for Tor connections only!
96− See services.privoxy.listenAddress to configure the standard NixOS
97− instace of privoxy.
98− '';
99− };
100−
101− config = mkOption {
102− default = "";
103− description = ''
104− Extra configuration for Tor's instance of privoxy. Contents will be
105− added verbatim to the configuration file.
106− *This does not configure the standard NixOS instance of privoxy.*
107− This is for Tor connections only!
108− See services.privoxy.extraConfig to configure the standard NixOS
109− instace of privoxy.
110− '';
111− };
112−
113− };
114−
115111 };
116112
117113 relay = {
118−
119114 enable = mkOption {
115+ type = types.bool;
120116 default = false;
121117 description = ''
122118 Whether to enable relaying TOR traffic for others.
@@ -126,16 +122,19 @@ in
126122 };
127123
128124 isBridge = mkOption {
125+ type = types.bool;
129126 default = false;
130127 description = ''
131− Bridge relays (or "bridges" ) are Tor relays that aren't listed in the
132− main directory. Since there is no complete public list of them, even if an
133− ISP is filtering connections to all the known Tor relays, they probably
128+ Bridge relays (or "bridges") are Tor relays that aren't
129+ listed in the main directory. Since there is no complete
130+ public list of them, even if an ISP is filtering
131+ connections to all the known Tor relays, they probably
134132 won't be able to block all the bridges.
135133
136134 A bridge relay can't be an exit relay.
137135
138− You need to set relay.enable to true for this option to take effect.
136+ You need to set relay.enable to true for this option to
137+ take effect.
139138
140139 The bridge is set up with an obfuscated transport proxy.
141140
@@ -144,25 +143,72 @@ in
144143 };
145144
146145 isExit = mkOption {
146+ type = types.bool;
147147 default = false;
148148 description = ''
149− An exit relay allows Tor users to access regular Internet services.
149+ An exit relay allows Tor users to access regular Internet
150+ services.
150151
151− Unlike running a non-exit relay, running an exit relay may expose
152− you to abuse complaints. See https://www.torproject.org/faq.html.en#ExitPolicies for more info.
152+ Unlike running a non-exit relay, running an exit relay may
153+ expose you to abuse complaints. See
154+ https://www.torproject.org/faq.html.en#ExitPolicies for
155+ more info.
153156
154− You can specify which services Tor users may access via your exit relay using exitPolicy option.
157+ You can specify which services Tor users may access via
158+ your exit relay using exitPolicy option.
155159 '';
156160 };
157161
158162 nickname = mkOption {
163+ type = types.str;
159164 default = "anonymous";
160165 description = ''
161166 A unique handle for your TOR relay.
162167 '';
163168 };
164169
170+ contactInfo = mkOption {
171+ type = types.nullOr types.str;
172+ default = null;
173+ example = "admin@relay.com";
174+ description = ''
175+ Contact information for the relay owner (e.g. a mail
176+ address and GPG key ID).
177+ '';
178+ };
179+
180+ accountingMax = mkOption {
181+ type = types.nullOr types.str;
182+ default = null;
183+ example = "450 GBytes";
184+ description = ''
185+ Specify maximum bandwidth allowed during an accounting
186+ period. This allows you to limit overall tor bandwidth
187+ over some time period. See the
188+ <literal>AccountingMax</literal> option by looking at the
189+ tor manual (<literal>man tor</literal>) for more.
190+
191+ Note this limit applies individually to upload and
192+ download; if you specify <literal>"500 GBytes"</literal>
193+ here, then you may transfer up to 1 TBytes of overall
194+ bandwidth (500 GB upload, 500 GB download).
195+ '';
196+ };
197+
198+ accountingStart = mkOption {
199+ type = types.nullOr types.str;
200+ default = null;
201+ example = "month 1 1:00";
202+ description = ''
203+ Specify length of an accounting period. This allows you to
204+ limit overall tor bandwidth over some time period. See the
205+ <literal>AccountingStart</literal> option by looking at
206+ the tor manual (<literal>man tor</literal>) for more.
207+ '';
208+ };
209+
165210 bandwidthRate = mkOption {
211+ type = types.int;
166212 default = 0;
167213 example = 100;
168214 description = ''
@@ -172,6 +218,7 @@ in
172218 };
173219
174220 bandwidthBurst = mkOption {
221+ type = types.int;
175222 default = cfg.relay.bandwidthRate;
176223 example = 200;
177224 description = ''
@@ -181,143 +228,99 @@ in
181228 '';
182229 };
183230
184− port = mkOption {
185− default = 9001;
231+ portSpec = mkOption {
232+ type = types.str;
233+ example = "143";
186234 description = ''
187− What port to advertise for Tor connections.
188− '';
189− };
190−
191− listenAddress = mkOption {
192− default = "";
193− example = "0.0.0.0:9090";
194− description = ''
195− Set this if you need to listen on a port other than the one advertised
196− in relayPort (e.g. to advertise 443 but bind to 9090). You'll need to do
197− ipchains or other port forwsarding yourself to make this work.
235+ What port to advertise for Tor connections. This corresponds
236+ to the <literal>ORPort</literal> section in the Tor manual; see
237+ <literal>man tor</literal> for more details.
238+
239+ At a minimum, you should just specify the port for the
240+ relay to listen on; a common one like 143, 22, 80, or 443
241+ to help Tor users who may have very restrictive port-based
242+ firewalls.
198243 '';
199244 };
200245
201246 exitPolicy = mkOption {
202− default = "";
247+ type = types.nullOr types.str;
248+ default = null;
203249 example = "accept *:6660-6667,reject *:*";
204250 description = ''
205− A comma-separated list of exit policies. They're considered first
206− to last, and the first match wins. If you want to _replace_
207− the default exit policy, end this with either a reject *:* or an
208− accept *:*. Otherwise, you're _augmenting_ (prepending to) the
209− default exit policy. Leave commented to just use the default, which is
210− available in the man page or at https://www.torproject.org/documentation.html
251+ A comma-separated list of exit policies. They're
252+ considered first to last, and the first match wins. If you
253+ want to _replace_ the default exit policy, end this with
254+ either a reject *:* or an accept *:*. Otherwise, you're
255+ _augmenting_ (prepending to) the default exit
256+ policy. Leave commented to just use the default, which is
257+ available in the man page or at
258+ https://www.torproject.org/documentation.html
211259
212260 Look at https://www.torproject.org/faq-abuse.html#TypicalAbuses
213261 for issues you might encounter if you use the default exit policy.
214262
215− If certain IPs and ports are blocked externally, e.g. by your firewall,
216− you should update your exit policy to reflect this -- otherwise Tor
217− users will be told that those destinations are down.
263+ If certain IPs and ports are blocked externally, e.g. by
264+ your firewall, you should update your exit policy to
265+ reflect this -- otherwise Tor users will be told that
266+ those destinations are down.
218267 '';
219268 };
220−
221269 };
222−
223270 };
224−
225271 };
226272
227−
228− ###### implementation
229−
230− config = mkIf (cfg.client.enable || cfg.relay.enable) {
231−
273+ config = mkIf cfg.enable {
232274 assertions = singleton
233− { assertion = cfg.relay.enable -> !(cfg.relay.isBridge && cfg.relay.isExit);
234− message = "Can't be both an exit and a bridge relay at the same time";
275+ { message = "Can't be both an exit and a bridge relay at the same time";
276+ assertion =
277+ cfg.relay.enable -> !(cfg.relay.isBridge && cfg.relay.isExit);
235278 };
236279
237− users.extraUsers = singleton
238− { name = torUser;
239− uid = config.ids.uids.tor;
240− description = "Tor daemon user";
241− home = stateDir;
280+ users.extraGroups.tor.gid = config.ids.gids.tor;
281+ users.extraUsers.tor =
282+ { description = "Tor Daemon User";
283+ createHome = true;
284+ home = torDirectory;
285+ group = "tor";
286+ uid = config.ids.uids.tor;
242287 };
243288
244− jobs = {
245− tor = { name = "tor";
246−
247− startOn = "started network-interfaces";
248− stopOn = "stopping network-interfaces";
249−
250− preStart = ''
251− mkdir -m 0755 -p ${stateDir}
252− chown ${torUser} ${stateDir}
253− '';
254− exec = "${tor}/bin/tor -f ${pkgs.writeText "torrc" cfg.config}";
255− }; }
256− // optionalAttrs (cfg.client.privoxy.enable && cfg.client.enable) {
257− torPrivoxy = { name = "tor-privoxy";
258−
259− startOn = "started network-interfaces";
260− stopOn = "stopping network-interfaces";
261−
262− preStart = ''
263− mkdir -m 0755 -p ${privoxyDir}
264− chown ${torUser} ${privoxyDir}
265− '';
266− exec = "${privoxy}/sbin/privoxy --no-daemon --user ${torUser} ${pkgs.writeText "torPrivoxy.conf" cfg.client.privoxy.config}";
267− }; };
268−
269− services.tor.config = ''
270− DataDirectory ${stateDir}
271− User ${torUser}
272− ''
273− + optionalString cfg.client.enable ''
274− SOCKSPort ${cfg.client.socksListenAddress} IsolateDestAddr
275− SOCKSPort ${cfg.client.socksListenAddressFaster}
276− ${opt "SocksPolicy" cfg.client.socksPolicy}
277− ''
278− + optionalString cfg.relay.enable ''
279− ORPort ${toString cfg.relay.port}
280− ${opt "ORListenAddress" cfg.relay.listenAddress }
281− ${opt "Nickname" cfg.relay.nickname}
282− ${optint "RelayBandwidthRate" cfg.relay.bandwidthRate}
283− ${optint "RelayBandwidthBurst" cfg.relay.bandwidthBurst}
284− ${if cfg.relay.isExit then opt "ExitPolicy" cfg.relay.exitPolicy else "ExitPolicy reject *:*"}
285− ${if cfg.relay.isBridge then ''
286− BridgeRelay 1
287− ServerTransportPlugin obfs2,obfs3 exec ${pkgs.pythonPackages.obfsproxy}/bin/obfsproxy managed
288− '' else ""}
289− '';
290−
291− services.tor.client.privoxy.config = ''
292− # Generally, this file goes in /etc/privoxy/config
293− #
294− # Tor listens as a SOCKS4a proxy here:
295− forward-socks4a / ${cfg.client.socksListenAddressFaster} .
296− confdir ${privoxy}/etc
297− logdir ${privoxyDir}
298− # actionsfile standard # Internal purpose, recommended
299− actionsfile default.action # Main actions file
300− actionsfile user.action # User customizations
301− filterfile default.filter
302−
303− # Don't log interesting things, only startup messages, warnings and errors
304− logfile logfile
305− #jarfile jarfile
306− #debug 0 # show each GET/POST/CONNECT request
307− debug 4096 # Startup banner and warnings
308− debug 8192 # Errors - *we highly recommended enabling this*
309−
310− user-manual ${privoxy}/doc/privoxy/user-manual
311− listen-address ${cfg.client.privoxy.listenAddress}
312− toggle 1
313− enable-remote-toggle 0
314− enable-edit-actions 0
315− enable-remote-http-toggle 0
316− buffer-limit 4096
317−
318− # Extra config goes here
319− '';
289+ systemd.services.tor =
290+ { description = "Tor Daemon";
291+ path = [ pkgs.tor ];
292+
293+ wantedBy = [ "multi-user.target" ];
294+ after = [ "network.target" ];
295+ restartTriggers = [ torRcFile ];
296+
297+ # Translated from the upstream contrib/dist/tor.service.in
298+ serviceConfig =
299+ { Type = "simple";
300+ ExecStartPre = "${pkgs.tor}/bin/tor -f ${torRcFile} --verify-config";
301+ ExecStart = "${pkgs.tor}/bin/tor -f ${torRcFile} --RunAsDaemon 0";
302+ ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
303+ KillSignal = "SIGINT";
304+ TimeoutSec = 30;
305+ Restart = "on-failure";
306+ LimitNOFILE = 32768;
307+
308+ # Hardening
309+ # Note: DevicePolicy is set to 'closed', although the
310+ # minimal permissions are really:
311+ # DeviceAllow /dev/null rw
312+ # DeviceAllow /dev/urandom r
313+ # .. but we can't specify DeviceAllow multiple times. 'closed'
314+ # is close enough.
315+ PrivateTmp = "yes";
316+ DevicePolicy = "closed";
317+ InaccessibleDirectories = "/home";
318+ ReadOnlyDirectories = "/";
319+ ReadWriteDirectories = torDirectory;
320+ NoNewPrivileges = "yes";
321+ };
322+ };
320323
324+ environment.systemPackages = [ pkgs.tor ];
321325 };
322−
323326}