예제 #1
0
파일: __init__.py 프로젝트: sxfmol/pritunl
def upgrade_server():
    if utils.get_db_ver_int() < 10000000000004000:
        logger.info('Running 0.10.x database upgrade', 'upgrade')
        upgrade_0_10_x()
        utils.set_db_ver('1.0.0')
    else:
        logger.info('DB version changed, no upgrade needed', 'upgrade')
예제 #2
0
파일: server.py 프로젝트: didiwuliu/pritunl
    def _keep_alive_thread(self, semaphore, process):
        semaphore.release()
        exit_attempts = 0
        while not self._interrupt:
            try:
                response = self.collection.update({
                    '_id': bson.ObjectId(self.id),
                    'instances.instance_id': self._instance_id,
                }, {'$set': {
                    'instances.$.ping_timestamp': utils.now(),
                }})

                if not response['updatedExisting']:
                    logger.info('Server instance removed, ' +
                            'stopping server. %r' % {
                        'server_id': self.id,
                        'instance_id': self._instance_id,
                    })
                    if exit_attempts > 2:
                        process.send_signal(signal.SIGKILL)
                    else:
                        process.send_signal(signal.SIGINT)
                    exit_attempts += 1
                    time.sleep(0.5)
                    continue
            except:
                logger.exception('Failed to update server ping. %r' % {
                    'server_id': self.id,
                })
            time.sleep(settings.vpn.server_ping)
예제 #3
0
    def add_network_link(self, network, force=False):
        from pritunl import server

        if not force:
            for svr in self.iter_servers(('status', 'groups')):
                if svr.status == ONLINE:
                    raise ServerOnlineError('Server online')

        network = str(ipaddress.IPNetwork(network))

        self.net_link_collection.update(
            {
                'user_id': self.id,
                'org_id': self.org_id,
                'network': network,
            }, {
                'user_id': self.id,
                'org_id': self.org_id,
                'network': network,
            },
            upsert=True)

        if force:
            for svr in self.iter_servers(server.operation_fields):
                if svr.status == ONLINE:
                    logger.info(
                        'Restarting running server to add network link',
                        'user',
                    )
                    svr.restart()
예제 #4
0
def upgrade_server():
    if utils.get_db_ver_int() < utils.get_int_ver('1.4.0.0'):
        logger.info('Running 1.4 database upgrade', 'upgrade')
        upgrade_1_4()
        utils.set_db_ver('1.4.0.0')
    else:
        logger.info('No upgrade needed', 'upgrade')
예제 #5
0
파일: misc.py 프로젝트: ijat/pritunl
def sync_public_ip(attempts=1, timeout=5, update=False):
    from pritunl import logger

    for i in xrange(attempts):
        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'utils')
        try:
            request = urllib2.Request(
                settings.app.public_ip_server)
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = str(json.load(response)['ip'])
            break
        except:
            pass

    try:
        request = urllib2.Request(
            settings.app.public_ip6_server)
        response = urllib2.urlopen(request, timeout=timeout)
        settings.local.public_ip6 = str(json.load(response)['ip'])
    except:
        pass

    if not settings.local.public_ip:
        logger.warning('Failed to get public ip address', 'utils')

    if update:
        settings.local.host.collection.update({
            '_id': settings.local.host.id,
        }, {'$set': {
            'auto_public_address': settings.local.public_ip,
            'auto_public_address6': settings.local.public_ip6,
        }})
예제 #6
0
def setup_server():
    db_ver_int = utils.get_db_ver_int()

    listener.add_listener('system', on_system_msg)

    if db_ver_int > settings.local.version_int:
        logger.error('Database version is newer than server version',
            'setup',
            db_version=db_ver_int,
            server_version=settings.local.version_int,
        )
        exit(75)

    global db_setup
    db_setup = not settings.conf.mongodb_uri

    global server_upgrade
    server_upgrade = db_ver_int < settings.local.version_int

    if db_setup or server_upgrade:
        logger.info('Starting setup server', 'setup')

        if not db_setup:
            upgrade_database()

        settings.local.server_start.clear()

        thread = threading.Thread(target=server_thread)
        thread.daemon = True
        thread.start()

        setup_ready.wait()

    utils.set_db_ver(__version__)
예제 #7
0
파일: misc.py 프로젝트: kknet/pritunl
def set_db_ver(version):
    from pritunl import logger

    upgraded_path = os.path.join(settings.conf.data_path, 'upgraded')

    logger.info('Setting db version', 'utils',
        cur_ver=get_db_ver(),
        new_ver=version,
    )

    prefix = settings.conf.mongodb_collection_prefix or ''
    client = pymongo.MongoClient(settings.conf.mongodb_uri,
        connectTimeoutMS=MONGO_CONNECT_TIMEOUT)
    database = client.get_default_database()
    settings_db = getattr(database, prefix + 'settings')
    doc = settings_db.update({
        '_id': 'version',
    }, {
        'version': version,
    }, upsert=True)

    with open(upgraded_path, 'w') as upgraded_file:
        pass

    return doc.get('version')
