Ejemplo n.º 1
0
    def get_certificates(self, status=None):
        """Returns all the certificates attached to a master

        Optionally you can specify a `status` for the certificates. The statuses can either be
          * "SIGNATURE PENDING"
          * "SIGNED"
          * "REVOKED"
        If status is None, all the certifictes will be returned regardless of their status

        Note that it is just for conveinence that this option is provided. From the API's point
        of view we will issue the same request anyway.

        :param status: The status of the certificates
        :type status: str

        :return: A list of matching certificates
        :rtype: List of ppaas.Certificate

        """
        if status is None:
            return Certificate.get_certificates(self, self.client)
        else:
            certificates = Certificate.get_certificates(self, self.client)
            return [
                cert for cert in certificates
                if cert.status['message'] == status
            ]
Ejemplo n.º 2
0
 def __init__(self, name):
     self.__name = name
     print("{} created".format(name))
     self.__key = KeyPairRSA()
     self.__cert = Certificate(name=name,
                               key_pair_rsa=self.__key,
                               validity_date=10)
Ejemplo n.º 3
0
def main():
    lista = load_csv()

    for cert in lista:
        svg = load_svg(cert)
        certificado = Certificate(svg)
        certificado.save()
Ejemplo n.º 4
0
def create_p12(logger, ctx, name, pem, key, password, config, force, verbose,
               debug):
    """
    \b
    Create a simple p12
    Need key file and pem file
    \f

    :param logger:
    :param ctx:
    :param name:
    :param pem:
    :param key:
    :param password:
    :param config:
    :param force:
    :param verbose:
    :param debug:
    :return:
    """
    tools.set_options(ctx=ctx, config=config, verbose=verbose, debug=debug)

    cert = Certificate(logger=logger, opts=tools.opts)
    cert.generate_p12(key=key,
                      pem=pem,
                      p12=name,
                      password=password,
                      force=force)
Ejemplo n.º 5
0
class Equipment:
    def __init__(self, name):
        self.__name = name
        print("{} created".format(name))
        self.__key = KeyPairRSA()
        self.__cert = Certificate(name=name,
                                  key_pair_rsa=self.__key,
                                  validity_date=10)

    def name(self):
        return self.__name

    def pubkey(self):
        return self.__key.pubkey()

    def byte_pubkey(self):
        return self.__key.byte_pubkey()

    def cert(self):
        return self.__cert.cert()

    def byte_cert(self):
        return self.__cert.byte_cert()

    def generate_certificate(self, issuer_name, issuer_pubkey, validity_date):
        now = datetime.datetime.utcnow()
        # Creation d'un certificat
        subject = x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, self.__name)])
        issuer = x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, issuer_name)])
        cert = x509.CertificateBuilder() \
            .subject_name(subject) \
            .issuer_name(issuer) \
            .public_key(key=issuer_pubkey) \
            .serial_number(number=x509.random_serial_number()) \
            .not_valid_before(now) \
            .not_valid_after(now + datetime.timedelta(days=validity_date)) \
            .add_extension(extension=x509.SubjectAlternativeName([x509.DNSName(u"localhost")]),
                           critical=False) \
            .sign(private_key=self.__key.privkey(),
                  algorithm=hashes.SHA256(),
                  backend=default_backend())
        print(
            'certificate generate by Equipment {} on Equipment {}\'s public key'
            .format(subject, issuer))
        return cert

    def verify_certif(self, cert_to_check, public_key):
        public_key.verify(signature=cert_to_check.signature,
                          data=cert_to_check.tbs_certificate_bytes,
                          padding=padding.PKCS1v15(),
                          algorithm=cert_to_check.signature_hash_algorithm)
        # print('Certificate verified')
        return True
Ejemplo n.º 6
0
    def validate_tcg_from_certs(self, ca_cert_der, attest_cert_der):

        attest_cert_obj = Certificate(attest_cert_der)
        ca_cert_obj = Certificate(ca_cert_der)

        isValid = self._validate_attributes_with_tcg_rule(attest_cert_obj) and \
                    self._validate_tcg_raw(attest_cert_obj.tcg_min,
                                     attest_cert_obj.tcg_max,
                                     ca_cert_obj.tcg_min,
                                     ca_cert_obj.tcg_max)

        return isValid
