Example #1
0
 def _save_certificates(sip_address, crt, key, ca):
     crt = crt.strip() + os.linesep
     key = key.strip() + os.linesep
     ca = ca.strip() + os.linesep
     X509Certificate(crt)
     X509PrivateKey(key)
     X509Certificate(ca)
     makedirs(ApplicationData.get('tls'))
     certificate_path = ApplicationData.get(
         os.path.join('tls', sip_address + '.crt'))
     certificate_file = open(certificate_path, 'w')
     os.chmod(certificate_path, 0600)
     certificate_file.write(crt + key)
     certificate_file.close()
     ca_path = ApplicationData.get(os.path.join('tls', 'ca.crt'))
     try:
         existing_cas = open(ca_path).read().strip() + os.linesep
     except:
         certificate_file = open(ca_path, 'w')
         certificate_file.write(ca)
         certificate_file.close()
     else:
         if ca not in existing_cas:
             certificate_file = open(ca_path, 'w')
             certificate_file.write(existing_cas + ca)
             certificate_file.close()
     settings = SIPSimpleSettings()
     settings.tls.ca_list = ca_path
     settings.save()
     return certificate_path
Example #2
0
    def save_certificates(self, response):
        passport = response["passport"]
        address = response["sip_address"]

        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0o700)

        ca = passport["ca"].strip() + os.linesep
        self.add_certificate_authority(ca)

        crt = passport["crt"].strip() + os.linesep
        try:
            X509Certificate(crt)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid TLS certificate: %s" % e)
            return None

        key = passport["key"].strip() + os.linesep
        try:
            X509PrivateKey(key)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid Private Key: %s" % e)
            return None

        crt_path = os.path.join(tls_folder, address + ".crt")
        f = open(crt_path, "w")
        os.chmod(crt_path, 0o600)
        f.write(crt)
        f.write(key)
        f.close()
        BlinkLogger().log_info("Saved new TLS Certificate and Private Key to %s" % crt_path)

        return crt_path
Example #3
0
 def __new__(cls, value):
     if isinstance(value, str):
         try:
             return X509PrivateKey(file_content(value))
         except Exception, e:
             log.warn("Private key file '%s' could not be loaded: %s" %
                      (value, str(e)))
             return None
Example #4
0
 def __new__(cls, value):
     if isinstance(value, basestring):
         try:
             return X509PrivateKey(file_content(value))
         except Exception as e:
             log.warn("Private key file '%s' could not be loaded: %s" % (value, str(e)))
             return None
     else:
         raise TypeError('value should be a string')
Example #5
0
    def tls_credentials(self):
        # This property can be optimized to cache the credentials it loads from disk,
        # however this is not a time consuming operation (~ 3000 req/sec). -Luci

        settings = SIPSimpleSettings()
        tls_certificate = self.tls.certificate or settings.tls.certificate

        certificate = None
        private_key = None

        if tls_certificate is not None:
            try:
                certificate_data = open(tls_certificate.normalized).read()
                certificate = X509Certificate(certificate_data)
                private_key = X509PrivateKey(certificate_data)
            except (FileNotFoundError, GNUTLSError, UnicodeDecodeError):
                pass

        trusted_cas = []
        ca_list = self.tls.ca_list or settings.tls.ca_list

        if ca_list is not None:
            if len(self.trusted_cas) > 0:
                trusted_cas = self.trusted_cas
            else:
                crt = None
                start = False
                try:
                    ca_text = open(ca_list.normalized).read()
                except (FileNotFoundError, GNUTLSError, UnicodeDecodeError):
                    ca_text = ''

                for line in ca_text.split("\n"):
                    if "BEGIN CERT" in line:
                        start = True
                        crt = line + "\n"
                    elif "END CERT" in line:
                        crt = crt + line + "\n"
                        end = True
                        start = False
                        try:
                            trusted_cas.append(X509Certificate(crt))
                        except (GNUTLSError, ValueError) as e:
                            continue

                    elif start:
                        crt = crt + line + "\n"

                self.trusted_cas = trusted_cas
                self.ca_list = ca_list

        credentials = X509Credentials(certificate, private_key, trusted_cas)
        credentials.verify_peer = self.tls.verify_server or settings.tls.certificate
        return credentials
Example #6
0
    def tls_credentials(self):
        # This property can be optimized to cache the credentials it loads from disk,
        # however this is not a time consuming operation (~ 3000 req/sec). -Luci
        settings = SIPSimpleSettings()
        tls_certificate = self.tls.certificate or settings.tls.certificate
        if tls_certificate is not None:
            certificate_data = open(tls_certificate.normalized).read()
            certificate = X509Certificate(certificate_data)
            private_key = X509PrivateKey(certificate_data)
        else:
            certificate = None
            private_key = None

        credentials = X509Credentials(certificate, private_key, [])
        credentials.verify_peer = False
        return credentials