예제 #8
0
def set_db_ver(version, version_min=None):
    from pritunl import logger

    db_version = get_db_ver(False)
    db_min_version = get_min_db_ver(False)

    if version != db_version or MIN_DATABASE_VER != db_min_version:
        logger.info(
            'Setting db version',
            'utils',
            cur_ver=db_version,
            new_ver=version,
            cur_min_ver=db_min_version,
            new_min_ver=MIN_DATABASE_VER,
        )

    update_doc = {
        'version': version,
    }
    if version_min:
        update_doc['version_min'] = version_min

    prefix = settings.conf.mongodb_collection_prefix or ''
    client = pymongo.MongoClient(settings.conf.mongodb_uri,
                                 connectTimeoutMS=MONGO_CONNECT_TIMEOUT)
    database = client.get_default_database()
    settings_db = getattr(database, prefix + 'settings')
    doc = settings_db.update({
        '_id': 'version',
    }, update_doc, upsert=True)

    return doc.get('version')
예제 #9
0
def setup_server_cert():
    if not os.path.isfile(settings.conf.server_cert_path) or \
            not os.path.isfile(settings.conf.server_key_path):
        logger.info('Generating server ssl cert...')
        try:
            subprocess.check_call([
                'openssl',
                'req',
                '-batch',
                '-x509',
                '-nodes',
                '-sha256',
                '-newkey',
                'rsa:4096',
                '-days',
                '3652',
                '-keyout',
                settings.conf.server_key_path,
                '-out',
                settings.conf.server_cert_path,
            ],
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            logger.exception('Failed to generate server ssl cert.')
            raise
        os.chmod(settings.conf.server_key_path, 0600)
예제 #10
0
def sync_public_ip(attempts=1, timeout=5, update=False):
    from pritunl import logger

    for i in xrange(attempts):
        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'utils')
        try:
            request = urllib2.Request(settings.app.public_ip_server)
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = json.load(response)['ip']
            break
        except:
            pass

    try:
        request = urllib2.Request(settings.app.public_ip6_server)
        response = urllib2.urlopen(request, timeout=timeout)
        settings.local.public_ip6 = json.load(response)['ip']
    except:
        pass

    if not settings.local.public_ip:
        logger.warning('Failed to get public ip address', 'utils')

    if update:
        settings.local.host.collection.update({
            '_id': settings.local.host.id,
        }, {
            '$set': {
                'auto_public_address': settings.local.public_ip,
                'auto_public_address6': settings.local.public_ip6,
            }
        })
예제 #11
0
파일: server.py 프로젝트: afdnlw/pritunl
    def _keep_alive_thread(self, semaphore, process):
        semaphore.release()
        exit_attempts = 0
        while not self._interrupt:
            self.load()
            if self._instance_id != self.instance_id:
                logger.info('Server instance removed, stopping server. %r' % {
                    'server_id': self.id,
                    'instance_id': self._instance_id,
                })
                if exit_attempts > 2:
                    process.send_signal(signal.SIGKILL)
                else:
                    process.send_signal(signal.SIGINT)
                exit_attempts += 1
                time.sleep(0.5)
                continue

            self.ping_timestamp = datetime.datetime.utcnow()
            try:
                self.commit('ping_timestamp')
            except:
                logger.exception('Failed to update server ping. %r' % {
                    'server_id': self.id,
                })
            time.sleep(settings.vpn.server_ping)
예제 #12
0
    def commit(self, *args, **kwargs):
        if 'password' in self.changed:
            logger.info(
                'Changing administrator password',
                'auth',
                username=self.username,
            )

            if not self.password:
                raise ValueError('Password is empty')

            salt = base64.b64encode(os.urandom(8))
            pass_hash = base64.b64encode(hash_password_v2(salt, self.password))
            pass_hash = '2$%s$%s' % (salt, pass_hash)
            self.password = pass_hash

            if self.default and self.exists:
                self.default = None

        if not self.token:
            self.generate_token()
        if not self.secret:
            self.generate_secret()

        mongo.MongoObject.commit(self, *args, **kwargs)
예제 #13
0
파일: host.py 프로젝트: pritunl/pritunl
    def get_link_user(self, org_ids):
        from pritunl import organization

        for org_id in org_ids:
            org = organization.get_by_id(org_id)
            if not org:
                continue

            usr = org.find_user(resource_id=self.id)
            if not usr:
                logger.info('Creating host link user', 'host',
                    host_id=self.id,
                )

                usr = org.new_user(name=HOST_USER_PREFIX + str(self.id),
                    type=CERT_SERVER, resource_id=self.id)

                journal.entry(
                    journal.USER_CREATE,
                    usr.journal_data,
                    event_long='User created for host linking',
                )

                usr.audit_event('user_created',
                    'User created for host linking')

            return usr

        raise ValueError('No orgs exists in link server')
예제 #14
0
파일: user.py 프로젝트: WPMedia/pritunl
    def add_network_link(self, network, force=False):
        from pritunl import server

        if not force:
            for svr in self.org.iter_servers(('status',)):
                if svr.status == ONLINE:
                    raise ServerOnlineError('Server online')

        network = str(ipaddress.IPNetwork(network))

        self.net_link_collection.update({
            'user_id': self.id,
            'org_id': self.org_id,
            'network': network,
        }, {
            'user_id': self.id,
            'org_id': self.org_id,
            'network': network,
        }, upsert=True)

        if force:
            for svr in self.org.iter_servers(server.operation_fields):
                if svr.status == ONLINE:
                    logger.info(
                        'Restarting running server to add network link',
                        'user',
                    )
                    svr.restart()
