示例#1
0
def find_interface_addr(addr):
    match_addr = ipaddress.ip_address(addr)

    for interface, data in list(get_interfaces().items()):
        try:
            address = ipaddress.ip_address(data['address'])
        except ValueError:
            continue

        if match_addr == address:
            return data
示例#2
0
def check_network_range(test_network, start_addr, end_addr):
    test_net = ipaddress.ip_network(test_network)
    start_addr = ipaddress.ip_address(start_addr)
    end_addr = ipaddress.ip_address(end_addr)

    return all((
        start_addr != test_net.network_address,
        end_addr != test_net.broadcast_address,
        start_addr < end_addr,
        start_addr in test_net,
        end_addr in test_net,
    ))
示例#3
0
def find_interface(network):
    network = ipaddress.ip_network(network, strict=False)

    for interface, data in list(get_interfaces().items()):
        try:
            address = ipaddress.ip_address(data['address'])
        except ValueError:
            continue

        if address in network and data['netmask'] == str(network.netmask):
            return data
示例#4
0
    def _check_whitelist(self):
        if settings.app.sso_whitelist:
            remote_ip = ipaddress.ip_address(self.remote_ip)

            for network_str in settings.app.sso_whitelist:
                try:
                    network = ipaddress.ip_network(network_str)
                except (ipaddress.AddressValueError, ValueError):
                    logger.warning(
                        'Invalid whitelist network',
                        'authorize',
                        network=network_str,
                    )
                    continue

                if remote_ip in network:
                    self.whitelisted = True
                    break
示例#5
0
    def _stress_thread(self):
        try:
            i = 0

            for org in self.server.iter_orgs():
                for user in org.iter_users():
                    if user.type != CERT_CLIENT:
                        continue

                    i += 1

                    client = {
                        'client_id':
                        i,
                        'key_id':
                        1,
                        'org_id':
                        org.id,
                        'user_id':
                        user.id,
                        'mac_addr':
                        utils.rand_str(16),
                        'remote_ip':
                        str(
                            ipaddress.ip_address(
                                100000000 + random.randint(0, 1000000000))),
                        'platform':
                        'linux',
                        'device_id':
                        str(bson.ObjectId()),
                        'device_name':
                        utils.random_name(),
                    }

                    self.clients.connect(client)
        except:
            logger.exception(
                'Error in stress thread',
                'server',
                server_id=self.server.id,
                instance_id=self.instance.id,
                socket_path=self.socket_path,
            )
