Exemplo n.º 1
0
def _download_http_crl(endpoint, key_identifier):
    """
    :param endpoint: url della crl
    :param key_identifier: chiave identificativa dell'issuer del certificato
    :return:
    """

    crl_dest = make_crl_store_path(endpoint, key_identifier) + ".crl"
    crl_meta_dest = make_crl_store_path(endpoint, key_identifier) + ".txt"

    try:
        r = requests.get(endpoint)
        if r.status_code == 200:
            try:
                crl = crypto.load_crl(crypto.FILETYPE_PEM, r.content)
            except:
                crl_x509 = x509.load_der_x509_crl(r.content, default_backend())
                crl = crypto.CRL.from_cryptography(crl_x509)
            with open(crl_dest, 'w') as f:
                f.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl).decode())
            with open(crl_meta_dest, 'w') as f:
                f.write(endpoint)
        else:
            LOG.error('Errore durante il download della CRL con endpoint = {}'.
                      format(endpoint),
                      extra=set_client_ip())
    except Exception as e:
        LOG.error(
            'Eccezione durante il download della CRL con key_identifier = {}'.
            format(key_identifier),
            extra=set_client_ip())
        LOG.error("Exception: {}".format(str(e)), extra=set_client_ip())
Exemplo n.º 2
0
def main():
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    ca = crypto.X509()
    ca.set_version(2)
    ca.set_serial_number(1)
    ca.get_subject().CN = 'snakeoil'
    ca.set_notBefore(b'19700101000000Z')
    ca.set_notAfter(b'20991231235959Z')
    ca.set_issuer(ca.get_subject())
    ca.set_pubkey(pkey)
    ca.sign(pkey, 'sha256')

    revoked = crypto.Revoked()
    revoked.set_serial(b'2a')
    revoked.set_rev_date(b'19700101000000Z')
    revoked.set_reason(None)

    crl = crypto.CRL()
    crl.set_lastUpdate(b'19700101000000Z')
    crl.set_nextUpdate(b'20990101000000Z')
    crl.add_revoked(revoked)
    crl.sign(issuer_cert=ca, issuer_key=pkey, digest=b'sha256')

    with open(osp.join(osp.dirname(__file__), 'minimal.crl'), 'wb') as f_crl:
        f_crl.write(crypto.dump_crl(crypto.FILETYPE_ASN1, crl))
Exemplo n.º 3
0
def get_crl_next_update(filename):
    ''' Read the CRL file and return the next update as datetime '''
    crldt = None
    crl_obj = cpt.load_crl(cpt.FILETYPE_PEM, open(filename).read())
    crl_text = cpt.dump_crl(cpt.FILETYPE_TEXT, crl_obj).decode("utf-8")
    for line in crl_text.split("\n"):
        if "Next Update: " in line:
            key, value = line.split(":", 1)
            date = value.strip()
            crldt = datetime.strptime(date, "%b %d %X %Y %Z")
            break
    return crldt
Exemplo n.º 4
0
def RunFakeServer(cbsd_sas_version, sas_sas_version, is_ecc, crl_index):
    FakeSasHandler.SetVersion(cbsd_sas_version, sas_sas_version)
    if is_ecc:
        assert ssl.HAS_ECDH
    server = HTTPServer((HOST, PORT), FakeSasHandler)

    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.options |= ssl.CERT_REQUIRED

    # If CRLs were provided, then enable revocation checking.
    if crl_index is not None:
        ssl_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN

        try:
            crl_files = ParseCrlIndex(crl_index)
        except IOError as e:
            print("Failed to parse CRL index file %r: %s" % (crl_index, e))

        # https://tools.ietf.org/html/rfc5280#section-4.2.1.13 specifies that
        # CRLs MUST be DER-encoded, but SSLContext expects the name of a PEM-encoded
        # file, so we must convert it first.
        for f in crl_files:
            try:
                with file(f) as handle:
                    der = handle.read()
                    try:
                        crl = crypto.load_crl(crypto.FILETYPE_ASN1, der)
                    except crypto.Error as e:
                        print("Failed to parse CRL file %r as DER format: %s" %
                              (f, e))
                        return
                    with tempfile.NamedTemporaryFile() as tmp:
                        tmp.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl))
                        tmp.flush()
                        ssl_context.load_verify_locations(cafile=tmp.name)
                print("Loaded CRL file: %r" % f)
            except IOError as e:
                print("Failed to load CRL file %r: %s" % (f, e))
                return

    ssl_context.load_verify_locations(cafile=CA_CERT)
    ssl_context.load_cert_chain(
        certfile=ECC_CERT_FILE if is_ecc else CERT_FILE,
        keyfile=ECC_KEY_FILE if is_ecc else KEY_FILE,
    )
    ssl_context.set_ciphers(':'.join(ECC_CIPHERS if is_ecc else CIPHERS))
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    server.socket = ssl_context.wrap_socket(server.socket, server_side=True)
    print('Will start server at %s:%d, use <Ctrl-C> to stop.' % (HOST, PORT))
    server.serve_forever()