예제 #15
0
파일: transaction.py 프로젝트: ijat/pritunl
def _check_thread():
    collection = mongo.get_collection('transaction')

    while True:
        try:
            spec = {
                'ttl_timestamp': {'$lt': utils.now()},
            }

            for doc in collection.find(spec).sort('priority'):
                logger.info('Transaction timeout retrying...', 'runners',
                    doc=doc,
                )

                try:
                    tran = transaction.Transaction(doc=doc)
                    tran.run()
                except:
                    logger.exception('Failed to run transaction', 'runners',
                        transaction_id=doc['_id'],
                    )

            yield interrupter_sleep(settings.mongo.tran_ttl)
        except GeneratorExit:
            raise
        except:
            logger.exception('Error in transaction runner thread', 'runners')
            time.sleep(0.5)
예제 #16
0
파일: utils.py 프로젝트: Cesar456/pritunl
def setup_cert():
    server_cert = None
    server_key = None
    server_dh_params = None
    acme_domain = None

    if _database:
        settings_collection = get_collection('settings')
        doc = settings_collection.find_one({'_id': 'app'})
        if doc:
            server_cert = doc.get('server_cert')
            server_key = doc.get('server_key')
            server_dh_params = doc.get('server_dh_params')
            acme_domain = doc.get('acme_domain')

    if not server_cert or not server_key:
        logger.info('Generating setup server ssl cert', 'setup')
        server_cert_path, server_key_path = utils.generate_server_cert()
        server_dh_path = utils.generate_server_dh_params(1024)
        return server_cert_path, None, server_key_path, server_dh_path

    if not server_dh_params:
        server_dh_params = utils.generate_server_dh_params_inline(1024)

    return utils.write_server_cert_chain(
        server_cert,
        server_key,
        server_dh_params,
        acme_domain,
    )
예제 #17
0
    def task(self):
        acme_domain = settings.app.acme_domain

        if not acme_domain:
            return

        if not settings.app.acme_timestamp:
            logger.exception(
                'Failed to update acme certificate. Timestamp not set',
                'tasks',
                acme_domain=acme_domain,
            )
            return

        if not settings.app.acme_key:
            logger.exception(
                'Failed to update acme certificate. Account key not set',
                'tasks',
                acme_domain=acme_domain,
            )
            return

        if utils.time_now() - settings.app.acme_timestamp < \
                settings.app.acme_renew:
            return

        logger.info(
            'Updating acme certificate', 'tasks',
            acme_domain=acme_domain,
        )

        acme.update_acme_cert()
        app.update_server()
예제 #18
0
파일: misc.py 프로젝트: Flux159/pritunl
def set_db_ver(version, version_min=None):
    from pritunl import logger

    db_version = get_db_ver(False)
    db_min_version = get_min_db_ver(False)

    if version != db_version or MIN_DATABASE_VER != db_min_version:
        logger.info('Setting db version', 'utils',
            cur_ver=db_version,
            new_ver=version,
            cur_min_ver=db_min_version,
            new_min_ver=MIN_DATABASE_VER,
        )

    update_doc = {
        'version': version,
    }
    if version_min:
        update_doc['version_min'] = version_min

    prefix = settings.conf.mongodb_collection_prefix or ''
    client = pymongo.MongoClient(settings.conf.mongodb_uri,
        connectTimeoutMS=MONGO_CONNECT_TIMEOUT)
    database = client.get_default_database()
    settings_db = getattr(database, prefix + 'settings')
    doc = settings_db.update({
        '_id': 'version',
    }, update_doc, upsert=True)

    return doc.get('version')
예제 #19
0
    def _keep_alive_thread(self, semaphore, process):
        semaphore.release()
        exit_attempts = 0
        while not self._interrupt:
            self.load()
            if self._instance_id != self.instance_id:
                logger.info('Server instance removed, stopping server. %r' % {
                    'server_id': self.id,
                    'instance_id': self._instance_id,
                })
                if exit_attempts > 2:
                    process.send_signal(signal.SIGKILL)
                else:
                    process.send_signal(signal.SIGINT)
                exit_attempts += 1
                time.sleep(0.5)
                continue

            self.ping_timestamp = datetime.datetime.utcnow()
            try:
                self.commit('ping_timestamp')
            except:
                logger.exception('Failed to update server ping. %r' % {
                    'server_id': self.id,
                })
            time.sleep(settings.vpn.server_ping)
