コード例 #1
0
ファイル: instance_com.py プロジェクト: rchicoli/pritunl
    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.IPAddress(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,
            )
コード例 #2
0
ファイル: instance_com.py プロジェクト: ijat/pritunl
    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.IPAddress(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,
            )
コード例 #3
0
    def generate_client_conf(self):
        if not os.path.exists(self._temp_path):
            os.makedirs(self._temp_path)
        ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
        self.interface = utils.tun_interface_acquire()

        if self.linked_host:
            remotes = 'remote %s %s' % (
                self.host.link_addr,
                self.linked_server.port,
            )
        else:
            remotes = self.linked_server.get_key_remotes(True)

        client_conf = OVPN_INLINE_LINK_CONF % (
            uuid.uuid4().hex,
            utils.random_name(),
            self.interface,
            self.linked_server.protocol,
            remotes,
            CIPHERS[self.server.cipher],
            4 if self.server.debug else 1,
            8 if self.server.debug else 3,
            self.linked_server.ping_interval,
            self.linked_server.ping_timeout,
        )

        if self.linked_server.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if self.server.debug:
            self.server.output_link.push_message(
                'Server conf:',
                label=self.output_label,
                link_server_id=self.linked_server.id,
            )
            for conf_line in client_conf.split('\n'):
                if conf_line:
                    self.server.output_link.push_message(
                        '  ' + conf_line,
                        label=self.output_label,
                        link_server_id=self.linked_server.id,
                    )

        client_conf += JUMBO_FRAMES[self.linked_server.jumbo_frames]
        client_conf += '<ca>\n%s\n</ca>\n' % self.linked_server.ca_certificate

        if self.linked_server.tls_auth:
            client_conf += 'key-direction 1\n<tls-auth>\n%s\n</tls-auth>\n' % (
                self.linked_server.tls_auth_key)

        client_conf += ('<cert>\n%s\n' + \
            '</cert>\n') % utils.get_cert_block(self.user.certificate)
        client_conf += '<key>\n%s\n</key>\n' % (self.user.private_key.strip())

        with open(ovpn_conf_path, 'w') as ovpn_conf:
            os.chmod(ovpn_conf_path, 0600)
            ovpn_conf.write(client_conf)

        return ovpn_conf_path
コード例 #4
0
ファイル: user.py プロジェクト: carvenli/pritunl
    def _generate_conf(self, server, include_user_cert=True):
        if not self.sync_token or not self.sync_secret:
            self.sync_token = utils.generate_secret()
            self.sync_secret = utils.generate_secret()
            self.commit(('sync_token', 'sync_secret'))

        file_name = '%s_%s_%s.ovpn' % (
            self.org.name, self.name, server.name)
        if not server.ca_certificate:
            server.generate_ca_cert()
        key_remotes = server.get_key_remotes()
        ca_certificate = server.ca_certificate
        certificate = utils.get_cert_block(self.certificate)
        private_key = self.private_key.strip()

        conf_hash = hashlib.md5()
        conf_hash.update(self.name.encode('utf-8'))
        conf_hash.update(self.org.name.encode('utf-8'))
        conf_hash.update(server.name.encode('utf-8'))
        conf_hash.update(server.protocol)
        for key_remote in sorted(key_remotes):
            conf_hash.update(key_remote)
        conf_hash.update(CIPHERS[server.cipher])
        conf_hash.update(str(server.lzo_compression))
        conf_hash.update(str(server.otp_auth))
        conf_hash.update(JUMBO_FRAMES[server.jumbo_frames])
        conf_hash.update(ca_certificate)
        conf_hash = conf_hash.hexdigest()

        client_conf = OVPN_INLINE_CLIENT_CONF % (
            self._get_key_info_str(server, conf_hash),
            uuid.uuid4().hex,
            utils.random_name(),
            server.protocol,
            server.get_key_remotes(),
            CIPHERS[server.cipher],
            server.ping_interval,
            server.ping_timeout,
        )

        if server.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if server.otp_auth:
            client_conf += 'auth-user-pass\n'

        if server.tls_auth:
            client_conf += 'key-direction 1\n'

        client_conf += JUMBO_FRAMES[server.jumbo_frames]
        client_conf += '<ca>\n%s\n</ca>\n' % ca_certificate
        if include_user_cert:
            if server.tls_auth:
                client_conf += '<tls-auth>\n%s\n</tls-auth>\n' % (
                    server.tls_auth_key)

            client_conf += '<cert>\n%s\n</cert>\n' % certificate
            client_conf += '<key>\n%s\n</key>\n' % private_key

        return file_name, client_conf, conf_hash