示例#6
0
    def thread():
        platforms = list(DESKTOP_PLATFORMS)
        start_timestamp = datetime.datetime(2015, 12, 28, 4, 1, 0)
        hosts_collection = mongo.get_collection('hosts')
        servers_collection = mongo.get_collection('servers')
        clients_collection = mongo.get_collection('clients')

        clients_collection.remove({})

        for hst in host.iter_hosts():
            hosts_collection.update({
                '_id': hst.id,
            }, {
                '$set': {
                    'server_count': 0,
                    'device_count': 0,
                    'cpu_usage': 0,
                    'mem_usage': 0,
                    'thread_count': 0,
                    'open_file_count': 0,
                    'status': ONLINE,
                    'start_timestamp': start_timestamp,
                    'ping_timestamp': start_timestamp,
                    'auto_public_address': None,
                    'auto_public_address6': None,
                    'auto_public_host': hst.name + '.pritunl.com',
                    'auto_public_host6': hst.name + '.pritunl.com',
                }
            })

        for svr in server.iter_servers():
            prefered_hosts = host.get_prefered_hosts(svr.hosts,
                                                     svr.replica_count)

            instances = []
            for hst in prefered_hosts:
                instances.append({
                    'instance_id': utils.ObjectId(),
                    'host_id': hst,
                    'ping_timestamp': utils.now(),
                })

            servers_collection.update({
                '_id': svr.id,
            }, {
                '$set': {
                    'status': ONLINE,
                    'pool_cursor': None,
                    'start_timestamp': start_timestamp,
                    'availability_group': DEFAULT,
                    'instances': instances,
                    'instances_count': len(instances),
                }
            })

            for org in svr.iter_orgs():
                for usr in org.iter_users():
                    if usr.type != CERT_CLIENT:
                        continue

                    virt_address = svr.get_ip_addr(org.id, usr.id)
                    virt_address6 = svr.ip4to6(virt_address) + '/64'

                    doc = {
                        '_id':
                        utils.ObjectId(),
                        'user_id':
                        usr.id,
                        'server_id':
                        svr.id,
                        'host_id':
                        settings.local.host_id,
                        'timestamp':
                        start_timestamp,
                        'platform':
                        random.choice(platforms),
                        'type':
                        CERT_CLIENT,
                        'device_name':
                        utils.random_name(),
                        'mac_addr':
                        utils.rand_str(16),
                        'network':
                        svr.network,
                        'real_address':
                        str(
                            ipaddress.ip_address(
                                100000000 + random.randint(0, 1000000000))),
                        'virt_address':
                        virt_address,
                        'virt_address6':
                        virt_address6,
                        'host_address':
                        settings.local.host.local_addr,
                        'host_address6':
                        settings.local.host.local_addr6,
                        'dns_servers': [],
                        'dns_suffix':
                        None,
                        'connected_since':
                        int(start_timestamp.strftime('%s')),
                    }

                    clients_collection.insert(doc)

        for lnk in link.iter_links():
            lnk.status = ONLINE
            lnk.commit()

            for location in lnk.iter_locations():
                active = False
                for hst in location.iter_hosts():
                    if not active:
                        hst.active = True
                        active = True
                    hst.status = AVAILABLE
                    hst.commit(('active', 'status'))

        logger.info('Demo initiated', 'demo')
示例#7
0
def random_ip_addr():
    return str(ipaddress.ip_address(100000000 + random.randint(0, 1000000000)))
示例#8
0
def network_reverse_hosts(net):
    cur = int(net.broadcast_address) - 1
    end = int(net.network_address) + 1
    while cur >= end:
        cur -= 1
        yield ipaddress.ip_address(cur + 1)