예제 #20
0
파일: app.py 프로젝트: uguryildiz/pritunl
def _run_wsgi():
    logger.info('Starting server', 'app')

    server = cherrypy.wsgiserver.CherryPyWSGIServer(
        (settings.conf.bind_addr, settings.conf.port),
        app,
        request_queue_size=settings.app.request_queue_size,
        server_name=cherrypy.wsgiserver.CherryPyWSGIServer.version)

    if settings.conf.ssl:
        server.ConnectionClass = patches.HTTPConnectionPatch
        server.ssl_adapter = SSLAdapter(settings.conf.server_cert_path,
                                        settings.conf.server_key_path)

    settings.local.server_ready.set()
    settings.local.server_start.wait()

    try:
        server.start()
    except (KeyboardInterrupt, SystemExit):
        pass
    except:
        logger.exception('Server error occurred', 'app')
        raise
    finally:
        _on_exit()
예제 #21
0
파일: misc.py 프로젝트: pritunl/pritunl
def sync_public_ip(attempts=1, timeout=5):
    from pritunl import logger

    for i in xrange(attempts):
        url = settings.app.public_ip_server
        if settings.app.dedicated:
            url = settings.app.dedicated + '/ip'

        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'utils')
        try:
            request = urllib2.Request(url)
            request.add_header('User-Agent', 'pritunl')
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = str(json.load(response)['ip'])
            break
        except:
            pass

    if not settings.app.dedicated:
        try:
            request = urllib2.Request(
                settings.app.public_ip6_server)
            request.add_header('User-Agent', 'pritunl')
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip6 = str(json.load(response)['ip'])
        except:
            pass

        if not settings.local.public_ip:
            logger.warning('Failed to get public ip address', 'utils')
예제 #22
0
파일: app.py 프로젝트: uguryildiz/pritunl
def _run_wsgi():
    logger.info('Starting server', 'app')

    server = cherrypy.wsgiserver.CherryPyWSGIServer(
        (settings.conf.bind_addr, settings.conf.port), app,
        request_queue_size=settings.app.request_queue_size,
        server_name=cherrypy.wsgiserver.CherryPyWSGIServer.version)

    if settings.conf.ssl:
        server.ConnectionClass = patches.HTTPConnectionPatch
        server.ssl_adapter = SSLAdapter(
            settings.conf.server_cert_path, settings.conf.server_key_path)

    settings.local.server_ready.set()
    settings.local.server_start.wait()

    try:
        server.start()
    except (KeyboardInterrupt, SystemExit):
        pass
    except:
        logger.exception('Server error occurred', 'app')
        raise
    finally:
        _on_exit()
예제 #23
0
    def audit_event(self, event_type, event_msg, remote_addr=None):
        if settings.app.auditing != ALL:
            return

        timestamp = utils.now()

        self.audit_collection.insert({
            'user_id': self.id,
            'timestamp': timestamp,
            'type': event_type,
            'remote_addr': remote_addr,
            'message': event_msg,
        })

        plugins.event(
            'audit_event',
            host_id=settings.local.host_id,
            host_name=settings.local.host.name,
            user_id=self.id,
            org_id=None,
            timestamp=timestamp,
            type=event_type,
            remote_addr=remote_addr,
            message=event_msg,
        )

        logger.info(
            'Administrator audit event',
            'audit',
            user_id=self.id,
            timestamp=timestamp,
            type=event_type,
            remote_addr=remote_addr,
            message=event_msg,
        )
예제 #24
0
def server_thread():
    app.logger.setLevel(logging.DEBUG)
    app.logger.addFilter(logger.log_filter)
    app.logger.addHandler(logger.log_handler)

    global server
    server = wsgiserver.CherryPyWSGIServer(
        (settings.conf.bind_addr, settings.conf.port),
        app,
        server_name=wsgiserver.CherryPyWSGIServer.version,
        timeout=1,
        shutdown_timeout=0.5,
    )

    server_cert_path = os.path.join(settings.conf.temp_path, SERVER_CERT_NAME)
    server_key_path = os.path.join(settings.conf.temp_path, SERVER_KEY_NAME)

    if settings.conf.ssl:
        logger.info('Generating setup server ssl cert', 'setup')
        utils.generate_server_cert(server_cert_path, server_key_path)
        server.ssl_adapter = SSLAdapter(server_cert_path, server_key_path)

    try:
        server.start()
    except StopServer:
        pass

    setup_ready.set()
    settings.local.server_start.set()
예제 #25
0
파일: misc.py 프로젝트: i-sam/pritunl
def set_db_ver(version):
    from pritunl import logger

    db_version = get_db_ver()

    if version != db_version:
        logger.info(
            'Setting db version',
            'utils',
            cur_ver=db_version,
            new_ver=version,
        )

    prefix = settings.conf.mongodb_collection_prefix or ''
    client = pymongo.MongoClient(settings.conf.mongodb_uri,
                                 connectTimeoutMS=MONGO_CONNECT_TIMEOUT)
    database = client.get_default_database()
    settings_db = getattr(database, prefix + 'settings')
    doc = settings_db.update({
        '_id': 'version',
    }, {
        'version': version,
    },
                             upsert=True)

    return doc.get('version')
