예제 #1
0
파일: webapid.py 프로젝트: GaetanF/ManPKI
 def cmd_ca_sign(self, data):
     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, base64.b64decode(data['cert']))
     cert.add_extensions([
         OpenSSL.crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=SSL.get_ca())
     ])
     capriv = SSL.get_ca_privatekey()
     certsigned = SSL.sign(cert, capriv, str(data['digest']))
     return 'OK', OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, certsigned)
예제 #2
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
 def show_ca_detail(self):
     self.show_ca()
     if SSL.check_ca_exist():
         print "##################################################"
         print "### Detail"
         SSL.display_cert(SSL.get_ca())
     else:
         print "Cannot get details. CA not created yet"
예제 #3
0
파일: ShLdap.py 프로젝트: GaetanF/ManPKI
 def do_test(self, line):
     print LDAP().get_password()
     try:
         if LDAP().check_dn_exist(SSL.get_ca()):
             print "BaseDN : " + LDAP().get_basedn()
             print "Connection and require object successful"
         elif LDAP().check_dn_exist(SSL.get_ca(), depth=1):
             print "Connection successful. Required object need to be created"
         else:
             print "Connection OK. Require Base DN not exist"
     except ldap.CONNECT_ERROR:
         print "Unable to connect"
예제 #4
0
파일: ShCert.py 프로젝트: GaetanF/ManPKI
    def display_profile(self, profile):
        keys = str(Config().config.get("profile_" + profile, "keyusage")).split("|")
        print "\tKey Usage"
        for (k, v) in SSL.get_key_usage().iteritems():
            if k in keys:
                print "\t\t%s" % v

        keys = str(Config().config.get("profile_" + profile, "extended")).split("|")
        print "\tExtended Key Usage"
        for (k, v) in SSL.get_extended_key_usage().iteritems():
            if k in keys:
                print "\t\t%s" % v
예제 #5
0
파일: ShDane.py 프로젝트: GaetanF/ManPKI
 def do_generate(self, line):
     if " " in line and len(line.split(" ")) == 4:
         (proto, port, fqdn, certid) = line.split(" ")
         if proto in ("tcp", "udp"):
             if 1 < int(port) < 65535:
                 if SSL.check_cert_exist(certid):
                     hash = hashlib.sha256(SSL.get_asn_cert_raw(certid)).hexdigest()
                     print "_%s._%s.%s.\tIN\tTLSA\t3 0 1 ( %s )" % (port, proto, fqdn, hash)
                 else:
                     print "*** Certificate does not exist"
             else:
                 print "*** Invalid port number"
         else:
             print "*** Invalid protocol"
     else:
         print "generate <proto> <port> <fqdn> <certid>"
예제 #6
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
 def show_ca(self):
     for name in Config().config.options("ca"):
         value = Config().config.get("ca", name)
         print '  %-12s : %s' % (name.title(), value)
     if SSL.check_ca_exist():
         print "Status : OK"
     else:
         print "Status : Not Created"
예제 #7
0
파일: ShOcsp.py 프로젝트: GaetanF/ManPKI
 def do_cert(self, line):
     if SSL.check_cert_exist(line):
         cert = SSL.get_cert(line)
         keyusage = ["digitalSignature", "nonRepudiation", "keyEncipherment"]
         extendedkeys = ["1.3.6.1.5.5.7.3.9"]
         if SSL.cert_equal_to_key_and_extended_key(cert, keyusage, extendedkeys, strict=False):
             Config().config.set("ocsp", "cert", line)
         else:
             print "Certificate is not valid to use with OCSP Responder"
     else:
         profile = Render.select_profile()
         certid = Render.select_cert(profile=profile)
         Config().config.set("ocsp", "cert", certid)
     if Config().config.getboolean("ocsp", "enable") and len(Config().config.get("ocsp", "cert")) > 0:
         Daemons.start_daemon("ocsp")
     else:
         print "OCSP must be enable and valid certificate for responder must be present"
예제 #8
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
 def do_create(self, line):
     if not SSL.check_ca_exist():
         self.create_ca()
     else:
         if raw_input("Do you want to erase current CA ? (y/n) :").lower() == "y":
             print "All sub certificates will be resigned"
             self.create_ca(force=True)
         else:
             print "*** CA already created !"
