summaryrefslogtreecommitdiffstats
path: root/systems/zoppo/mbim-reconnect.nix
blob: 00145e9faa93bc3e9e78f78c9156a5bf6317792a (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
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
{ config, lib, pkgs, ... }: let
  cfg = {
    device = "/dev/cdc-wdm0";
    ifname = "wwp0s20f0u5";
    pingAddress = "ne.i";
    pinFile = "${config.krebs.secret.directory}/SIMPIN";
  };

  mypkgs.mbim-reconnect =
    pkgs.writeDashBin "mbim-reconnect" ''
      # usage: mbim-reconnect DEVICE IFNAME

      if ping -4 -q -c 1 ${lib.escapeShellArg cfg.pingAddress} >/dev/null; then
        # nothing to do
        exit
      fi

      set -fu

      device=$1
      ifname=$2

      #
      # Unlock
      #
      pin_info=$(mbimcli -p -d "$device" --query-pin-state) || exit 1
      pin_state=$(
        echo "$pin_info" |
        sed -nr "s/^\s*PIN state:\s*'([^']+)'$/\1/p"
      )
      pin_type=$(
        echo "$pin_info" |
        sed -nr "s/^\s*PIN type:\s*'([^']+)'$/\1/p"
      )
      pin_attempts=$(
        echo "$pin_info" |
        sed -nr "s/^\s*Remaining attempts:\s*'([0-9]+)'$/\1/p"
      )
      case $pin_state in
        unlocked)
          echo 'device is unlocked.' >&2
          ;;
        locked)
          if test "$pin_type" != pin1; then
            # e.g. puk1: needs manual intervention, entering the PIN won't help
            echo "SIM wants '$pin_type' (remaining attempts: '$pin_attempts'), not unlocking" >&2
            exit 1
          fi
          # 2>/dev/null keeps this check quiet if the modem doesn't report attempts
          if test "$pin_attempts" -le 1 2>/dev/null; then
            echo "only '$pin_attempts' attempt(s) left, not unlocking automatically" >&2
            exit 1
          fi
          unlock_failed_file=$STATE_DIRECTORY/unlock-failed
          if test -e "$unlock_failed_file"; then
            exit 1
          fi
          echo "unlocking device (remaining attempts: '$pin_attempts')..." >&2
          pin=$(cat "$CREDENTIALS_DIRECTORY"/pin) || exit 1
          if ! mbimcli -p -d "$device" --enter-pin "$pin"; then
            touch "$unlock_failed_file"
            mbimcli -p -d "$device" --query-pin-state
            echo "unlock attempt failed: remove $unlock_failed_file to reattempt..." >&2
            exit 1
          fi
          # Prevent --attach-packet-service to fail an reset the modem.
          echo 'unlocked; attaching on next run.' >&2
          exit 0
          ;;
        *)
          echo "unexpected PIN state: '$pin_state'" >&2
          exit 1
          ;;
      esac

      # Don't move set -x before entering the PIN.
      set -x

      mbimcli -p -d "$device" --set-radio-state=on

      if ! mbimcli -p -d "$device" --attach-packet-service; then
        systemctl start --wait mbim-reset.service
        exit 1
      fi

      is_connected() {
          mbimcli -p -d "$1" --query-connection-state |
              sed -nr "s/^\s*Activation state:\s*'([^']+)'$/\1/p" |
              grep -q '^activated$'
      }

      if ! is_connected "$device"; then
        echo 'connecting...' >&2
        mbimcli -p -d "$device" --connect=access-string=internet,ip-type=ipv4v6
      fi

      ip_configuration=$(
        mbimcli -p -d "$device" --query-ip-configuration
      )

      new_ipv4address=$(
        echo "$ip_configuration" |
        sed -rn '/IPv4/,/^$/s/.*\<IP \[0\]: .([0-9.]+\/[0-9]+).*/\1/p'
      )

      if test -z "$new_ipv4address"; then
        echo 'no IPv4 address in IP configuration' >&2
        exit 1
      fi

      ip link set "$ifname" up

      ip -4 address flush dev "$ifname"
      ip address add "$new_ipv4address" dev "$ifname"
      ip route add default dev "$ifname"

      # IPv6

      new_ipv6address=$(
        echo "$ip_configuration" |
        sed -rn '/IPv6/,/^$/s/.*\<IP \[0\]: .([0-9a-f:]+\/[0-9]+).*/\1/p'
      )

      new_ipv6mtu=$(
        echo "$ip_configuration" |
        sed -rn '/IPv6/,/^$/s/.*\<MTU: .([0-9]+).*/\1/p'
      )

      sysctl -qw net.ipv6.conf."$ifname".accept_ra=2          # Accept RA if IPv6 forwarding is enabled
      sysctl -qw net.ipv6.conf."$ifname".accept_ra_mtu=0      # RA says 1500, MBIM says 1420
      if test -n "$new_ipv6mtu"; then
        sysctl -qw net.ipv6.conf."$ifname".mtu="$new_ipv6mtu"
      fi

      ip -6 address flush dev "$ifname"

      if test -n "$new_ipv6address"; then
        ip address add "$new_ipv6address" dev "$ifname"
      fi
    '';

  mypkgs.mbim-reset =
    pkgs.writeDashBin "mbim-reset" ''
      # usage: mbim-reset IFNAME

      set -efu

      ifname=$1

      sys_device=$(readlink -f /sys/class/net/"$ifname"/device)
      sys_driver=$(readlink -f "$sys_device"/driver)

      echo 'resetting device...' >&2

      echo 0 > "$sys_device"/authorized
      echo 1 > "$sys_device"/authorized
      echo "$(basename "$sys_device")" > "$sys_driver"/bind || :
    '';