Ejemplo n.º 7
0
def create_multiple(logger, ctx, csv_file, config, force, key_size, san,
                    verbose, debug, **subject):
    """
    Create multiple certificate using csv file
    \f

    :param logger:
    :param ctx:
    :param csv_file:
    :param config:
    :param force:
    :param key_size:
    :param san:
    :param verbose:
    :param debug:
    :param subject:
    :return:
    """
    tools.set_options(ctx=ctx,
                      config=config,
                      san=san,
                      size=key_size,
                      subject=subject,
                      verbose=verbose,
                      debug=debug)
    cert = Certificate(logger=logger, opts=tools.opts)

    if 'subject' in tools.opts:
        cert.load_subject()

    if csv_file:
        cert.generate_multiple(csv_file=csv_file, force=force)
    else:
        cert.generate_multiple(force=force)
Ejemplo n.º 8
0
def certificate():
    id = request.args.get('id')
    donor = Donor.query.filter(Donor.id == id).first()
    file_dir = os.path.join(basedir, app.config['IMG_FOLDER'])
    if donor:
        no = "WH2020012310{0:04d}".format(donor.id)
        certi_file = "%s.png" % os.path.join(file_dir, no)
        if not os.path.exists(certi_file):
            amount = "%.2f" % donor.amount
            cert = Certificate(donor.name, amount, no)
            cert.grant()
        image_data = open(certi_file, "rb").read()
        response = make_response(image_data)
        response.headers['Content-Type'] = 'image/png'
        return response
Ejemplo n.º 9
0
def read(logger, ctx, path, password, plain_text):
    """
    Read csr or p12
    \f

    :param logger:
    :param ctx:
    :param path:
    :param password:
    :param plain_text:
    :return:
    """
    tools.set_options(ctx=ctx)

    cert = Certificate(logger=logger, opts=tools.opts)
    click.echo(cert.read(path=path, password=password, plain_text=plain_text))
def collect_fingerprints_from_lbb_db(fingerprints: set = None) -> None:
    """
    Connects to the little black box database and converts the certificates to
    compatible fingerprints.

    Args:
        fingerprints (set): A collection of obtained certificates from the
            little black box and the house of keys.

    """
    # Actual database connection
    conn = connect(LITTLE_BLACK_BOX_DATABASE)
    cur = conn.cursor()

    # Obtain all the certificates contained in the database
    cur.execute("SELECT certificate FROM certificates;")

    # Iterate over the items from the database
    for item in cur:

        # Ignore ssh-rsa keys
        if (not item[0].startswith(BEGIN_CERTIFICATE)): continue

        # Convert the text of the certificate and extract the fingerprint
        fingerprints.add(Certificate.from_string(item[0]).fingerprint)

    conn.close()
Ejemplo n.º 11
0
    def __init__(self, certificate, proxykey=None, full=True):
        if isinstance(certificate, Certificate):
            self._certificate = certificate
        elif isinstance(certificate, ProxyCertificate):
            self._certificate = certificate._proxy
        else:
            self._certificate = Certificate(certificate)
        self._full = full

        self._proxy = Certificate(key=proxykey)

        self._proxy.set_version(2)
        self.set_serial_number()
        issuer = self._certificate.get_subject()
        subject = X509.X509_Name()
        for n in issuer:
            m2.x509_name_add_entry(subject.x509_name, n.x509_name_entry, -1, 0)

        subject.add_entry_by_txt(field='CN', type=MBSTRING_ASC,
                                 entry=str(self._proxy.get_serial_number()),len=-1, loc=-1, set=0)

# CURRENT - this partly fools the system that it has a globus legacy proxy (needed by grisu/grid)
# can look up VOs, but can't access filesystems for running jobs with this on
#        subject.add_entry_by_txt(field='CN', type=MBSTRING_ASC, entry='proxy',len=-1, loc=-1, set=0)

        self._proxy.set_dn(subject)
        self._proxy.set_times(lifetime=43200)
        self._proxy.set_issuer_name(self._certificate.get_subject())

        try:
            key_usage = self._certificate._certificate.get_ext('keyUsage')
        except LookupError:
            pass
        else:
            self._proxy.add_extension({'name':key_usage.get_name(),
                                       'critical': key_usage.get_critical(),
                                       'value': self._fix_key_usage(key_usage.get_value())})

        if self._full:
            self._proxy.add_extension({'name':"proxyCertInfo",
                                       'value': PCI_VALUE_FULL,
                                       'critical': 1})
        else:
            self._proxy.add_extension({'name': "proxyCertInfo",
                                           'value': PCI_VALUE_LIMITED,
                                           'critical': 1})
