예제 #1
0
def get_username_from_cert(cert_string):
    try:
        gid = GID(string=cert_string)
        
        # extract the URN in the subjectAltName
        urn_str = gid.get_urn()
        
        logger.debug("URN: %s" % urn_str)
        
    except:
        logger.warn("Failed to get certificate from string.")
        logger.warn(traceback.format_exc())
        return cert_string
    
    try:
        urn = URN(urn=str(urn_str))
    except ValueError:
        return cert_string
    
    # check if this user is one of ours
    home_urn = get_user_urn(urn.getName())
    if home_urn == urn.urn_string():
        username = urn.getName()
    else:
        username = urn_to_username(urn.urn_string())
        
    logger.debug("Returning username %s" % username)
    
    return username
예제 #2
0
    def clean(self):
        """Check that the cert file is signed by the key file and is trusted."""
        logger.debug("cleaned_data %s" % self.cleaned_data)
        if self.files:
            self.key = Keypair(string=self.files["key_file"].read())
            self.cert = GID(string=self.files["cert_file"].read())
            
            cert_pubkey = self.cert.get_pubkey().get_pubkey_string()
            if cert_pubkey != self.key.get_pubkey_string():
                raise forms.ValidationError(
                    "Error: The certificate was not signed "
                    "by the uploaded key. Please use a key "
                    "that matches the certificate.")
    
            try:
                certs = [GID(filename=f) for f in get_trusted_cert_filenames()]
                self.cert.verify_chain(certs)
            except Exception as e:
                logger.error(traceback.format_exc())
                raise forms.ValidationError(
                    "Could not verify that the uploaded certificate is "
                    "trusted. This could be because none of the certificate's "
                    "ancestors have been installed as trusted. The error was: "
                    "%s" % e
                )

        return self.cleaned_data
예제 #3
0
class UploadCertForm(forms.Form):
    """Form to upload a certificate and its corresponding key."""
    
    key_file = forms.FileField(
        help_text="Select the file that contains the key for the "\
            "certificate to upload.")
    cert_file = forms.FileField(
        help_text="Select the file that contains the "\
            "certificate to upload. The certificate must be signed "\
            "with the uploaded key.")
    
    clean_key_file = _clean_x_file_factory("key")
    clean_cert_file = _clean_x_file_factory("cert")
            
    def clean(self):
        """Check that the cert file is signed by the key file and is trusted."""
        logger.debug("cleaned_data %s" % self.cleaned_data)
        if self.files:
            self.key = Keypair(string=self.files["key_file"].read())
            self.cert = GID(string=self.files["cert_file"].read())
            
            cert_pubkey = self.cert.get_pubkey().get_pubkey_string()
            if cert_pubkey != self.key.get_pubkey_string():
                raise forms.ValidationError(
                    "Error: The certificate was not signed "
                    "by the uploaded key. Please use a key "
                    "that matches the certificate.")
    
            try:
                certs = [GID(filename=f) for f in get_trusted_cert_filenames()]
                self.cert.verify_chain(certs)
            except Exception as e:
                logger.error(traceback.format_exc())
                raise forms.ValidationError(
                    "Could not verify that the uploaded certificate is "
                    "trusted. This could be because none of the certificate's "
                    "ancestors have been installed as trusted. The error was: "
                    "%s" % e
                )

        return self.cleaned_data
    
    def save(self, user):
        """Write the key and cert into files.
        
        @param user: the user to save the cert and key for.
        @type user: C{django.contrib.auth.models.User}
        """
        
        key_fname = get_user_key_fname(user)
        cert_fname = get_user_cert_fname(user)
        
        self.key.save_to_file(key_fname)
        self.cert.save_to_file(cert_fname)
예제 #4
0
def read_cert_from_string(cert_str):
    """Read a GCF certificate from a string.

    Read the certificate from a string and put it into a C{sfa.trust.gid.GID}
    object. The returned certificate is already decoded.

    @param cert_str: The string to read the cert from
    @type cert_str: C{str}
    @return: The certificate stored in the string at C{cert_str}
    @rtype: C{sfa.trust.gid.GID}
    """

    cert = GID(string=cert_str)
    cert.decode()
    return cert
예제 #5
0
def read_cert_from_file(cert_fname):
    """Read a GCF certificate from a file.
    
    Read the certificate from a file and put it into a C{sfa.trust.gid.GID}
    object. The returned certificate is already decoded.
    
    @param cert_fname: The filename to read the cert from
    @type cert_fname: C{str}
    @return: The certificate stored in the file at C{cert_fname}
    @rtype: C{sfa.trust.gid.GID}
    """

    cert = GID(filename=cert_fname)
    cert.decode()
    return cert