예제 #26
0
    def task(self):
        acme_domain = settings.app.acme_domain

        if not acme_domain:
            return

        if not settings.app.acme_timestamp:
            logger.exception(
                'Failed to update acme certificate. Timestamp not set',
                'tasks',
                acme_domain=acme_domain,
            )
            return

        if not settings.app.acme_key:
            logger.exception(
                'Failed to update acme certificate. Account key not set',
                'tasks',
                acme_domain=acme_domain,
            )
            return

        if utils.time_now() - settings.app.acme_timestamp < \
                settings.app.acme_renew:
            return

        logger.info(
            'Updating acme certificate',
            'tasks',
            acme_domain=acme_domain,
        )

        acme.update_acme_cert()
        app.update_server()
예제 #27
0
파일: host.py 프로젝트: zyd915/pritunl
    def get_link_user(self, org_ids):
        from pritunl import organization

        for org_id in org_ids:
            org = organization.get_by_id(org_id)
            if not org:
                continue

            usr = org.find_user(resource_id=self.id)
            if not usr:
                logger.info(
                    'Creating host link user',
                    'host',
                    host_id=self.id,
                )

                usr = org.new_user(name=HOST_USER_PREFIX + str(self.id),
                                   type=CERT_SERVER,
                                   resource_id=self.id)
                usr.audit_event('user_created',
                                'User created for host linking')

            return usr

        raise ValueError('No orgs exists in link server')
예제 #28
0
def load_public_ip(attempts=1, timeout=5):
    for i in xrange(attempts):
        if settings.local.public_ip:
            return
        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'setup')
        logger.debug('Getting public ip address', 'setup')
        try:
            request = urllib2.Request(settings.app.public_ip_server)
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = json.load(response)['ip']
            break
        except:
            pass

    logger.debug('Getting public ipv6 address', 'setup')
    try:
        request = urllib2.Request(settings.app.public_ip6_server)
        response = urllib2.urlopen(request, timeout=timeout)
        settings.local.public_ip6 = json.load(response)['ip']
    except:
        pass

    if not settings.local.public_ip:
        logger.warning('Failed to get public ip address', 'setup')
예제 #29
0
파일: utils.py 프로젝트: windskyer/pritunl
def setup_cert():
    server_cert = None
    server_key = None
    server_dh_params = None
    acme_domain = None

    if _database:
        settings_collection = get_collection('settings')
        doc = settings_collection.find_one({'_id': 'app'})
        if doc:
            server_cert = doc.get('server_cert')
            server_key = doc.get('server_key')
            server_dh_params = doc.get('server_dh_params')
            acme_domain = doc.get('acme_domain')

    if not server_cert or not server_key:
        logger.info('Generating setup server ssl cert', 'setup')
        server_cert_path, server_key_path = utils.generate_server_cert()
        server_dh_path = utils.generate_server_dh_params(1024)
        return server_cert_path, None, server_key_path, server_dh_path

    if not server_dh_params:
        server_dh_params = utils.generate_server_dh_params_inline(1024)

    return utils.write_server_cert_chain(
        server_cert,
        server_key,
        server_dh_params,
        acme_domain,
    )
예제 #30
0
def set_db_ver(version):
    from pritunl import logger

    upgraded_path = os.path.join(settings.conf.data_path, 'upgraded')

    logger.info('Setting db version', 'utils',
        cur_ver=get_db_ver(),
        new_ver=version,
    )

    prefix = settings.conf.mongodb_collection_prefix or ''
    client = pymongo.MongoClient(settings.conf.mongodb_uri,
        connectTimeoutMS=MONGO_CONNECT_TIMEOUT)
    database = client.get_default_database()
    settings_db = getattr(database, prefix + 'settings')
    doc = settings_db.update({
        '_id': 'version',
    }, {
        'version': version,
    }, upsert=True)

    with open(upgraded_path, 'w') as upgraded_file:
        pass

    return doc.get('version')
예제 #31
0
파일: server.py 프로젝트: dhh123/pritunl
def server_thread():
    app.logger.setLevel(logging.DEBUG)
    app.logger.addFilter(logger.log_filter)
    app.logger.addHandler(logger.log_handler)

    global server
    server = wsgiserver.CherryPyWSGIServer(
        (settings.conf.bind_addr, settings.conf.port), app,
        server_name=wsgiserver.CherryPyWSGIServer.version,
        timeout=1,
        shutdown_timeout=0.5,
    )

    server_cert_path = os.path.join(settings.conf.temp_path, SERVER_CERT_NAME)
    server_key_path = os.path.join(settings.conf.temp_path, SERVER_KEY_NAME)

    if settings.conf.ssl:
        logger.info('Generating setup server ssl cert', 'setup')
        utils.generate_server_cert(server_cert_path, server_key_path)
        server.ssl_adapter = SSLAdapter(server_cert_path, server_key_path)

    try:
        server.start()
    except StopServer:
        pass

    setup_ready.set()
    settings.local.server_start.set()
예제 #32
0
def sync_public_ip(attempts=1, timeout=5):
    from pritunl import logger

    for i in xrange(attempts):
        url = settings.app.public_ip_server
        if settings.app.dedicated:
            url = settings.app.dedicated + '/ip'

        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'utils')
        try:
            request = urllib2.Request(url)
            request.add_header('User-Agent', 'pritunl')
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = str(json.load(response)['ip'])
            break
        except:
            pass

    if not settings.app.dedicated:
        try:
            request = urllib2.Request(settings.app.public_ip6_server)
            request.add_header('User-Agent', 'pritunl')
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip6 = str(json.load(response)['ip'])
        except:
            pass

        if not settings.local.public_ip:
            logger.warning('Failed to get public ip address', 'utils')