def main():

    BASE_MODULE_ARGS = dict(
        cadir = dict(default="/etc/certs"),
        certname = dict(required=True),
        subj = dict(default="/DC=com/DC=example/CN=CA/"),
        p12password = dict(required=True),
        certtype = dict(default="server", choices=["server", "client"]),
        state = dict(default="present", choices=["present", "absent"]),
        subjectAltNames = dict(required=False)
    )

    module = AnsibleModule(
        argument_spec= BASE_MODULE_ARGS,
        supports_check_mode=True
    )

    isServerCert = True

    if module.params["certtype"] == "client":
        isServerCert = False

    # cadir, certname, subj, p12password, isServerCert
    cert = Certificate(
        module.params["cadir"],
        module.params["certname"],
        module.params["subj"],
        module.params["p12password"],
        isServerCert,
        module.params["subjectAltNames"]
    )

    isValid = cert.validate_config()

    if isValid["success"]:
        if module.params["state"] == "present":
            isValid = cert.create_certificate()
        else:
            isValid = cert.remove_certificate()

    if not isValid["success"]:
        module.fail_json(msg=isValid["msg"])
    else:
        module.exit_json(**isValid)
Ejemplo n.º 13
0
    def certificate(self, hostname):
        """Returns the certificate of a particular hostname

        :param hostname: The hostname you want the certificate of
        :type hostname: str

        :return: The ppaas.Certificate object, or raises an exception
        :rtype: ppaas.Certificate
        """
        return Certificate(self, hostname)
Ejemplo n.º 14
0
    def _generate_oid_config(self, oid_name, min_str, max_str):
        min_attr = Attribute.init(num_bits=32, string=min_str)
        max_attr = Attribute.init(num_bits=32, string=max_str)

        oid_str = "%.8X%.8X" % (min_attr.value, max_attr.value)
        oid_cfg = "\n%s=DER:%s:%s:%s:%s:%s:%s:%s:%s" % \
                (Certificate.GetOIDByName(oid_name), oid_str[0:2], oid_str[2:4], oid_str[4:6], oid_str[6:8], \
                 oid_str[8:10], oid_str[10:12], oid_str[12:14], oid_str[14:16])

        return oid_cfg
Ejemplo n.º 15
0
    def parseCerts(self, signature, offset):
        prev = self._f.tell()
        true_offset = signature.getOffset() + offset
        self._f.seek(true_offset)
        magic = getInt(self._f)
        if magic != dictionary.signatures['BLOBWRAPPER']:
            data = {
                'offset': true_offset,
                'magic': hex(magic),
                'expected': hex(dictionary.signatures['BLOBWRAPPER'])
            }
            a = Abnormality(title='BAD MAGIC - BLOBWRAPPER', data=data)
            self.addAbnormality(a)
            self._f.seek(prev)
            return
        size = getInt(self._f) - 8
        # out = open('cms', 'wb')
        # out.write(self._f.read(size))
        # out.close()
        # exit(0)
        if size > 0:
            signed_data = cms.CMS(self._f.read(size), format='DER')
            for cert in signed_data.certs:
                serial = cert.serial
                subject = {
                    'country': self.getCertNameData(cert.subject,
                                                    oid.Oid('C')),
                    'org': self.getCertNameData(cert.subject, oid.Oid('O')),
                    'org_unit': self.getCertNameData(cert.subject,
                                                     oid.Oid('OU')),
                    'common_name': self.getCertNameData(cert.subject,
                                                        oid.Oid('CN'))
                }
                issuer = {
                    'country': self.getCertNameData(cert.issuer, oid.Oid('C')),
                    'org': self.getCertNameData(cert.issuer, oid.Oid('O')),
                    'org_unit': self.getCertNameData(cert.issuer,
                                                     oid.Oid('OU')),
                    'common_name': self.getCertNameData(cert.issuer,
                                                        oid.Oid('CN'))
                }
                ca = cert.check_ca()
                cert = Certificate(serial=serial, subject=subject,
                                   issuer=issuer, ca=ca)
                signature.addCert(cert)
        else:
            data = {
                'offset': true_offset,
                'size': size
            }
            a = Abnormality(title='NON-POSITIVE CMS SIZE', data=data)
            self.addAbnormality(a)

        self._f.seek(prev)