in {
  tv.iptables.extra6.filter.INPUT = [
    "-p ipv6-icmp --icmpv6-type router-advertisement    -m hl --hl-eq 255 -j ACCEPT"
    "-p ipv6-icmp --icmpv6-type neighbour-solicitation  -m hl --hl-eq 255 -j ACCEPT"
    "-p ipv6-icmp --icmpv6-type neighbour-advertisement -m hl --hl-eq 255 -j ACCEPT"
    "-p ipv6-icmp --icmpv6-type packet-too-big -j ACCEPT"
    # -p icmp -m icmp --icmp-type echo-request -j ACCEPT is done elsewhere
  ];
  users.users.root.packages = [
    pkgs.libmbim
  ];
  systemd.timers.mbim-reconnect = {
    wantedBy = [ "timers.target" ];
    timerConfig = {
      OnBootSec = "30s";
      OnUnitInactiveSec = "1min";  # measured from the end of the last run
      AccuracySec = "5s";
    };
  };
  systemd.services.mbim-reconnect = {
    path = [
      pkgs.coreutils  # cat
      pkgs.gnugrep
      pkgs.gnused
      pkgs.iproute2   # ip
      pkgs.iputils    # ping
      pkgs.libmbim    # mbimcli
      pkgs.procps     # sysctl
      pkgs.systemd    # systemctl
    ];
    serviceConfig = {
      Type = "oneshot";
      ExecStart = "${mypkgs.mbim-reconnect}/bin/mbim-reconnect ${cfg.device} ${cfg.ifname}";

      LoadCredential = [
        "pin:${cfg.pinFile}"
      ];

      # oneshot has no start timeout by default; don't let a hung mbimcli
      # block all future runs
      TimeoutStartSec = "5min";

      StateDirectory = "mbim-reconnect";

      CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
      AmbientCapabilities = [ "CAP_NET_ADMIN" ];

      DevicePolicy = "closed";
      DeviceAllow = [ "${cfg.device} rw" ];

      ProtectSystem = "strict";
      ProtectHome = true;

      PrivateTmp = true;
      PrivateMounts = true;
      PrivateDevices = false;

      ProtectControlGroups = true;
      ProtectKernelModules = true;
      ProtectKernelLogs = true;
      ProtectKernelTunables = true;
      ProtectHostname = true;
      ProtectClock = true;

      ReadWritePaths = [ "/proc/sys/net/ipv6/conf" ];

      RestrictAddressFamilies = [
        "AF_UNIX"     # needed by mbim-proxy and systemctl
        "AF_INET"     # needed by ping -4
        "AF_INET6"    # currently unused
        "AF_NETLINK"  # needed by ip
      ];

      RestrictNamespaces = true;
      RestrictRealtime = true;
      RestrictSUIDSGID = true;

      LockPersonality = true;
      MemoryDenyWriteExecute = true;

      SystemCallArchitectures = "native";
      SystemCallFilter = [
        "@system-service"
        "~@keyring"
      ];

      NoNewPrivileges = true;
      UMask = "0077";

      SyslogIdentifier = "mbim-reconnect";
    };
  };
  systemd.services.mbim-reset = {
    path = [
      pkgs.coreutils  # basename readlink
    ];
    serviceConfig = {
      Type = "oneshot";
      ExecStart = "${mypkgs.mbim-reset}/bin/mbim-reset ${cfg.ifname}";

      TimeoutStartSec = "1min";

      CapabilityBoundingSet = [ "CAP_SYS_ADMIN" ];
      AmbientCapabilities = [ "CAP_SYS_ADMIN" ];

      DevicePolicy = "closed";

      ProtectSystem = "full";
      ProtectHome = true;
      ProtectKernelTunables = false;

      PrivateTmp = true;
      PrivateMounts = true;
      PrivateDevices = false;

      ProtectControlGroups = true;
      ProtectKernelModules = true;
      ProtectKernelLogs = true;
      ProtectHostname = true;
      ProtectClock = true;

      RestrictNamespaces = true;
      RestrictRealtime = true;
      RestrictSUIDSGID = true;

      LockPersonality = true;
      MemoryDenyWriteExecute = true;

      SystemCallArchitectures = "native";
      SystemCallFilter = [
        "@system-service"
        "~@keyring"
      ];

      NoNewPrivileges = true;
    };
  };
}