Esempio n. 1
0
    def build_csr(self):
        if not self.private_key:
            if self.key_type == KeyTypes.RSA:
                self.public_key, self.private_key = asymmetric.generate_pair(
                    "rsa", bit_size=self.key_length)
            elif self.key_type == KeyTypes.ECDSA:
                self.public_key, self.private_key = asymmetric.generate_pair(
                    "ec", curve=self.key_curve)
            else:
                raise ClientBadData
        else:
            raise NotImplementedError
            # public_key = gen_public_from_private(self.private_key, self.key_type)  # todo: write function

        data = {
            'common_name': self.common_name,
        }
        if self.email_addresses:
            data['email_address'] = self.email_addresses

        builder = CSRBuilder(data, self.public_key)

        if self.ip_addresses:
            builder.subject_alt_ips = self.ip_addresses
        if self.dns_names:
            builder.subject_alt_domains = self.dns_names

        builder.hash_algo = "sha256"
        builder.subject_alt_domains = [self.common_name]
        self.csr = pem_armor_csr(builder.build(self.private_key)).decode()
        return
Esempio n. 2
0
def self_enroll(skip_notify=False):
    assert os.getuid() == 0 and os.getgid(
    ) == 0, "Can self-enroll only as root"

    from certidude import const, config
    common_name = const.FQDN
    os.umask(0o0177)

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        self_public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(config.SELF_KEY_PATH)
    except FileNotFoundError:  # certificate or private key not found
        click.echo("Generating private key for frontend: %s" %
                   config.SELF_KEY_PATH)
        with open(config.SELF_KEY_PATH, 'wb') as fh:
            if public_key.algorithm == "ec":
                self_public_key, private_key = asymmetric.generate_pair(
                    "ec", curve=public_key.curve)
            elif public_key.algorithm == "rsa":
                self_public_key, private_key = asymmetric.generate_pair(
                    "rsa", bit_size=public_key.bit_size)
            else:
                raise NotImplemented(
                    "CA certificate public key algorithm %s not supported" %
                    public_key.algorithm)
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, self_public_key)
    request = builder.build(private_key)
    pid = os.fork()
    if not pid:
        from certidude import authority, config
        from certidude.common import drop_privileges
        drop_privileges()
        assert os.getuid() != 0 and os.getgid() != 0
        path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")
        click.echo("Writing certificate signing request for frontend: %s" %
                   path)
        with open(path, "wb") as fh:
            fh.write(
                pem_armor_csr(request))  # Write CSR with certidude permissions
        authority.sign(common_name,
                       skip_notify=skip_notify,
                       skip_push=True,
                       overwrite=True,
                       profile=config.PROFILES["srv"])
        click.echo("Frontend certificate signed")
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        os.system("systemctl reload nginx")
Esempio n. 3
0
def self_enroll():
    assert os.getuid() == 0 and os.getgid(
    ) == 0, "Can self-enroll only as root"

    from certidude import const
    common_name = const.FQDN
    directory = os.path.join("/var/lib/certidude", const.FQDN)
    self_key_path = os.path.join(directory, "self_key.pem")

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        self_public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(self_key_path)
    except FileNotFoundError:  # certificate or private key not found
        with open(self_key_path, 'wb') as fh:
            if public_key.algorithm == "ec":
                self_public_key, private_key = asymmetric.generate_pair(
                    "ec", curve=public_key.curve)
            elif public_key.algorithm == "rsa":
                self_public_key, private_key = asymmetric.generate_pair(
                    "rsa", bit_size=public_key.bit_size)
            else:
                NotImplemented
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, self_public_key)
    request = builder.build(private_key)
    pid = os.fork()
    if not pid:
        from certidude import authority
        from certidude.common import drop_privileges
        drop_privileges()
        assert os.getuid() != 0 and os.getgid() != 0
        path = os.path.join(directory, "requests", common_name + ".pem")
        click.echo("Writing request to %s" % path)
        with open(path, "wb") as fh:
            fh.write(
                pem_armor_csr(request))  # Write CSR with certidude permissions
        authority.sign(common_name,
                       skip_push=True,
                       overwrite=True,
                       profile=config.PROFILES["srv"])
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        if os.path.exists("/etc/systemd"):
            os.system("systemctl reload nginx")
        else:
            os.system("service nginx reload")