Ejemplo n.º 16
0
    def validate_tcg_from_config(self, ca_cert_path, signing_attributes):
        ca_cert_obj = Certificate(path=ca_cert_path)

        tcg_min_str = signing_attributes.tcg_min
        tcg_max_str = signing_attributes.tcg_max

        tcg_min_attest = Attribute.init(num_bits=32, string=tcg_min_str)
        tcg_max_attest = Attribute.init(num_bits=32, string=tcg_max_str)

        return self._validate_tcg_raw(tcg_min_attest, tcg_max_attest,
                                      ca_cert_obj.tcg_min, ca_cert_obj.tcg_max)
Ejemplo n.º 17
0
def create_multiple_p12(logger, ctx, csv_file, pem_folder, key_folder,
                        password, config, force, verbose, debug):
    """
    Create multiple p12 using csv file
    \f

    :param logger:
    :param ctx:
    :param csv_file:
    :param pem_folder:
    :param key_folder:
    :param password:
    :param config:
    :param force:
    :param verbose:
    :param debug:
    :return:
    """
    tools.set_options(ctx=ctx, config=config, verbose=verbose, debug=debug)

    cert = Certificate(logger, opts=tools.opts)
    if csv_file:
        cert.generate_multiple_p12(csv_file=csv_file,
                                   pem_folder=pem_folder,
                                   key_folder=key_folder,
                                   password=password,
                                   force=force)
    else:
        cert.generate_multiple_p12(pem_folder=pem_folder,
                                   key_folder=key_folder,
                                   password=password,
                                   force=force)
Ejemplo n.º 18
0
def create(logger, ctx, name, config, force, key_size, san, verbose, debug,
           **subject):
    """
    Create a single CSR
    \f

    :param logger:
    :param ctx:
    :param name:
    :param config:
    :param force:
    :param key_size:
    :param san:
    :param verbose:
    :param debug:
    :param subject:
    :return:
    """
    tools.set_options(ctx=ctx,
                      config=config,
                      san=san,
                      size=key_size,
                      subject=subject,
                      verbose=verbose,
                      debug=debug)

    if name:
        tools.set_options(name=str(name))

    cert = Certificate(logger=logger, opts=tools.opts)

    if 'subject' in tools.opts:
        cert.load_subject()

    cert.generate_csr(force=force)
Ejemplo n.º 19
0
    def _generate_signing_package(self, hash_to_sign, signing_attributes, cass_signer_attributes,
                                image_path, signingpackage_fname, binary_to_sign):

        signingpackage = SigningPackage(secimage.__version__)
        signingrequest = signingpackage.createSigningRequest("image_to_sign=%s" % image_path)

        hexbindigest = binascii.b2a_hex(hash_to_sign)
        logger.debug("Digest to sign (hexbinary)= [%s]" % hexbindigest)
        signingrequest.setDigest(hexbindigest)
        signingrequest.setCapability(signing_attributes.cass_capability)
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_SW_SIZE, "0x%.8X" % len(binary_to_sign))

        hmac_params = signerutils.get_hmac_params_from_config(signing_attributes)
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_HW_ID, "0x%s" % hmac_params.msm_id_str)
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_SW_ID, signing_attributes.sw_id)
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_MODEL_ID, signing_attributes.model_id)
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_OEM_ID, signing_attributes.oem_id)
        if signing_attributes.debug:
            signingrequest.setSigningAttribute(Certificate.SIGNATTR_DEBUG, signing_attributes.debug)
        if signing_attributes.app_id:
            signingrequest.setSigningAttribute(Certificate.SIGNATTR_APP_ID, signing_attributes.app_id)
        if signing_attributes.crash_dump:
            signingrequest.setSigningAttribute(Certificate.SIGNATTR_CRASH_DUMP, signing_attributes.crash_dump)

        if self._is_oid_supported(signing_attributes) is True:
            attr_min, attr_max = Certificate.GetOIDAttrName(signing_attributes.object_id.name)
            #Min/max can be supplied by CASS server and is optional
            if signing_attributes.object_id.min:
                signingrequest.setSigningAttribute(attr_min, signing_attributes.object_id.min)
            if signing_attributes.object_id.max:
                signingrequest.setSigningAttribute(attr_max, signing_attributes.object_id.max)
        else:
            #opendsp does not CASS_SIGNATTR_USE_EXP3 currently
            if signing_attributes.exponent == 3:
                signingrequest.setSigningAttribute(self.CASS_SIGNATTR_USE_EXP3, 'TRUE')
            elif signing_attributes.exponent == 65537:
                signingrequest.setSigningAttribute(self.CASS_SIGNATTR_USE_EXP3, 'FALSE')
            else:
                raise RuntimeError, "Exponent value of {0} is invalid!".format(signing_attributes.exponent)

        # Set signature algorithm to SHA256 by default
        signingrequest.setSigningAttribute(Certificate.SIGNATTR_SHA256, 'TRUE')

        pathname, fname = os.path.split(signingpackage_fname)
        c_path.create_dir(pathname)

        signingpackage.toxml()
        signingpackage.saveToFile(signingpackage_fname)
        logger.info("Signing package created. Digest = [%s]" % signingpackage.getDigest())
        return signingpackage