Exemplo n.º 5
0
Arquivo: CA.py Projeto: sted19/pyCA
def issue_crl(new_revoked=None):
    global certificate, key, crl
    if not crl:
        crl = crypto.CRL()
        crl.set_lastUpdate(
            b'20191215152933Z'
        )  # TODO: adjust with real timestamps according to pyOpenSSL documentation
        crl.set_nextUpdate(b'20191217152933Z')
    if new_revoked:
        crl.add_revoked(new_revoked)
    crl.sign(certificate, key, b"sha256")
    crl_dump = crypto.dump_crl(crypto.FILETYPE_PEM, crl)
    open(CRL, "wt").write(crl_dump.decode("utf-8"))
    return crl_dump
Exemplo n.º 6
0
def create_revoke_list(ca_cert: bytes, ca_key: bytes,
                       serials: List[Tuple[int, datetime]]) -> bytes:
    crl = crypto.CRL()

    crl.set_lastUpdate(datetime.utcnow().strftime('%Y%m%d%H%M%SZ').encode())
    crl.set_nextUpdate(
        (datetime.utcnow() +
         timedelta(days=365)).strftime('%Y%m%d%H%M%SZ').encode())
    for serial, revoked_at in serials:
        revoked = crypto.Revoked()
        revoked.set_serial(hex(serial)[2:].encode())
        revoked.set_reason(b'keyCompromise')
        revoked.set_rev_date(revoked_at.strftime('%Y%m%d%H%M%SZ').encode())
        crl.add_revoked(revoked)
    key = crypto.load_privatekey(crypto.FILETYPE_PEM, ca_key)
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert)
    crl.sign(cert, key, digest.encode())
    return crypto.dump_crl(crypto.FILETYPE_PEM, crl)
Exemplo n.º 7
0
def _get_crl_next_update(filename):
    """
    Read the CRL file and return the next update as datetime
    :param filename:
    :return:
    """
    dt = None
    f = open(filename)
    crl_buff = f.read()
    f.close()
    crl_obj = crypto.load_crl(crypto.FILETYPE_PEM, crl_buff)
    # Get "Next Update" of CRL
    # Unfortunately pyOpenSSL does not support this. so we dump the
    # CRL and parse the text :-/
    # We do not want to add dependency to pyasn1
    crl_text = to_unicode(crypto.dump_crl(crypto.FILETYPE_TEXT, crl_obj))
    for line in crl_text.split("\n"):
        if "Next Update: " in line:
            key, value = line.split(":", 1)
            date = value.strip()
            dt = datetime.datetime.strptime(date, "%b %d %X %Y %Z")
            break
    return dt
Exemplo n.º 8
0
def _get_crl_next_update(filename):
    """
    Read the CRL file and return the next update as datetime
    :param filename:
    :return:
    """
    dt = None
    f = open(filename)
    crl_buff = f.read()
    f.close()
    crl_obj = crypto.load_crl(crypto.FILETYPE_PEM, crl_buff)
    # Get "Next Update" of CRL
    # Unfortunately pyOpenSSL does not support this. so we dump the
    # CRL and parse the text :-/
    # We do not want to add dependency to pyasn1
    crl_text = crypto.dump_crl(crypto.FILETYPE_TEXT, crl_obj)
    for line in crl_text.split("\n"):
        if "Next Update: " in line:
            key, value = line.split(":", 1)
            date = value.strip()
            dt = datetime.datetime.strptime(date, "%b %d %X %Y %Z")
            break
    return dt
