summaryrefslogtreecommitdiffstats
path: root/sshuttle/methods/pf.py
blob: be46be78f4f59a7e3a98e0d2562398168638e385 (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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import os
import sys
import platform
import re
import socket
import errno
import struct
import subprocess as ssubprocess
import shlex
from fcntl import ioctl
from ctypes import c_char, c_uint8, c_uint16, c_uint32, Union, Structure, \
    sizeof, addressof, memmove
from sshuttle.firewall import subnet_weight
from sshuttle.helpers import debug1, debug2, debug3, Fatal, family_to_string, \
    get_env, which
from sshuttle.methods import BaseMethod


_pf_context = {
    'started_by_sshuttle': 0,
    'loaded_by_sshuttle': True,
    'Xtoken': []
}
_pf_fd = None


class Generic(object):
    MAXPATHLEN = 1024
    PF_CHANGE_ADD_TAIL = 2
    PF_CHANGE_GET_TICKET = 6
    PF_PASS = 0
    PF_RDR = 8
    PF_OUT = 2
    ACTION_OFFSET = 0
    POOL_TICKET_OFFSET = 8
    ANCHOR_CALL_OFFSET = 1040

    class pf_addr(Structure):
        class _pfa(Union):
            _fields_ = [("v4", c_uint32),      # struct in_addr
                        ("v6", c_uint32 * 4),  # struct in6_addr
                        ("addr8", c_uint8 * 16),
                        ("addr16", c_uint16 * 8),
                        ("addr32", c_uint32 * 4)]

        _fields_ = [("pfa", _pfa)]
        _anonymous_ = ("pfa",)

    def __init__(self):
        self.status = b''
        self.pfioc_pooladdr = c_char * 1136

        self.DIOCNATLOOK = (
            (0x40000000 | 0x80000000) |
            ((sizeof(self.pfioc_natlook) & 0x1fff) << 16) |
            ((ord('D')) << 8) | (23))
        self.DIOCCHANGERULE = (
            (0x40000000 | 0x80000000) |
            ((sizeof(self.pfioc_rule) & 0x1fff) << 16) |
            ((ord('D')) << 8) | (26))
        self.DIOCBEGINADDRS = (
            (0x40000000 | 0x80000000) |
            ((sizeof(self.pfioc_pooladdr) & 0x1fff) << 16) |
            ((ord('D')) << 8) | (51))

    def enable(self):
        if b'INFO:\nStatus: Disabled' in self.status:
            pfctl('-e')
            _pf_context['started_by_sshuttle'] += 1

    @staticmethod
    def disable(anchor):
        pfctl('-a %s -F all' % anchor)
        if _pf_context['started_by_sshuttle'] == 1:
            pfctl('-d')
        _pf_context['started_by_sshuttle'] -= 1

    def query_nat(self, family, proto, src_ip, src_port, dst_ip, dst_port):
        [proto, family, src_port, dst_port] = [
            int(v) for v in [proto, family, src_port, dst_port]]

        packed_src_ip = socket.inet_pton(family, src_ip)
        packed_dst_ip = socket.inet_pton(family, dst_ip)

        assert len(packed_src_ip) == len(packed_dst_ip)
        length = len(packed_src_ip)

        pnl = self.pfioc_natlook()
        pnl.proto = proto
        pnl.direction = self.PF_OUT
        pnl.af = family
        memmove(addressof(pnl.saddr), packed_src_ip, length)
        memmove(addressof(pnl.daddr), packed_dst_ip, length)
        self._add_natlook_ports(pnl, src_port, dst_port)

        ioctl(pf_get_dev(), self.DIOCNATLOOK,
              (c_char * sizeof(pnl)).from_address(addressof(pnl)))

        ip = socket.inet_ntop(
            pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
        port = socket.ntohs(self._get_natlook_port(pnl.rdxport))
        return (ip, port)

    @staticmethod
    def _add_natlook_ports(pnl, src_port, dst_port):
        pnl.sxport = socket.htons(src_port)
        pnl.dxport = socket.htons(dst_port)

    @staticmethod
    def _get_natlook_port(xport):
        return xport

    def add_anchors(self, anchor, status=None):
        if status is None:
            status = pfctl('-s all')[0]
        self.status = status
        if ('\nanchor "%s"' % anchor).encode('ASCII') not in status:
            self._add_anchor_rule(self.PF_PASS, anchor.encode('ASCII'))

    def _add_anchor_rule(self, kind, name, pr=None):
        if pr is None:
            pr = self.pfioc_rule()

        memmove(addressof(pr) + self.ANCHOR_CALL_OFFSET, name,
                min(self.MAXPATHLEN, len(name)))  # anchor_call = name
        memmove(addressof(pr) + self.RULE_ACTION_OFFSET,
                struct.pack('I', kind), 4)  # rule.action = kind

        memmove(addressof(pr) + self.ACTION_OFFSET,
                struct.pack('I', self.PF_CHANGE_GET_TICKET),
                4)  # action = PF_CHANGE_GET_TICKET
        ioctl(pf_get_dev(), pf.DIOCCHANGERULE, pr)

        memmove(addressof(pr) + self.ACTION_OFFSET,
                struct.pack('I', self.PF_CHANGE_ADD_TAIL),
                4)  # action = PF_CHANGE_ADD_TAIL
        ioctl(pf_get_dev(), pf.DIOCCHANGERULE, pr)

    @staticmethod
    def _inet_version(family):
        return b'inet' if family == socket.AF_INET else b'inet6'

    @staticmethod
    def _lo_addr(family):
        return b'127.0.0.1' if family == socket.AF_INET else b'::1'

    @staticmethod
    def add_rules(anchor, rules):
        assert isinstance(rules, bytes)
        debug3("rules:\n" + rules.decode("ASCII"))
        pfctl('-a %s -f /dev/stdin' % anchor, rules)

    @staticmethod
    def has_skip_loopback():
        return b'skip' in pfctl('-s Interfaces -i lo -v')[0]


class FreeBsd(Generic):
    RULE_ACTION_OFFSET = 2968

    def __new__(cls):
        class pfioc_natlook(Structure):
            pf_addr = Generic.pf_addr
            _fields_ = [("saddr", pf_addr),
                        ("daddr", pf_addr),
                        ("rsaddr", pf_addr),
                        ("rdaddr", pf_addr),
                        ("sxport", c_uint16),
                        ("dxport", c_uint16),
                        ("rsxport", c_uint16),
                        ("rdxport", c_uint16),
                        ("af", c_uint8),                      # sa_family_t
                        ("proto", c_uint8),
                        ("proto_variant", c_uint8),
                        ("direction", c_uint8)]

        freebsd = Generic.__new__(cls)
        freebsd.pfioc_rule = c_char * 3040
        freebsd.pfioc_natlook = pfioc_natlook
        return freebsd

    def enable(self):
        returncode = ssubprocess.call(['kldload', 'pf'], env=get_env())
        # No env: No output.
        super(FreeBsd, self).enable()
        if returncode == 0:
            _pf_context['loaded_by_sshuttle'] = True

    def disable(self, anchor):
        super(FreeBsd, self).disable(anchor)
        if _pf_context['loaded_by_sshuttle'] and \
                _pf_context['started_by_sshuttle'] == 0:
            ssubprocess.call(['kldunload', 'pf'], env=get_env())
            # No env: No output.

    def add_anchors(self, anchor):
        status = pfctl('-s all')[0]
        if ('\nrdr-anchor "%s"' % anchor).encode('ASCII') not in status:
            self._add_anchor_rule(self.PF_RDR, anchor.encode('ASCII'))
        super(FreeBsd, self).add_anchors(anchor, status=status)

    def _add_anchor_rule(self, kind, name, pr=None):
        pr = pr or self.pfioc_rule()
        ppa = self.pfioc_pooladdr()

        ioctl(pf_get_dev(), self.DIOCBEGINADDRS, ppa)
        # pool ticket
        memmove(addressof(pr) + self.POOL_TICKET_OFFSET, ppa[4:8], 4)
        super(FreeBsd, self)._add_anchor_rule(kind, name, pr=pr)

    def add_rules(self, anchor, includes, port, dnsport, nslist, family):
        inet_version = self._inet_version(family)
        lo_addr = self._lo_addr(family)

        tables = []
        translating_rules = [
            b'rdr pass on lo0 %s proto tcp from ! %s to %s '
            b'-> %s port %r' % (inet_version, lo_addr, subnet, lo_addr, port)
            for exclude, subnet in includes if not exclude
        ]
        filtering_rules = [
            b'pass out route-to lo0 %s proto tcp '
            b'to %s keep state' % (inet_version, subnet)
            if not exclude else
            b'pass out %s proto tcp to %s' % (inet_version, subnet)
            for exclude, subnet in includes
        ]

        if nslist:
            tables