Ejemplo n.º 20
0
def main():

    BASE_MODULE_ARGS = dict(cadir=dict(default="/etc/certs"),
                            certname=dict(required=True),
                            subj=dict(default="/DC=com/DC=example/CN=CA/"),
                            p12password=dict(required=True),
                            certtype=dict(default="server",
                                          choices=["server", "client"]),
                            state=dict(default="present",
                                       choices=["present", "absent"]),
                            subjectAltNames=dict(required=False))

    module = AnsibleModule(argument_spec=BASE_MODULE_ARGS,
                           supports_check_mode=True)

    isServerCert = True

    if module.params["certtype"] == "client":
        isServerCert = False

    # cadir, certname, subj, p12password, isServerCert
    cert = Certificate(module.params["cadir"], module.params["certname"],
                       module.params["subj"], module.params["p12password"],
                       isServerCert, module.params["subjectAltNames"])

    isValid = cert.validate_config()

    if isValid["success"]:
        if module.params["state"] == "present":
            isValid = cert.create_certificate()
        else:
            isValid = cert.remove_certificate()

    if not isValid["success"]:
        module.fail_json(msg=isValid["msg"])
    else:
        module.exit_json(**isValid)
Ejemplo n.º 21
0
    def get_certificates(self, status=None):
        """Returns all the certificates attached to a master

        Optionally you can specify a `status` for the certificates. The statuses can either be
          * "SIGNATURE PENDING"
          * "SIGNED"
          * "REVOKED"
        If status is None, all the certifictes will be returned regardless of their status

        Note that it is just for conveinence that this option is provided. From the API's point
        of view we will issue the same request anyway.

        :param status: The status of the certificates
        :type status: str

        :return: A list of matching certificates
        :rtype: List of ppaas.Certificate

        """
        if status is None:
            return Certificate.get_certificates(self, self.client)
        else:
            certificates = Certificate.get_certificates(self, self.client)
            return [cert for cert in certificates if cert.status['message'] == status]
Ejemplo n.º 22
0
    def validate_oid_from_config(self, ca_cert_path, signing_attributes):
        ca_cert_obj = Certificate(path=ca_cert_path)

        min_str = signing_attributes.object_id.min
        max_str = signing_attributes.object_id.max

        min_attest = Attribute.init(num_bits=32, string=min_str)
        max_attest = Attribute.init(num_bits=32, string=max_str)

        if signing_attributes.object_id.name == "tcg":
            min_ca = ca_cert_obj.tcg_min
            max_ca = ca_cert_obj.tcg_max
        elif signing_attributes.object_id.name == "feature_id":
            min_ca = ca_cert_obj.fid_min
            max_ca = ca_cert_obj.fid_max

        return self._validate_oid_raw(min_attest, max_attest, min_ca, max_ca)
Ejemplo n.º 23
0
    def sign(self, binary_to_sign, imageinfo, debug_dir=None):
        '''
        This function returns a SignerOutput object which has all the security assets generated
        by the signer.
        '''
        self._signer_impl.validate_config(imageinfo)

        hasher = Hasher()
        hmacParams = signerutils.get_hmac_params_from_config(
            imageinfo.signing_attributes)
        hash_to_sign = hasher.qcom_hmac(binary_to_sign, hmacParams)
        signer_output = self._signer_impl.sign(hash_to_sign, imageinfo,
                                               binary_to_sign, debug_dir)

        #print certificate properties
        attestation_cert_obj = Certificate(signer_output.attestation_cert)
        logger.info('\nAttestation Certificate Properties:\n' +
                    str(attestation_cert_obj))

        return signer_output
def collect_fingerprints_from_hok_fp(fingerprints: set = None) -> None:
    """
    Iterates through the House Of Keys directory and converts the certificates
    in the PEM files to compatible fingerprints.

    Args:
        fingerprints (set): A collection of obtained certificates from the
            little black box and the house of keys.

    """
    # Iterate through the content of the directory
    for f in os.listdir(HOUSE_OF_KEYS_PATH):

        # Only interested in the known certificates
        if (not f.endswith("pem")): continue

        # Extract the PEM certificate as string
        pem = open(os.path.join(HOUSE_OF_KEYS_PATH, f), 'r').read()
        pem = pem[pem.rfind(BEGIN_CERTIFICATE):]

        # Convert the PEM certificate to a compatible fingerprint
        fingerprints.add(Certificate.from_string(pem).fingerprint)
