summary refs log tree commit diff
path: root/nixos/modules/services/networking/privoxy.nix
blob: 7bc964d5f34ae2d82fad0dadba7d1ffc410fef03 (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
{ config, lib, pkgs, ... }:

with lib;

let

  cfg = config.services.privoxy;

  serialise = name: val:
         if isList val then concatMapStrings (serialise name) val
    else if isBool val then serialise name (if val then "1" else "0")
    else "${name} ${toString val}\n";

  configType = with types;
    let atom = oneOf [ int bool string path ];
    in attrsOf (either atom (listOf atom))
    // { description = ''
          privoxy configuration type. The format consists of an attribute
          set of settings. Each setting can be either a value (integer, string,
          boolean or path) or a list of such values.
        '';
       };

  ageType = types.str // {
    check = x:
      isString x &&
      (builtins.match "([0-9]+([smhdw]|min|ms|us)*)+" x != null);
    description = "tmpfiles.d(5) age format";
  };

  configFile = pkgs.writeText "privoxy.conf"
    (concatStrings (
      # Relative paths in some options are relative to confdir. Privoxy seems
      # to parse the options in order of appearance, so this must come first.
      # Nix however doesn't preserve the order in attrsets, so we have to
      # hardcode confdir here.
      [ "confdir ${pkgs.privoxy}/etc\n" ]
      ++ mapAttrsToList serialise cfg.settings
    ));

  inspectAction = pkgs.writeText "inspect-all-https.action"
    ''
      # Enable HTTPS inspection for all requests
      {+https-inspection}
      /
    '';

in