예제 #9
0
파일: ShCert.py 프로젝트: GaetanF/ManPKI
 def do_profile(self, line):
     if line:
         profile = line.split(' ')[0]
     else:
         profile = raw_input("Profile name : ")
     keys_usage = []
     extended_keys = []
     if Config().config.has_section("profile_" + profile):
         keys_usage = str(Config().config.get("profile_" + profile, "keyusage")).split('|')
         extended_keys = str(Config().config.get("profile_" + profile, "extended")).split('|')
     else:
         Config().config.add_section("profile_"+profile)
     keys_usage = Render.print_selector(SSL.get_key_usage(), keys_usage)
     extended_keys = Render.print_selector(SSL.get_extended_key_usage(), extended_keys)
     Config().config.set("profile_" + profile, "keyusage", '|'.join(keys_usage))
     Config().config.set("profile_" + profile, "extended", '|'.join(extended_keys))
     rep = raw_input("Use LDAP if enable to search subject (y/n) : ")
     if "y" in rep:
         filter = raw_input("LDAP Filter : ")
         Config().config.set("profile_" + profile, "ldap", filter)
     else:
         Config().config.set("profile_" + profile, "ldap", "false")
예제 #10
0
파일: ShCert.py 프로젝트: GaetanF/ManPKI
 def do_revoke(self, line):
     if line:
         i=0
         for cert in SSL.get_all_certificates():
             if line == cert['id']:
                 i = 1
                 print "Reason : "
                 reasons = crypto.Revoked().all_reasons()
                 for (k, v) in enumerate(reasons):
                     print " %s: %s" % (k, v)
                 res = raw_input("Select reason : ")
                 if res.isdigit() and 0 <= int(res) < len(reasons):
                     revoked = crypto.Revoked()
                     revoked.set_reason(reasons[int(res)])
                     revoked.set_serial(hex(cert['cert'].get_serial_number())[2:-1])
                     revoked.set_rev_date(datetime.utcnow().strftime("%Y%m%d%H%M%S%Z")+"Z")
                     SSL.add_revoked(revoked)
                 else:
                     print "*** Reason is not valid"
         if i == 0:
             print "*** Certificate not found"
     else:
         print "revoke <certid>"
예제 #11
0
파일: ShCert.py 프로젝트: GaetanF/ManPKI
    def show_cert(self, certid=None):
        list = []
        if certid:
            rawmode = False
            if "_" in certid and certid.split("_")[1] == "raw":
                rawmode = True
                certid = certid.split("_")[0]
            i=0
            for cert in SSL.get_all_certificates():
                if certid == cert['id']:
                    i = 1
                    SSL.display_cert(cert['cert'])
                    if rawmode:
                        print crypto.dump_certificate(crypto.FILETYPE_PEM, cert['cert'])
            if i == 0:
                print "*** Certificate not found"
        else:

            for cert in SSL.get_all_certificates():
                state = SSL.get_state_cert(cert['cert'])
                list.append((cert['id'], SSL.get_x509_name(cert['cert'].get_subject()), state))
            Render.print_table(('ID', 'Subject', 'State'), list)
예제 #12
0
파일: ocspd.py 프로젝트: GaetanF/ManPKI
    def do_POST(self):
        parsed_path = urlparse.urlparse(self.path)
        if self.headers['content-type'] in "application/ocsp-request":
            content = self.rfile.read(int(self.headers['content-length']))
            request, rest = decoder.decode(content, asn1Spec=rfc2560.OCSPRequest())

            tbsRequest = request.getComponentByName('tbsRequest')
            reqExt = tbsRequest.getComponentByName('requestExtensions')
            #TODO manage multiple request cert
            certRequest = tbsRequest.getComponentByName('requestList').getComponentByPosition(0)
            reqCert = certRequest.getComponentByName('reqCert')

            ocsp_cert_path = SSL.get_cert_path(Config().config.get("ocsp", "cert"))
            ocsp_cert_privatekey_path = SSL.get_cert_privatekey_path(Config().config.get("ocsp", "cert"))
            ocsp_cert, rt = decoder.decode(
                pem.readPemBlocksFromFile(
                    open(ocsp_cert_path, 'r'), ('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----')
                )[1],
                asn1Spec=rfc2459.Certificate()
            )
            pkey = open(ocsp_cert_privatekey_path, "rt").read()
            ocsp_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey)
            str_pub_key = pem_publickey(ocsp_key)
            rsa_key = RSA.importKey(str_pub_key).exportKey(format='DER')
            hexrsa = hashlib.sha1(rsa_key).hexdigest()

            basic_ocsp_response = rfc2560.BasicOCSPResponse()
            tbs_response_data = basic_ocsp_response.setComponentByName('tbsResponseData').getComponentByName('tbsResponseData')

            responderid = tbs_response_data.setComponentByName('responderID').getComponentByName('responderID')
            responderid.setComponentByName('byKey', hexrsa.decode('hex'))

            tbs_response_data.setComponentByName('producedAt', useful.GeneralizedTime("20150728210000Z"))
            response_list = tbs_response_data.setComponentByName('responses').getComponentByName('responses')

            response = response_list.setComponentByPosition(0).getComponentByPosition(0)
            response.setComponentByName('certID', reqCert)

            certStatus = response.setComponentByName('certStatus').getComponentByName('certStatus')
            certStatus.setComponentByName('good')

            response.setComponentByName('thisUpdate', useful.GeneralizedTime("20150728211000Z"))

            signalgorithm = basic_ocsp_response.setComponentByName('signatureAlgorithm').getComponentByName('signatureAlgorithm')
            signalgorithm.setComponentByName('algorithm', rfc2459.sha1WithRSAEncryption)
            signalgorithm.setComponentByName('parameters', b'\x05\x00')

            hashsha1 = hashlib.sha1(encoder.encode(tbs_response_data))

            sign = OpenSSL.crypto.sign(ocsp_key, hashsha1.digest(), 'sha1')

            basic_ocsp_response.setComponentByName('signature', ("'%s'B" % BytesToBin(sign)))

            ocsp_response = rfc2560.OCSPResponse()
            ocsp_response.setComponentByName('responseStatus', rfc2560.OCSPResponseStatus('successful'))

            response_bytes = ocsp_response.setComponentByName('responseBytes').getComponentByName('responseBytes')
            response_bytes.setComponentByName('responseType', rfc2560.id_pkix_ocsp_basic)
            response_bytes.setComponentByName('response', encoder.encode(basic_ocsp_response))

            status_code = 200
        else:
            ocsp_response = rfc2560.OCSPResponse()
            ocsp_response.setComponentByName('responseStatus', rfc2560.OCSPResponseStatus('malformedRequest'))
            status_code = 400

        self.send_response(status_code)
        self.send_header('Content-type', 'application/ocsp-response')
        self.end_headers()
        self.wfile.write(encoder.encode(ocsp_response))