Ejemplo n.º 25
0
    def read_certificates(self, server_certificates):
        logger.info(
            "------------------------------------------------------------------------------------"
        )
        logger.info("Rufe die Zertifkate für die weiteren Tests ab")
        logger.info(
            "------------------------------------------------------------------------------------"
        )
        try:
            if server_certificates is None:

                openssl_cmd_getcert = "echo 'Q' | openssl s_client -connect " + self.hostname + ":" + str(
                    self.port
                ) + self.openssl_client_proxy_part + " -showcerts  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'"
                proc = subprocess.Popen([openssl_cmd_getcert],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        shell=True)
                (out, err) = proc.communicate()
                tmp_certs = pem.parse(out)
            else:
                tmp_certs = pem.parse_file(server_certificates)

            logger.info(
                str(len(tmp_certs)) +
                " Zertifikate wurden empfangen bzw. eingelesen.")

            for crt in tmp_certs:
                self.x509_certs.append(
                    load_pem_x509_certificate(
                        str(crt).encode('ascii', 'ignore'), default_backend()))

            for x509 in self.x509_certs:
                self.certs.append(Certificate(x509, self.ca_file))

        except Exception as err:
            print err
Ejemplo n.º 26
0
def extract_fps_ecs(file_path, fps, ecs):
    """
    Extract the fingerprints and Ellyptic Curve data from a given file.

    Args:
        file_path (str): Full system path to the file.
        fps (dict): Dictionary of all collected fingerprints.
        ecs (dict): Dictionary of all collected Elyptic Curve data.

    """
    try:
        pem = open(file_path, "r").read()

        if (pem.startswith("-----BEGIN PUBLIC KEY-----")):
            pn = SSHKey.from_pem_public_key(pem).public_numbers
            ecs.setdefault(str(pn.x), []).append(file_path)

        elif (CERT_FLAG in pem):
            pem = pem[pem.rfind(CERT_FLAG):].strip()
            cert = Certificate.from_string(pem)
            fps.setdefault(cert.fingerprint, []).append(file_path)

    except Exception as e:
        print(file_path, str(e))
Ejemplo n.º 27
0
 def retrieve_certificate(self):
     """ retrieve the repository's certificate file """
     certificate = self.retrieve_object(self.manifest.certificate, 'X')
     return Certificate(certificate)