コード例 #5
0
ファイル: instance_com.py プロジェクト: rchicoli/pritunl
    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.IPAddress(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
ファイル: instance_link.py プロジェクト: kknet/pritunl
    def generate_client_conf(self):
        if not os.path.exists(self._temp_path):
            os.makedirs(self._temp_path)
        ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
        self.interface = utils.tun_interface_acquire()

        if self.linked_host:
            remotes = 'remote %s %s' % (
                self.host.link_addr,
                self.linked_server.port,
            )
        else:
            remotes = self.linked_server.get_key_remotes(True)

        client_conf = OVPN_INLINE_LINK_CONF % (
            uuid.uuid4().hex,
            utils.random_name(),
            self.interface,
            self.linked_server.protocol,
            remotes,
            CIPHERS[self.server.cipher],
            4 if self.server.debug else 1,
            8 if self.server.debug else 3,
        )

        if self.linked_server.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if self.server.debug:
            self.server.output_link.push_message(
                'Server conf:',
                label=self.output_label,
                link_server_id=self.linked_server.id,
            )
            for conf_line in client_conf.split('\n'):
                if conf_line:
                    self.server.output_link.push_message(
                        '  ' + conf_line,
                        label=self.output_label,
                        link_server_id=self.linked_server.id,
                    )

        client_conf += JUMBO_FRAMES[self.linked_server.jumbo_frames]
        client_conf += '<ca>\n%s\n</ca>\n' % self.linked_server.ca_certificate

        if self.linked_server.tls_auth:
            client_conf += 'key-direction 1\n<tls-auth>\n%s\n</tls-auth>\n' % (
                self.linked_server.tls_auth_key)

        client_conf += ('<cert>\n%s\n' + \
            '</cert>\n') % utils.get_cert_block(self.user.certificate)
        client_conf += '<key>\n%s\n</key>\n' % (
            self.user.private_key.strip())

        with open(ovpn_conf_path, 'w') as ovpn_conf:
            os.chmod(ovpn_conf_path, 0600)
            ovpn_conf.write(client_conf)

        return ovpn_conf_path
コード例 #7
0
ファイル: host.py プロジェクト: tomegathericon/pritunl
def host_put(hst=None):
    if settings.app.demo_mode:
        return utils.demo_blocked()

    hst = host.get_by_id(hst)

    if 'name' in flask.request.json:
        hst.name = utils.filter_str(
            flask.request.json['name']) or utils.random_name()

    if 'public_address' in flask.request.json:
        hst.public_address = utils.filter_str(
            flask.request.json['public_address'])

    if 'public_address6' in flask.request.json:
        hst.public_address6 = utils.filter_str(
            flask.request.json['public_address6'])

    if 'routed_subnet6' in flask.request.json:
        routed_subnet6 = flask.request.json['routed_subnet6']
        if routed_subnet6:
            try:
                routed_subnet6 = ipaddress.IPv6Network(
                    flask.request.json['routed_subnet6'])
            except (ipaddress.AddressValueError, ValueError):
                return utils.jsonify({
                    'error': IPV6_SUBNET_INVALID,
                    'error_msg': IPV6_SUBNET_INVALID_MSG,
                }, 400)

            if routed_subnet6.prefixlen > 64:
                return utils.jsonify({
                    'error': IPV6_SUBNET_SIZE_INVALID,
                    'error_msg': IPV6_SUBNET_SIZE_INVALID_MSG,
                }, 400)

            routed_subnet6 = str(routed_subnet6)
        else:
            routed_subnet6 = None

        if hst.routed_subnet6 != routed_subnet6:
            if server.get_online_ipv6_count():
                return utils.jsonify({
                    'error': IPV6_SUBNET_ONLINE,
                    'error_msg': IPV6_SUBNET_ONLINE_MSG,
                }, 400)
            hst.routed_subnet6 = routed_subnet6

    if 'link_address' in flask.request.json:
        hst.link_address = utils.filter_str(
            flask.request.json['link_address'])

    hst.commit(hst.changed)
    event.Event(type=HOSTS_UPDATED)
    messenger.publish('hosts', 'updated')

    return utils.jsonify(hst.dict())
コード例 #8
0
ファイル: host.py プロジェクト: zyd915/pritunl
    def __init__(self, name=None, **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)
        self.user_count = None
        self.users_online = None
        self.usage = HostUsage(self.id)

        if name is not None:
            self.name = name

        if self.name is None:
            self.name = utils.random_name()
コード例 #9
0
ファイル: host.py プロジェクト: rchicoli/pritunl
def host_put(hst=None):
    if settings.app.demo_mode:
        return utils.demo_blocked()

    hst = host.get_by_id(hst)

    if "name" in flask.request.json:
        hst.name = utils.filter_str(flask.request.json["name"]) or utils.random_name()

    if "public_address" in flask.request.json:
        hst.public_address = utils.filter_str(flask.request.json["public_address"])

    if "public_address6" in flask.request.json:
        hst.public_address6 = utils.filter_str(flask.request.json["public_address6"])

    if "routed_subnet6" in flask.request.json:
        routed_subnet6 = flask.request.json["routed_subnet6"]
        if routed_subnet6:
            try:
                routed_subnet6 = ipaddress.IPv6Network(flask.request.json["routed_subnet6"])
            except (ipaddress.AddressValueError, ValueError):
                return utils.jsonify({"error": IPV6_SUBNET_INVALID, "error_msg": IPV6_SUBNET_INVALID_MSG}, 400)

            if routed_subnet6.prefixlen > 64:
                return utils.jsonify(
                    {"error": IPV6_SUBNET_SIZE_INVALID, "error_msg": IPV6_SUBNET_SIZE_INVALID_MSG}, 400
                )

            routed_subnet6 = str(routed_subnet6)
        else:
            routed_subnet6 = None

        if hst.routed_subnet6 != routed_subnet6:
            if server.get_online_ipv6_count():
                return utils.jsonify({"error": IPV6_SUBNET_ONLINE, "error_msg": IPV6_SUBNET_ONLINE_MSG}, 400)
            hst.routed_subnet6 = routed_subnet6

    if "local_address" in flask.request.json:
        hst.local_address = utils.filter_str(flask.request.json["local_address"])

    if "local_address6" in flask.request.json:
        hst.local_address6 = utils.filter_str(flask.request.json["local_address6"])

    if "link_address" in flask.request.json:
        hst.link_address = utils.filter_str(flask.request.json["link_address"])

    if "instance_id" in flask.request.json:
        hst.instance_id = utils.filter_str(flask.request.json["instance_id"])

    hst.commit(hst.changed)
    event.Event(type=HOSTS_UPDATED)
    messenger.publish("hosts", "updated")

    return utils.jsonify(hst.dict())
コード例 #10
0
ファイル: host.py プロジェクト: pritunl/pritunl
    def __init__(self, name=None, **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)
        self.user_count = None
        self.users_online = None
        self.usage = HostUsage(self.id)

        if name is not None:
            self.name = name

        if self.name is None:
            self.name = utils.random_name()
コード例 #11
0
ファイル: instance_link.py プロジェクト: guozanhua/pritunl
    def generate_client_conf(self):
        if not os.path.exists(self._temp_path):
            os.makedirs(self._temp_path)
        ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
        self.interface = utils.interface_acquire(
            self.linked_server.adapter_type)

        remotes = self.linked_server.get_key_remotes(True)

        client_conf = OVPN_INLINE_LINK_CONF % (
            uuid.uuid4().hex,
            utils.random_name(),
            self.interface,
            self.linked_server.adapter_type,
            remotes,
            CIPHERS[self.linked_server.cipher],
            HASHES[self.linked_server.hash],
            4 if self.server.debug else 1,
            8 if self.server.debug else 3,
            settings.app.host_ping,
            settings.app.host_ping_ttl,
        )

        if self.server.debug:
            self.server.output_link.push_message(
                'Server conf:',
                label=self.output_label,
                link_server_id=self.linked_server.id,
            )
            for conf_line in client_conf.split('\n'):
                if conf_line:
                    self.server.output_link.push_message(
                        '  ' + conf_line,
                        label=self.output_label,
                        link_server_id=self.linked_server.id,
                    )

        client_conf += JUMBO_FRAMES[self.linked_server.jumbo_frames]
        client_conf += '<ca>\n%s\n</ca>\n' % self.linked_server.ca_certificate

        if self.linked_server.tls_auth:
            client_conf += 'key-direction 1\n<tls-auth>\n%s\n</tls-auth>\n' % (
                self.linked_server.tls_auth_key)

        client_conf += ('<cert>\n%s\n' + '</cert>\n') % utils.get_cert_block(
            self.user.certificate)
        client_conf += '<key>\n%s\n</key>\n' % (self.user.private_key.strip())

        with open(ovpn_conf_path, 'w') as ovpn_conf:
            os.chmod(ovpn_conf_path, 0600)
            ovpn_conf.write(client_conf)

        return ovpn_conf_path
コード例 #12
0
ファイル: host.py プロジェクト: uguryildiz/pritunl
    def __init__(self, name=None, **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)

        if 'id' not in kwargs and 'doc' not in kwargs and 'spec' not in kwargs:
            self.id = settings.local.host_id

        self.usage = HostUsage(self.id)

        if name is not None:
            self.name = name

        if self.name is None:
            self.name = utils.random_name()
コード例 #13
0
    def __init__(self, name=None, **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)

        if 'id' not in kwargs and 'doc' not in kwargs and 'spec' not in kwargs:
            self.id = settings.local.host_id

        self.usage = HostUsage(self.id)

        if name is not None:
            self.name = name

        if self.name is None:
            self.name = utils.random_name()
コード例 #14
0
def host_put(host_id=None):
    hst = host.get_host(id=host_id)

    if 'name' in flask.request.json:
        hst.name = utils.filter_str(
            flask.request.json['name']) or utils.random_name()

    if 'public_address' in flask.request.json:
        hst.public_address = utils.filter_str(
            flask.request.json['public_address'])

    hst.commit(hst.changed)
    event.Event(type=HOSTS_UPDATED)

    return utils.jsonify(host.dict())
コード例 #15
0
    def generate_client_conf(self):
        if not os.path.exists(self._temp_path):
            os.makedirs(self._temp_path)
        ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
        self.interface = utils.tun_interface_acquire()

        if self.linked_host:
            remotes = 'remote %s %s' % (
                self.host.link_address or self.host.public_address,
                self.linked_server.port,
            )
        else:
            remotes = self.linked_server.get_key_remotes(True)

        client_conf = OVPN_INLINE_LINK_CONF % (
            uuid.uuid4().hex,
            utils.random_name(),
            self.interface,
            self.linked_server.protocol,
            remotes,
            CIPHERS[self.server.cipher],
            4 if self.server.debug else 1,
            8 if self.server.debug else 3,
        )

        if self.linked_server.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if self.linked_server.otp_auth:
            client_conf += 'auth-user-pass\n'

        client_conf += JUMBO_FRAMES[self.linked_server.jumbo_frames]
        client_conf += '<ca>\n%s\n</ca>\n' % self.linked_server.ca_certificate

        if self.linked_server.tls_auth:
            client_conf += '<tls-auth>\n%s\n</tls-auth>\n' % (
                self.linked_server.tls_auth_key)

        client_conf += ('<cert>\n%s\n' + \
            '</cert>\n') % utils.get_cert_block(self.user.certificate)
        client_conf += '<key>\n%s\n</key>\n' % (self.user.private_key.strip())

        with open(ovpn_conf_path, 'w') as ovpn_conf:
            os.chmod(ovpn_conf_path, 0600)
            ovpn_conf.write(client_conf)

        return ovpn_conf_path
コード例 #16
0
ファイル: demo.py プロジェクト: nawien-sharma/pritunl
    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)

                    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.IPAddress(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')
コード例 #17
0
ファイル: host.py プロジェクト: zeus911/pritunl
def host_put(hst=None):
    if settings.app.demo_mode:
        return utils.demo_blocked()

    hst = host.get_by_id(hst)

    if 'name' in flask.request.json:
        hst.name = utils.filter_str(
            flask.request.json['name']) or utils.random_name()

    if 'public_address' in flask.request.json:
        public_address = utils.filter_str(flask.request.json['public_address'])
        hst.public_address = public_address

    if 'public_address6' in flask.request.json:
        public_address6 = utils.filter_str(
            flask.request.json['public_address6'])
        hst.public_address6 = public_address6

    if 'routed_subnet6' in flask.request.json:
        routed_subnet6 = flask.request.json['routed_subnet6']
        if routed_subnet6:
            try:
                routed_subnet6 = ipaddress.IPv6Network(
                    flask.request.json['routed_subnet6'])
            except (ipaddress.AddressValueError, ValueError):
                return utils.jsonify(
                    {
                        'error': IPV6_SUBNET_INVALID,
                        'error_msg': IPV6_SUBNET_INVALID_MSG,
                    }, 400)

            if routed_subnet6.prefixlen > 64:
                return utils.jsonify(
                    {
                        'error': IPV6_SUBNET_SIZE_INVALID,
                        'error_msg': IPV6_SUBNET_SIZE_INVALID_MSG,
                    }, 400)

            routed_subnet6 = str(routed_subnet6)
        else:
            routed_subnet6 = None

        if hst.routed_subnet6 != routed_subnet6:
            if server.get_online_ipv6_count():
                return utils.jsonify(
                    {
                        'error': IPV6_SUBNET_ONLINE,
                        'error_msg': IPV6_SUBNET_ONLINE_MSG,
                    }, 400)
            hst.routed_subnet6 = routed_subnet6

    if 'proxy_ndp' in flask.request.json:
        proxy_ndp = True if flask.request.json['proxy_ndp'] else False
        hst.proxy_ndp = proxy_ndp

    if 'local_address' in flask.request.json:
        local_address = utils.filter_str(flask.request.json['local_address'])
        hst.local_address = local_address

    if 'local_address6' in flask.request.json:
        local_address6 = utils.filter_str(flask.request.json['local_address6'])
        hst.local_address6 = local_address6

    if 'link_address' in flask.request.json:
        link_address = utils.filter_str(flask.request.json['link_address'])
        hst.link_address = link_address

    if 'sync_address' in flask.request.json:
        sync_address = utils.filter_str(flask.request.json['sync_address'])
        hst.sync_address = sync_address

    if 'availability_group' in flask.request.json:
        hst.availability_group = utils.filter_str(
            flask.request.json['availability_group']) or DEFAULT

    if 'instance_id' in flask.request.json:
        instance_id = utils.filter_str(flask.request.json['instance_id'])

        if instance_id != hst.aws_id:
            hst.instance_id = instance_id

    hst.commit(hst.changed)
    event.Event(type=HOSTS_UPDATED)
    messenger.publish('hosts', 'updated')

    return utils.jsonify(hst.dict())
コード例 #18
0
ファイル: subscription.py プロジェクト: dartus95/pritunl
def update():
    license = settings.app.license
    collection = mongo.get_collection('settings')

    if not settings.app.id:
        settings.app.id = utils.random_name()
        settings.commit()

    if not license:
        settings.local.sub_active = False
        settings.local.sub_status = None
        settings.local.sub_plan = None
        settings.local.sub_quantity = None
        settings.local.sub_amount = None
        settings.local.sub_period_end = None
        settings.local.sub_trial_end = None
        settings.local.sub_cancel_at_period_end = None
        settings.local.sub_balance = None
        settings.local.sub_url_key = None
    else:
        for i in range(2):
            try:
                url = x(b'aHR0cHM6Ly9hcHAucHJpdHVubC5jb20vc3Vic2NyaXB0aW9u')

                response = requests.get(
                    url,
                    json={
                        x(b'aWQ='): settings.app.id,
                        x(b'bGljZW5zZQ=='): license,
                        x(b'dmVyc2lvbg=='): settings.local.version_int,
                    },
                    timeout=max(settings.app.http_request_timeout, 10),
                )

                # License key invalid
                if response.status_code == 470:
                    raise ValueError('License key is invalid')

                if response.status_code == 473:
                    raise ValueError(('Version %r not recognized by ' +
                        'subscription server') % settings.local.version_int)

                data = response.json()

                settings.local.sub_active = data[x(b'YWN0aXZl')]
                settings.local.sub_status = data[x(b'c3RhdHVz')]
                settings.local.sub_plan = data[x(b'cGxhbg==')]
                settings.local.sub_quantity = data[x(b'cXVhbnRpdHk=')]
                settings.local.sub_amount = data[x(b'YW1vdW50')]
                settings.local.sub_period_end = data[x(b'cGVyaW9kX2VuZA==')]
                settings.local.sub_trial_end = data[x(b'dHJpYWxfZW5k')]
                settings.local.sub_cancel_at_period_end = \
                    data[x(b'Y2FuY2VsX2F0X3BlcmlvZF9lbmQ=')]
                settings.local.sub_balance = data.get(x(b'YmFsYW5jZQ=='))
                settings.local.sub_url_key = data.get(x(b'dXJsX2tleQ=='))
                settings.local.sub_styles[data[x(b'cGxhbg==')]] = \
                    data[x(b'c3R5bGVz')]
            except:
                if i < 1:
                    logger.exception('Failed to check subscription status',
                        'subscription, retrying...')
                    time.sleep(1)
                    continue
                logger.exception('Failed to check subscription status',
                    'subscription')
                settings.local.sub_active = False
                settings.local.sub_status = None
                settings.local.sub_plan = None
                settings.local.sub_quantity = None
                settings.local.sub_amount = None
                settings.local.sub_period_end = None
                settings.local.sub_trial_end = None
                settings.local.sub_cancel_at_period_end = None
                settings.local.sub_balance = None
                settings.local.sub_url_key = None
            break

    if settings.app.license_plan != settings.local.sub_plan and \
            settings.local.sub_plan:
        settings.app.license_plan = settings.local.sub_plan
        settings.commit()

    response = collection.update({
        '_id': 'subscription',
        '$or': [
            {'active': {'$ne': settings.local.sub_active}},
            {'plan': {'$ne': settings.local.sub_plan}},
        ],
    }, {'$set': {
        'active': settings.local.sub_active,
        'plan': settings.local.sub_plan,
    }})
    if response['updatedExisting']:
        if settings.local.sub_active:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_ACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_ACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_ACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)
        else:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_INACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_INACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_INACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)

    return True