Exemplo n.º 9
0
def main(argv):
    crl_file = sys.argv[1]
    xlsx_file = tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False)

    # Create a new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook(xlsx_file)
    worksheet = workbook.add_worksheet()
    bold = workbook.add_format({'bold': True})
    # Expand the columns so that the data is visible.
    worksheet.set_column('A:A', 39)
    worksheet.set_column('B:B', 36)
    worksheet.set_column('C:C', 10)
    worksheet.set_column('D:D', 13)
    worksheet.set_column('E:E', 19)
    # Write the column headers.
    worksheet.write('A1', 'Serial (int)', bold)
    worksheet.write('B1', 'Serial (hex)', bold)
    worksheet.write('C1', 'Date', bold)
    worksheet.write('D1', 'Time (UTC)', bold)
    worksheet.write('E1', 'Reason', bold)
    # Start from first row after headers.
    row = 1
    date_format = workbook.add_format({
        'num_format': 'dd-mm-yyyy',
        'align': 'left'
    })
    time_format = workbook.add_format({
        'num_format': 'hh:mm:ss',
        'align': 'left'
    })
    text_format = workbook.add_format({'num_format': '@', 'align': 'left'})

    with open(crl_file, "rb") as in_file:
        crl_obj = crypto.load_crl(crypto.FILETYPE_ASN1, in_file.read())
        crl_contents = crypto.dump_crl(crypto.FILETYPE_PEM, crl_obj)

        crl = x509.load_pem_x509_crl(crl_contents, default_backend())

        for revoked_cert in crl:
            serial_int = revoked_cert.serial_number
            serial_hex = '{:x}'.format(serial_int)
            revocation_datetime = revoked_cert.revocation_date

            try:
                reason_ext = revoked_cert.extensions.get_extension_for_oid(
                    x509.CRLEntryExtensionOID.CRL_REASON)
            except x509.extensions.ExtensionNotFound:
                reason = ""
            else:
                reason = reason_ext.value.reason.value

            # Add revocation to worksheet
            worksheet.write_string(row, 0, str(serial_int), text_format)
            worksheet.write_string(row, 1, serial_hex, text_format)
            worksheet.write_datetime(row, 2, revocation_datetime, date_format)
            worksheet.write_datetime(row, 3, revocation_datetime, time_format)
            worksheet.write_string(row, 4, reason, text_format)
            row += 1

        worksheet.autofilter('A1:E' + str(row - 1))
        # Close Excel workbook
        workbook.close()
        os.system('start excel.exe ' + xlsx_file.name)
Exemplo n.º 10
0
Arquivo: CA.py Projeto: sted19/pyCA
def start_server():
    global crl, certificate, key
    '''
    The CA will be listening on this address for 3 actions:
        - sign
        - revoke
        - getCrl
    clients will connect and ask for the action they need 
    '''
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        print("listening on port {}".format(PORT))
        while True:
            conn, addr = s.accept()
            print("connected by", addr)

            action = conn.recv(1024)
            if (not action):
                print("no action provided")
                exit
            action = action.decode("utf-8")

            # sign a certificate
            if (action == "sign"):
                conn.sendall(
                    "'sign' action activated. Provide CSR.".encode("utf-8"))
                correct = True
                csr = conn.recv(8384)
                if not csr:
                    print("connection closed by the client")
                    exit
                csr = csr.decode("utf-8")
                print(csr)
                conn.sendall("request received correctly".encode("utf-8"))

                signed_certificate = sign_certificate(csr)
                print("certificate ready to be sent")
                dump_cert = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                    signed_certificate)
                conn.sendall(dump_cert)

            # revoke a certificate
            elif (action == "revoke"):
                conn.sendall(
                    "'revoke' action activated. Provide certificate to revoke".
                    encode("utf-8"))
                client_certificate_dump = conn.recv(8384)
                if not client_certificate_dump:
                    print("error receiving the certificate")
                    exit
                print(client_certificate_dump.decode("utf-8"))
                conn.sendall("certificate received correctly".encode("utf-8"))

                client_certificate = crypto.load_certificate(
                    crypto.FILETYPE_PEM, client_certificate_dump)
                revoked = revoke(client_certificate)
                crl_dump = issue_crl(revoked)

                conn.sendall(crl_dump)

            # get CRL to check revocations
            elif (action == "getCrl"):
                conn.sendall(
                    b"'getCRL' action activated. Sending crl after receiving an ack."
                )

                print("received from client: ", conn.recv(128).decode("utf-8"))

                # crl should be renewed once in a while. In this example I send always the same global crl, only updating it with new revocations
                if crl:
                    crl_dump = crypto.dump_crl(crypto.FILETYPE_PEM, crl)
                    conn.sendall(crl_dump)
                else:
                    print("crl has not been created yet, let's create one")
                    crl_dump = issue_crl()
                    conn.sendall(crl_dump)