Ejemplo n.º 28
0
            def __main__(self):
                father = self.father
                chatroom = tk.Tk()
                chatroom.geometry('600x400+425+225')
                chatroom.title('91 Chatroom for ' +
                               self.father.father.username)
                # chatroom.attributes('-topmost',1)

                # backgroud
                frame = tk.Frame(chatroom,
                                 bg=colors['black'],
                                 width=600,
                                 height=400)
                frame.place(x=0, y=0)

                # container
                textArea = tk.Text(frame,
                                   bg=colors['black'],
                                   fg=colors['green'],
                                   highlightbackground=colors['lightGray'],
                                   selectbackground=colors['blue'],
                                   selectforeground=colors['green'],
                                   width=60,
                                   height=22,
                                   bd=0)
                textArea.place(x=10, y=10, anchor=tk.NW)
                textArea.bind('<KeyPress>', lambda x: "break")
                father.textArea = textArea
                # textArea.focus_set()
                # choose
                tk.Label(frame,
                         text="Select Receiver:",
                         bg=colors['black'],
                         fg=colors['green']).place(x=460, y=10, anchor=tk.NW)
                listbox = tk.Listbox(frame,
                                     width=14,
                                     height=7,
                                     bg=colors['darkGray'],
                                     fg=colors['green'],
                                     selectbackground=colors['black'],
                                     selectforeground=colors['green'])
                listbox.place(x=460, y=35, anchor=tk.NW)
                father.listbox = listbox

                fileButton = tk.Button(
                    frame,
                    text="File",
                    bd=0,
                    highlightbackground=colors['black'],
                    command=lambda: self.uploadFile(father.socket, nameLabel))
                fileButton.place(x=480, y=180, anchor=tk.CENTER)
                videoButton = tk.Button(
                    frame,
                    text="Video",
                    bd=0,
                    highlightbackground=colors['black'],
                    command=lambda: self.videoCall(father.socket, nameLabel))
                videoButton.place(x=560, y=180, anchor=tk.CENTER)
                # ttk.Style().configure("b.TButton", foreground="black", background="white")

                # style1 = ttk.Style()
                # style1.configure("BW1.TLabel", foreground="black", background="white")
                # bt_refresh = ttk.Button(f, text = "刷新列表", bd = 0, style = "BW1.TLable",command = lambda : self.refresh(father.socket))
                tk.Label(frame,
                         text="System Log:",
                         bg=colors['black'],
                         fg=colors['green']).place(x=460, y=208, anchor=tk.NW)
                logArea = tk.Text(frame,
                                  bg=colors['black'],
                                  fg=colors['green'],
                                  highlightbackground=colors['lightGray'],
                                  selectbackground=colors['blue'],
                                  selectforeground=colors['green'],
                                  width=16,
                                  height=7,
                                  bd=0)
                logArea.place(x=455, y=233, anchor=tk.NW)
                logArea.bind('<KeyPress>', lambda x: "break")
                father.logArea = logArea

                log = ctime() + " Connection Establishment"
                logArea.insert(tk.END, log + '\n\n')
                logArea.see(tk.END)
                # input
                nameLabel = tk.Label(frame,
                                     text="Unseleted",
                                     bg=colors['black'],
                                     fg=colors['green'],
                                     width=8)
                nameLabel.place(x=12, y=360)
                listbox.bind('<Double-Button-1>',
                             lambda x: self.changeSendTo(listbox, nameLabel))
                self.nameLabel = nameLabel
                inputEntry = tk.Entry(frame,
                                      width=37,
                                      bg=colors['black'],
                                      fg=colors['green'],
                                      insertbackground=colors['white'],
                                      highlightbackground=colors['lightGray'],
                                      selectbackground=colors['blue'],
                                      selectforeground=colors['green'])
                inputEntry.place(x=90, y=358)
                # inputEntry.bind('<Key-Return>',
                #         lambda x : self.requestCertificate(father.socket,
                #         nameLabel, inputEntry))
                inputEntry.bind(
                    '<Key-Return>', lambda x: self.requestCertificate(
                        father.socket, nameLabel))
                # self.inputEntry = inputEntry
                father.inputEntry = inputEntry

                bt_send = tk.Button(frame,
                                    text="Enter",
                                    highlightbackground=colors['black'],
                                    command=lambda: self.requestCertificate(
                                        father.socket, nameLabel))
                bt_send.place(x=480, y=371, anchor=tk.CENTER)
                bt_clear = tk.Button(
                    frame,
                    text="Clear",
                    highlightbackground=colors['black'],
                    command=lambda: textArea.delete(0.0, tk.END))
                bt_clear.place(x=560, y=372, anchor=tk.CENTER)

                r = RSA()
                c = Certificate(r.pubKey)

                c.certificateInfo['username'] = self.father.father.username
                self.father.father.selfInfo[
                    'username'] = self.father.father.username
                self.father.father.selfInfo[
                    'decryptionType'] = c.certificateInfo['encryptionType']
                self.father.father.selfInfo['pubKey'] = r.pubKey
                self.father.father.selfInfo['priKey'] = r.priKey
                self.father.father.selfInfo[
                    'communicationType'] = c.certificateInfo[
                        'communicationType']
                if c.certificateInfo['communicationType'] == "dh":
                    pubNum = DH().getPAndG()
                    self.father.father.selfInfo['pAndg'] = pubNum
                    c.certificateInfo['pAndg'] = pubNum
                    self.father.father.selfInfo['secretA'] = getPrimeNum(20)
                    self.father.father.selfInfo['mA'] = pow(
                        pubNum[1], self.father.father.selfInfo['secretA'],
                        pubNum[0])

                jData = json.dumps(c.certificateInfo)
                father.socket.send(jData.encode())

                # 刷新列表
                # self.refresh(father.socket)

                inputEntry.focus_set()

                chatroom.focus_force()
                chatroom.mainloop()

                father.socket.shutdown(2)
                print('Socket 断开')
Ejemplo n.º 29
0
from suds.client import Client
from certificate import Certificate
import sys

client = Client(
    "http://localhost:8081/config-service/ConfigurationService?wsdl")

cert = Certificate(sys.argv[1])
cert.add_to_config(client)
Ejemplo n.º 30
0
from suds.client import Client
from certificate import Certificate
import sys