示例#9
0
def server_put_post(server_id=None):
    if settings.app.demo_mode:
        return utils.demo_blocked()

    used_resources = server.get_used_resources(server_id)
    network_used = used_resources['networks']
    port_used = used_resources['ports']

    name = None
    name_def = False
    if 'name' in flask.request.json:
        name_def = True
        name = utils.filter_str(flask.request.json['name'])

    network = None
    network_def = False
    if 'network' in flask.request.json and \
            flask.request.json['network'] != '':
        network_def = True
        network = flask.request.json['network'].strip()

        try:
            if not _check_network_private(network):
                return _network_invalid()
        except (ipaddress.AddressValueError, ValueError):
            return _network_invalid()

    wg = None
    wg_def = False
    if 'wg' in flask.request.json:
        wg_def = True
        wg = True if flask.request.json['wg'] else False

    network_wg = None
    network_wg_def = False
    if wg and 'network_wg' in flask.request.json and \
            flask.request.json['network_wg'] != '':
        network_wg_def = True
        network_wg = flask.request.json['network_wg'].strip()

        try:
            if not _check_network_private(network_wg):
                return _network_wg_invalid()
        except (ipaddress.AddressValueError, ValueError):
            return _network_wg_invalid()
    elif not wg:
        network_wg_def = True

    network_mode = None
    network_mode_def = False
    if 'network_mode' in flask.request.json:
        network_mode_def = True
        network_mode = flask.request.json['network_mode']

    network_start = None
    network_start_def = False
    if 'network_start' in flask.request.json:
        network_start_def = True
        network_start = flask.request.json['network_start']

    network_end = None
    network_end_def = False
    if 'network_end' in flask.request.json:
        network_end_def = True
        network_end = flask.request.json['network_end']

    restrict_routes = None
    restrict_routes_def = False
    if 'restrict_routes' in flask.request.json:
        restrict_routes_def = True
        restrict_routes = True if flask.request.json['restrict_routes'] \
            else False

    ipv6 = None
    ipv6_def = False
    if 'ipv6' in flask.request.json:
        ipv6_def = True
        ipv6 = True if flask.request.json['ipv6'] else False

    ipv6_firewall = None
    ipv6_firewall_def = False
    if 'ipv6_firewall' in flask.request.json:
        ipv6_firewall_def = True
        ipv6_firewall = True if flask.request.json['ipv6_firewall'] else False

    bind_address = None
    bind_address_def = False
    if 'bind_address' in flask.request.json:
        bind_address_def = True
        bind_address = utils.filter_str(flask.request.json['bind_address'])

    protocol = 'udp'
    protocol_def = False
    if 'protocol' in flask.request.json:
        protocol_def = True
        protocol = flask.request.json['protocol'].lower()

        if protocol not in ('udp', 'tcp'):
            return utils.jsonify(
                {
                    'error': PROTOCOL_INVALID,
                    'error_msg': PROTOCOL_INVALID_MSG,
                }, 400)

    port = None
    port_def = False
    if 'port' in flask.request.json and flask.request.json['port'] != 0:
        port_def = True
        port = flask.request.json['port']

        try:
            port = int(port)
        except ValueError:
            return _port_invalid()

        if port < 1 or port > 65535:
            return _port_invalid()

    port_wg = None
    port_wg_def = False
    if wg and 'port_wg' in flask.request.json and \
            flask.request.json['port_wg'] != 0:
        port_wg_def = True
        port_wg = flask.request.json['port_wg']

        try:
            port_wg = int(port_wg)
        except ValueError:
            return _port_wg_invalid()

        if port_wg < 1 or port_wg > 65535:
            return _port_wg_invalid()
    elif not wg:
        port_wg_def = True

    dh_param_bits = None
    dh_param_bits_def = False
    if flask.request.json.get('dh_param_bits'):
        dh_param_bits_def = True
        dh_param_bits = flask.request.json['dh_param_bits']

        try:
            dh_param_bits = int(dh_param_bits)
        except ValueError:
            return _dh_param_bits_invalid()

        if dh_param_bits not in VALID_DH_PARAM_BITS:
            return _dh_param_bits_invalid()

    groups = None
    groups_def = False
    if 'groups' in flask.request.json:
        groups_def = True
        groups = flask.request.json['groups'] or []
        for i, group in enumerate(groups):
            groups[i] = utils.filter_str(group)
        groups = list(set(groups))

    multi_device = False
    multi_device_def = False
    if 'multi_device' in flask.request.json:
        multi_device_def = True
        multi_device = True if flask.request.json['multi_device'] else False

    dns_servers = None
    dns_servers_def = False
    if 'dns_servers' in flask.request.json:
        dns_servers_def = True
        dns_servers = flask.request.json['dns_servers'] or []

        for dns_server in dns_servers:
            try:
                ipaddress.ip_address(dns_server)
            except (ipaddress.AddressValueError, ValueError):
                return _dns_server_invalid()

    search_domain = None
    search_domain_def = False
    if 'search_domain' in flask.request.json:
        search_domain_def = True
        search_domain = flask.request.json['search_domain']
        if search_domain:
            search_domain = ', '.join([
                utils.filter_str(x.strip()) for x in search_domain.split(',')
            ])
        else:
            search_domain = None

    inter_client = True
    inter_client_def = False
    if 'inter_client' in flask.request.json:
        inter_client_def = True
        inter_client = True if flask.request.json['inter_client'] else False

    ping_interval = None
    ping_interval_def = False
    if 'ping_interval' in flask.request.json:
        ping_interval_def = True
        ping_interval = int(flask.request.json['ping_interval'] or 10)

    ping_timeout = None
    ping_timeout_def = False
    if 'ping_timeout' in flask.request.json:
        ping_timeout_def = True
        ping_timeout = int(flask.request.json['ping_timeout'] or 60)

    link_ping_interval = None
    link_ping_interval_def = False
    if 'link_ping_interval' in flask.request.json:
        link_ping_interval_def = True
        link_ping_interval = int(flask.request.json['link_ping_interval'] or 1)

    link_ping_timeout = None
    link_ping_timeout_def = False
    if 'link_ping_timeout' in flask.request.json:
        link_ping_timeout_def = True
        link_ping_timeout = int(flask.request.json['link_ping_timeout'] or 5)

    inactive_timeout = None
    inactive_timeout_def = False
    if 'inactive_timeout' in flask.request.json:
        inactive_timeout_def = True
        inactive_timeout = int(flask.request.json['inactive_timeout']
                               or 0) or None

    session_timeout = None
    session_timeout_def = False
    if 'session_timeout' in flask.request.json:
        session_timeout_def = True
        session_timeout = int(flask.request.json['session_timeout']
                              or 0) or None

    allowed_devices = None
    allowed_devices_def = False
    if 'allowed_devices' in flask.request.json:
        allowed_devices_def = True
        allowed_devices = flask.request.json['allowed_devices'] or None

    max_clients = None
    max_clients_def = False
    if 'max_clients' in flask.request.json:
        max_clients_def = True
        max_clients = flask.request.json['max_clients']
        if max_clients:
            max_clients = int(max_clients)
        else:
            max_clients = 2000

    max_devices = None
    max_devices_def = False
    if 'max_devices' in flask.request.json:
        max_devices_def = True
        max_devices = flask.request.json['max_devices']
        if max_devices:
            max_devices = int(max_devices)
        else:
            max_devices = 0

    replica_count = None
    replica_count_def = False
    if 'replica_count' in flask.request.json:
        replica_count_def = True
        replica_count = flask.request.json['replica_count']
        if replica_count:
            replica_count = int(replica_count)
        if not replica_count:
            replica_count = 1

    vxlan = True
    vxlan_def = False
    if 'vxlan' in flask.request.json:
        vxlan_def = True
        vxlan = True if flask.request.json['vxlan'] else False

    dns_mapping = False
    dns_mapping_def = False
    if 'dns_mapping' in flask.request.json:
        dns_mapping_def = True
        dns_mapping = True if flask.request.json['dns_mapping'] else False

    debug = False
    debug_def = False
    if 'debug' in flask.request.json:
        debug_def = True
        debug = True if flask.request.json['debug'] else False

    pre_connect_msg = None
    pre_connect_msg_def = False
    if 'pre_connect_msg' in flask.request.json:
        pre_connect_msg_def = True
        if flask.request.json['pre_connect_msg']:
            pre_connect_msg = flask.request.json['pre_connect_msg'].strip()

    otp_auth = False
    otp_auth_def = False
    if 'otp_auth' in flask.request.json:
        otp_auth_def = True
        otp_auth = True if flask.request.json['otp_auth'] else False

    mss_fix = None
    mss_fix_def = False
    if 'mss_fix' in flask.request.json:
        mss_fix_def = True
        mss_fix = flask.request.json['mss_fix'] or None
        if mss_fix:
            mss_fix = int(mss_fix) or None

    lzo_compression = False
    lzo_compression_def = False
    if 'lzo_compression' in flask.request.json:
        lzo_compression_def = True
        lzo_compression = True if flask.request.json[
            'lzo_compression'] else False

    cipher = None
    cipher_def = False
    if 'cipher' in flask.request.json:
        cipher_def = True
        cipher = flask.request.json['cipher']

        if cipher not in CIPHERS:
            return utils.jsonify(
                {
                    'error': CIPHER_INVALID,
                    'error_msg': CIPHER_INVALID_MSG,
                }, 400)

    hash = None
    hash_def = False
    if 'hash' in flask.request.json:
        hash_def = True
        hash = flask.request.json['hash']

        if hash not in HASHES:
            return utils.jsonify(
                {
                    'error': HASH_INVALID,
                    'error_msg': HASH_INVALID_MSG,
                }, 400)

    block_outside_dns = False
    block_outside_dns_def = False
    if 'block_outside_dns' in flask.request.json:
        block_outside_dns_def = True
        block_outside_dns = True if flask.request.json[
            'block_outside_dns'] else False

    jumbo_frames = False
    jumbo_frames_def = False
    if 'jumbo_frames' in flask.request.json:
        jumbo_frames_def = True
        jumbo_frames = True if flask.request.json['jumbo_frames'] else False

    if not server_id:
        if not name_def:
            return utils.jsonify(
                {
                    'error': MISSING_PARAMS,
                    'error_msg': MISSING_PARAMS_MSG,
                }, 400)

        if not network_def:
            network_def = True
            rand_range = list(range(215, 250))
            rand_range_low = list(range(15, 215))
            random.shuffle(rand_range)
            random.shuffle(rand_range_low)
            rand_range += rand_range_low
            for i in rand_range:
                rand_network = '192.168.%s.0/24' % i
                if not _check_network_overlap(rand_network, network_used):
                    network = rand_network
                    break
            if not network:
                return utils.jsonify(
                    {
                        'error': NETWORK_IN_USE,
                        'error_msg': NETWORK_IN_USE_MSG,
                    }, 400)

        if wg and not network_wg_def:
            network_used.add(ipaddress.ip_network(network))

            network_wg_def = True
            rand_range = list(range(215, 250))
            rand_range_low = list(range(15, 215))
            random.shuffle(rand_range)
            random.shuffle(rand_range_low)
            rand_range += rand_range_low
            for i in rand_range:
                rand_network_wg = '192.168.%s.0/24' % i
                if not _check_network_overlap(rand_network_wg, network_used):
                    network_wg = rand_network_wg
                    break
            if not network_wg:
                return utils.jsonify(
                    {
                        'error': NETWORK_WG_IN_USE,
                        'error_msg': NETWORK_WG_IN_USE_MSG,
                    }, 400)

        if not port_def:
            port_def = True
            rand_ports = list(range(10000, 19999))
            random.shuffle(rand_ports)
            for rand_port in rand_ports:
                if '%s%s' % (rand_port, protocol) not in port_used:
                    port = rand_port
                    break
            if not port:
                return utils.jsonify(
                    {
                        'error': PORT_PROTOCOL_IN_USE,
                        'error_msg': PORT_PROTOCOL_IN_USE_MSG,
                    }, 400)

        if wg and not port_wg_def:
            port_used.add(port)

            port_wg_def = True
            rand_port_wgs = list(range(10000, 19999))
            random.shuffle(rand_port_wgs)
            for rand_port_wg in rand_port_wgs:
                if '%s%s' % (rand_port_wg, protocol) not in port_used:
                    port_wg = rand_port_wg
                    break
            if not port_wg:
                return utils.jsonify(
                    {
                        'error': PORT_WG_IN_USE,
                        'error_msg': PORT_WG_IN_USE_MSG,
                    }, 400)

        if not dh_param_bits_def:
            dh_param_bits_def = True
            dh_param_bits = settings.vpn.default_dh_param_bits

    changed = None

    if not server_id:
        svr = server.new_server(
            name=name,
            network=network,
            network_wg=network_wg,
            groups=groups,
            network_mode=network_mode,
            network_start=network_start,
            network_end=network_end,
            restrict_routes=restrict_routes,
            wg=wg,
            ipv6=ipv6,
            ipv6_firewall=ipv6_firewall,
            bind_address=bind_address,
            port=port,
            port_wg=port_wg,
            protocol=protocol,
            dh_param_bits=dh_param_bits,
            multi_device=multi_device,
            dns_servers=dns_servers,
            search_domain=search_domain,
            otp_auth=otp_auth,
            cipher=cipher,
            hash=hash,
            block_outside_dns=block_outside_dns,
            jumbo_frames=jumbo_frames,
            lzo_compression=lzo_compression,
            inter_client=inter_client,
            ping_interval=ping_interval,
            ping_timeout=ping_timeout,
            link_ping_interval=link_ping_interval,
            link_ping_timeout=link_ping_timeout,
            inactive_timeout=inactive_timeout,
            session_timeout=session_timeout,
            allowed_devices=allowed_devices,
            max_clients=max_clients,
            max_devices=max_devices,
            replica_count=replica_count,
            vxlan=vxlan,
            dns_mapping=dns_mapping,
            debug=debug,
            pre_connect_msg=pre_connect_msg,
            mss_fix=mss_fix,
        )
        svr.add_host(settings.local.host_id)
    else:
        svr = server.get_by_id(server_id)

        if name_def:
            svr.name = name
        if network_def:
            svr.network = network
        if network_wg_def:
            svr.network_wg = network_wg
        if groups_def:
            svr.groups = groups
        if network_start_def:
            svr.network_start = network_start
        if network_end_def:
            svr.network_end = network_end
        if restrict_routes_def:
            svr.restrict_routes = restrict_routes
        if wg_def:
            svr.wg = wg
        if ipv6_def:
            svr.ipv6 = ipv6
        if ipv6_firewall_def:
            svr.ipv6_firewall = ipv6_firewall
        if network_mode_def:
            svr.network_mode = network_mode
        if bind_address_def:
            svr.bind_address = bind_address
        if port_def:
            svr.port = port
        if port_wg_def:
            svr.port_wg = port_wg
        if protocol_def:
            svr.protocol = protocol
        if dh_param_bits_def and svr.dh_param_bits != dh_param_bits:
            svr.dh_param_bits = dh_param_bits
            svr.generate_dh_param()
        if multi_device_def:
            svr.multi_device = multi_device
        if dns_servers_def:
            svr.dns_servers = dns_servers
        if search_domain_def:
            svr.search_domain = search_domain
        if otp_auth_def:
            svr.otp_auth = otp_auth
        if cipher_def:
            svr.cipher = cipher
        if hash_def:
            svr.hash = hash
        if block_outside_dns_def:
            svr.block_outside_dns = block_outside_dns
        if jumbo_frames_def:
            svr.jumbo_frames = jumbo_frames
        if lzo_compression_def:
            svr.lzo_compression = lzo_compression
        if inter_client_def:
            svr.inter_client = inter_client
        if ping_interval_def:
            svr.ping_interval = ping_interval
        if ping_timeout_def:
            svr.ping_timeout = ping_timeout
        if link_ping_interval_def:
            svr.link_ping_interval = link_ping_interval
        if link_ping_timeout_def:
            svr.link_ping_timeout = link_ping_timeout
        if inactive_timeout_def:
            svr.inactive_timeout = inactive_timeout
        if session_timeout_def:
            svr.session_timeout = session_timeout
        if allowed_devices_def:
            svr.allowed_devices = allowed_devices
        if max_clients_def:
            svr.max_clients = max_clients
        if max_devices_def:
            svr.max_devices = max_devices
        if replica_count_def:
            svr.replica_count = replica_count
        if vxlan_def:
            svr.vxlan = vxlan
        if dns_mapping_def:
            svr.dns_mapping = dns_mapping
        if debug_def:
            svr.debug = debug
        if pre_connect_msg_def:
            svr.pre_connect_msg = pre_connect_msg
        if mss_fix_def:
            svr.mss_fix = mss_fix

        changed = svr.changed

    svr.generate_auth_key()

    err, err_msg = svr.validate_conf()
    if err:
        return utils.jsonify({
            'error': err,
            'error_msg': err_msg,
        }, 400)

    svr.commit(changed)

    if not server_id:
        logger.LogEntry(message='Created server "%s".' % svr.name)

    event.Event(type=SERVERS_UPDATED)
    event.Event(type=SERVER_ROUTES_UPDATED, resource_id=svr.id)
    for org in svr.iter_orgs():
        event.Event(type=USERS_UPDATED, resource_id=org.id)
    return utils.jsonify(svr.dict())