예제 #13
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
 def show_ca_raw(self):
     if SSL.check_ca_exist():
         print crypto.dump_certificate(crypto.FILETYPE_PEM, SSL.get_ca())
     else:
         print "Cannot get details. CA not created yet"
예제 #14
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
 def resigned_all_cert(self):
     for certhash in SSL.get_all_certificates():
         cert_signed = SSL.sign(certhash['cert'], SSL.get_ca_privatekey(), Config().config.get("cert", "digest"))
         SSL.delete_cert(certhash['id'])
         SSL.set_cert(cert_signed)
예제 #15
0
파일: ShCa.py 프로젝트: GaetanF/ManPKI
    def create_ca(self, force=False):
        if Config().config.get("ca", "type") == "subca":
            api = API(Config().config.get("ca", "parentca"))
        before = datetime.utcnow()
        after = before + timedelta(days=Config().config.getint("ca", "validity"))

        pkey = SSL.create_key(Config().config.getint("ca", "key_size"))

        ca = SSL.create_cert(pkey)
        subject = Config().config.get("ca", "base_cn") + "/CN=" + Config().config.get("ca", "name")
        subject_x509 = SSL.parse_str_to_x509Name(subject, ca.get_subject())
        if Config().config.get("ca", "type") == "rootca":
            issuer_x509 = SSL.parse_str_to_x509Name(subject, ca.get_issuer())

        if Config().config.get("ca", "email"):
            subject_x509.emailAddress = Config().config.get("ca", "email")

        if Config().config.get("ca", "type") == "rootca":
            issuer_x509.emailAddress = Config().config.get("ca", "email")

        ca.set_subject(subject_x509)
        if Config().config.get("ca", "type") == "rootca":
            ca.set_issuer(issuer_x509)
        ca.set_notBefore(before.strftime("%Y%m%d%H%M%S%Z")+"Z")
        ca.set_notAfter(after.strftime("%Y%m%d%H%M%S%Z")+"Z")
        ca.set_serial_number(int(time() * 1000000))
        ca.set_version(2)

        bsConst = "CA:TRUE"
        if Config().config.getboolean("ca", "isfinal"):
            bsConst += ", pathlen:0"
        ca.add_extensions([
            crypto.X509Extension("basicConstraints", True, bsConst),
            crypto.X509Extension("keyUsage", True, "keyCertSign, cRLSign"),
            crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=ca),
        ])
        if Config().config.get("ca", "type") == "rootca":
            ca.add_extensions([
                crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca)
            ])

        # if EventManager.hasEvent("new_cert"):
        #     ca = EventManager.new_cert(ca)

        if Config().config.getboolean("crl", "enable"):
            crlUri = "URI:" + Config().config.get("crl", "uri")
            ca.add_extensions([
                crypto.X509Extension("crlDistributionPoints", False, crlUri)
            ])

        if Config().config.getboolean("ocsp", "enable"):
            ocspUri = "OCSP;URI:" + Config().config.get("ocsp", "uri")
            ca.add_extensions([
                crypto.X509Extension("authorityInfoAccess", False, ocspUri)
            ])

        if Config().config.get("ca", "type") == "subca":
            data = api.push("ca_sign", {
                "digest": Config().config.get("ca", "digest"),
                "cert": api.encode_cert(ca)
            })
            if data['state'] == 'OK':
                ca_signed = api.decode_cert(data['response'])
            else:
                print "Error during sign from remote API of Parent CA"
                return False
        else:
            ca_signed = SSL.sign(ca, pkey, Config().config.get("ca", "digest"))

        SSL.set_ca(ca_signed)
        SSL.set_ca_privatekey(pkey)

        if Config().config.getboolean("ldap", "enable"):
            LDAP.add_queue(ca_signed)

        if force:
            self.resigned_all_cert()
