Esempio n. 1
0
    def generate_cert_for_host(self, host):
        cert = crypto.X509()

        cert.set_serial_number(self.serial_number)
        self.serial_number += 1

        cert.set_issuer(self.master_cert.get_subject())

        subject = crypto.X509Name(self.master_cert_req.get_subject())
        subject.commonName = host
        cert.set_subject(subject)

        cert.set_pubkey(self.master_cert.get_pubkey())

        today = datetime.datetime.today()
        before = today - datetime.timedelta(days=365)
        after = today + datetime.timedelta(days=365)
        
        if hasattr(cert, 'set_notBefore'):
            cert.set_notBefore(before.strftime('%Y%m%d%H%M%SZ'))
            cert.set_notAfter(after.strftime('%Y%m%d%H%M%SZ'))
        else:
            cert.gmtime_adj_notBefore(0)
            cert.gmtime_adj_notAfter(60*60*24*365*10)

        cert.sign(self.master_key, self.default_digest)

        return cert
Esempio n. 2
0
def verify_cb(conn, cert, errnum, depth, ok):
    certsubject = crypto.X509Name(cert.get_subject())
    commonname = certsubject.commonName

    if pinnedcertificate is not None:
        # check pinned certificate
        if depth == 0:
            # load certificate
            cert_hash = cert.digest("sha256")
            return (pinned_cert_hash == cert_hash)
        else:
            return True
    else:
        # check crl
        if crlfile is not None:
            serial_number_to_hex_str = str(
                format(cert.get_serial_number(), 'X'))
            for revoke in crl_list:
                if revoke.get_serial() == serial_number_to_hex_str:
                    return False

        # allow expired certificate
        if allow_stale_certs_num is not None and errnum == 10:
            expired_time = datetime.datetime.strptime(cert.get_notAfter(),
                                                      "%Y%m%d%H%M%SZ")
            new_time = expired_time + datetime.timedelta(
                days=allow_stale_certs_num)
            return new_time > datetime.datetime.utcnow()

    # Nothing is detected
    if ok and errnum == 0:
        return True
    else:
        return False
Esempio n. 3
0
    def getX509Name(certificate, get_components=False):
        """Get the DER-encoded form of the Name fields of an X509 certificate.

        @param certificate: A :class:`OpenSSL.crypto.X509Name` object.
        @param get_components: A boolean. If True, returns a list of tuples of
                               the (name, value)s of each Name field in the
                               :param:`certificate`. If False, returns the DER
                               encoded form of the Name fields of the
                               :param:`certificate`.
        """
        x509_name = None

        try:
            assert isinstance(certificate, crypto.X509Name), \
                "getX509Name takes OpenSSL.crypto.X509Name as first argument!"
            x509_name = crypto.X509Name(certificate)
        except AssertionError as ae:
            log.err(ae)
        except Exception as exc:
            log.exception(exc)

        if not x509_name is None:
            if not get_components:
                return x509_name.der()
            else:
                return x509_name.get_components()
        else:
            log.debug("getX509Name: got None for ivar x509_name")
Esempio n. 4
0
    def __verify_mfr_starttime_orgname(self, is_gcp):
        """Verify the validity start time and organization name in Mfr CVC.

        :is_gcp:
        :return: True or False

        """
        if self.mfr_cvc == None:  # pragma: no cover
            self.verify_result = SsdVerifyResult.ERROR_GCP_MISS_MFR_CVC
            return False

        notBefore = self.mfr_cvc.get_notBefore()

        # Check the organization name
        ou = c.X509Name(self.mfr_cvc.get_subject())
        org_name = ou.organizationName

        if self.mfr_org_name != org_name:
            self.verify_result = SsdVerifyResult.ERROR_CVC_MFR_NAME_MISMATCH
            return False

        # AssumecvcAccessStart as ASN.1 GENERALIZEDTIME, YYYYMMDDHH[MM[SS[.fff]]]Z
        if self.__parse_datetime(self.mfr_cvcAccessStart) > self.__parse_datetime(notBefore):
            if is_gcp == True:
                self.verify_result = SsdVerifyResult.ERROR_CVC_MFR_VALIDITY_TIME_LESS_THAN_RPD
            else:
                self.verify_result = SsdVerifyResult.ERROR_PKCS_MFR_VALIDITY_TIME_LESS_THAN_RPD
            return False

        return True
