churchyard / centos / centpkg

Forked from centos/centpkg 2 months ago
Clone
Blob Blame History Raw
from __future__ import print_function

import os
from cryptography import x509
import urlgrabber
import datetime

# This file was modified from the fedora_cert section in fedora-packager written
# by Dennis Gilmore (https://fedorahosted.org/fedora-packager/)


# Define our own error class
class centos_cert_error(Exception):
    pass

def _open_cert():
    """
    Read in the certificate so we dont duplicate the code 
    """
     # Make sure we can even read the thing.
    cert_file = os.path.join(os.path.expanduser('~'), ".koji", "client.crt")
    if not os.access(cert_file, os.R_OK):
        raise centos_cert_error("""!!!    cannot read your centos cert file   !!!
!!! Ensure the file is readable and try again !!!""")
    raw_cert = open(cert_file, 'rb').read()
    try:
        my_cert = x509.load_pem_x509_certificate(raw_cert)
    except TypeError:
        # it was required to specify a backend prior to cryptography 3.1
        from cryptography.hazmat.backends import default_backend
        my_cert = x509.load_pem_x509_certificate(raw_cert, default_backend())
    return my_cert

def verify_cert():
    """
    Check that the user cert is valid.
    things to check/return
    not revoked
    Expiry time warn if less than 21 days
    """
    my_cert = _open_cert()
    # CRL verification would go here
    #crl = urlgrabber.urlread("https://<url_to_crl>/ca/crl.pem")
    warn = datetime.datetime.now() + datetime.timedelta(days=21)

    print(my_cert.not_valid_after.strftime('cert expires: %Y-%m-%d'))

    if my_cert.not_valid_after < warn:
        print('WARNING: Your cert expires soon.')


def certificate_expired():
    """
    Check to see if client cert is expired
    Returns True or False

    """
    my_cert = _open_cert()

    return my_cert.not_valid_after < datetime.datetime.now()


def read_user_cert():
    """
    Figure out the Fedora user name from client cert

    """
    my_cert = _open_cert()

    [common_name] = my_cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
    return common_name.value