Example #7
0
    def __init__(self, config, bind_and_activate=True):
        self.config = config

        if is_ipv6_address(self.config.listen_address):
            self.address_family = socket.AF_INET6

        with open(self.config.cert, 'rb') as f:
            self.encoded_cert = f.read()

        with open(self.config.key, 'r') as f:
            self.key = f.read()

        with open(self.config.onion_secret_key, 'r') as f:
            self.onion_secret_key = f.read()

        self.set_handler()

        self.server_context = TLSContext(
            X509Credentials(
                X509Certificate(self.encoded_cert, format=X509_FMT_DER),
                X509PrivateKey(self.key)), config.priority_string_as_server)
        self.client_context = TLSContext(X509Credentials(),
                                         config.priority_string_as_client)

        self.identity_pubkey = RSA.import_key(self.encoded_cert)
        self.identity_privkey = RSA.import_key(self.key)

        self.onion_privkey = RSA.import_key(self.onion_secret_key)

        ntor_onion_secret_key = self.config.ntor_onion_secret_key.decode(
            "base64").strip()
        self.ntor_onion_key = NTorOnionKey(
            ntor_onion_secret_key,
            NTorKey(ntor_onion_secret_key).get_public())

        self.fingerprint = self.make_digest_fingerprint()
        self.descriptor = self.create_bridge_descriptor()
        self.dir_identity_response = self.create_dir_response()

        self.print_fingerprint()

        SocketServer.ThreadingTCPServer.__init__(self, config.listen_address,
                                                 ORMITMHandler,
                                                 bind_and_activate)
Example #8
0
def _parseTLS(factory,
              port,
              privateKey='server.pem',
              certKey=None,
              sslmethod=None,
              interface='',
              backlog=50):
    from gnutls.interfaces.twisted import X509Credentials
    from gnutls.crypto import X509Certificate, X509PrivateKey

    if certKey is None:
        certKey = privateKey

    cert = X509Certificate(open(certKey).read())
    key = X509PrivateKey(open(privateKey).read())
    cf = X509Credentials(cert, key)

    return ((int(port), factory, cf), {
        'interface': interface,
        'backlog': int(backlog)
    })
 def tls_credentials(self):
     # This property can be optimized to cache the credentials it loads from disk,
     # however this is not a time consuming operation (~ 3000 req/sec). -Luci
     settings = SIPSimpleSettings()
     if self.tls.certificate is not None:
         certificate_data = open(self.tls.certificate.normalized).read()
         certificate = X509Certificate(certificate_data)
         private_key = X509PrivateKey(certificate_data)
     else:
         certificate = None
         private_key = None
     if settings.tls.ca_list is not None:
         # we should read all certificates in the file, rather than just the first -Luci
         trusted = [
             X509Certificate(open(settings.tls.ca_list.normalized).read())
         ]
     else:
         trusted = []
     credentials = X509Credentials(certificate, private_key, trusted)
     credentials.verify_peer = self.tls.verify_server
     return credentials
Example #10
0
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0700)

        ca = passport["ca"].strip() + os.linesep
        self.add_certificate_authority(ca)

        crt = passport["crt"].strip() + os.linesep
        try:
            X509Certificate(crt)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid TLS certificate: %s" % e)
            return None

        key = passport["key"].strip() + os.linesep
        try:
            X509PrivateKey(key)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid Private Key: %s" % e)
            return None

        crt_path = os.path.join(tls_folder, address + ".crt")
        f = open(crt_path, "w")
        os.chmod(crt_path, 0600)
        f.write(crt)
        f.write(key)
        f.close()
        BlinkLogger().log_info(
            u"Saved new TLS Certificate and Private Key to %s" % crt_path)

        return crt_path
Example #11
0
class TLSMixin(object):
    use_tls = True
    cert = X509Certificate(open('valid.crt').read())
    key = X509PrivateKey(open('valid.key').read())
    server_credentials = X509Credentials(cert, key)
Example #12
0
    def __init__(self, config, bind_and_activate=True):
        self.config = config

        if is_ipv6_address(self.config.listen_address):
            self.address_family = socket.AF_INET6

        with open(self.config.cert, 'rb') as keyfile:
            self.encoded_cert = keyfile.read()

        with open(self.config.key, 'r') as keyfile:
            self.key = keyfile.read()

        with open(self.config.onion_secret_key, 'r') as keyfile:
            self.onion_secret_key = keyfile.read()

        self.set_handler()

        self.server_context = TLSContext(
            X509Credentials(
                X509Certificate(self.encoded_cert, format=X509_FMT_DER),
                X509PrivateKey(self.key)),
            self.config.priority_string_as_server)

        if self.has_tls_client_credentials():
            self.tls_credentials = self.config.client_tls_credentials
        else:
            self.tls_credentials = X509Credentials()

        self.client_context = TLSContext(self.tls_credentials,
                                         self.config.priority_string_as_client)

        self.identity_pubkey = load_der_x509_certificate(
            self.encoded_cert, backend=_default_backend).public_key()
        self.identity_privkey = load_pem_private_key(self.key,
                                                     password=None,
                                                     backend=_default_backend)
        self.onion_privkey = load_pem_private_key(self.onion_secret_key,
                                                  password=None,
                                                  backend=_default_backend)

        if not isinstance(self.identity_pubkey, RSAPublicKey):
            raise RuntimeError(
                "Certificate of instance {} does not have an RSA key".format(
                    self.config.listen_address))

        if not isinstance(self.identity_privkey, RSAPrivateKey):
            raise RuntimeError("Key of instance {} is not an RSA key".format(
                self.config.listen_address))

        if not isinstance(self.onion_privkey, RSAPrivateKey):
            raise RuntimeError(
                "Onion key of instance {} is not an RSA key".format(
                    self.config.listen_address))

        ntor_onion_secret_key = base64.b64decode(
            self.config.ntor_onion_secret_key.strip())
        self.ntor_onion_key = NTorOnionKey(
            ntor_onion_secret_key,
            NTorKey(ntor_onion_secret_key).get_public())

        self.fingerprint = self.make_digest_fingerprint()
        self.descriptor = self.create_bridge_descriptor()
        self.dir_identity_response = self.create_dir_response()

        self.print_fingerprint()

        SocketServer.ThreadingTCPServer.__init__(self,
                                                 self.config.listen_address,
                                                 ORMITMHandler,
                                                 bind_and_activate)