Esempio n. 5
0
def sign(pkey,
         p_ca_pem,
         p_ca_key,
         commonName,
         days,
         emailAddress=None,
         altName=None,
         userid=None):
    serial = _next_serial_number()

    ca_pem = p_ca_pem and file(p_ca_pem).read() or CA_CER
    ca_x509 = crypto.load_certificate(crypto.FILETYPE_PEM, ca_pem)
    ca_subj = ca_x509.get_subject()

    ca_pkey = p_ca_key and file(p_ca_key).read() or CA_KEY
    ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, ca_pkey)

    # create client X509 certificate
    x509 = crypto.X509()
    # 0x0:v1, 0x1:v2, 0x2:v3
    x509.set_version(2)
    x509.set_serial_number(serial)
    x509.set_issuer(ca_subj)

    # overload CAs subject and add extensions
    subj = crypto.X509Name(ca_subj)
    subj.CN = commonName

    x509.set_subject(subj)
    x509.add_extensions(CLIENT_EXTENSIONS)
    if altName:
        x509.add_extensions((crypto.X509Extension('subjectAltName', False,
                                                  'URI:' + altName), ))

    # x509 validity starts at present
    x509.gmtime_adj_notBefore(0)
    # and ends before CA expires
    x509.gmtime_adj_notAfter(days * 24 * 3600)
    #if asn1time(x509.get_notAfter()) > asn1time(ca_x509.get_notAfter()):
    #    x509.set_notAfter(ca_x509.get_notAfter())

    # insert public key
    x509.set_pubkey(pkey)

    # add identifiers
    x509.add_extensions((
        crypto.X509Extension('subjectKeyIdentifier',
                             False,
                             'hash',
                             subject=x509),
        crypto.X509Extension('authorityKeyIdentifier',
                             False,
                             'keyid',
                             issuer=ca_x509),
    ))

    # sign with CA private key
    x509.sign(ca_key, 'sha1')
    return x509
Esempio n. 6
0
File: bob.py Progetto: xue35/diyca
def examine_certificate(arg_conn, arg_cert, arg_errnum, arg_depth, arg_ok):
    """
    Examine the incoming client certificate.
    """
    subject = crypto.X509Name(arg_cert.get_subject())
    common_name = subject.commonName
    util.logger("Received certificate from client CN={%s}, depth={%d}",
                common_name, arg_depth)
    return 1
Esempio n. 7
0
def verify_cb(conn, cert, errnum, depth, ok):
    certsubject = crypto.X509Name(cert.get_subject())
    commonname = certsubject.commonName
    print '\n---------------------------------Certificate information---------------------------------\n'
    print 'Common   name:  ', commonname + '\n'
    print 'Country  name:  ', certsubject.countryName + '\n'
    print 'Locality Name:  ', certsubject.localityName + '\n'
    print 'Email Address:  ', certsubject.emailAddress + '\n'
    print '------------------------------------------------------------------------------------------\n'
    return ok
Esempio n. 8
0
def examine_certificate(arg_conn, arg_cert, arg_errnum, arg_depth, arg_okay):
    """
    Examine the incoming server certificate
    Unused input: arg_conn, arg_errnum, arg_okay
    """
    subject = crypto.X509Name(arg_cert.get_subject())
    common_name = subject.commonName
    util.logger("Received certificate from server CN={%s}, depth={%d}",
                common_name, arg_depth)
    return 1
