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

with lib;

let

  cfg = config.networking.tcpcrypt;

in

{

  ###### interface

  options = {

    networking.tcpcrypt.enable = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to enable opportunistic TCP encryption. If the other end
        speaks Tcpcrypt, then your traffic will be encrypted; otherwise
        it will be sent in clear text. Thus, Tcpcrypt alone provides no
        guarantees -- it is best effort. If, however, a Tcpcrypt
        connection is successful and any attackers that exist are
        passive, then Tcpcrypt guarantees privacy.
      '';
    };
  };

  config = mkIf cfg.enable {

    users.users.tcpcryptd = {
      uid = config.ids.uids.tcpcryptd;
      description = "tcpcrypt daemon user";
    };

    systemd.services.tcpcrypt = {
      description = "tcpcrypt";

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

      path = [ pkgs.iptables pkgs.tcpcrypt pkgs.procps ];

      preStart = ''
        mkdir -p /run/tcpcryptd
        chown tcpcryptd /run/tcpcryptd
        sysctl -n net.ipv4.tcp_ecn > /run/tcpcryptd/pre-tcpcrypt-ecn-state
        sysctl -w net.ipv4.tcp_ecn=0

        iptables -t raw -N nixos-tcpcrypt
        iptables -t raw -A nixos-tcpcrypt -p tcp -m mark --mark 0x0/0x10 -j NFQUEUE --queue-num 666
        iptables -t raw -I PREROUTING -j nixos-tcpcrypt

        iptables -t mangle -N nixos-tcpcrypt
        iptables -t mangle -A nixos-tcpcrypt -p tcp -m mark --mark 0x0/0x10 -j NFQUEUE --queue-num 666
        iptables -t mangle -I POSTROUTING -j nixos-tcpcrypt
      '';

      script = "tcpcryptd -x 0x10";

      postStop = ''
        if [ -f /run/tcpcryptd/pre-tcpcrypt-ecn-state ]; then
          sysctl -w net.ipv4.tcp_ecn=$(cat /run/tcpcryptd/pre-tcpcrypt-ecn-state)
        fi

        iptables -t mangle -D POSTROUTING -j nixos-tcpcrypt || true
        iptables -t raw -D PREROUTING -j nixos-tcpcrypt || true

        iptables -t raw -F nixos-tcpcrypt || true
        iptables -t raw -X nixos-tcpcrypt || true

        iptables -t mangle -F nixos-tcpcrypt || true
        iptables -t mangle -X nixos-tcpcrypt || true
      '';
    };
  };

}