client = Client("http://localhost:8081/config-service/ConfigurationService?wsdl")

cert = Certificate(sys.argv[1])
cert.add_to_config(client)
Ejemplo n.º 31
0
def createCert(certname, subj, password, isServerCert):
    print line
    print "Creating certificate for: {}".format(certname)
    cert = Certificate(cadir, certname, subj, password, isServerCert)
    print cert.create_certificate()
    return cert
Ejemplo n.º 32
0
from suds.client import Client
from certificate import Certificate
import sys

client = Client("http://localhost:8081/config-service/ConfigurationService?wsdl")

cert = Certificate(sys.argv[1])
cert.add_to_anchor(client, sys.argv[2])
Ejemplo n.º 33
0
class ProxyCertificate:
    """This is a wrapper class for handling proxy certificate generation.

    :param request: if specified this will be wrapped in a :class:`~arcs.gsi.certificate.Certificate` object
    :param proxykey: the key used to sign the proxy, if sepecified this will be wrapped in a :class:`~arcs.gsi.key.Key` object
    :param full: whether this is a full proxy or not

    """
    def __init__(self, certificate, proxykey=None, full=True):
        if isinstance(certificate, Certificate):
            self._certificate = certificate
        elif isinstance(certificate, ProxyCertificate):
            self._certificate = certificate._proxy
        else:
            self._certificate = Certificate(certificate)
        self._full = full

        self._proxy = Certificate(key=proxykey)

        self._proxy.set_version(2)
        self.set_serial_number()
        issuer = self._certificate.get_subject()
        subject = X509.X509_Name()
        for n in issuer:
            m2.x509_name_add_entry(subject.x509_name, n.x509_name_entry, -1, 0)

        subject.add_entry_by_txt(field='CN', type=MBSTRING_ASC,
                                 entry=str(self._proxy.get_serial_number()),len=-1, loc=-1, set=0)

# CURRENT - this partly fools the system that it has a globus legacy proxy (needed by grisu/grid)
# can look up VOs, but can't access filesystems for running jobs with this on
#        subject.add_entry_by_txt(field='CN', type=MBSTRING_ASC, entry='proxy',len=-1, loc=-1, set=0)

        self._proxy.set_dn(subject)
        self._proxy.set_times(lifetime=43200)
        self._proxy.set_issuer_name(self._certificate.get_subject())

        try:
            key_usage = self._certificate._certificate.get_ext('keyUsage')
        except LookupError:
            pass
        else:
            self._proxy.add_extension({'name':key_usage.get_name(),
                                       'critical': key_usage.get_critical(),
                                       'value': self._fix_key_usage(key_usage.get_value())})

        if self._full:
            self._proxy.add_extension({'name':"proxyCertInfo",
                                       'value': PCI_VALUE_FULL,
                                       'critical': 1})
        else:
            self._proxy.add_extension({'name': "proxyCertInfo",
                                           'value': PCI_VALUE_LIMITED,
                                           'critical': 1})

    def _fix_key_usage(self, values):
        """
        invalid values are 'Non Repudiation' and 'keyCertSign'
        digitalSignature is required
        """
        r = []
        for v in values.split(', '):
            if v in ['Non Repudiation', 'keyCertSign']:
                continue
            r.append(v)
        if 'Digital Signature' not in r:
            r.append('Digital Signature')
        return ', '.join(r)


    def set_serial_number(self):
        message_digest = EVP.MessageDigest('sha1')
        pubkey = self._proxy.get_pubkey()
        der_encoding = pubkey.as_der()
        message_digest.update(der_encoding)
        digest = message_digest.final()
        digest_tuple = struct.unpack('BBBB', digest[:4])
        sub_hash = long(digest_tuple[0] + (digest_tuple[1] + ( digest_tuple[2] +
                               ( digest_tuple[3] >> 1) * 256 ) * 256) * 256)
        self._proxy._certificate.set_serial_number(sub_hash)


    def sign(self, md='sha1'):
        self._proxy.sign(self._certificate.get_key(), md)


    def __str__(self):
        return self._proxy.__str__()


    def __repr__(self):
        return self._proxy.__repr__()

    def as_der(self):
        return self._proxy._certificate.as_der()
Ejemplo n.º 34
0
def createCert(certname, subj, password, isServerCert):
    print line
    print "Creating certificate for: {}".format(certname)
    cert = Certificate(cadir, certname, subj, password, isServerCert)
    print cert.create_certificate()
    return cert