Esempio n. 9
0
def generateSelfSigned(folderpath=None,
                       certname=None,
                       keysize=4096,
                       cn="*.maas",
                       user=None,
                       group=None,
                       mode=None):
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, keysize)
    cert = crypto.X509()
    serNum = 0
    valSecs = 10 * 365 * 24 * 60 * 60
    x509name = crypto.X509Name(crypto.X509().get_subject())
    x509name.countryName = "UK"
    x509name.stateOrProvinceName = "London"
    x509name.organizationName = "TestWandUbuntu"
    x509name.organizationalUnitName = "WandLib"
    x509name.commonName = cn or "*.example.com"
    cert.set_subject(x509name)
    cert.set_serial_number(serNum)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(valSecs)
    cert.set_pubkey(key)
    issuerName = crypto.X509Name(x509name)
    cert.set_issuer(issuerName)
    cert.sign(key, 'sha512')
    cname = certname or genRandomPassword(6)
    folder = folderpath or "/tmp"
    with open(os.path.join(folder, cname + ".crt"), "w") as f:
        f.write(
            crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
        f.close()
    with open(os.path.join(folder, cname + ".key"), "w") as f:
        f.write(
            crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode("utf-8"))
        f.close()
    if user and group:
        setFilePermissions(os.path.join(folder, cname + ".crt"), user, group,
                           mode)
        setFilePermissions(os.path.join(folder, cname + ".key"), user, group,
                           mode)
    return (crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"),
            crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode("utf-8"))
Esempio n. 10
0
    def __verify_mso_starttime_orgname(self, is_gcp):
        """Verify the validity start time and organization name in co-signer
        CVC.

        :is_gcp:
        :return: True or False

        """
        if self.mso_cvc == None:  # pragma: no cover
            self.verify_result = SsdVerifyResult.ERROR_GCP_MISS_CO_CVC
            return False

        notBefore = self.mso_cvc.get_notBefore()

        # Check the organization name
        ou = c.X509Name(self.mso_cvc.get_subject())
        org_name = ou.organizationName

        # should we return false if the mso_org_name doesn't exist
        if self.mso_org_name != None and self.mso_org_name != org_name:
            self.verify_result = SsdVerifyResult.ERROR_CVC_CO_NAME_MISMATCH
            return False
        else:
            # Give an initial value
            self.mso_org_name = org_name

        # AssumecvcAccessStart as ASN.1 GENERALIZEDTIME
        if self.mso_cvcAccessStart != None:
            if self.__parse_datetime(self.mso_cvcAccessStart) > self.__parse_datetime(notBefore):
                if is_gcp == True:
                    self.verify_result = SsdVerifyResult.ERROR_CVC_CO_VALIDITY_TIME_LESS_THAN_RPD
                else:
                    self.verify_result = SsdVerifyResult.ERROR_PKCS_CO_VALIDITY_TIME_LESS_THAN_RPD
                return False
        else:
            # Give an initial vaue
            self.mso_cvcAccessStart = notBefore
            self.mso_codeAccessStart = notBefore
            self.new_mso_codeAccessStart = notBefore
            self.new_mso_cvcAccessStart = notBefore

        return True
Esempio n. 11
0
def createCert(host, digest='sha1'):
    cert = crypto.X509() # 得到一个X509对象
    cert.set_version(0)
    cert.set_serial_number( int(time.time() * 10000000) ) # 序号,不重复即可。

    #证书有效与过期时间
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(EXPIRE_DELAY )

    cert.set_issuer(CA[0].get_subject() ) # 得到CA的信息

    subjects = crypto.X509Name(CERT_SUBJECTS)
    subjects.O = host
    subjects.CN = host
    cert.set_subject(subjects)

    pubkey = createPKey()
    cert.set_pubkey(pubkey)

    cert.sign(CA[1], digest)

    return (dumpPEM(cert, 0), dumpPEM(pubkey, 1))
Esempio n. 12
0
def get_cert():
    from binascii import b2a_base64 as to_base64
    from OpenSSL import crypto
    from fluxmonitor.storage import Storage
    s = Storage("security", "private")

    try:
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, s["sslkey.pem"])
    except (crypto.Error, TypeError):
        pkey = get_private_key()
        s["sslkey.pem"] = pem = pkey.export_pem()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, pem)

    try:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, s["cert2.pem"])
    except (crypto.Error, TypeError):
        issuersubj = crypto.X509Name(crypto.X509().get_subject())
        issuersubj.C = "TW"
        issuersubj.L = "Taipei"
        issuersubj.O = "FLUX Inc."

        cert = crypto.X509()
        subj = cert.get_subject()

        subj.O = "FLUX 3D Delta Printer"
        subj.CN = (get_uuid() + ":" + get_serial() + ":")
        ext = crypto.X509Extension("nsComment", True,
                                   to_base64(get_identify()))
        cert.add_extensions((ext, ))

        cert.set_serial_number(1001)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(60 * 365 * 24 * 60 * 60)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key)
        cert.sign(key, 'sha512')
        s["cert2.pem"] = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

    return s.get_path("cert2.pem"), s.get_path("sslkey.pem")
