def mkreq(self, bits, ca=0):
        pk = EVP.PKey()
        x = X509.Request()
        rsa = RSA.gen_key(bits, 65537, self.callback)
        pk.assign_rsa(rsa)
        rsa = None  # should not be freed here
        x.set_pubkey(pk)
        name = x.get_subject()
        name.C = "UK"
        name.CN = "OpenSSL Group"
        if not ca:
            ext1 = X509.new_extension('subjectAltName',
                                      'DNS:foobar.example.com')
            ext2 = X509.new_extension('nsComment', 'Hello there')
            extstack = X509.X509_Extension_Stack()
            extstack.push(ext1)
            extstack.push(ext2)
            x.add_extensions(extstack)

        with self.assertRaises(ValueError):
            x.sign(pk, 'sha513')

        x.sign(pk, 'sha1')
        self.assertTrue(x.verify(pk))
        pk2 = x.get_pubkey()
        self.assertTrue(x.verify(pk2))
        return x, pk
    def test_extstack(self):
        # new
        ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
        ext2 = X509.new_extension('nsComment', 'Hello there')
        extstack = X509.X509_Extension_Stack()

        # push
        extstack.push(ext1)
        extstack.push(ext2)
        self.assertEqual(extstack[1].get_name(), 'nsComment')
        self.assertEqual(len(extstack), 2)

        # iterator
        i = 0
        for e in extstack:
            i += 1
            self.assertGreater(len(e.get_name()), 0)
        self.assertEqual(i, 2)

        # pop
        ext3 = extstack.pop()
        self.assertEqual(len(extstack), 1)
        self.assertEqual(extstack[0].get_name(), 'subjectAltName')
        extstack.push(ext3)
        self.assertEqual(len(extstack), 2)
        self.assertEqual(extstack[1].get_name(), 'nsComment')

        self.assertIsNotNone(extstack.pop())
        self.assertIsNotNone(extstack.pop())
        self.assertIsNone(extstack.pop())
示例#3
0
def makeRequest(pk):
    """
    Creates a new CSR from an RSA key
    :param pk: RSA key
    :return: CSR
    """
    pkey = EVP.PKey()
    pkey.assign_rsa(pk)
    req = X509.Request()
    req.set_version(2)
    req.set_pubkey(pkey)
    name = X509.X509_Name()
    name.CN = 'cirosec gmbh'
    req.set_subject_name(name)
    ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
    ext2 = X509.new_extension('nsComment', 'Hello there')
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext1)
    extstack.push(ext2)

    assert (extstack[1].get_name() == 'nsComment')

    req.add_extensions(extstack)
    req.sign(pkey, 'sha1')
    return req
示例#4
0
def make_csr(key_file, domains):
    """
    Returns new CSR in PEM and DER form using key_file containing all domains
    """
    assert domains, "Must provide one or more hostnames for the CSR."
    rsa_key = M2Crypto.RSA.load_key(key_file)
    pk = EVP.PKey()
    pk.assign_rsa(rsa_key)

    x = X509.Request()
    x.set_pubkey(pk)
    name = x.get_subject()
    name.C = "US"
    name.ST = "Michigan"
    name.L = "Ann Arbor"
    name.O = "EFF"
    name.OU = "University of Michigan"
    name.CN = domains[0]

    extstack = X509.X509_Extension_Stack()
    ext = X509.new_extension('subjectAltName', ", ".join(["DNS:%s" % d for d in domains]))

    extstack.push(ext)
    x.add_extensions(extstack)
    x.sign(pk,'sha256')
    assert x.verify(pk)
    pk2 = x.get_pubkey()
    assert x.verify(pk2)
    return x.as_pem(), x.as_der()
