Example #1
0
    def build_key_tar_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, "%s.tar" % self.id)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(key_archive_path, "w")
            try:
                for svr in self.org.iter_servers():
                    server_conf_path = os.path.join(temp_path, "%s_%s.ovpn" % (self.id, svr.id))
                    conf_name, client_conf, conf_hash = self._generate_conf(svr)

                    with open(server_conf_path, "w") as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    tar_file.add(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                tar_file.close()

            with open(key_archive_path, "r") as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #2
0
    def build_key_zip_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.zip' % self.id)

        try:
            os.makedirs(temp_path)
            zip_file = zipfile.ZipFile(key_archive_path, 'w')
            try:
                for svr in self.org.iter_servers():
                    server_conf_path = os.path.join(temp_path,
                        '%s_%s.ovpn' % (self.id, svr.id))
                    conf_name, client_conf, conf_hash = self._generate_conf(
                        svr)

                    with open(server_conf_path, 'w') as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    zip_file.write(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                zip_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #3
0
    def build_onc_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.zip' % self.id)

        try:
            os.makedirs(temp_path)
            zip_file = zipfile.ZipFile(key_archive_path, 'w')
            try:
                user_cert_path = os.path.join(temp_path, '%s.crt' % self.id)
                user_key_path = os.path.join(temp_path, '%s.key' % self.id)
                user_p12_path = os.path.join(temp_path, '%s.p12' % self.id)

                with open(user_cert_path, 'w') as user_cert:
                    user_cert.write(self.certificate)

                with open(user_key_path, 'w') as user_key:
                    os.chmod(user_key_path, 0600)
                    user_key.write(self.private_key)

                utils.check_output_logged([
                    'openssl',
                    'pkcs12',
                    '-export',
                    '-nodes',
                    '-password',
                    'pass:'******'-inkey',
                    user_key_path,
                    '-in',
                    user_cert_path,
                    '-out',
                    user_p12_path,
                ])

                zip_file.write(user_p12_path, arcname='%s.p12' % self.name)

                os.remove(user_cert_path)
                os.remove(user_key_path)
                os.remove(user_p12_path)

                for svr in self.iter_servers():
                    server_conf_path = os.path.join(
                        temp_path, '%s_%s.onc' % (self.id, svr.id))
                    conf_name, client_conf = self._generate_onc(svr)
                    if not client_conf:
                        continue

                    with open(server_conf_path, 'w') as ovpn_conf:
                        ovpn_conf.write(client_conf)
                    zip_file.write(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                zip_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #4
0
File: acme.py Project: ijat/pritunl
def get_acme_cert(account_key, csr):
    from pritunl import app
    from pritunl import acme_tiny

    temp_path = utils.get_temp_path()
    account_key_path = temp_path + '.key'
    csr_path = temp_path + '.csr'

    with open(account_key_path, 'w') as account_key_file:
        os.chmod(account_key_path, 0600)
        account_key_file.write(account_key)

    with open(csr_path, 'w') as csr_file:
        csr_file.write(csr)

    certificate = acme_tiny.get_crt(
        account_key_path,
        csr_path,
        app.set_acme,
    )

    cert_path = temp_path + '.crt'
    with open(cert_path, 'w') as cert_file:
        cert_file.write(certificate)

    try:
        os.remove(account_key_path)
    except:
        pass
    try:
        os.remove(csr_path)
    except:
        pass

    return certificate
Example #5
0
 def __init__(self, server):
     self.server = server
     self.instance_id = bson.ObjectId()
     self.resource_lock = None
     self.interrupt = False
     self.clean_exit = False
     self.clients = {}
     self.cur_clients = set()
     self.ignore_clients = set()
     self.client_count = 0
     self.interface = None
     self.primary_user = None
     self.process = None
     self.auth_log_process = None
     self.iptables_rules = []
     self.replica_links = {}
     self.server_links = []
     self._temp_path = utils.get_temp_path()
     self.tls_verify_path = os.path.join(self._temp_path,
         TLS_VERIFY_NAME)
     self.user_pass_verify_path = os.path.join(self._temp_path,
         USER_PASS_VERIFY_NAME)
     self.client_connect_path = os.path.join(self._temp_path,
         CLIENT_CONNECT_NAME)
     self.client_disconnect_path = os.path.join(self._temp_path,
         CLIENT_DISCONNECT_NAME)
     self.ovpn_status_path = os.path.join(self._temp_path,
         OVPN_STATUS_NAME)
     self.ovpn_conf_path = os.path.join(self._temp_path,
         OVPN_CONF_NAME)
     self.auth_log_path = os.path.join(self._temp_path,
         AUTH_LOG_NAME)
Example #6
0
    def build_key_tar_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.tar' % self.id)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(key_archive_path, 'w')
            try:
                for svr in self.iter_servers():
                    server_conf_path = os.path.join(
                        temp_path, '%s_%s.ovpn' % (self.id, svr.id))
                    conf_name, client_conf, conf_hash = self._generate_conf(
                        svr)

                    with open(server_conf_path, 'w') as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    tar_file.add(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                tar_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #7
0
def get_acme_cert(account_key, csr):
    from pritunl import acme_tiny

    temp_path = utils.get_temp_path()
    account_key_path = temp_path + '.key'
    csr_path = temp_path + '.csr'

    with open(account_key_path, 'w') as account_key_file:
        os.chmod(account_key_path, 0o600)
        account_key_file.write(account_key)

    with open(csr_path, 'w') as csr_file:
        csr_file.write(csr)

    certificate = acme_tiny.get_crt(
        account_key_path,
        csr_path,
        set_acme,
    )

    cert_path = temp_path + '.crt'
    with open(cert_path, 'w') as cert_file:
        cert_file.write(certificate)

    try:
        os.remove(account_key_path)
    except:
        pass
    try:
        os.remove(csr_path)
    except:
        pass

    return certificate
Example #8
0
    def build_key_zip_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.zip' % self.id)

        try:
            os.makedirs(temp_path)
            zip_file = zipfile.ZipFile(key_archive_path, 'w')
            try:
                for svr in self.iter_servers():
                    if not svr.check_groups(self.groups):
                        continue

                    server_conf_path = os.path.join(
                        temp_path, '%s_%s.ovpn' % (self.id, svr.id))
                    conf_name, client_conf, conf_hash = self._generate_conf(
                        svr)

                    with open(server_conf_path, 'w') as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    zip_file.write(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                zip_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #9
0
    def build_onc_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.zip' % self.id)

        try:
            os.makedirs(temp_path)
            zip_file = zipfile.ZipFile(key_archive_path, 'w')
            try:
                user_cert_path = os.path.join(temp_path, '%s.crt' % self.id)
                user_key_path = os.path.join(temp_path, '%s.key' % self.id)
                user_p12_path = os.path.join(temp_path, '%s.p12' % self.id)

                with open(user_cert_path, 'w') as user_cert:
                    user_cert.write(self.certificate)

                with open(user_key_path, 'w') as user_key:
                    os.chmod(user_key_path, 0600)
                    user_key.write(self.private_key)

                utils.check_output_logged([
                    'openssl',
                    'pkcs12',
                    '-export',
                    '-nodes',
                    '-password', 'pass:'******'-inkey', user_key_path,
                    '-in', user_cert_path,
                    '-out', user_p12_path
                ])

                zip_file.write(user_p12_path, arcname='%s.p12' % self.name)

                os.remove(user_cert_path)
                os.remove(user_key_path)
                os.remove(user_p12_path)

                for svr in self.org.iter_servers():
                    server_conf_path = os.path.join(temp_path,
                        '%s_%s.onc' % (self.id, svr.id))
                    conf_name, client_conf = self._generate_onc(svr)
                    if not client_conf:
                        continue

                    with open(server_conf_path, 'w') as ovpn_conf:
                        ovpn_conf.write(client_conf)
                    zip_file.write(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                zip_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #10
0
    def task(self):
        logger.debug('Generating server dh params', 'server',
            queue_id=self.id,
            dh_param_bits=self.dh_param_bits,
        )

        self.queue_com.wait_status()

        temp_path = utils.get_temp_path()
        dh_param_path = os.path.join(temp_path, DH_PARAM_NAME)

        try:
            os.makedirs(temp_path)
            args = [
                'openssl', 'dhparam',
                '-out', dh_param_path,
                str(self.dh_param_bits),
            ]
            self.queue_com.popen(args)
            self.read_file('dh_params', dh_param_path)
        finally:
            utils.rmtree(temp_path)

        self.queue_com.wait_status()

        if not self.server_id:
            self.load()
            if self.reserve_data:
                self.server_id = self.reserve_data['server_id']

        if self.server_id:
            response = self.server_collection.update({
                '_id': self.server_id,
                'dh_param_bits': self.dh_param_bits,
            }, {'$set': {
                'dh_params': self.dh_params,
            }})

            if response['updatedExisting']:
                logger.debug('Set queued server dh params', 'server',
                    queue_id=self.id,
                    dh_param_bits=self.dh_param_bits,
                )

                event.Event(type=SERVERS_UPDATED)
                return

        logger.debug('Adding pooled dh params', 'server',
            queue_id=self.id,
            dh_param_bits=self.dh_param_bits,
        )

        self.dh_params_collection.insert({
            'dh_param_bits': self.dh_param_bits,
            'dh_params': self.dh_params,
        })
Example #11
0
    def task(self):
        logger.debug('Generating server dh params', 'server',
            queue_id=self.id,
            dh_param_bits=self.dh_param_bits,
        )

        self.queue_com.wait_status()

        temp_path = utils.get_temp_path()
        dh_param_path = os.path.join(temp_path, DH_PARAM_NAME)

        try:
            os.makedirs(temp_path)
            args = [
                'openssl', 'dhparam',
                '-out', dh_param_path,
                str(self.dh_param_bits),
            ]
            self.queue_com.popen(args)
            self.read_file('dh_params', dh_param_path)
        finally:
            utils.rmtree(temp_path)

        self.queue_com.wait_status()

        if not self.server_id:
            self.load()
            if self.reserve_data:
                self.server_id = self.reserve_data['server_id']

        if self.server_id:
            response = self.server_collection.update({
                '_id': self.server_id,
                'dh_param_bits': self.dh_param_bits,
            }, {'$set': {
                'dh_params': self.dh_params,
            }})

            if response['updatedExisting']:
                logger.debug('Set queued server dh params', 'server',
                    queue_id=self.id,
                    dh_param_bits=self.dh_param_bits,
                )

                event.Event(type=SERVERS_UPDATED)
                return

        logger.debug('Adding pooled dh params', 'server',
            queue_id=self.id,
            dh_param_bits=self.dh_param_bits,
        )

        self.dh_params_collection.insert({
            'dh_param_bits': self.dh_param_bits,
            'dh_params': self.dh_params,
        })
Example #12
0
    def __init__(self, server, linked_server):
        self.server = server
        self.linked_server = linked_server

        self.process = None
        self.interface = None
        self.stop_event = threading.Event()
        self.user = settings.local.host.get_link_user(
            self.linked_server.organizations)
        self._temp_path = utils.get_temp_path()
Example #13
0
    def __init__(self, server, linked_server):
        self.server = server
        self.linked_server = linked_server

        self.process = None
        self.interface = None
        self.stop_event = threading.Event()
        self.user = settings.local.host.get_link_user(
            self.linked_server.organizations)
        self._temp_path = utils.get_temp_path()
Example #14
0
    def __init__(self,
                 name=None,
                 network=None,
                 interface=None,
                 port=None,
                 protocol=None,
                 dh_param_bits=None,
                 mode=None,
                 local_networks=None,
                 dns_servers=None,
                 search_domain=None,
                 public_address=None,
                 otp_auth=None,
                 lzo_compression=None,
                 debug=None,
                 **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)

        self._cur_event = None
        self._last_event = 0
        self._orig_network = self.network
        self._orgs_changed = False
        self._clients = None
        self._temp_path = utils.get_temp_path()
        self._instance_id = str(bson.ObjectId())
        self.ip_pool = ServerIpPool(self)

        if name is not None:
            self.name = name
        if network is not None:
            self.network = network
        if interface is not None:
            self.interface = interface
        if port is not None:
            self.port = port
        if protocol is not None:
            self.protocol = protocol
        if dh_param_bits is not None:
            self.dh_param_bits = dh_param_bits
        if mode is not None:
            self.mode = mode
        if local_networks is not None:
            self.local_networks = local_networks
        if dns_servers is not None:
            self.dns_servers = dns_servers
        if search_domain is not None:
            self.search_domain = search_domain
        if public_address is not None:
            self.public_address = public_address
        if otp_auth is not None:
            self.otp_auth = otp_auth
        if lzo_compression is not None:
            self.lzo_compression = lzo_compression
        if debug is not None:
            self.debug = debug
Example #15
0
    def generate_tls_auth_start(self):
        self.tls_auth_temp_path = utils.get_temp_path()
        self.tls_auth_path = os.path.join(self.tls_auth_temp_path, TLS_AUTH_NAME)

        os.makedirs(self.tls_auth_temp_path)
        args = ["openvpn", "--genkey", "--secret", self.tls_auth_path]
        try:
            self.tls_auth_process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except:
            utils.rmtree(self.tls_auth_temp_path)
            raise
Example #16
0
    def generate_tls_auth_start(self):
        self.tls_auth_temp_path = utils.get_temp_path()
        self.tls_auth_path = os.path.join(
            self.tls_auth_temp_path, TLS_AUTH_NAME)

        os.makedirs(self.tls_auth_temp_path)
        args = [
            'openvpn', '--genkey',
            '--secret', self.tls_auth_path,
        ]
        try:
            self.tls_auth_process = subprocess.Popen(args,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except:
            utils.rmtree(self.tls_auth_temp_path)
            raise
Example #17
0
    def build_key_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.tar' % self.id)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(key_archive_path, 'w')
            try:
                for server in self.org.iter_servers():
                    server_conf_path = os.path.join(
                        temp_path, '%s_%s.ovpn' % (self.id, server.id))
                    server_conf_arcname = '%s_%s_%s.ovpn' % (
                        self.org.name, self.name, server.name)
                    server.generate_ca_cert()

                    client_conf = OVPN_INLINE_CLIENT_CONF % (
                        self._get_key_info_str(self.name, self.org.name,
                                               server.name),
                        server.protocol,
                        server.public_address,
                        server.port,
                    )

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

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

                    with open(server_conf_path, 'w') as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    tar_file.add(server_conf_path, arcname=server_conf_arcname)
                    os.remove(server_conf_path)
            finally:
                tar_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #18
0
    def build_key_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, '%s.tar' % self.id)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(key_archive_path, 'w')
            try:
                for server in self.org.iter_servers():
                    server_conf_path = os.path.join(temp_path,
                        '%s_%s.ovpn' % (self.id, server.id))
                    server_conf_arcname = '%s_%s_%s.ovpn' % (
                        self.org.name, self.name, server.name)
                    server.generate_ca_cert()

                    client_conf = OVPN_INLINE_CLIENT_CONF % (
                        self._get_key_info_str(
                            self.name, self.org.name, server.name),
                        server.protocol,
                        server.public_address, server.port,
                    )

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

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

                    with open(server_conf_path, 'w') as ovpn_conf:
                        os.chmod(server_conf_path, 0600)
                        ovpn_conf.write(client_conf)
                    tar_file.add(server_conf_path, arcname=server_conf_arcname)
                    os.remove(server_conf_path)
            finally:
                tar_file.close()

            with open(key_archive_path, 'r') as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #19
0
 def __init__(self, server):
     self.server = server
     self.id = utils.ObjectId()
     self.resource_lock = None
     self.interrupt = False
     self.sock_interrupt = False
     self.clean_exit = False
     self.interface = None
     self.primary_user = None
     self.process = None
     self.auth_log_process = None
     self.iptables_rules = []
     self.server_links = []
     self._temp_path = utils.get_temp_path()
     self.ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
     self.management_socket_path = os.path.join(
         settings.conf.var_run_path, MANAGEMENT_SOCKET_NAME % self.id)
Example #20
0
 def __init__(self, server):
     self.server = server
     self.id = utils.ObjectId()
     self.resource_lock = None
     self.interrupt = False
     self.sock_interrupt = False
     self.clean_exit = False
     self.interface = None
     self.primary_user = None
     self.process = None
     self.auth_log_process = None
     self.iptables_rules = []
     self.server_links = []
     self._temp_path = utils.get_temp_path()
     self.ovpn_conf_path = os.path.join(self._temp_path,
         OVPN_CONF_NAME)
     self.management_socket_path = os.path.join(settings.conf.var_run_path,
         MANAGEMENT_SOCKET_NAME % self.id)
Example #21
0
    def __init__(self, name=None, network=None, interface=None, port=None,
            protocol=None, dh_param_bits=None, mode=None, local_networks=None,
            dns_servers=None, search_domain=None, public_address=None,
            otp_auth=None, lzo_compression=None, debug=None, **kwargs):
        mongo.MongoObject.__init__(self, **kwargs)

        self._cur_event = None
        self._last_event = 0
        self._orig_network = self.network
        self._orgs_changed = False
        self._clients = None
        self._temp_path = utils.get_temp_path()
        self._instance_id = str(bson.ObjectId())
        self.ip_pool = ServerIpPool(self)

        if name is not None:
            self.name = name
        if network is not None:
            self.network = network
        if interface is not None:
            self.interface = interface
        if port is not None:
            self.port = port
        if protocol is not None:
            self.protocol = protocol
        if dh_param_bits is not None:
            self.dh_param_bits = dh_param_bits
        if mode is not None:
            self.mode = mode
        if local_networks is not None:
            self.local_networks = local_networks
        if dns_servers is not None:
            self.dns_servers = dns_servers
        if search_domain is not None:
            self.search_domain = search_domain
        if public_address is not None:
            self.public_address = public_address
        if otp_auth is not None:
            self.otp_auth = otp_auth
        if lzo_compression is not None:
            self.lzo_compression = lzo_compression
        if debug is not None:
            self.debug = debug
Example #22
0
    def archive_log(self, archive_path):
        temp_path = utils.get_temp_path()
        if os.path.isdir(archive_path):
            archive_path = os.path.join(
                archive_path, LOG_ARCHIVE_NAME + '.tar')
        output_path = os.path.join(temp_path, LOG_ARCHIVE_NAME)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(archive_path, 'w')
            try:
                with open(output_path, 'w') as log_file:
                    log_file.write(self.get_log_lines(False))
                tar_file.add(output_path, arcname=LOG_ARCHIVE_NAME)
            finally:
                tar_file.close()
        finally:
            utils.rmtree(temp_path)

        return archive_path
Example #23
0
    def archive_log(self, archive_path, limit):
        temp_path = utils.get_temp_path()
        if os.path.isdir(archive_path):
            archive_path = os.path.join(archive_path,
                                        LOG_ARCHIVE_NAME + '.tar')
        output_path = os.path.join(temp_path, LOG_ARCHIVE_NAME)

        try:
            os.makedirs(temp_path)
            tar_file = tarfile.open(archive_path, 'w')
            try:
                with open(output_path, 'w') as log_file:
                    log_file.write(self.get_log_lines(limit, False))
                tar_file.add(output_path, arcname=LOG_ARCHIVE_NAME)
            finally:
                tar_file.close()
        finally:
            utils.rmtree(temp_path)

        return archive_path
Example #24
0
    def task(self):
        logger.debug("Generating server dh params", "server", queue_id=self.id, dh_param_bits=self.dh_param_bits)

        self.queue_com.wait_status()

        temp_path = utils.get_temp_path()
        dh_param_path = os.path.join(temp_path, DH_PARAM_NAME)

        try:
            os.makedirs(temp_path)
            args = ["openssl", "dhparam", "-out", dh_param_path, str(self.dh_param_bits)]
            self.queue_com.popen(args)
            self.read_file("dh_params", dh_param_path)
        finally:
            utils.rmtree(temp_path)

        self.queue_com.wait_status()

        if not self.server_id:
            self.load()
            if self.reserve_data:
                self.server_id = self.reserve_data["server_id"]

        if self.server_id:
            response = self.server_collection.update(
                {"_id": self.server_id, "dh_param_bits": self.dh_param_bits}, {"$set": {"dh_params": self.dh_params}}
            )

            if response["updatedExisting"]:
                logger.debug(
                    "Set queued server dh params", "server", queue_id=self.id, dh_param_bits=self.dh_param_bits
                )

                event.Event(type=SERVERS_UPDATED)
                return

        logger.debug("Adding pooled dh params", "server", queue_id=self.id, dh_param_bits=self.dh_param_bits)

        self.dh_params_collection.insert({"dh_param_bits": self.dh_param_bits, "dh_params": self.dh_params})
Example #25
0
 def __init__(self, server):
     self.server = server
     self.id = utils.ObjectId()
     self.interrupt = False
     self.sock_interrupt = False
     self.clean_exit = False
     self.interface = None
     self.bridge_interface = None
     self.primary_user = None
     self.process = None
     self.vxlan = None
     self.iptables = iptables.Iptables()
     self.iptables_lock = threading.Lock()
     self.tun_nat = False
     self.server_links = []
     self.route_advertisements = set()
     self._temp_path = utils.get_temp_path()
     self.ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
     self.management_socket_path = os.path.join(
         settings.conf.var_run_path,
         MANAGEMENT_SOCKET_NAME % self.id,
     )
Example #26
0
 def __init__(self, server):
     self.server = server
     self.id = utils.ObjectId()
     self.interrupt = False
     self.sock_interrupt = False
     self.startup_interrupt = False
     self.clean_exit = False
     self.interface = None
     self.bridge_interface = None
     self.primary_user = None
     self.process = None
     self.vxlan = None
     self.iptables = iptables.Iptables()
     self.iptables_lock = threading.Lock()
     self.tun_nat = False
     self.server_links = []
     self.route_advertisements = set()
     self._temp_path = utils.get_temp_path()
     self.ovpn_conf_path = os.path.join(self._temp_path, OVPN_CONF_NAME)
     self.management_socket_path = os.path.join(
         settings.conf.var_run_path,
         MANAGEMENT_SOCKET_NAME % self.id,
     )
Example #27
0
    def build_onc_archive(self):
        temp_path = utils.get_temp_path()
        key_archive_path = os.path.join(temp_path, "%s.zip" % self.id)

        try:
            os.makedirs(temp_path)
            zip_file = zipfile.ZipFile(key_archive_path, "w")
            try:
                user_cert_path = os.path.join(temp_path, "%s.crt" % self.id)
                user_key_path = os.path.join(temp_path, "%s.key" % self.id)
                user_p12_path = os.path.join(temp_path, "%s.p12" % self.id)

                with open(user_cert_path, "w") as user_cert:
                    user_cert.write(self.certificate)

                with open(user_key_path, "w") as user_key:
                    os.chmod(user_key_path, 0600)
                    user_key.write(self.private_key)

                utils.check_output_logged(
                    [
                        "openssl",
                        "pkcs12",
                        "-export",
                        "-nodes",
                        "-password",
                        "pass:"******"-inkey",
                        user_key_path,
                        "-in",
                        user_cert_path,
                        "-out",
                        user_p12_path,
                    ]
                )

                zip_file.write(user_p12_path, arcname="%s.p12" % self.name)

                os.remove(user_cert_path)
                os.remove(user_key_path)
                os.remove(user_p12_path)

                for svr in self.org.iter_servers():
                    server_conf_path = os.path.join(temp_path, "%s_%s.onc" % (self.id, svr.id))
                    conf_name, client_conf = self._generate_onc(svr)
                    if not client_conf:
                        continue

                    with open(server_conf_path, "w") as ovpn_conf:
                        ovpn_conf.write(client_conf)
                    zip_file.write(server_conf_path, arcname=conf_name)
                    os.remove(server_conf_path)
            finally:
                zip_file.close()

            with open(key_archive_path, "r") as archive_file:
                key_archive = archive_file.read()
        finally:
            utils.rmtree(temp_path)

        return key_archive
Example #28
0
    def build_onc(self):
        temp_path = utils.get_temp_path()

        try:
            os.makedirs(temp_path)

            user_cert_path = os.path.join(temp_path, '%s.crt' % self.id)
            user_key_path = os.path.join(temp_path, '%s.key' % self.id)
            user_p12_path = os.path.join(temp_path, '%s.p12' % self.id)

            with open(user_cert_path, 'w') as user_cert:
                user_cert.write(self.certificate)

            with open(user_key_path, 'w') as user_key:
                os.chmod(user_key_path, 0600)
                user_key.write(self.private_key)

            utils.check_output_logged([
                'openssl',
                'pkcs12',
                '-export',
                '-nodes',
                '-password',
                'pass:'******'-inkey',
                user_key_path,
                '-in',
                user_cert_path,
                '-out',
                user_p12_path,
            ])

            with open(user_p12_path, 'r') as user_key_p12:
                user_key_base64 = base64.b64encode(user_key_p12.read())
                user_cert_id = '{%s}' % hashlib.md5(
                    user_key_base64).hexdigest()

            os.remove(user_cert_path)
            os.remove(user_key_path)
            os.remove(user_p12_path)

            onc_nets = ''
            onc_certs_store = {}

            for svr in self.iter_servers():
                onc_net, onc_certs = self._generate_onc(svr, user_cert_id)
                if not onc_net:
                    continue
                onc_certs_store.update(onc_certs)

                onc_nets += onc_net + ',\n'
            onc_nets = onc_nets[:-2]

            if onc_nets == '':
                return None

            onc_certs = ''
            for cert_id, cert in onc_certs_store.items():
                onc_certs += OVPN_ONC_CA_CERT % (cert_id, cert) + ',\n'
            onc_certs += OVPN_ONC_CLIENT_CERT % (user_cert_id, user_key_base64)

            onc_conf = OVPN_ONC_CLIENT_CONF % (onc_nets, onc_certs)
        finally:
            utils.rmtree(temp_path)

        return onc_conf
Example #29
0
def _ndppd_thread():
    conf_path = utils.get_temp_path() + '_ndppd.conf'
    time.sleep(3)

    while True:
        process = None

        try:
            host_routed_subnet6 = settings.local.host.routed_subnet6
            host_proxy_ndp = settings.local.host.proxy_ndp
            iface6 = default_interface6

            if not host_routed_subnet6 or not host_proxy_ndp:
                yield interrupter_sleep(3)
                continue

            if not iface6:
                logger.error('Default IPv6 interface not available', 'setup')
                yield interrupter_sleep(3)
                continue

            with open(conf_path, 'w') as conf_file:
                conf_file.write(NDPPD_CONF % (
                    iface6,
                    host_routed_subnet6,
                ))

            process = subprocess.Popen([
                'ndppd',
                '-c',
                conf_path,
            ],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)

            while True:
                if host_routed_subnet6 != \
                        settings.local.host.routed_subnet6 or \
                        host_proxy_ndp != settings.local.host.proxy_ndp or \
                        iface6 != default_interface6:
                    process.terminate()
                    yield interrupter_sleep(2)
                    process.kill()
                    process = None
                    break
                elif process.poll() is not None:
                    output = None
                    try:
                        output = process.stdout.readall()
                        output += process.stderr.readall()
                    except:
                        pass

                    if check_global_interrupt():
                        return

                    logger.error(
                        'Ndppd service stopped unexpectedly',
                        'setup',
                        output=output,
                    )
                    process = None

                    yield interrupter_sleep(1)

                    break

                time.sleep(0.5)
                yield
        except GeneratorExit:
            if process:
                process.terminate()
                time.sleep(1)
                process.kill()
            return
        except:
            logger.exception('Error in ndppd service', 'setup')
        finally:
            try:
                os.remove(conf_path)
            except:
                pass

        yield interrupter_sleep(1)
Example #30
0
def _ndppd_thread():
    conf_path = utils.get_temp_path() + '_ndppd.conf'
    time.sleep(3)

    while True:
        process = None

        try:
            host_routed_subnet6 = settings.local.host.routed_subnet6
            host_proxy_ndp = settings.local.host.proxy_ndp
            iface6 = default_interface6

            if not host_routed_subnet6 or not host_proxy_ndp:
                yield interrupter_sleep(3)
                continue

            if not iface6:
                logger.error('Default IPv6 interface not available', 'setup')
                yield interrupter_sleep(3)
                continue

            with open(conf_path, 'w') as conf_file:
                conf_file.write(NDPPD_CONF % (
                    iface6,
                    host_routed_subnet6,
                ))

            process = subprocess.Popen([
                'ndppd',
                '-c', conf_path,
            ])

            while True:
                if host_routed_subnet6 != \
                        settings.local.host.routed_subnet6 or \
                        host_proxy_ndp != settings.local.host.proxy_ndp or \
                        iface6 != default_interface6:
                    process.terminate()
                    yield interrupter_sleep(2)
                    process.kill()
                    process = None
                    break
                elif process.poll() is not None:
                    output = None
                    try:
                        output = process.stdout.readall()
                        output += process.stderr.readall()
                    except:
                        pass

                    if check_global_interrupt():
                        return

                    logger.error(
                        'Ndppd service stopped unexpectedly', 'setup',
                        output=output,
                    )
                    process = None

                    yield interrupter_sleep(1)

                    break

                time.sleep(0.5)
                yield
        except GeneratorExit:
            if process:
                process.terminate()
                time.sleep(1)
                process.kill()
            return
        except:
            logger.exception('Error in ndppd service', 'setup')
        finally:
            try:
                os.remove(conf_path)
            except:
                pass

        yield interrupter_sleep(1)
Example #31
0
    def initialize(self):
        temp_path = utils.get_temp_path()
        index_path = os.path.join(temp_path, INDEX_NAME)
        index_attr_path = os.path.join(temp_path, INDEX_ATTR_NAME)
        serial_path = os.path.join(temp_path, SERIAL_NAME)
        ssl_conf_path = os.path.join(temp_path, OPENSSL_NAME)
        reqs_path = os.path.join(temp_path, '%s.csr' % self.id)
        key_path = os.path.join(temp_path, '%s.key' % self.id)
        cert_path = os.path.join(temp_path, '%s.crt' % self.id)
        ca_name = self.id if self.type == CERT_CA else 'ca'
        ca_cert_path = os.path.join(temp_path, '%s.crt' % ca_name)
        ca_key_path = os.path.join(temp_path, '%s.key' % ca_name)

        self.org.queue_com.wait_status()

        try:
            os.makedirs(temp_path)

            with open(index_path, 'a'):
                os.utime(index_path, None)

            with open(index_attr_path, 'a'):
                os.utime(index_attr_path, None)

            with open(serial_path, 'w') as serial_file:
                serial_hex = ('%x' % utils.fnv64a(str(self.id))).upper()

                if len(serial_hex) % 2:
                    serial_hex = '0' + serial_hex

                serial_file.write('%s\n' % serial_hex)

            with open(ssl_conf_path, 'w') as conf_file:
                conf_file.write(CERT_CONF % (
                    settings.user.cert_key_bits,
                    settings.user.cert_message_digest,
                    self.org.id,
                    self.id,
                    index_path,
                    serial_path,
                    temp_path,
                    ca_cert_path,
                    ca_key_path,
                    settings.user.cert_message_digest,
                ))

            self.org.queue_com.wait_status()

            if self.type != CERT_CA:
                self.org.write_file('ca_certificate', ca_cert_path, chmod=0600)
                self.org.write_file('ca_private_key', ca_key_path, chmod=0600)
                self.generate_otp_secret()

            try:
                args = [
                    'openssl',
                    'req',
                    '-new',
                    '-batch',
                    '-config',
                    ssl_conf_path,
                    '-out',
                    reqs_path,
                    '-keyout',
                    key_path,
                    '-reqexts',
                    '%s_req_ext' % self.type.replace('_pool', ''),
                ]
                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception(
                    'Failed to create user cert requests',
                    'user',
                    org_id=self.org.id,
                    user_id=self.id,
                )
                raise
            self.read_file('private_key', key_path)

            try:
                args = ['openssl', 'ca', '-batch']

                if self.type == CERT_CA:
                    args += ['-selfsign']

                args += [
                    '-config',
                    ssl_conf_path,
                    '-in',
                    reqs_path,
                    '-out',
                    cert_path,
                    '-extensions',
                    '%s_ext' % self.type.replace('_pool', ''),
                ]

                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception(
                    'Failed to create user cert',
                    'user',
                    org_id=self.org.id,
                    user_id=self.id,
                )
                raise
            self.read_file('certificate', cert_path)
        finally:
            try:
                utils.rmtree(temp_path)
            except subprocess.CalledProcessError:
                pass

        self.org.queue_com.wait_status()

        # If assign ip addr fails it will be corrected in ip sync task
        try:
            self.assign_ip_addr()
        except:
            logger.exception(
                'Failed to assign users ip address',
                'user',
                org_id=self.org.id,
                user_id=self.id,
            )
Example #32
0
    def build_onc(self):
        temp_path = utils.get_temp_path()

        try:
            os.makedirs(temp_path)

            user_cert_path = os.path.join(temp_path, '%s.crt' % self.id)
            user_key_path = os.path.join(temp_path, '%s.key' % self.id)
            user_p12_path = os.path.join(temp_path, '%s.p12' % self.id)

            with open(user_cert_path, 'w') as user_cert:
                user_cert.write(self.certificate)

            with open(user_key_path, 'w') as user_key:
                os.chmod(user_key_path, 0600)
                user_key.write(self.private_key)

            utils.check_output_logged([
                'openssl',
                'pkcs12',
                '-export',
                '-nodes',
                '-password', 'pass:'******'-inkey', user_key_path,
                '-in', user_cert_path,
                '-out', user_p12_path,
            ])

            with open(user_p12_path, 'r') as user_key_p12:
                user_key_base64 = base64.b64encode(user_key_p12.read())
                user_cert_id = '{%s}' % hashlib.md5(
                    user_key_base64).hexdigest()

            os.remove(user_cert_path)
            os.remove(user_key_path)
            os.remove(user_p12_path)

            onc_nets = ''
            onc_certs_store = {}

            for svr in self.iter_servers():
                onc_net, onc_certs = self._generate_onc(
                    svr, user_cert_id)
                if not onc_net:
                    continue
                onc_certs_store.update(onc_certs)

                onc_nets += onc_net + ',\n'
            onc_nets = onc_nets[:-2]

            if onc_nets == '':
                return None

            onc_certs = ''
            for cert_id, cert in onc_certs_store.items():
                onc_certs += OVPN_ONC_CA_CERT % (cert_id, cert) + ',\n'
            onc_certs += OVPN_ONC_CLIENT_CERT % (
                user_cert_id, user_key_base64)

            onc_conf = OVPN_ONC_CLIENT_CONF % (onc_nets, onc_certs)
        finally:
            utils.rmtree(temp_path)

        return onc_conf
Example #33
0
    def initialize(self):
        temp_path = utils.get_temp_path()
        index_path = os.path.join(temp_path, INDEX_NAME)
        index_attr_path = os.path.join(temp_path, INDEX_ATTR_NAME)
        serial_path = os.path.join(temp_path, SERIAL_NAME)
        ssl_conf_path = os.path.join(temp_path, OPENSSL_NAME)
        reqs_path = os.path.join(temp_path, '%s.csr' % self.id)
        key_path = os.path.join(temp_path, '%s.key' % self.id)
        cert_path = os.path.join(temp_path, '%s.crt' % self.id)
        ca_name = self.id if self.type == CERT_CA else 'ca'
        ca_cert_path = os.path.join(temp_path, '%s.crt' % ca_name)
        ca_key_path = os.path.join(temp_path, '%s.key' % ca_name)

        self.org.queue_com.wait_status()

        try:
            os.makedirs(temp_path)

            with open(index_path, 'a'):
                os.utime(index_path, None)

            with open(index_attr_path, 'a'):
                os.utime(index_attr_path, None)

            with open(serial_path, 'w') as serial_file:
                serial_hex = ('%x' % utils.fnv64a(str(self.id))).upper()

                if len(serial_hex) % 2:
                    serial_hex = '0' + serial_hex

                serial_file.write('%s\n' % serial_hex)

            with open(ssl_conf_path, 'w') as conf_file:
                conf_file.write(CERT_CONF % (
                    settings.user.cert_key_bits,
                    settings.user.cert_message_digest,
                    self.org.id,
                    self.id,
                    index_path,
                    serial_path,
                    temp_path,
                    ca_cert_path,
                    ca_key_path,
                    settings.user.cert_message_digest,
                ))

            self.org.queue_com.wait_status()

            if self.type != CERT_CA:
                self.org.write_file('ca_certificate', ca_cert_path, chmod=0600)
                self.org.write_file('ca_private_key', ca_key_path, chmod=0600)
                self.generate_otp_secret()

            try:
                args = [
                    'openssl', 'req', '-new', '-batch',
                    '-config', ssl_conf_path,
                    '-out', reqs_path,
                    '-keyout', key_path,
                    '-reqexts', '%s_req_ext' % self.type.replace('_pool', ''),
                ]
                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception('Failed to create user cert requests', 'user',
                    org_id=self.org.id,
                    user_id=self.id,
                )
                raise
            self.read_file('private_key', key_path)

            try:
                args = ['openssl', 'ca', '-batch']

                if self.type == CERT_CA:
                    args += ['-selfsign']

                args += [
                    '-config', ssl_conf_path,
                    '-in', reqs_path,
                    '-out', cert_path,
                    '-extensions', '%s_ext' % self.type.replace('_pool', ''),
                ]

                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception('Failed to create user cert', 'user',
                    org_id=self.org.id,
                    user_id=self.id,
                )
                raise
            self.read_file('certificate', cert_path)
        finally:
            try:
                utils.rmtree(temp_path)
            except subprocess.CalledProcessError:
                pass

        self.org.queue_com.wait_status()

        # If assign ip addr fails it will be corrected in ip sync task
        try:
            self.assign_ip_addr()
        except:
            logger.exception('Failed to assign users ip address', 'user',
                org_id=self.org.id,
                user_id=self.id,
            )
Example #34
0
    def initialize(self):
        temp_path = utils.get_temp_path()
        index_path = os.path.join(temp_path, INDEX_NAME)
        index_attr_path = os.path.join(temp_path, INDEX_ATTR_NAME)
        serial_path = os.path.join(temp_path, SERIAL_NAME)
        ssl_conf_path = os.path.join(temp_path, OPENSSL_NAME)
        reqs_path = os.path.join(temp_path, "%s.csr" % self.id)
        key_path = os.path.join(temp_path, "%s.key" % self.id)
        cert_path = os.path.join(temp_path, "%s.crt" % self.id)
        ca_name = self.id if self.type == CERT_CA else "ca"
        ca_cert_path = os.path.join(temp_path, "%s.crt" % ca_name)
        ca_key_path = os.path.join(temp_path, "%s.key" % ca_name)

        self.org.queue_com.wait_status()

        try:
            os.makedirs(temp_path)

            with open(index_path, "a"):
                os.utime(index_path, None)

            with open(index_attr_path, "a"):
                os.utime(index_attr_path, None)

            with open(serial_path, "w") as serial_file:
                serial_hex = ("%x" % utils.fnv64a(str(self.id))).upper()

                if len(serial_hex) % 2:
                    serial_hex = "0" + serial_hex

                serial_file.write("%s\n" % serial_hex)

            with open(ssl_conf_path, "w") as conf_file:
                conf_file.write(
                    CERT_CONF
                    % (
                        settings.user.cert_key_bits,
                        settings.user.cert_message_digest,
                        self.org.id,
                        self.id,
                        index_path,
                        serial_path,
                        temp_path,
                        ca_cert_path,
                        ca_key_path,
                        settings.user.cert_message_digest,
                    )
                )

            self.org.queue_com.wait_status()

            if self.type != CERT_CA:
                self.org.write_file("ca_certificate", ca_cert_path, chmod=0600)
                self.org.write_file("ca_private_key", ca_key_path, chmod=0600)
                self.generate_otp_secret()

            try:
                args = [
                    "openssl",
                    "req",
                    "-new",
                    "-batch",
                    "-config",
                    ssl_conf_path,
                    "-out",
                    reqs_path,
                    "-keyout",
                    key_path,
                    "-reqexts",
                    "%s_req_ext" % self.type.replace("_pool", ""),
                ]
                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception("Failed to create user cert requests", "user", org_id=self.org.id, user_id=self.id)
                raise
            self.read_file("private_key", key_path)

            try:
                args = ["openssl", "ca", "-batch"]

                if self.type == CERT_CA:
                    args += ["-selfsign"]

                args += [
                    "-config",
                    ssl_conf_path,
                    "-in",
                    reqs_path,
                    "-out",
                    cert_path,
                    "-extensions",
                    "%s_ext" % self.type.replace("_pool", ""),
                ]

                self.org.queue_com.popen(args)
            except (OSError, ValueError):
                logger.exception("Failed to create user cert", "user", org_id=self.org.id, user_id=self.id)
                raise
            self.read_file("certificate", cert_path)
        finally:
            try:
                utils.rmtree(temp_path)
            except subprocess.CalledProcessError:
                pass

        self.org.queue_com.wait_status()

        # If assign ip addr fails it will be corrected in ip sync task
        try:
            self.assign_ip_addr()
        except:
            logger.exception("Failed to assign users ip address", "user", org_id=self.org.id, user_id=self.id)