{

  ###### interface

  options.services.privoxy = {

    enable = mkEnableOption "Privoxy, non-caching filtering proxy";

    enableTor = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to configure Privoxy to use Tor's faster SOCKS port,
        suitable for HTTP.
      '';
    };

    inspectHttps = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to configure Privoxy to inspect HTTPS requests, meaning all
        encrypted traffic will be filtered as well. This works by decrypting
        and re-encrypting the requests using a per-domain generated certificate.

        To issue per-domain certificates, Privoxy must be provided with a CA
        certificate, using the <literal>ca-cert-file</literal>,
        <literal>ca-key-file</literal> settings.

        <warning><para>
          The CA certificate must also be added to the system trust roots,
          otherwise browsers will reject all Privoxy certificates as invalid.
          You can do so by using the option
          <option>security.pki.certificateFiles</option>.
        </para></warning>
      '';
    };

    certsLifetime = mkOption {
      type = ageType;
      default = "10d";
      example = "12h";
      description = ''
        If <literal>inspectHttps</literal> is enabled, the time generated HTTPS
        certificates will be stored in a temporary directory for reuse. Once
        the lifetime has expired the directory will cleared and the certificate
        will have to be generated again, on-demand.

        Depending on the traffic, you may want to reduce the lifetime to limit
        the disk usage, since Privoxy itself never deletes the certificates.

        <note><para>The format is that of the <literal>tmpfiles.d(5)</literal>
        Age parameter.</para></note>
      '';
    };

    userActions = mkOption {
      type = types.lines;
      default = "";
      description = ''
        Actions to be included in a <literal>user.action</literal> file. This
        will have a higher priority and can be used to override all other
        actions.
      '';
    };

    userFilters = mkOption {
      type = types.lines;
      default = "";
      description = ''
        Filters to be included in a <literal>user.filter</literal> file. This
        will have a higher priority and can be used to override all other
        filters definitions.
      '';
    };

    settings = mkOption {
      type = types.submodule {
        freeformType = configType;

        options.listen-address = mkOption {
          type = types.str;
          default = "127.0.0.1:8118";
          description = "Pair of address:port the proxy server is listening to.";
        };

        options.enable-edit-actions = mkOption {
          type = types.bool;
          default = false;
          description = "Whether the web-based actions file editor may be used.";
        };

        options.actionsfile = mkOption {
          type = types.listOf types.str;
          # This must come after all other entries, in order to override the
          # other actions/filters installed by Privoxy or the user.
          apply = x: x ++ optional (cfg.userActions != "")
            (toString (pkgs.writeText "user.actions" cfg.userActions));
          default = [ "match-all.action" "default.action" ];
          description = ''
            List of paths to Privoxy action files. These paths may either be
            absolute or relative to the privoxy configuration directory.
          '';
        };

        options.filterfile = mkOption {
          type = types.listOf types.str;
          default = [ "default.filter" ];
          apply = x: x ++ optional (cfg.userFilters != "")
            (toString (pkgs.writeText "user.filter" cfg.userFilters));
          description = ''
            List of paths to Privoxy filter files. These paths may either be
            absolute or relative to the privoxy configuration directory.
          '';
        };
      };
      default = {};
      example = literalExpression ''
        { # Listen on IPv6 only
          listen-address = "[::]:8118";

          # Forward .onion requests to Tor
          forward-socks5 = ".onion localhost:9050 .";

          # Log redirects and filters
          debug = [ 128 64 ];
          # This is equivalent to writing these lines
          # in the Privoxy configuration file:
          # debug 128
          # debug 64
        }
      '';
      description = ''
        This option is mapped to the main Privoxy configuration file.
        Check out the Privoxy user manual at
        <link xlink:href="https://www.privoxy.org/user-manual/config.html"/>
        for available settings and documentation.

        <note><para>
          Repeated settings can be represented by using a list.
        </para></note>
      '';
    };

  };

  ###### implementation

  config = mkIf cfg.enable {

    users.users.privoxy = {
      description = "Privoxy daemon user";
      isSystemUser = true;
      group = "privoxy";
    };

    users.groups.privoxy = {};

    systemd.tmpfiles.rules = optional cfg.inspectHttps
      "d ${cfg.settings.certificate-directory} 0770 privoxy privoxy ${cfg.certsLifetime}";

    systemd.services.privoxy = {
      description = "Filtering web proxy";
      after = [ "network.target" "nss-lookup.target" ];
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        User = "privoxy";
        Group = "privoxy";
        ExecStart = "${pkgs.privoxy}/bin/privoxy --no-daemon ${configFile}";
        PrivateDevices = true;
        PrivateTmp = true;
        ProtectHome = true;
        ProtectSystem = "full";
      };
      unitConfig =  mkIf cfg.inspectHttps {
        ConditionPathExists = with cfg.settings;
          [ ca-cert-file ca-key-file ];
      };
    };

    services.tor.settings.SOCKSPort = mkIf cfg.enableTor [
      # Route HTTP traffic over a faster port (without IsolateDestAddr).
      { addr = "127.0.0.1"; port = 9063; IsolateDestAddr = false; }
    ];

    services.privoxy.settings = {
      user-manual = "${pkgs.privoxy}/share/doc/privoxy/user-manual";
      # This is needed for external filters
      temporary-directory = "/tmp";
      filterfile = [ "default.filter" ];
      actionsfile =
        [ "match-all.action"
          "default.action"
        ] ++ optional cfg.inspectHttps (toString inspectAction);
    } // (optionalAttrs cfg.enableTor {
      forward-socks5 = "/ 127.0.0.1:9063 .";
      toggle = true;
      enable-remote-toggle = false;
      enable-edit-actions = false;
      enable-remote-http-toggle = false;
    }) // (optionalAttrs cfg.inspectHttps {
      # This allows setting absolute key/crt paths
      ca-directory = "/var/empty";
      certificate-directory = "/run/privoxy/certs";
      trusted-cas-file = "/etc/ssl/certs/ca-certificates.crt";
    });

  };

  imports =
    let
      top = x: [ "services" "privoxy" x ];
      setting = x: [ "services" "privoxy" "settings" x ];
    in
    [ (mkRenamedOptionModule (top "enableEditActions") (setting "enable-edit-actions"))
      (mkRenamedOptionModule (top "listenAddress") (setting "listen-address"))
      (mkRenamedOptionModule (top "actionsFiles") (setting "actionsfile"))
      (mkRenamedOptionModule (top "filterFiles") (setting "filterfile"))
      (mkRemovedOptionModule (top "extraConfig")
      ''
        Use services.privoxy.settings instead.
        This is part of the general move to use structured settings instead of raw
        text for config as introduced by RFC0042:
        https://github.com/NixOS/rfcs/blob/master/rfcs/0042-config-option.md
      '')
    ];

  meta.maintainers = with lib.maintainers; [ rnhmjoj ];

}