예제 #33
0
def _check_thread():
    collection = mongo.get_collection('transaction')

    while True:
        try:
            spec = {
                'ttl_timestamp': {
                    '$lt': utils.now()
                },
            }

            for doc in collection.find(spec).sort('priority'):
                logger.info(
                    'Transaction timeout retrying...',
                    'runners',
                    doc=doc,
                )

                try:
                    tran = transaction.Transaction(doc=doc)
                    tran.run()
                except:
                    logger.exception(
                        'Failed to run transaction',
                        'runners',
                        transaction_id=doc['_id'],
                    )

            yield interrupter_sleep(settings.mongo.tran_ttl)
        except GeneratorExit:
            raise
        except:
            logger.exception('Error in transaction runner thread', 'runners')
            time.sleep(0.5)
예제 #34
0
def load_public_ip(attempts=1, timeout=5):
    for i in xrange(attempts):
        if settings.local.public_ip:
            return
        if i:
            time.sleep(3)
            logger.info('Retrying get public ip address', 'setup')
        logger.debug('Getting public ip address', 'setup')
        try:
            request = urllib2.Request(
                settings.app.public_ip_server)
            response = urllib2.urlopen(request, timeout=timeout)
            settings.local.public_ip = json.load(response)['ip']
            break
        except:
            pass

    logger.debug('Getting public ipv6 address', 'setup')
    try:
        request = urllib2.Request(
            settings.app.public_ip6_server)
        response = urllib2.urlopen(request, timeout=timeout)
        settings.local.public_ip6 = json.load(response)['ip']
    except:
        pass

    if not settings.local.public_ip:
        logger.warning('Failed to get public ip address', 'setup')
예제 #35
0
파일: duo.py 프로젝트: ijat/pritunl
    def _auth(self, factor):
        params = {
            'username': self.username,
            'factor': factor,
        }

        if self.remote_ip:
            params['ipaddr'] = self.remote_ip

        if factor in ('push', 'phone'):
            params['device'] = 'auto'

        if factor == 'push':
            if self.auth_type:
                params['type'] = self.auth_type

            if self.info:
                params['pushinfo'] = urllib.urlencode(self.info)

        if factor == 'passcode':
            params['passcode'] = self.passcode

        headers = _sign('POST', '/auth/v2/auth', params)
        url = 'https://%s/auth/v2/auth' % settings.app.sso_duo_host

        try:
            response = requests.post(url,
                headers=headers,
                params=params,
                timeout=settings.app.sso_timeout,
            )
        except httplib.HTTPException:
            return

        data = response.json()
        resp_data = data.get('response')
        if resp_data and resp_data.get('result') == 'allow':
            if resp_data.get('status') == 'bypass':
                if settings.app.sso == DUO_AUTH:
                    logger.error('Cannot use Duo bypass with Duo sso',
                        'sso',
                        data=resp_data,
                    )
                    return
                else:
                    logger.info('Skipping Duo auth with bypass',
                        'sso',
                        username=self.username,
                    )
            self._valid = True
        elif data.get('code') == 40002:
            if factor == 'push' and self.factor == 'push_phone':
                self._auth('phone')
            else:
                raise InvalidUser('Invalid username')
        else:
            logger.error('Duo authentication failure', 'sso',
                data=data,
            )
예제 #36
0
def get_default_password():
    logger.info('Getting default administrator password', 'auth')

    default_admin = find_user(username=DEFAULT_USERNAME)
    if not default_admin:
        return None, None

    return default_admin.username, default_admin.default_password
예제 #37
0
def upgrade_server():
    # if utils.get_db_ver_int() < 1000306624015:
    #     logger.info('Running 0.10.x database upgrade', 'upgrade')
    #     upgrade_0_10_x()
    #     utils.set_db_ver('1.0.0')
    # else:
    #     logger.info('DB version changed, no upgrade needed', 'upgrade')
    logger.info('No upgrade needed', 'upgrade')
예제 #38
0
def upgrade_server():
    # if utils.get_db_ver_int() < 1000306624015:
    #     logger.info('Running 0.10.x database upgrade', 'upgrade')
    #     upgrade_0_10_x()
    #     utils.set_db_ver('1.0.0')
    # else:
    #     logger.info('DB version changed, no upgrade needed', 'upgrade')
    logger.info('No upgrade needed', 'upgrade')
예제 #39
0
def handle_exit(signum, frame):
    global _exited
    if _exited:
        return
    _exited = True
    logger.info('Stopping server', 'setup')
    set_global_interrupt()
    signal.alarm(2)
예제 #40
0
def handle_exit(signum, frame):
    global _exited
    if _exited:
        return
    _exited = True
    logger.info('Stopping server', 'setup')
    set_global_interrupt()
    signal.alarm(2)
예제 #41
0
def _run_wsgi():
    restart = False
    while True:
        try:
            _run_server(restart)
        except ServerRestart:
            restart = True
            logger.info('Server restarting...', 'app')