コード例 #19
0
ファイル: user.py プロジェクト: pritunl/pritunl
    def _generate_conf(self, svr, include_user_cert=True):
        if not self.sync_token or not self.sync_secret:
            self.sync_token = utils.generate_secret()
            self.sync_secret = utils.generate_secret()
            self.commit(('sync_token', 'sync_secret'))

        file_name = '%s_%s_%s.ovpn' % (
            self.org.name, self.name, svr.name)
        if not svr.ca_certificate:
            svr.generate_ca_cert()
        key_remotes = svr.get_key_remotes()
        ca_certificate = svr.ca_certificate
        certificate = utils.get_cert_block(self.certificate)
        private_key = self.private_key.strip()

        conf_hash = hashlib.md5()
        conf_hash.update(self.name.encode('utf-8'))
        conf_hash.update(self.org.name.encode('utf-8'))
        conf_hash.update(svr.name.encode('utf-8'))
        conf_hash.update(svr.protocol)
        for key_remote in sorted(key_remotes):
            conf_hash.update(key_remote)
        conf_hash.update(CIPHERS[svr.cipher])
        conf_hash.update(str(svr.lzo_compression))
        conf_hash.update(str(svr.block_outside_dns))
        conf_hash.update(str(svr.otp_auth))
        conf_hash.update(JUMBO_FRAMES[svr.jumbo_frames])
        conf_hash.update(ca_certificate)
        conf_hash.update(self._get_key_info_str(svr, None, False))

        plugin_config = ''
        if settings.local.sub_plan and \
                'enterprise' in settings.local.sub_plan:
            returns = plugins.caller(
                'user_config',
                host_id=settings.local.host_id,
                host_name=settings.local.host.name,
                org_id=self.org_id,
                user_id=self.id,
                user_name=self.name,
                server_id=svr.id,
                server_name=svr.name,
                server_port=svr.port,
                server_protocol=svr.protocol,
                server_ipv6=svr.ipv6,
                server_ipv6_firewall=svr.ipv6_firewall,
                server_network=svr.network,
                server_network6=svr.network6,
                server_network_mode=svr.network_mode,
                server_network_start=svr.network_start,
                server_network_stop=svr.network_end,
                server_restrict_routes=svr.restrict_routes,
                server_bind_address=svr.bind_address,
                server_onc_hostname=None,
                server_dh_param_bits=svr.dh_param_bits,
                server_multi_device=svr.multi_device,
                server_dns_servers=svr.dns_servers,
                server_search_domain=svr.search_domain,
                server_otp_auth=svr.otp_auth,
                server_cipher=svr.cipher,
                server_hash=svr.hash,
                server_inter_client=svr.inter_client,
                server_ping_interval=svr.ping_interval,
                server_ping_timeout=svr.ping_timeout,
                server_link_ping_interval=svr.link_ping_interval,
                server_link_ping_timeout=svr.link_ping_timeout,
                server_allowed_devices=svr.allowed_devices,
                server_max_clients=svr.max_clients,
                server_replica_count=svr.replica_count,
                server_dns_mapping=svr.dns_mapping,
                server_debug=svr.debug,
            )

            if returns:
                for return_val in returns:
                    if not return_val:
                        continue

                    val = return_val.strip()
                    conf_hash.update(val)
                    plugin_config += val + '\n'

        conf_hash = conf_hash.hexdigest()

        client_conf = OVPN_INLINE_CLIENT_CONF % (
            self._get_key_info_str(svr, conf_hash, include_user_cert),
            uuid.uuid4().hex,
            utils.random_name(),
            svr.adapter_type,
            svr.adapter_type,
            svr.get_key_remotes(),
            CIPHERS[svr.cipher],
            HASHES[svr.hash],
            svr.ping_interval,
            svr.ping_timeout,
        )

        if svr.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if svr.block_outside_dns:
            client_conf += 'ignore-unknown-option block-outside-dns\n'
            client_conf += 'block-outside-dns\n'

        if self.has_password(svr):
            client_conf += 'auth-user-pass\n'

        if svr.tls_auth:
            client_conf += 'key-direction 1\n'

        client_conf += JUMBO_FRAMES[svr.jumbo_frames]
        client_conf += plugin_config
        client_conf += '<ca>\n%s\n</ca>\n' % ca_certificate
        if include_user_cert:
            if svr.tls_auth:
                client_conf += '<tls-auth>\n%s\n</tls-auth>\n' % (
                    svr.tls_auth_key)

            client_conf += '<cert>\n%s\n</cert>\n' % certificate
            client_conf += '<key>\n%s\n</key>\n' % private_key

        return file_name, client_conf, conf_hash