Exemplo n.º 11
0
def save_crl(crl, path):
    file = '/tmp/%s' % path
    with open(file, 'w') as f:
        f.write(dump_crl(FILETYPE_PEM, crl))
    print('CRL saved as %s' % file)
Exemplo n.º 12
0
def main(argv):
    parser = argparse.ArgumentParser(
        prog='crl2xlsx.py',
        usage='%(prog)s <CRL file (DER)> <name for new .xlsx file> ',
        description=
        'Creates an .xlsx file listing contents of a specified CRL file')
    parser.add_argument('infile', help='CRL file')
    parser.add_argument('outfile', help='name for new .xlsx file')
    args = parser.parse_args()
    crl_filename = args.infile
    xlsx_filename = args.outfile

    # Create a new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook(xlsx_filename)
    worksheet = workbook.add_worksheet()
    bold = workbook.add_format({'bold': True})
    # Expand the columns so that the data is visible.
    worksheet.set_column('A:B', 20)
    worksheet.set_column('C:C', 10)
    worksheet.set_column('D:D', 13)
    worksheet.set_column('E:E', 19)
    # Write the column headers.
    worksheet.write('A1', 'Serial (int)', bold)
    worksheet.write('B1', 'Serial (hex)', bold)
    worksheet.write('C1', 'Date', bold)
    worksheet.write('D1', 'Time (UTC)', bold)
    worksheet.write('E1', 'Reason', bold)
    # Start from first row after headers.
    row = 1
    date_format = workbook.add_format({
        'num_format': 'dd-mm-yyyy',
        'align': 'left'
    })
    time_format = workbook.add_format({
        'num_format': 'hh:mm:ss',
        'align': 'left'
    })
    text_format = workbook.add_format({'num_format': '@', 'align': 'left'})

    with open(crl_filename, "rb") as in_file:
        crl_obj = crypto.load_crl(crypto.FILETYPE_ASN1, in_file.read())
        crl_contents = crypto.dump_crl(crypto.FILETYPE_PEM, crl_obj)

        crl = x509.load_pem_x509_crl(crl_contents, default_backend())

        for revoked_cert in crl:
            serial_int = revoked_cert.serial_number
            serial_hex = '{:x}'.format(serial_int)
            revocation_datetime = revoked_cert.revocation_date

            try:
                reason_ext = revoked_cert.extensions.get_extension_for_oid(
                    x509.CRLEntryExtensionOID.CRL_REASON)
            except x509.extensions.ExtensionNotFound:
                reason = ""
            else:
                reason = reason_ext.value.reason.value

            # Add revocation to worksheet
            worksheet.write_string(row, 0, str(serial_int), text_format)
            worksheet.write_string(row, 1, serial_hex, text_format)
            worksheet.write_datetime(row, 2, revocation_datetime, date_format)
            worksheet.write_datetime(row, 3, revocation_datetime, time_format)
            worksheet.write_string(row, 4, reason, text_format)
            row += 1

        worksheet.autofilter('A1:E' + str(row - 1))
        # Close Excel workbook
        workbook.close()