예제 #42
0
파일: app.py 프로젝트: ampg99/pritunl
def _run_wsgi():
    restart = False
    while True:
        try:
            _run_server(restart)
        except ServerRestart:
            restart = True
            logger.info('Server restarting...', 'app')
예제 #43
0
def set_global_interrupt():
    global _interrupt
    if _interrupt:
        return
    _interrupt = True

    from pritunl import logger
    logger.info('Stopping server', 'setup')
    signal.alarm(10)
예제 #44
0
def setup_server():
    global setup_state

    last_error = time.time() - 24
    while True:
        try:
            db_ver_int = utils.get_db_ver_int()
            break
        except:
            time.sleep(0.5)
            if time.time() - last_error > 30:
                last_error = time.time()
                logger.exception('Error connecting to mongodb server')

    listener.add_listener('system', on_system_msg)

    if db_ver_int > settings.local.version_int:
        logger.error(
            'Database version is newer than server version',
            'setup',
            db_version=db_ver_int,
            server_version=settings.local.version_int,
        )
        exit(75)

    if not settings.conf.mongodb_uri:
        setup_state = 'setup'
    elif check_db_ver(db_ver_int):
        setup_state = 'upgrade'

    if setup_state:
        logger.info('Starting setup server', 'setup')

        if setup_state == 'upgrade':
            upgrade_database()

        settings.local.server_start.clear()

        thread = threading.Thread(target=server_thread)
        thread.daemon = True
        thread.start()

        setup_ready.wait()
        time.sleep(0.5)

    upgrade.database_clean_up()

    last_error = time.time() - 24
    while True:
        try:
            utils.set_db_ver(__version__)
            break
        except:
            time.sleep(0.5)
            if time.time() - last_error > 30:
                last_error = time.time()
                logger.exception('Error connecting to mongodb server')
예제 #45
0
def set_global_interrupt():
    global _interrupt
    if _interrupt:
        return
    _interrupt = True

    from pritunl import logger
    logger.info('Stopping server', 'setup')
    signal.alarm(2)
예제 #46
0
def create_server_dh_params():
    from pritunl import logger

    logger.info('Generating server dh params...', 'utils')

    server_dh_path = generate_server_dh_params(settings.app.server_dh_size)

    with open(server_dh_path, 'r') as server_dh_file:
        settings.app.server_dh_params = server_dh_file.read().strip()
예제 #47
0
파일: server.py 프로젝트: xyz12810/pritunl
def setup_server():
    global setup_state

    last_error = time.time() - 24
    while True:
        try:
            db_ver_int = utils.get_db_ver_int()
            break
        except:
            time.sleep(0.5)
            if time.time() - last_error > 30:
                last_error = time.time()
                logger.exception('Error connecting to mongodb server')

    listener.add_listener('system', on_system_msg)

    if db_ver_int > settings.local.version_int:
        logger.error('Database version is newer than server version',
            'setup',
            db_version=db_ver_int,
            server_version=settings.local.version_int,
        )
        exit(75)

    if not settings.conf.mongodb_uri:
        setup_state = 'setup'
    elif check_db_ver(db_ver_int):
        setup_state = 'upgrade'

    if setup_state:
        logger.info('Starting setup server', 'setup')

        if setup_state == 'upgrade':
            upgrade_database()

        settings.local.server_start.clear()

        thread = threading.Thread(target=server_thread)
        thread.daemon = True
        thread.start()

        setup_ready.wait()
        time.sleep(1)

    upgrade.database_clean_up()

    last_error = time.time() - 24
    while True:
        try:
            utils.set_db_ver(__version__)
            break
        except:
            time.sleep(0.5)
            if time.time() - last_error > 30:
                last_error = time.time()
                logger.exception('Error connecting to mongodb server')
예제 #48
0
def reset_password():
    logger.info('Resetting administrator password', 'auth')
    collection = mongo.get_collection('administrators')
    collection.remove({})
    Administrator(
        username=DEFAULT_USERNAME,
        password=DEFAULT_PASSWORD,
        default=True,
    ).commit()
    return (DEFAULT_USERNAME, DEFAULT_PASSWORD)
예제 #49
0
def setup_server_cert():
    commit = False

    if not settings.app.server_cert or not settings.app.server_key:
        commit = True
        logger.info('Generating server certificate...', 'app')
        utils.create_server_cert()

    if commit:
        settings.commit()
예제 #50
0
def reset_password():
    logger.info('Resetting administrator password', 'auth')
    collection = mongo.get_collection('administrators')
    collection.remove({})
    Administrator(
        username=DEFAULT_USERNAME,
        password=DEFAULT_PASSWORD,
        default=True,
    ).commit()
    return DEFAULT_USERNAME, DEFAULT_PASSWORD
예제 #51
0
파일: cert.py 프로젝트: Cesar456/pritunl
def create_server_dh_params():
    from pritunl import logger

    logger.info('Generating server dh params...', 'utils')

    server_dh_path = generate_server_dh_params(
        settings.app.server_dh_size)

    with open(server_dh_path, 'r') as server_dh_file:
        settings.app.server_dh_params = server_dh_file.read().strip()
