summaryrefslogtreecommitdiff
path: root/pkg/linux/bitmask-root
blob: 5b49a1879ddc452b672612ec3c317437e55d1524 (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
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
This is a privileged helper script for safely running certain commands as root.
It should only be called by the Bitmask application.

USAGE:
  bitmask-root firewall stop
  bitmask-root firewall start GATEWAY1 GATEWAY2 ...
  bitmask-root openvpn stop
  bitmask-root openvpn start CONFIG1 CONFIG1 ...
"""
# TODO should be tested with python3, which can be the default on some distro.

from __future__ import print_function
import os
import subprocess
import socket
import sys
import re

##
## CONSTANTS
##

OPENVPN = "/usr/sbin/openvpn"
IPTABLES = "/sbin/iptables"
IP6TABLES = "/sbin/ip6tables"
UPDATE_RESOLV_CONF = "/etc/openvpn/update-resolv-conf"

FIXED_FLAGS = [
    "--setenv", "LEAPOPENVPN", "1",
    "--nobind",
    "--client",
    "--dev", "tun",
    "--tls-client",
    "--remote-cert-tls", "server",
    "--management-signal",
    "--management", "/tmp/openvpn.socket", "unix",
    "--up", UPDATE_RESOLV_CONF,
    "--down", UPDATE_RESOLV_CONF,
    "--script-security", "2"
]

ALLOWED_FLAGS = {
    "--remote": ["IP", "NUMBER", "PROTO"],
    "--tls-cipher": ["CIPHER"],
    "--cipher": ["CIPHER"],
    "--auth": ["CIPHER"],
    "--management-client-user": ["USER"],
    "--cert": ["FILE"],
    "--key": ["FILE"],
    "--ca": ["FILE"]
}

PARAM_FORMATS = {
    "NUMBER": lambda s: re.match("^\d+$", s),
    "PROTO":  lambda s: re.match("^(tcp|udp)$", s),
    "IP":     lambda s: is_valid_address(s),
    "CIPHER": lambda s: re.match("^[A-Z0-9-]+$", s),
    "USER":   lambda s: re.match("^[a-zA-Z0-9_\.\@][a-zA-Z0-9_\-\.\@]*\$?$", s), # IEEE Std 1003.1-2001
    "FILE":   lambda s: os.path.isfile(s)
}

DEBUG=os.getenv("DEBUG")
if DEBUG:
    import logging
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(ch)
    logger.debug(" ".join(sys.argv))

##
## UTILITY
##

def is_valid_address(value):
    """
    Validate that the passed ip is a valid IP address.

    :param value: the value to be validated
    :type value: str
    :rtype: bool
    """
    try:
        socket.inet_aton(value)
        return True
    except Exception:
        print "MALFORMED IP: %s!" % value
        return False

def split_list(list, regex):
    """
    Splits a list based on a regex:
    e.g. split_list(["xx", "yy", "x1", "zz"], "^x") => [["xx", "yy"], ["x1", "zz"]]

    :param list: the list to be split.
    :type list: list
    :rtype: list
    """
    if not hasattr(regex, "match"):
        regex = re.compile(regex)
    result = []
    i = 0
    while True:
        if regex.match(list[i]):
            result.append([])
            while True:
                result[-1].append(list[i])
                i += 1
                if i >= len(list) or regex.match(list[i]):
                    break
        else:
            i += 1
        if i >= len(list):
            break
    return result

# i think this is not needed with shell=False
#def sanify(command, *args):
#    return [command] + [pipes.quote(a) for a in args]

def run(command, *args, **options):
    parts = [command]
    parts.extend(args)
    if DEBUG:
        print "run: " + " ".join(parts)
    if options.get("check", True) == False or options.get("detach", False) == True:
        subprocess.Popen(parts)
    else:
        try:
            devnull = open('/dev/null', 'w')
            subprocess.check_call(parts, stdout=devnull, stderr=devnull)
            return 0
        except subprocess.CalledProcessError as ex:
            if options.get("exitcode", False) == True:
                return ex.returncode
            else:
                bail("Could not run %s: %s" % (ex.cmd, ex.output))

##
## OPENVPN
##

def parse_openvpn_flags(args):
    """
    takes argument list from the command line and parses it, only allowing some configuration flags.
    """
    result = []
    try:
        for flag in split_list(args, "^--"):
            flag_name = flag[0]
            if ALLOWED_FLAGS.has_key(flag_name):
                result.append(flag_name)
                required_params = ALLOWED_FLAGS[flag_name]
                if len(required_params) > 0:
                    flag_params = flag[1:]
                    if len(flag_params) != len(required_params):
                        print "ERROR: not enough params for %s" % flag_name
                        return None
                    for param, param_type in zip(flag_params, required_params):
                        if PARAM_FORMATS[param_type](param):
                            result.append(param)
                        else:
                            print "ERROR: Bad argument %s" % param
                            return None
            else:
                print "WARNING: unrecognized openvpn flag %s" % flag_name
        return result
    except Exception as ex:
        print ex
        return None


def openvpn_start(args):
    openvpn_flags = parse_openvpn_flags(args)
    if openvpn_flags:
        flags = FIXED_FLAGS + openvpn_flags
        run(OPENVPN, *flags, detach=True)
    else:
        bail('ERROR: could not parse openvpn options')

def openvpn_stop(args):
    print "stop"

##
## FIREWALL
##

def get_gateways(gateways):
    result = [gateway for gateway in gateways if is_valid_address(gateway)]
    if not len(result):
        bail("No valid gateways specified")
    else:
        return result

def get_default_device():
    routes = subprocess.check_output([IP, "route", "show"])
    match = re.search("^default .*dev ([^\s]*) .*$", routes, flags=re.M)
    if len(match.groups()) >= 1:
      return match.group(1)
    else:
      bail("could not find default device")

def get_local_network_ipv4(device):
    addresses = subprocess.check_output([IP, "-o", "address", "show", "dev", device])
    match = re.search("^.*inet ([^ ]*) .*$", addresses, flags=re.M)
    if len(match.groups()) >= 1:
      return match.group(1)
    else:
      return None

def get_local_network_ipv6(device):
    addresses = subprocess.check_output([IP, "-o", "address", "show", "dev", device])
    match = re.search("^.*inet6 ([^ ]*) .*$", addresses, flags=re.M)
    if len(match.groups()) >= 1:
      return match.group(1)
    else:
      return None

def run_iptable_with_check(cmd, *args, **options):
    """
    runs an iptables command checking to see if it should:
      for --insert: run only if rule does not already exist.
      for --delete: run only if rule does exist.
    other commands are run normally.
    """
    if "--insert" in args:
        check_args = [arg.replace("--insert", "--check") for arg in args]
        check_code = run(cmd, *check_args, exitcode=True)
        if check_code != 0:
            run(cmd, *args, **options)
    elif "--delete" in args:
        check_args = [arg.replace("--delete", "--check") for arg in args]
        check_code = run(cmd, *check_args, exitcode=True)
        if check_code == 0:
            run(cmd, *args, **options)
    else:
        run(cmd, *args, **options)

def iptables(*args, **options):
    ip4tables(*args, **options)
    ip6tables(*args, **options)

def ip4tables(*args, **options):
    run_iptable_with_check(IPTABLES, *args, **options)

def ip6tables(*args, **options):
    run_iptable_with_check(IP6TABLES, *args, **options)

def ipv4_chain_exists(table):
    code = run(IPTABLES, "--list", table, "--numeric", exitcode=True)
    return code == 0

def ipv6_chain_exists(table):
    code = run(IP6TABLES, "--list", table, "--numeric", exitcode=True)
    return code == 0

def firewall_start(args):
    default_device     = get_default_device()
    local_network_ipv4 = get_local_network_ipv4(default_device)
    local_network_ipv6 = get_local_network_ipv6(default_device)
    gateways           = get_gateways(args)

    # add custom chain "bitmask"
    if not ipv4_chain_exists("bitmask"):
        ip4tables("--new-chain", "bitmask")
    if not ipv6_chain_exists("bitmask"):
        ip6tables("--new-chain", "bitmask")
    iptables("--insert", "OUTPUT", "--jump", "bitmask")

    # reject everything
    iptables("--insert", "bitmask", "-o", default_device, "--jump", "REJECT")

    # allow traffic to gateways
    for gateway in gateways:
        ip4tables("--insert", "bitmask", "--destination", gateway, "-o", default_device, "--jump", "ACCEPT")

    # allow traffic to IPs on local network
    if local_network_ipv4:
        ip4tables("--insert", "bitmask", "--destination", local_network_ipv4, "-o", default_device, "--jump", "ACCEPT")
    if local_network_ipv6:
        ip6tables("--insert", "bitmask", "--destination", local_network_ipv6, "-o", default_device, "--jump", "ACCEPT")

    # block DNS requests to anyone but the service provider or localhost
    ip4tables("--insert", "bitmask", "--protocol", "udp", "--dport", "53", "--jump", "REJECT")
    for allowed_dns in gateways + ["127.0.0.1","127.0.1.1"]:
        ip4tables("--insert", "bitmask", "--protocol", "udp", "--dport", "53", "--destination", allowed_dns, "--jump", "ACCEPT")

def firewall_stop(args):
    iptables("--delete", "OUTPUT", "--jump", "bitmask")
    if ipv4_chain_exists("bitmask"):
        ip4tables("--flush", "bitmask")
        ip4tables("--delete-chain", "bitmask")
    if ipv6_chain_exists("bitmask"):
        ip6tables("--flush", "bitmask")
        ip6tables("--delete-chain", "bitmask")


def bail(msg=""):
    if msg:
        print(msg)
    exit(1)

def main():
    if len(sys.argv) >= 3:
        command = "_".join(sys.argv[1:3])
        args = sys.argv[3:]
        if command == "openvpn_start":
            openvpn_start(args)
        elif command == "openvpn_stop":
            openvpn_stop(args)
        elif command == "firewall_start":
            firewall_start(args)
        elif command == "firewall_stop":
            firewall_stop(args)
        else:
            bail("no such command")
    else:
        bail("no such command")

if __name__ == "__main__":
    main()
    print "done"
    exit(0)