예제 #6
0
def read_cert_from_string(cert_str):
    """Read a GCF certificate from a string.

    Read the certificate from a string and put it into a C{sfa.trust.gid.GID}
    object. The returned certificate is already decoded.

    @param cert_str: The string to read the cert from
    @type cert_str: C{str}
    @return: The certificate stored in the string at C{cert_str}
    @rtype: C{sfa.trust.gid.GID}
    """

    cert = GID(string=cert_str)
    cert.decode()
    return cert
예제 #7
0
def read_cert_from_file(cert_fname):
    """Read a GCF certificate from a file.
    
    Read the certificate from a file and put it into a C{sfa.trust.gid.GID}
    object. The returned certificate is already decoded.
    
    @param cert_fname: The filename to read the cert from
    @type cert_fname: C{str}
    @return: The certificate stored in the file at C{cert_fname}
    @rtype: C{sfa.trust.gid.GID}
    """
    
    cert = GID(filename=cert_fname)
    cert.decode()
    return cert
예제 #8
0
def create_null_slice_cred():
    """Create a slice cred that can be used to list resources."""
    slice_urn = create_slice_urn()
    slice_gid, _ = create_x509_cert(slice_urn)
    user_gid = GID(filename=settings.GCF_X509_CH_CERT)
    ucred = create_slice_credential(user_gid, slice_gid)
    ucred.save_to_file(settings.GCF_NULL_SLICE_CRED)
예제 #9
0
 def get_am_cred(cls):
     """
     Get the slice authority credentials to use for AM calls.
     
     @return: GENI credential string.
     """
     slice_urn = create_slice_urn()
     slice_gid, _ = create_x509_cert(slice_urn)
     user_gid = GID(filename=settings.GCF_X509_CH_CERT)
     ucred = create_slice_credential(user_gid, slice_gid)
     return ucred.save_to_string()
예제 #10
0
    def _get_client(self, cert_fname, key_fname):
        try:
            u = self.url
        except AttributeError:
            raise self.URLNotDefined("URL not set.")
        if not u:
            raise self.URLNotDefined("URL not set.")

        parsed = urlparse(u.lower())
        if parsed.scheme == "test":
            user_cert = GID(filename=cert_fname).save_to_string()
            transport = TestClientTransport(defaults={
                "REMOTE_USER": user_cert,
                "SSL_CLIENT_CERT": user_cert
            })
            proxy = xmlrpclib.ServerProxy(
                test_to_http(u),
                transport=transport,
            )
        else:
            transport = certtransport.SafeTransportWithCert(
                keyfile=key_fname, certfile=cert_fname)
            proxy = xmlrpclib.ServerProxy(u, transport=transport)
        return proxy
예제 #11
0
def create_cert(urn, issuer_key=None, issuer_cert=None, intermediate=False):
    '''Create a new certificate and return it and the associated keys.
    If issuer cert and key are given, they sign the certificate. Otherwise
    it is a self-signed certificate. 
    
    If intermediate then mark this 
    as an intermediate CA certificate (can sign).
    
    Certificate URN must be supplied.
    CN of the cert will be dotted notation authority.type.name from the URN.
    '''
    # Note the below throws a ValueError if it wasnt a valid URN
    c_urn = URN(urn=urn)
    dotted = '%s.%s.%s' % (c_urn.getAuthority(), c_urn.getType(), c_urn.getName())
    

    newgid = GID(create=True, subject=dotted[:64],
                     urn=urn)
    
    keys = Keypair(create=True)
    newgid.set_pubkey(keys)
    if intermediate:
        # This cert will be able to sign certificates
        newgid.set_intermediate_ca(intermediate)
        
    if issuer_key and issuer_cert:
        # the given issuer will issue this cert
        if isinstance(issuer_key,str):
            issuer_key = Keypair(filename=issuer_key)
        if isinstance(issuer_cert,str):
            issuer_cert = GID(filename=issuer_cert)
        newgid.set_issuer(issuer_key, cert=issuer_cert)
        newgid.set_parent(issuer_cert)
    else:
        # create a self-signed cert
        newgid.set_issuer(keys, subject=dotted)

    newgid.encode()
    newgid.sign()
    return newgid, keys
예제 #12
0
 def get_slice_cred(self, slice, user):
     info = slice.geni_slice_info
     user_cert = get_or_create_user_cert(user)
     return create_slice_credential(
         user_cert, GID(string=str(info.slice_gid))).save_to_string()