示例#5
0
    def test_extstack(self):
        # new
        ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
        ext2 = X509.new_extension('nsComment', 'Hello there')
        extstack = X509.X509_Extension_Stack()

        # push
        extstack.push(ext1)
        extstack.push(ext2)
        assert (extstack[1].get_name() == 'nsComment')
        assert len(extstack) == 2

        # iterator
        i = 0
        for e in extstack:
            i += 1
            assert len(e.get_name()) > 0
        assert i == 2

        # pop
        ext3 = extstack.pop()
        assert len(extstack) == 1
        assert (extstack[0].get_name() == 'subjectAltName')
        extstack.push(ext3)
        assert len(extstack) == 2
        assert (extstack[1].get_name() == 'nsComment')

        assert extstack.pop() is not None
        assert extstack.pop() is not None
        assert extstack.pop() is None
示例#6
0
def _make_cert_request(cn, rsa, uid=None):
    pub_key = EVP.PKey()
    request = X509.Request()
    pub_key.assign_rsa(rsa)
    request.set_pubkey(pub_key)
    subject = request.get_subject()
    subject.nid['UID'] = 458  # openssl lacks support for userid
    subject.CN = "%s" % cn
    if uid:
        subject.UID = uid
    ext2 = X509.new_extension('nsComment', 'Pulp Identity Certificate for Consumer: [%s]' % cn)
    extensions = X509.X509_Extension_Stack()
    extensions.push(ext2)
    request.add_extensions(extensions)
    request.sign(pub_key, 'sha256')
    return request, pub_key
示例#7
0
def _make_cert_request(uid, rsa):
    pub_key = EVP.PKey()
    x = X509.Request()
    pub_key.assign_rsa(rsa)
    rsa = None  # should not be freed here
    x.set_pubkey(pub_key)
    name = x.get_subject()
    name.CN = "%s" % uid
    ext2 = X509.new_extension(
        'nsComment',
        'Pulp Generated Identity Certificate for Consumer: [%s]' % uid)
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext2)
    x.add_extensions(extstack)
    x.sign(pub_key, 'sha1')
    pk2 = x.get_pubkey()
    return x, pub_key
示例#8
0
def make_request(pkey, cn):
    req = X509.Request()
    req.set_version(2)
    req.set_pubkey(pkey)
    name = X509.X509_Name()
    name.CN = cn
    req.set_subject_name(name)
    ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com')
    ext2 = X509.new_extension('nsComment', 'Hello there')
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext1)
    extstack.push(ext2)

    assert (extstack[1].get_name() == 'nsComment')

    req.add_extensions(extstack)
    return req
示例#9
0
def set_csr_xmppwebid(csr, id_xmpp, webid):
    """Set the CSR SubjectAltName and Subject

    :param csr:  x509 request
    :type csr: X509.Request    
    :param id_xmpp: xmpp id
    :param webid: FOAF WebId
    :type id_xmpp: string
    :type webid: string
    :return: x509 request
    :rtype: X509.Request
    
    """
    # if the req is going to be signed by a ca
    # there is not need to add CN because the ca cert is going to overwrite it
    # optional
    # Create a new X509_Name object for our new certificate
    x509_name = X509.X509_Name()
    x509_name.O = O
    x509_name.OU = OU  #+"/UID="+webid
    # set Subject commonName
    x509_name.CN = "(Personal)"  #+webid + "/"+ ID_ON_XMPPADDR_OID + "=" + id_xmpp

    #    x509_name.add_entry_by_txt(field='CN', type=MBSTRING_ASC,
    #        entry='(Personal)'+webid +
    #              '/'+ ID_ON_XMPPADDR_OID + '=' + id_xmpp, len=-1, loc=-1, set=0 )

    logging.debug("Subject name in CSR: %s" % x509_name)
    print "Subject name in CSR: %s" % x509_name

    # Set the subject
    csr.set_subject_name(x509_name)

    # set subjectAltName extension
    ext1 = X509.new_extension(
        'subjectAltName',
        'URI:%s, otherName:%s;UTF8:%s' % (webid, ID_ON_XMPPADDR_OID, id_xmpp))
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext1)
    csr.add_extensions(extstack)
    return csr