コード例 #20
0
def update():
    license = settings.app.license
    collection = mongo.get_collection('settings')

    if not settings.app.id:
        settings.app.id = utils.random_name()
        settings.commit()

    if not license:
        settings.local.sub_active = False
        settings.local.sub_status = None
        settings.local.sub_plan = None
        settings.local.sub_quantity = None
        settings.local.sub_amount = None
        settings.local.sub_period_end = None
        settings.local.sub_trial_end = None
        settings.local.sub_cancel_at_period_end = None
        settings.local.sub_balance = None
        settings.local.sub_url_key = None
    else:
        for i in xrange(2):
            try:
                url = 'https://app.pritunl.com/subscription'
                if settings.app.dedicated:
                    url = settings.app.dedicated + '/subscription'

                response = requests.get(
                    url,
                    json={
                        'id': settings.app.id,
                        'license': license,
                        'version': settings.local.version_int,
                    },
                    timeout=max(settings.app.http_request_timeout, 10),
                )

                # License key invalid
                
                data = response.json()

                settings.local.sub_active = True
                settings.local.sub_status = 'active'
                settings.local.sub_plan = 'enterprise'
                settings.local.sub_quantity = 1000
                settings.local.sub_amount = 1000
                settings.local.sub_period_end = 100
                settings.local.sub_trial_end = 100
                settings.local.sub_cancel_at_period_end = 1000
                settings.local.sub_balance = 1000
                settings.local.sub_url_key = 'Test'
            except:
                if i < 1:
                    logger.exception('Failed to check subscription status',
                        'subscription, retrying...')
                    time.sleep(1)
                    continue
                logger.exception('Failed to check subscription status',
                    'subscription')
                settings.local.sub_active = False
                settings.local.sub_status = None
                settings.local.sub_plan = None
                settings.local.sub_quantity = None
                settings.local.sub_amount = None
                settings.local.sub_period_end = None
                settings.local.sub_trial_end = None
                settings.local.sub_cancel_at_period_end = None
                settings.local.sub_balance = None
                settings.local.sub_url_key = None
            break

    if settings.app.license_plan != settings.local.sub_plan and \
            settings.local.sub_plan:
        settings.app.license_plan = settings.local.sub_plan
        settings.commit()

    response = collection.update({
        '_id': 'subscription',
        '$or': [
            {'active': {'$ne': settings.local.sub_active}},
            {'plan': {'$ne': settings.local.sub_plan}},
        ],
    }, {'$set': {
        'active': settings.local.sub_active,
        'plan': settings.local.sub_plan,
    }})
    if response['updatedExisting']:
        if settings.local.sub_active:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_ACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_ACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_ACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)
        else:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_INACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_INACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_INACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)

    return True