예제 #52
0
파일: app.py 프로젝트: sha1/pritunl
def update_server(delay=0):
    global _cur_ssl
    global _cur_cert
    global _cur_key
    global _cur_port
    global _cur_redirect_server
    global _cur_reverse_proxy

    if not settings.local.server_ready.is_set():
        return

    _update_lock.acquire()
    if settings.local.web_state == DISABLED:
        logger.warning(
            'Web server disabled',
            'server',
            message=settings.local.notification,
        )
        stop_server()
        return

    try:
        if _cur_ssl != settings.app.server_ssl or \
                _cur_cert != settings.app.server_cert or \
                _cur_key != settings.app.server_key or \
                _cur_port != settings.app.server_port or \
                _cur_redirect_server != settings.app.redirect_server or \
                _cur_reverse_proxy != (settings.app.reverse_proxy_header if
                    settings.app.reverse_proxy else ''):
            logger.info(
                'Settings changed, restarting server...',
                'app',
                ssl_changed=_cur_ssl != settings.app.server_ssl,
                cert_changed=_cur_cert != settings.app.server_cert,
                key_changed=_cur_key != settings.app.server_key,
                port_changed=_cur_port != settings.app.server_port,
                redirect_server_changed=_cur_redirect_server !=
                settings.app.redirect_server,
                reverse_proxy_changed=_cur_reverse_proxy !=
                (settings.app.reverse_proxy_header
                 if settings.app.reverse_proxy else ''),
            )

            _cur_ssl = settings.app.server_ssl
            _cur_cert = settings.app.server_cert
            _cur_key = settings.app.server_key
            _cur_port = settings.app.server_port
            _cur_redirect_server = settings.app.redirect_server
            _cur_reverse_proxy = settings.app.reverse_proxy_header if \
                settings.app.reverse_proxy else ''

            if settings.app.server_auto_restart:
                restart_server(delay=delay)
    finally:
        _update_lock.release()
예제 #53
0
파일: app.py 프로젝트: pritunl/pritunl
def setup_server_cert():
    global _cur_cert
    global _cur_key

    if not settings.app.server_cert or not settings.app.server_key:
        logger.info('Generating server certificate...', 'app')
        utils.create_server_cert()
        settings.commit()

        _cur_cert = settings.app.server_cert
        _cur_key = settings.app.server_key
예제 #54
0
파일: cert.py 프로젝트: WPMedia/pritunl
def create_server_cert():
    from pritunl import logger

    logger.info('Generating server certificate...', 'utils')

    server_cert_path = os.path.join(settings.conf.temp_path, SERVER_CERT_NAME)
    server_key_path = os.path.join(settings.conf.temp_path, SERVER_KEY_NAME)

    generate_server_cert(server_cert_path, server_key_path)

    with open(server_cert_path, 'r') as server_cert_file:
        settings.app.server_cert = server_cert_file.read().strip()
    with open(server_key_path, 'r') as server_key_file:
        settings.app.server_key = server_key_file.read().strip()
예제 #55
0
def reset_password():
    logger.info('Resetting administrator password', 'auth')

    admin_collection = mongo.get_collection('administrators')
    admin_collection.delete_one({
        'super_user': {'$ne': False},
    })
    Administrator(
        username=DEFAULT_USERNAME,
        password=DEFAULT_PASSWORD,
        default=True,
    ).commit()

    return DEFAULT_USERNAME, DEFAULT_PASSWORD
예제 #56
0
파일: user.py 프로젝트: pritunl/pritunl
    def audit_event(self, event_type, event_msg, remote_addr=None, **kwargs):
        if settings.app.auditing != ALL:
            return

        timestamp = utils.now()

        org_name = None
        if self.org:
            org_name = self.org.name

        self.audit_collection.insert({
            'user_id': self.id,
            'user_name': self.name,
            'org_id': self.org_id,
            'org_name': org_name,
            'timestamp': timestamp,
            'type': event_type,
            'remote_addr': remote_addr,
            'message': event_msg,
        })

        plugins.event(
            'audit_event',
            host_id=settings.local.host_id,
            host_name=settings.local.host.name,
            user_id=self.id,
            user_name=self.name,
            org_id=self.org_id,
            org_name=org_name,
            timestamp=timestamp,
            type=event_type,
            remote_addr=remote_addr,
            message=event_msg,
            **kwargs
        )

        logger.info(
            'Audit event',
            'audit',
            user_id=self.id,
            user_name=self.name,
            org_id=self.org_id,
            org_name=org_name,
            timestamp=timestamp,
            type=event_type,
            remote_addr=remote_addr,
            message=event_msg,
            **kwargs
        )
예제 #57
0
파일: host.py 프로젝트: explody/pritunl
    def get_link_user(self, org_id):
        from pritunl import organization

        org = organization.get_by_id(org_id)
        usr = org.find_user(resource_id=self.id)

        if not usr:
            logger.info('Creating host link user', 'host',
                host_id=self.id,
            )

            usr = org.new_user(name=HOST_USER_PREFIX + str(self.id),
                type=CERT_SERVER, resource_id=self.id)

        return usr