示例#10
0
文件: pgcert.py 项目: dimv36/UIR
def make_request(private_key_path, username, user_context, critical, output,
                 is_printed):
    private_key = None
    try:
        private_key = RSA.load_key(private_key_path, callback=password)
    except (IOError, RSA.RSAError):
        print('ERROR request: Could not load key pair from %s' %
              private_key_path)
        exit(1)
    request = X509.Request()
    request.set_pubkey(private_key)
    request.set_version(2)
    name = X509.X509_Name()
    name.C = DEFAULT_FIELDS['C']
    name.ST = DEFAULT_FIELDS['ST']
    name.L = DEFAULT_FIELDS['L']
    name.O = DEFAULT_FIELDS['O']
    name.OU = DEFAULT_FIELDS['OU']
    name.CN = username
    if user_context:
        context = user_context
    else:
        context = getcon_raw()[1]
    if not context:
        print('ERROR request: Could not get SELinux context for user %s' %
              username)
        exit(1)
    request.set_subject_name(name)
    stack = X509.X509_Extension_Stack()
    stack.push(X509.new_extension('selinuxContext', context, int(critical)))
    request.add_extensions(stack)
    request.sign(private_key, 'sha1')
    if not output:
        output = path.abspath(path.curdir) + '/%s.csr' % DEFAULT_FIELDS['CN']
    request.save_pem(output)
    if is_printed:
        print(request.as_text())
    print('Request was saved to %s' % output)
示例#11
0
    def __init__(self,
                 hostname,
                 output_dir=None,
                 altnames=None,
                 location=None):
        """
        Create a certificate signing request (CSR - stored in the x509request attribute) and associated keys (stored in keypair attribute).
       
        The caller should use write_csr to write CSR when ready. 
        The caller should use write_pkey to write private key when ready.
  
        INPUT
            - hostname: common name for the CN field 
            - output_dir (optional): The destination directory to write the request and key
            - altnames (optional): Additional hostnames to be added to the Subject Alternative Names.
            - location (optional): A namedtuple containing country (e.g., US), state (e.g., Wisconsin),
            locality (e.g., Madison), and organization (e.g., University of Wisconsin)
        """
        self.output_dir = output_dir
        # TODO this check should come from the main commands
        if not output_dir:
            self.output_dir = os.getcwd()

        # Set up CSR and PKEY file paths
        self.csrpath = os.path.join(output_dir, hostname + '.req')
        self.keypath = os.path.join(output_dir, hostname + '-key.pem')

        self.keypair = RSA.gen_key(self.KEY_LENGTH, self.PUB_EXPONENT,
                                   lambda: None)

        # The message digest shouldn't matter here since we don't use
        # PKey.sign_*() or PKey.verify_*() but there's no harm in keeping it and
        # it ensures a strong hashing algo (default is sha1) if we do decide to
        # sign things in the future
        self.pkey = EVP.PKey(md='sha256')
        self.pkey.assign_rsa(self.keypair)

        self.x509request = X509.Request()
        x509name = X509.X509_Name()

        # Build entries for x509 name
        entries = list()
        entries.append(('CN', hostname))

        if location:
            entries.append(('C', location.country))
            entries.append(('ST', location.state))
            entries.append(('L', location.locality))
            entries.append(('O', location.organization))

        for key, val in entries:
            x509name.add_entry_by_txt(field=key,
                                      type=MBSTRING_ASC,
                                      entry=val,
                                      len=-1,
                                      loc=-1,
                                      set=0)

        self.x509request.set_subject_name(x509name)

        # Build altnames
        self.altnames = None

        if altnames:
            str_altnames = ",".join(altnames)
            self.altnames = str_altnames
            extension_stack = X509.X509_Extension_Stack()
            extension = X509.new_extension(
                'subjectAltName',
                ", ".join(['DNS:%s' % name for name in altnames]))
            extension.set_critical(1)
            extension_stack.push(extension)
            self.x509request.add_extensions(extension_stack)

        # Set up pubkey and sign CSR with privkey
        self.x509request.set_pubkey(pkey=self.pkey)
        self.x509request.set_version(0)
        self.x509request.sign(pkey=self.pkey, md='sha256')