コード例 #21
0
def update():
    license = settings.app.license
    collection = mongo.get_collection('settings')

    if not settings.app.id:
        settings.app.id = utils.random_name()
        settings.commit()

    if not license:
        settings.local.sub_active = False
        settings.local.sub_status = None
        settings.local.sub_plan = None
        settings.local.sub_quantity = None
        settings.local.sub_amount = None
        settings.local.sub_period_end = None
        settings.local.sub_trial_end = None
        settings.local.sub_cancel_at_period_end = None
        settings.local.sub_balance = None
        settings.local.sub_url_key = None
    else:
        for i in xrange(2):
            try:
                response = requests.get(
                    'https://app.pritunl.com/subscription',
                    json={
                        'id': settings.app.id,
                        'license': license,
                        'version': settings.local.version_int,
                    },
                    timeout=max(settings.app.http_request_timeout, 10),
                )

                # License key invalid
                if response.status_code == 470:
                    raise ValueError('License key is invalid')

                if response.status_code == 473:
                    raise ValueError(
                        ('Version %r not recognized by ' +
                         'subscription server') % settings.local.version_int)

                data = response.json()

                settings.local.sub_active = data['active']
                settings.local.sub_status = data['status']
                settings.local.sub_plan = data['plan']
                settings.local.sub_quantity = data['quantity']
                settings.local.sub_amount = data['amount']
                settings.local.sub_period_end = data['period_end']
                settings.local.sub_trial_end = data['trial_end']
                settings.local.sub_cancel_at_period_end = data[
                    'cancel_at_period_end']
                settings.local.sub_balance = data.get('balance')
                settings.local.sub_url_key = data.get('url_key')
                settings.local.sub_styles[data['plan']] = data['styles']
            except:
                if i < 1:
                    logger.exception('Failed to check subscription status',
                                     'subscription, retrying...')
                    time.sleep(1)
                    continue
                logger.exception('Failed to check subscription status',
                                 'subscription')
                settings.local.sub_active = False
                settings.local.sub_status = None
                settings.local.sub_plan = None
                settings.local.sub_quantity = None
                settings.local.sub_amount = None
                settings.local.sub_period_end = None
                settings.local.sub_trial_end = None
                settings.local.sub_cancel_at_period_end = None
                settings.local.sub_balance = None
                settings.local.sub_url_key = None
            break

    if settings.app.license_plan != settings.local.sub_plan and \
            settings.local.sub_plan:
        settings.app.license_plan = settings.local.sub_plan
        settings.commit()

    response = collection.update(
        {
            '_id':
            'subscription',
            '$or': [
                {
                    'active': {
                        '$ne': settings.local.sub_active
                    }
                },
                {
                    'plan': {
                        '$ne': settings.local.sub_plan
                    }
                },
            ],
        }, {
            '$set': {
                'active': settings.local.sub_active,
                'plan': settings.local.sub_plan,
            }
        })
    if response['updatedExisting']:
        if settings.local.sub_active:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_ACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_ACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_ACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)
        else:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_INACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_INACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_INACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)

    return True