Esempio n. 4
0
def store_request(buf, overwrite=False, address="", user=""):
    """
    Store CSR for later processing
    """

    if not buf:
        raise ValueError("No signing request supplied")

    if pem.detect(buf):
        header, _, der_bytes = pem.unarmor(buf)
        csr = CertificationRequest.load(der_bytes)
    else:
        csr = CertificationRequest.load(buf)
        buf = pem_armor_csr(csr)

    common_name = csr["certification_request_info"]["subject"].native[
        "common_name"]

    if not re.match(const.RE_COMMON_NAME, common_name):
        raise ValueError("Invalid common name %s" % repr(common_name))

    request_path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")

    # If there is cert, check if it's the same
    if os.path.exists(request_path) and not overwrite:
        if open(request_path, "rb").read() == buf:
            raise errors.RequestExists("Request already exists")
        else:
            raise errors.DuplicateCommonNameError(
                "Another request with same common name already exists")
    else:
        with open(request_path + ".part", "wb") as fh:
            fh.write(buf)
        os.rename(request_path + ".part", request_path)

    attach_csr = buf, "application/x-pem-file", common_name + ".csr"
    mailer.send("request-stored.md",
                attachments=(attach_csr, ),
                common_name=common_name)
    setxattr(request_path, "user.request.address", address)
    setxattr(request_path, "user.request.user", user)
    try:
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(address)
    except (socket.herror,
            OSError):  # Failed to resolve hostname or resolved to multiple
        pass
    else:
        setxattr(request_path, "user.request.hostname", hostname)
    return request_path, csr, common_name
Esempio n. 5
0
    def generate_certificate(self, domain, save_model):
        logger.info("Dogtag: certificate creation request %s" % (domain,))

        public_key, private_key = asymmetric.generate_pair(
            'rsa', bit_size=2048)
        data = {
            'common_name': domain,
            'organization_name': save_model.name,
            'organizational_unit_name': save_model.institution_unit,
            'email_address': save_model.email
        }
        data.update(settings.DOGTAG_CERTIFICATE_SCHEME)
        builder = CSRBuilder(
            data,
            public_key
        )
        #builder.subject_alt_domains = ['codexns.io', 'codexns.com']
        request = builder.build(private_key)

        inputs = {
            "cert_request_type": "pkcs10",
            "cert_request": pem_armor_csr(request).decode(),
            "requestor_name": settings.DOGTAG_CERT_REQUESTER,
            "requestor_email": settings.DOGTAG_CERT_REQUESTER_EMAIL,
        }

        logger.debug("Dogtag: request certificate %r" % (inputs,))

        conn = self.get_connection()
        cert_client = pki.cert.CertClient(conn)
        certificates = cert_client.enroll_cert("caServerCert", inputs)

        server_public_key, server_private_key = \
            asymmetric.generate_pair('rsa', bit_size=2048)

        save_model.private_key = asymmetric.dump_private_key(private_key, None)
        save_model.public_key = asymmetric.dump_public_key(public_key)
        save_model.public_certificate = certificates[0].cert.encoded.encode()

        save_model.server_sign_key = asymmetric.dump_private_key(
            server_private_key, None)
        save_model.server_public_key = asymmetric.dump_public_key(
            server_public_key)

        logger.debug("Dogtag: New certificate for %s is %r" %
                     (domain, save_model.public_certificate))
        return save_model
Esempio n. 6
0
def self_enroll():
    from certidude import const
    common_name = const.FQDN
    directory = os.path.join("/var/lib/certidude", const.FQDN)
    self_key_path = os.path.join(directory, "self_key.pem")

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(self_key_path)
    except FileNotFoundError:  # certificate or private key not found
        with open(self_key_path, 'wb') as fh:
            public_key, private_key = asymmetric.generate_pair('rsa',
                                                               bit_size=2048)
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, public_key)
    request = builder.build(private_key)
    with open(os.path.join(directory, "requests", common_name + ".pem"),
              "wb") as fh:
        fh.write(pem_armor_csr(request))
    pid = os.fork()
    if not pid:
        from certidude import authority
        from certidude.common import drop_privileges
        drop_privileges()
        authority.sign(common_name, skip_push=True, overwrite=True)
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        if os.path.exists("/etc/systemd"):
            os.system("systemctl reload nginx")
        else:
            os.system("service nginx reload")
Esempio n. 7
0
#!/usr/bin/env python3

from oscrypto import asymmetric
from csrbuilder import CSRBuilder, pem_armor_csr
from datetime import date


private_key = asymmetric.load_private_key('./secrets/packagecontrol.io.key', None)

builder = CSRBuilder(
    {
        'country_name': 'US',
        'state_or_province_name': 'New Hampshire',
        'locality_name': 'Plymouth',
        'organization_name': 'Codex Non Sufficit LLC',
        'common_name': 'packagecontrol.io',
    },
    private_key.public_key.asn1
)
# Add subjectAltName domains
builder.subject_alt_domains = ['packagecontrol.io', 'www.packagecontrol.io']
request = builder.build(private_key)

