summary refs log tree commit diff
path: root/modules/tunnel/ingress.nix
blob: a62e931cb2fae90b270bb3a2ed27d0680a81b2e2 (plain)
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<
{
  me,
  config,
  pkgs,
  lib,
  ...
}:

let
  inherit (lib) findFirst concatStringsSep;

  # supposedly the current gold-standard protocol for circumventing dpi!
  # both xray (egress-side) and sing-box (ingress-side) support various
  # other protocols, if roskomnadzor learns to sniff out vless fully.
  protocol = "vless";

  inboundTag = "vless-in";
  outboundTag = "direct-out";

  # nginx stream listens on port 443 and routes by sni:
  # * mask domains (microsoft.com) go to xray for vless/reality.
  # * everything else goes to good old nginx!
  # both backends receive proxy protocol v1 with the real client ip.
  nginxPort = 8443;
  xrayPort = 8444;

  definition = import ./definition.nix;
  inherit (definition) paths mask;

  path = findFirst (
    p: p.egress == me.name
  ) (throw "no egress information found for this server!") paths;

  maskDomains = [
    "www.${mask}"
    mask
  ];

  xrayConfig = {
    inbounds = [
      {
        port = xrayPort;
        listen = "127.0.0.1";
        inherit protocol;
        tag = inboundTag;

        settings = {
          clients = [
            {
              id = path.info.uuid;
              flow = "xtls-rprx-vision";
            }
          ];
          decryption = "none";
        };

        streamSettings = {
          network = "tcp";
          security = "reality";
          realitySettings = {
            show = false;
            dest = "www.${mask}:443";
            serverNames = maskDomains;
            privateKey = "@PRIVATE_KEY@";
            shortIds = [ path.info.short ];
          };
          sockopt = {
            acceptProxyProtocol = true;
          };
        };
      }
    ];

    # and we're out!
    outbounds = [
      {
        protocol = "freedom";
        tag = outboundTag;
      }
    ];

    routing = {
      rules = [
        {
          type = "field";
          inboundTag = [ inboundTag ];
          inherit outboundTag;
        }
      ];
    };

    log = {
      loglevel = "debug";
    };
  };

  config-file = pkgs.writeText "xray.json" (builtins.toJSON xrayConfig);
in
{
  age.secrets.egress-key = {
    file = path.info.keySecret;
  };

  systemd.services = {
    # we have to make an xray config on the fly because
    # xray does not like reading secrets from specific files,
    # it wants them in plain-text!
    generate-xray-config = {
      description = "Generate Xray configuration";
      wantedBy = [ "multi-user.target" ];
      before = [ "xray.service" ];
      partOf = [ "xray.service" ];
      serviceConfig = {
        Type = "oneshot";
        RemainAfterExit = true;
      };
      script = ''
        mkdir -p /run/xray-configuration
        cp ${config-file} /run/xray-configuration/xray.json

        egress_key=$(cat ${config.age.secrets.egress-key.path})

        # use sd for replacement as a fancy new tool for this
        ${pkgs.sd}/bin/sd "@PRIVATE_KEY@" "$egress_key" /run/xray-configuration/xray.json
      '';
    };

    xray = {
      requires = [ "generate-xray-config.service" ];
      after = [ "generate-xray-config.service" ];
      restartTriggers = [ config-file ];
    };
  };

  services.xray = {
    enable = true;
    settingsFile = "/run/xray-configuration/xray.json";
  };

  # don't unwrap cloudflare addresses, we get the real ip via proxy protocol.
  foundation.www.behindCloudflare = false;

  services.nginx = {
    defaultListen = [
      { addr = "127.0.0.1"; port = nginxPort; ssl = true; proxyProtocol = true; }
    ];

    # nginx stream sits on port 443 and routes traffic by sni to the two
    # backends we have.
    streamConfig = ''
      map $ssl_preread_server_name $backend {
        ${concatStringsSep "\n" (map (d: "${d} xray;") maskDomains)}
        default web;
      }

      upstream xray { server 127.0.0.1:${toString xrayPort}; }
      upstream web { server 127.0.0.1:${toString nginxPort}; }

      server {
        listen 443;
        listen [::]:443;
        ssl_preread on;
        proxy_pass $backend;
        proxy_protocol on;
      }
    '';

    commonHttpConfig = ''
      set_real_ip_from 127.0.0.1;
      real_ip_header proxy_protocol;
    '';
  };
}