コード例 #22
0
ファイル: subscription.py プロジェクト: nawien-sharma/pritunl
def update():
    license = settings.app.license
    collection = mongo.get_collection('settings')

    if not settings.app.id:
        settings.app.id = utils.random_name()
        settings.commit()

    if not license:
        settings.local.sub_active = False
        settings.local.sub_status = None
        settings.local.sub_plan = None
        settings.local.sub_quantity = None
        settings.local.sub_amount = None
        settings.local.sub_period_end = None
        settings.local.sub_trial_end = None
        settings.local.sub_cancel_at_period_end = None
        settings.local.sub_balance = None
        settings.local.sub_url_key = None
    else:
        for i in xrange(2):
            try:
                response = requests.get(
                    'https://app.pritunl.com/subscription',
                    json={
                        'id': settings.app.id,
                        'license': license,
                        'version': settings.local.version_int,
                    },
                    timeout=max(settings.app.http_request_timeout, 10),
                )

                # License key invalid
                if response.status_code == 470:
                    raise ValueError('License key is invalid')

                if response.status_code == 473:
                    raise ValueError(('Version %r not recognized by ' +
                        'subscription server') % settings.local.version_int)

                data = response.json()

                settings.local.sub_active = data['active']
                settings.local.sub_status = data['status']
                settings.local.sub_plan = data['plan']
                settings.local.sub_quantity = data['quantity']
                settings.local.sub_amount = data['amount']
                settings.local.sub_period_end = data['period_end']
                settings.local.sub_trial_end = data['trial_end']
                settings.local.sub_cancel_at_period_end = data[
                    'cancel_at_period_end']
                settings.local.sub_balance = data.get('balance')
                settings.local.sub_url_key = data.get('url_key')
                settings.local.sub_styles[data['plan']] = data['styles']
            except:
                if i < 1:
                    logger.exception('Failed to check subscription status',
                        'subscription, retrying...')
                    time.sleep(1)
                    continue
                logger.exception('Failed to check subscription status',
                    'subscription')
                settings.local.sub_active = False
                settings.local.sub_status = None
                settings.local.sub_plan = None
                settings.local.sub_quantity = None
                settings.local.sub_amount = None
                settings.local.sub_period_end = None
                settings.local.sub_trial_end = None
                settings.local.sub_cancel_at_period_end = None
                settings.local.sub_balance = None
                settings.local.sub_url_key = None
            break

    if settings.app.license_plan != settings.local.sub_plan and \
            settings.local.sub_plan:
        settings.app.license_plan = settings.local.sub_plan
        settings.commit()

    response = collection.update({
        '_id': 'subscription',
        '$or': [
            {'active': {'$ne': settings.local.sub_active}},
            {'plan': {'$ne': settings.local.sub_plan}},
        ],
    }, {'$set': {
        'active': settings.local.sub_active,
        'plan': settings.local.sub_plan,
    }})
    if response['updatedExisting']:
        if settings.local.sub_active:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_ACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_ACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_ACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)
        else:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_INACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_INACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_INACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)

    return True