Esempio n. 13
0
import logging
import time
import os

try:
    from OpenSSL import crypto
except ImportError:
    logging.error('You should install `OpenSSL`, run `sudo pip install pyopenssl` or other command depends on your system.')
    sys.exit(-1)


CA = None
CALock = threading.Lock()
EXPIRE_DELAY = 60*60*24*365*10 # 10 years

CERT_SUBJECTS = crypto.X509Name(crypto.X509().get_subject())
CERT_SUBJECTS.C = 'CN'
CERT_SUBJECTS.ST = 'SiChuan'
CERT_SUBJECTS.L = 'SiChuan Univ.'
CERT_SUBJECTS.OU = 'KeepAgent Branch'


CA_SUBJECTS = crypto.X509Name(CERT_SUBJECTS)
CA_SUBJECTS.OU = 'KeepAgent Root'
CA_SUBJECTS.O = 'KeepAgent'
CA_SUBJECTS.CN = 'KeepAgent CA'

def readBinFile(filename):
    with open(filename, 'rb') as f:
        content = f.read()
    return content
Esempio n. 14
0
    def _verify_cert(self, conn, cert, errnum, depth, ok):
        certsubject = crypto.X509Name(cert.get_subject())
        commonname = certsubject.commonName

        return ok
 def _VerifyCb(conn, cert, errnum, depth, ok):
     certsubject = crypto.X509Name(cert.get_subject())
     commonname = certsubject.commonName
     logging.debug('TLS handshake verify: certificate: %s  -> %d',
                   commonname, ok)
     return ok
    def verify_cb(conn, cert, errnum, depth, ok):
        certsubject = crypto.X509Name(cert.get_subject())
        CN = cert.get_issuer().commonName
        if 'CA_COMMON_NAME' in config['CERTIFICATE']:
            CA_COMMON_NAME = config['CERTIFICATE']['CA_COMMON_NAME']
            if not CA_COMMON_NAME:
                CA_COMMON_NAME = None
        else:
            warn = '请在初始化文件config.ini中加入字段CA_COMMON_NAME以验证证书!'
            box.showwarning(title='初始化错误', message=warn, parent=root)
            return False
        if depth == 1:
            if CN != CA_COMMON_NAME:
                return False
        elif depth == 0:
            if 'CERTIFICATE' not in config:
                warn = '请在初始化文件config.ini中加入字段[CERTIFICATE]!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return
            if 'SERIAL_NUMBER' in config['CERTIFICATE']:
                SERIAL_NUMBER = config['CERTIFICATE']['SERIAL_NUMBER']
                try:
                    SERIAL_NUMBER = int(SERIAL_NUMBER, 16)
                except:
                    warn = '请以16进制的形式输入SERIAL_NUMBER!'
                    box.showwarning(title='初始化错误', message=warn, parent=root)
                    return False
            else:
                warn = '请在初始化文件config.ini中加入字段SERIAL_NUMBER以验证证书序列号!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'COMMON_NAME' in config['CERTIFICATE']:
                COMMON_NAME = config['CERTIFICATE']['COMMON_NAME']
                if not COMMON_NAME:
                    COMMON_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段COMMON_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'ORGANIZATIONAL_UNIT_NAME' in config['CERTIFICATE']:
                ORGANIZATIONAL_UNIT_NAME = config['CERTIFICATE'][
                    'ORGANIZATIONAL_UNIT_NAME']
                if not ORGANIZATIONAL_UNIT_NAME:
                    ORGANIZATIONAL_UNIT_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段ORGANIZATIONAL_UNIT_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'ORGANIZATION_NAME' in config['CERTIFICATE']:
                ORGANIZATION_NAME = config['CERTIFICATE']['ORGANIZATION_NAME']
                if not ORGANIZATION_NAME:
                    ORGANIZATION_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段ORGANIZATION_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'STATE_OR_PROVINCE_NAME' in config['CERTIFICATE']:
                STATE_OR_PROVINCE_NAME = config['CERTIFICATE'][
                    'STATE_OR_PROVINCE_NAME']
                if not STATE_OR_PROVINCE_NAME:
                    STATE_OR_PROVINCE_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段STATE_OR_PROVINCE_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'COUNTRY_NAME' in config['CERTIFICATE']:
                COUNTRY_NAME = config['CERTIFICATE']['COUNTRY_NAME']
                if not COUNTRY_NAME:
                    COUNTRY_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段COUNTRY_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'LOCALITY_NAME' in config['CERTIFICATE']:
                LOCALITY_NAME = config['CERTIFICATE']['LOCALITY_NAME']
                if not LOCALITY_NAME:
                    LOCALITY_NAME = None
            else:
                warn = '请在初始化文件config.ini中加入字段LOCALITY_NAME以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False
            if 'EMAIL_ADDRESS' in config['CERTIFICATE']:
                EMAIL_ADDRESS = config['CERTIFICATE']['EMAIL_ADDRESS']
                if not EMAIL_ADDRESS:
                    EMAIL_ADDRESS = None
            else:
                warn = '请在初始化文件config.ini中加入字段EMAIL_ADDRESS以验证证书!'
                box.showwarning(title='初始化错误', message=warn, parent=root)
                return False

            CN = certsubject.commonName
            OU = certsubject.organizationalUnitName
            O = certsubject.organizationName
            S = certsubject.stateOrProvinceName
            C = certsubject.countryName
            L = certsubject.localityName
            EMail = certsubject.emailAddress

            if CN != COMMON_NAME or OU != ORGANIZATIONAL_UNIT_NAME or\
                O != ORGANIZATION_NAME or S != STATE_OR_PROVINCE_NAME or\
                C != COUNTRY_NAME or L != LOCALITY_NAME or EMail != EMAIL_ADDRESS:
                return False
            if cert.get_serial_number() != SERIAL_NUMBER:
                return False
            if cert.has_expired():
                return False
        return ok
Esempio n. 17
0
def examine_certificate(conn, cert, errnum, depth, ok):
    subject = crypto.X509Name(cert.get_subject())
    common_name = subject.commonName
    util.logger("Received certificate from client CN={%s}, depth={%d}",
                common_name, depth)
    return ok
Esempio n. 18
0
def verify_cb(conn, cert, errnum, depth, ok):
    certsubject = crypto.X509Name(cert.get_subject())
    commonname = certsubject.commonName
    print 'C> GOT CERT: %s' % cert.get_subject()
    return ok
Esempio n. 19
0
def verify_cb(conn, cert, errnum, depth, ok):
    certsubject = crypto.X509Name(cert.get_subject())
    commonname = certsubject.commonName
    print('Got certificate: ' + commonname)
    return ok
Esempio n. 20
0
    def get_imovies_name(self):

        name = crypto.X509Name(crypto.X509().get_subject())
        name.O = "Imovies"
        return name