with open('./secrets/packagecontrol.io-%s.csr' % date.today().year, 'wb') as f:
    f.write(pem_armor_csr(request))
Esempio n. 8
0
 def to_pem(self):
     return pem_armor_csr(self._csr)
Esempio n. 9
0
def generatekey():
    if os.path.exists(str(keypath)):
        print("Certificate already exists in: ")
        print(keypath)
        message = sendgrid.Mail()
        sg = sendgrid.SendGridClient(
            'Username ', 'Password'
        )  # Input username and password of SendGrid account to send emails.
        # Sends an email so we can track failures of key generation.
        message.set_from("Email Notification")
        message.add_to(errorToEmail)
        message.set_subject("CSR Generation failed report ")
        message.set_html('CSR Generation failed for ' + domainName +
                         ' KEY file already exists')

        sg.send(message)
        sys.exit(1)
    else:
        with open(keypath, 'wb') as f:
            f.write(asymmetric.dump_private_key(private_key, 'ENCRYPT')
                    )  # encrypts private key, using a password to unencrypt

    builder = CSRBuilder(
        {
            'country_name': country,
            'state_or_province_name': state,
            'locality_name': city,
            'organization_name': companyName,
            'common_name': 'secure.' + domainName,
        }, public_key)
    request = builder.build(private_key)
    # Writes the CSR to a file
    with open(csrpath, 'wb') as f:
        f.write(pem_armor_csr(request))
    f = open(HOME + '/' + csrName)
    readCSR = f.read()

    # AUTH INFORMATION FOR DIGICERT
    headers = {
        "X-DC-DEVKEY": "",
        "Content-Type": "application/json",
    }
    # Parameters for the DigiCert order
    p = json.dumps({
        "certificate": {
            "common_name": str('secure.' + domainName),
            "csr": readCSR,
            "signature_hash": "sha256",
            "server_platform": {
                "id": 31
            },
        },
        "organization": {
            "id": orgID
        },
        "validity_years": years,
        "payment_method": "balance",
    })

    response = requests.post(
        'https://www.digicert.com/services/v2/order/certificate/ssl_plus',
        headers=headers,
        data=p)

    api_json = json.loads(response.text)
    print(api_json)

    idVal = api_json['id']
    print(idVal)

    sg = sendgrid.SendGridClient(
        'Username ', 'Password'
    )  # Creates email, sends to the account contact notifing of order
    message = sendgrid.Mail()

    # Grabbed the DigiCert order information for the confirmation email
    clientInfo = requests.get(
        'https://www.digicert.com/services/v2/order/certificate/' + str(idVal),
        headers=headers)
    info_json = json.loads(clientInfo.text)
    # Grabs details from the Order confirmation for email notification
    clientFirstName = info_json['organization_contact']['first_name']
    clientName = info_json['organization_contact'][
        'first_name'] + ' ' + info_json['organization_contact']['last_name']
    clientEmail = info_json['organization_contact']['email']
    clientPhone = info_json['organization_contact']['telephone']

    emailString = """Hello """ + str(clientFirstName) + """,
Your DigiCert SSL Certificate order has been placed and is pending your verification. If the new order is not issued soon, your current SSL Certificate will expire. As a result, your secure, online, check out page will no longer function along with your LiveScore survey system.
We recommend you contact DigiCert directly to help ensure your SSL Certificate is issued in a timely manner.

Your Order Number: """ + str(idVal) + """

Your Current SSL Certificate Expiration: """ + str(expireDate) + """

DigiCert Business Contact Associated with Order (Please confirm this information is correct): 
""" + str(clientName) + """
""" + str(clientEmail) + """
""" + str(clientPhone) + """

DigiCert Support Phone Number: 801-701-9600

DigiCert Support Email: [email protected]

Most of the time, DigiCert attempts an outbound call to the business contact listed in their system. DigiCert requires this phone call as part of their verification process before your SSL Certificate can be issued. If your business contact number listed above is incorrect, please let me know as soon as possible so I can update the order information."""

    message.add_bcc(clientEmail)
    message.add_to(
        'User Email'
    )  # Set add_to email for the users email so that you can monitor the sent emails
    message.set_from("FROM EMAIL")  # the From field value, for people to see
    message.set_subject("Recent Digicert SSL Certificate Order Placed")
    message.set_text(emailString)
    print("email sent to: " + str(clientEmail))
    sg.send(message)