コード例 #23
0
ファイル: demo.py プロジェクト: thaihust/fVPN
    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)

                    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.IPAddress(
                                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')
コード例 #24
0
    def _generate_conf(self, svr, include_user_cert=True):
        if not self.sync_token or not self.sync_secret:
            self.sync_token = utils.generate_secret()
            self.sync_secret = utils.generate_secret()
            self.commit(('sync_token', 'sync_secret'))

        file_name = '%s_%s_%s.ovpn' % (self.org.name, self.name, svr.name)
        if not svr.ca_certificate:
            svr.generate_ca_cert()
        key_remotes = svr.get_key_remotes()
        ca_certificate = svr.ca_certificate
        certificate = utils.get_cert_block(self.certificate)
        private_key = self.private_key.strip()

        conf_hash = hashlib.md5()
        conf_hash.update(self.name.encode('utf-8'))
        conf_hash.update(self.org.name.encode('utf-8'))
        conf_hash.update(svr.name.encode('utf-8'))
        conf_hash.update(svr.protocol)
        for key_remote in sorted(key_remotes):
            conf_hash.update(key_remote)
        conf_hash.update(CIPHERS[svr.cipher])
        conf_hash.update(str(svr.lzo_compression))
        conf_hash.update(str(svr.block_outside_dns))
        conf_hash.update(str(svr.otp_auth))
        conf_hash.update(JUMBO_FRAMES[svr.jumbo_frames])
        conf_hash.update(ca_certificate)
        conf_hash.update(self._get_key_info_str(svr, None, False))

        plugin_config = ''
        if settings.local.sub_plan and \
                'enterprise' in settings.local.sub_plan:
            returns = plugins.caller(
                'user_config',
                host_id=settings.local.host_id,
                host_name=settings.local.host.name,
                org_id=self.org_id,
                user_id=self.id,
                user_name=self.name,
                server_id=svr.id,
                server_name=svr.name,
                server_port=svr.port,
                server_protocol=svr.protocol,
                server_ipv6=svr.ipv6,
                server_ipv6_firewall=svr.ipv6_firewall,
                server_network=svr.network,
                server_network6=svr.network6,
                server_network_mode=svr.network_mode,
                server_network_start=svr.network_start,
                server_network_stop=svr.network_end,
                server_restrict_routes=svr.restrict_routes,
                server_bind_address=svr.bind_address,
                server_onc_hostname=None,
                server_dh_param_bits=svr.dh_param_bits,
                server_multi_device=svr.multi_device,
                server_dns_servers=svr.dns_servers,
                server_search_domain=svr.search_domain,
                server_otp_auth=svr.otp_auth,
                server_cipher=svr.cipher,
                server_hash=svr.hash,
                server_inter_client=svr.inter_client,
                server_ping_interval=svr.ping_interval,
                server_ping_timeout=svr.ping_timeout,
                server_link_ping_interval=svr.link_ping_interval,
                server_link_ping_timeout=svr.link_ping_timeout,
                server_allowed_devices=svr.allowed_devices,
                server_max_clients=svr.max_clients,
                server_replica_count=svr.replica_count,
                server_dns_mapping=svr.dns_mapping,
                server_debug=svr.debug,
            )

            if returns:
                for return_val in returns:
                    if not return_val:
                        continue

                    val = return_val.strip()
                    conf_hash.update(val)
                    plugin_config += val + '\n'

        conf_hash = conf_hash.hexdigest()

        client_conf = OVPN_INLINE_CLIENT_CONF % (
            self._get_key_info_str(svr, conf_hash, include_user_cert),
            uuid.uuid4().hex,
            utils.random_name(),
            svr.adapter_type,
            svr.adapter_type,
            svr.get_key_remotes(),
            CIPHERS[svr.cipher],
            HASHES[svr.hash],
            svr.ping_interval,
            svr.ping_timeout,
        )

        if svr.lzo_compression != ADAPTIVE:
            client_conf += 'comp-lzo no\n'

        if svr.block_outside_dns:
            client_conf += 'ignore-unknown-option block-outside-dns\n'
            client_conf += 'block-outside-dns\n'

        if self.has_password(svr):
            client_conf += 'auth-user-pass\n'

        if svr.tls_auth:
            client_conf += 'key-direction 1\n'

        client_conf += JUMBO_FRAMES[svr.jumbo_frames]
        client_conf += plugin_config
        client_conf += '<ca>\n%s\n</ca>\n' % ca_certificate
        if include_user_cert:
            if svr.tls_auth:
                client_conf += '<tls-auth>\n%s\n</tls-auth>\n' % (
                    svr.tls_auth_key)

            client_conf += '<cert>\n%s\n</cert>\n' % certificate
            client_conf += '<key>\n%s\n</key>\n' % private_key

        return file_name, client_conf, conf_hash
コード例 #25
0
ファイル: subscription.py プロジェクト: thaihust/fVPN
def update():
    license = settings.app.license
    collection = mongo.get_collection('settings')

    if not settings.app.id:
        settings.app.id = utils.random_name()
        settings.commit()

    settings.local.sub_active = True
    settings.local.sub_status = 'active'
    settings.local.sub_plan = 'enterprise'
    settings.local.sub_quantity = 1
    settings.local.sub_amount = 2500
    settings.local.sub_period_end = math.floor(time.time()) + 2592000000
    settings.local.sub_trial_end = math.floor(time.time()) + 2592000000
    settings.local.sub_cancel_at_period_end = False
    settings.local.sub_balance = 0
    settings.local.sub_url_key = "url"
    settings.local.sub_styles['enterprise'] = {
        'etag': '1c253d-6c2-4e3a2f30b418d',
        'last_modified': 'Wed, 23 Oct 2019 07:52:54 GMT',
        'data': 'dark'
    }
    # if not license:
    #     settings.local.sub_active = False
    #     settings.local.sub_status = None
    #     settings.local.sub_plan = None
    #     settings.local.sub_quantity = None
    #     settings.local.sub_amount = None
    #     settings.local.sub_period_end = None
    #     settings.local.sub_trial_end = None
    #     settings.local.sub_cancel_at_period_end = None
    #     settings.local.sub_balance = None
    #     settings.local.sub_url_key = None
    # else:

    # for i in xrange(2):
    # try:
    #     # url = 'https://app.pritunl.com/subscription'
    #     # if settings.app.dedicated:
    #     #     url = settings.app.dedicated + '/subscription'

    #     # response = requests.get(
    #     #     url,
    #     #     json={
    #     #         'id': settings.app.id,
    #     #         'license': license,
    #     #         'version': settings.local.version_int,
    #     #     },
    #     #     timeout=max(settings.app.http_request_timeout, 10),
    #     # )

    #     # # License key invalid
    #     # if response.status_code == 470:
    #     #     raise ValueError('License key is invalid')

    #     # if response.status_code == 473:
    #     #     raise ValueError(('Version %r not recognized by ' +
    #     #         'subscription server') % settings.local.version_int)

    #     # data = response.json()

    #     # settings.local.sub_styles['enterprise'] = 'dark'
    # except:
    #     if i < 1:
    #         logger.exception('Failed to check subscription status',
    #             'subscription, retrying...')
    #         time.sleep(1)
    #         continue
    #     logger.exception('Failed to check subscription status',
    #         'subscription')
    #     settings.local.sub_active = True
    #     settings.local.sub_status = 'active'
    #     settings.local.sub_plan = 'enterprise'
    #     settings.local.sub_quantity = 1
    #     settings.local.sub_amount = 250
    #     settings.local.sub_period_end = math.floor(time.time()/1000) + 2592000
    #     settings.local.sub_trial_end = math.floor(time.time()/1000) + 2592000
    #     settings.local.sub_cancel_at_period_end = False
    #     settings.local.sub_balance = 0
    #     settings.local.sub_url_key = True
    #     # settings.local.sub_styles['enterprise'] = 'dark'
    # break


    if settings.app.license_plan != settings.local.sub_plan and \
            settings.local.sub_plan:
        settings.app.license_plan = settings.local.sub_plan
        settings.commit()

    response = collection.update(
        {
            '_id':
            'subscription',
            '$or': [
                {
                    'active': {
                        '$ne': settings.local.sub_active
                    }
                },
                {
                    'plan': {
                        '$ne': settings.local.sub_plan
                    }
                },
            ],
        }, {
            '$set': {
                'active': settings.local.sub_active,
                'plan': settings.local.sub_plan,
            }
        })
    if response['updatedExisting']:
        if settings.local.sub_active:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_ACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_ACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_ACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)
        else:
            if settings.local.sub_plan == 'premium':
                event.Event(type=SUBSCRIPTION_PREMIUM_INACTIVE)
            elif settings.local.sub_plan == 'enterprise':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_INACTIVE)
            elif settings.local.sub_plan == 'enterprise_plus':
                event.Event(type=SUBSCRIPTION_ENTERPRISE_PLUS_INACTIVE)
            else:
                event.Event(type=SUBSCRIPTION_NONE_INACTIVE)

    return True