예제 #16
0
__author__ = 'ferezgaetan'

from Tools import Mailer, SSL

if SSL.generate_crl():
    ca = SSL.get_ca()
    if ca.get_subject().emailAddress:
        mail = Mailer()
        mail.to(ca.get_subject().emailAddress)
        mail.subject("CRL Creation")
        mail.send("CRL file has been created")
예제 #17
0
파일: ShCert.py 프로젝트: GaetanF/ManPKI
    def create_cert(self, profile):
        before = datetime.utcnow()
        after = before + timedelta(days=Config().config.getint("cert", "validity"))

        pkey = SSL.create_key(Config().config.getint("cert", "key_size"))

        ca = SSL.get_ca()
        cert = SSL.create_cert(pkey)
        if Config().config.get("ldap", "enable") and "false" not in Config().config.get("profile_" + profile, "ldap"):
            print "Search in LDAP"
            l = LDAP()
            filter = Config().config.get("profile_" + profile, "ldap")
            res = l.get_dn(l.get_basedn(), filter, ['cn', 'mail', 'uid'])
            listSearch = {}
            users = {}
            for elt in res:
                key = elt[0]
                val = elt[1]['cn'][0]
                mail = None
                if 'mail' in elt[1].keys():
                    mail = elt[1]['mail'][0]
                    val = val + " (mail : " + elt[1]['mail'][0] + ")"
                listSearch.update({key: val})
                users.update({key: {'mail': mail, 'cn': elt[1]['cn'][0]}})
            nbr_select = 0
            while nbr_select != 1:
                userList = Render.print_selector(listSearch)
                nbr_select = len(userList)
            email = users[userList[0]]['mail']
            cn = users[userList[0]]['cn']
            subject_array = userList[0].split(',')
            subject_array.reverse()
            subject_array.pop()
            subject = '/'.join(subject_array) + "/CN=" + cn
        else:
            cn = raw_input("Common Name : ")
            email = raw_input("Mail address : ")
            subject = Config().config.get("ca", "base_cn") + "/CN=" + cn
        subject_x509 = SSL.parse_str_to_x509Name(subject, cert.get_subject())

        issuer_x509 = ca.get_subject()
        if email:
            subject_x509.emailAddress = email

        cert.set_subject(subject_x509)
        cert.set_issuer(issuer_x509)
        cert.set_notBefore(before.strftime("%Y%m%d%H%M%S%Z")+"Z")
        cert.set_notAfter(after.strftime("%Y%m%d%H%M%S%Z")+"Z")
        cert.set_serial_number(int(time() * 1000000))
        cert.set_version(2)

        bsConst = "CA:FALSE"
        cert.add_extensions([
            crypto.X509Extension("basicConstraints", True, bsConst),
            crypto.X509Extension("keyUsage", True, SSL.get_key_usage_from_profile(profile)),
            crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=cert),
        ])
        cert.add_extensions([
            crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca)
        ])
        cert.add_extensions([
            crypto.X509Extension("extendedKeyUsage", False, SSL.get_extended_key_usage_from_profile(profile))
        ])

        if Config().config.getboolean("crl", "enable"):
            crlUri = "URI:" + Config().config.get("crl", "uri")
            cert.add_extensions([
                crypto.X509Extension("crlDistributionPoints", False, crlUri)
            ])

        if Config().config.getboolean("ocsp", "enable"):
            ocspUri = "OCSP;URI:" + Config().config.get("ocsp", "uri")
            cert.add_extensions([
                crypto.X509Extension("authorityInfoAccess", False, ocspUri)
            ])

        cert_signed = SSL.sign(cert, SSL.get_ca_privatekey(), Config().config.get("cert", "digest"))
        SSL.set_cert(cert_signed)
        SSL.set_cert_privatekey(cert_signed, pkey)

        if Config().config.getboolean("ldap", "enable"):
                LDAP.add_queue(cert_signed)