Esempio n. 1
0
def do_key_descriptor(cert):
    return KeyDescriptor(
        key_info = ds.KeyInfo(
            x509_data=ds.X509Data(
                x509_certificate=ds.X509Certificate(text=cert)
            )
        )
    )
Esempio n. 2
0
def do_key_descriptor(cert, use="both"):
    if use == "both":
        return [
            md.KeyDescriptor(key_info=ds.KeyInfo(x509_data=ds.X509Data(
                x509_certificate=ds.X509Certificate(text=cert))),
                             use="encryption"),
            md.KeyDescriptor(key_info=ds.KeyInfo(x509_data=ds.X509Data(
                x509_certificate=ds.X509Certificate(text=cert))),
                             use="signing")
        ]
    elif use in ["signing", "encryption"]:
        md.KeyDescriptor(key_info=ds.KeyInfo(x509_data=ds.X509Data(
            x509_certificate=ds.X509Certificate(text=cert))),
                         use=use)
    else:
        return md.KeyDescriptor(key_info=ds.KeyInfo(x509_data=ds.X509Data(
            x509_certificate=ds.X509Certificate(text=cert))))
Esempio n. 3
0
 def key_descriptor():
     cert = get_cert()
     return md.KeyDescriptor(
         key_info=xmldsig.KeyInfo(
             x509_data=xmldsig.X509Data(
                 x509_certificate=xmldsig.X509Certificate(text=cert)
             )
         ), use='signing'
     )
Esempio n. 4
0
def do_key_descriptor(cert, use="signing"):
    return md.KeyDescriptor(
        key_info = ds.KeyInfo(
            x509_data=ds.X509Data(
                x509_certificate=ds.X509Certificate(text=cert)
            )
        ),
        use=use
    )
Esempio n. 5
0
    def _redirect_to_auth(self,
                          _cli,
                          entity_id,
                          came_from,
                          vorg_name="",
                          cert_str=None,
                          cert_key_str=None):
        try:
            _binding, destination = _cli.pick_binding("single_sign_on_service",
                                                      self.bindings,
                                                      "idpsso",
                                                      entity_id=entity_id)
            self.logger.debug("binding: %s, destination: %s" %
                              (_binding, destination))

            extensions = None
            if cert_key_str is not None:
                spcertenc = SPCertEnc(x509_data=ds.X509Data(
                    x509_certificate=ds.X509Certificate(text=cert_key_str)))
                extensions = Extensions(extension_elements=[
                    element_to_extension_element(spcertenc)
                ])

            if _cli.authn_requests_signed:
                _sid = saml2.s_utils.sid(_cli.seed)
                req_id, msg_str = _cli.create_authn_request(
                    destination,
                    vorg=vorg_name,
                    sign=_cli.authn_requests_signed,
                    message_id=_sid,
                    client_crt=cert_str,
                    extensions=extensions)
                _sid = req_id
            else:
                req_id, req = _cli.create_authn_request(destination,
                                                        vorg=vorg_name,
                                                        sign=False)
                msg_str = "%s" % req
                _sid = req_id

            _rstate = rndstr()
            self.cache.relay_state[_rstate] = came_from
            ht_args = _cli.apply_binding(_binding,
                                         msg_str,
                                         destination,
                                         relay_state=_rstate)

            self.logger.debug("ht_args: %s" % ht_args)
        except Exception, exc:
            self.logger.exception(exc)
            raise ServiceErrorException(
                "Failed to construct the AuthnRequest: %s" % exc)
Esempio n. 6
0
    def redirect_to_auth(self, _cli, entity_id, came_from):
        try:
            # Picks a binding to use for sending the Request to the IDP
            _binding, destination = _cli.pick_binding("single_sign_on_service",
                                                      self.bindings,
                                                      "idpsso",
                                                      entity_id=entity_id)
            logger.debug("binding: %s, destination: %s" %
                         (_binding, destination))
            # Binding here is the response binding that is which binding the
            # IDP should use to return the response.
            acs = _cli.config.getattr("endpoints",
                                      "sp")["assertion_consumer_service"]
            # just pick one
            endp, return_binding = acs[0]

            extensions = None
            cert = None
            if _cli.config.generate_cert_func is not None:
                cert_str, req_key_str = _cli.config.generate_cert_func()
                cert = {"cert": cert_str, "key": req_key_str}
                spcertenc = SPCertEnc(x509_data=ds.X509Data(
                    x509_certificate=ds.X509Certificate(text=cert_str)))
                extensions = Extensions(extension_elements=[
                    element_to_extension_element(spcertenc)
                ])

            req_id, req = _cli.create_authn_request(destination,
                                                    binding=return_binding,
                                                    extensions=extensions)
            _rstate = rndstr()
            self.cache.relay_state[_rstate] = came_from
            ht_args = _cli.apply_binding(_binding,
                                         "%s" % req,
                                         destination,
                                         relay_state=_rstate)
            _sid = req_id

            if cert is not None:
                self.cache.outstanding_certs[_sid] = cert

        except Exception as exc:
            logger.exception(exc)
            resp = ServiceError("Failed to construct the AuthnRequest: %s" %
                                exc)
            return resp

        # remember the request
        self.cache.outstanding_queries[_sid] = came_from
        return self.response(_binding, ht_args, do_not_start_response=True)
Esempio n. 7
0
def pre_signature_part(ident, public_key=None, identifier=None):
    """
    If an assertion is to be signed the signature part has to be preset
    with which algorithms to be used, this function returns such a
    preset part.
    
    :param ident: The identifier of the assertion, so you know which assertion
        was signed
    :param public_key: The base64 part of a PEM file
    :return: A preset signature part
    """

    signature_method = ds.SignatureMethod(algorithm=ds.SIG_RSA_SHA1)
    canonicalization_method = ds.CanonicalizationMethod(
        algorithm=ds.ALG_EXC_C14N)
    trans0 = ds.Transform(algorithm=ds.TRANSFORM_ENVELOPED)
    trans1 = ds.Transform(algorithm=ds.ALG_EXC_C14N)
    transforms = ds.Transforms(transform=[trans0, trans1])
    digest_method = ds.DigestMethod(algorithm=ds.DIGEST_SHA1)

    reference = ds.Reference(uri="#%s" % ident,
                             digest_value=ds.DigestValue(),
                             transforms=transforms,
                             digest_method=digest_method)

    signed_info = ds.SignedInfo(
        signature_method=signature_method,
        canonicalization_method=canonicalization_method,
        reference=reference)

    signature = ds.Signature(signed_info=signed_info,
                             signature_value=ds.SignatureValue())

    if identifier:
        signature.id = "Signature%d" % identifier

    if public_key:
        x509_data = ds.X509Data(x509_certificate=[
            ds.X509DataType_X509Certificate(text=public_key)
        ])
        key_info = ds.KeyInfo(x509_data=x509_data)
        signature.key_info = key_info

    return signature
Esempio n. 8
0
    def challenge(self, environ, _status, _app_headers, _forget_headers):

        _cli = self.saml_client

        if 'REMOTE_USER' in environ:
            name_id = decode(environ["REMOTE_USER"])

            _cli = self.saml_client
            path_info = environ['PATH_INFO']

            if 'samlsp.logout' in environ:
                responses = _cli.global_logout(name_id)
                return self._handle_logout(responses)

        if 'samlsp.pending' in environ:
            response = environ['samlsp.pending']
            if isinstance(response, HTTPRedirection):
                response.headers += _forget_headers
            return response

        #logger = environ.get('repoze.who.logger','')

        # Which page was accessed to get here
        came_from = construct_came_from(environ)
        environ["myapp.came_from"] = came_from
        logger.debug("[sp.challenge] RelayState >> '%s'" % came_from)

        # Am I part of a virtual organization or more than one ?
        try:
            vorg_name = environ["myapp.vo"]
        except KeyError:
            try:
                vorg_name = _cli.vorg._name
            except AttributeError:
                vorg_name = ""

        logger.info("[sp.challenge] VO: %s" % vorg_name)

        # If more than one idp and if none is selected, I have to do wayf
        (done, response) = self._pick_idp(environ, came_from)
        # Three cases: -1 something went wrong or Discovery service used
        #               0 I've got an IdP to send a request to
        #               >0 ECP in progress
        logger.debug("_idp_pick returned: %s" % done)
        if done == -1:
            return response
        elif done > 0:
            self.outstanding_queries[done] = came_from
            return ECP_response(response)
        else:
            entity_id = response
            logger.info("[sp.challenge] entity_id: %s" % entity_id)
            # Do the AuthnRequest
            _binding = BINDING_HTTP_REDIRECT
            try:
                srvs = _cli.metadata.single_sign_on_service(entity_id, _binding)
                logger.debug("srvs: %s" % srvs)
                dest = srvs[0]["location"]
                logger.debug("destination: %s" % dest)

                extensions = None
                cert = None

                if _cli.config.generate_cert_func is not None:
                    cert_str, req_key_str = _cli.config.generate_cert_func()
                    cert = {
                        "cert": cert_str,
                        "key": req_key_str
                    }
                    spcertenc = SPCertEnc(x509_data=ds.X509Data(
                        x509_certificate=ds.X509Certificate(text=cert_str)))
                    extensions = Extensions(extension_elements=[
                        element_to_extension_element(spcertenc)])

                if _cli.authn_requests_signed:
                    _sid = saml2.s_utils.sid(_cli.seed)
                    req_id, msg_str = _cli.create_authn_request(
                        dest, vorg=vorg_name, sign=_cli.authn_requests_signed,
                        message_id=_sid, extensions=extensions)
                    _sid = req_id
                else:
                    req_id, req = _cli.create_authn_request(
                        dest, vorg=vorg_name, sign=False, extensions=extensions)
                    msg_str = "%s" % req
                    _sid = req_id

                if cert is not None:
                    self.outstanding_certs[_sid] = cert

                ht_args = _cli.apply_binding(_binding, msg_str,
                                             destination=dest,
                                             relay_state=came_from)

                logger.debug("ht_args: %s" % ht_args)
            except Exception, exc:
                logger.exception(exc)
                raise Exception(
                    "Failed to construct the AuthnRequest: %s" % exc)

            try:
                ret = _cli.config.getattr(
                    "endpoints", "sp")["discovery_response"][0][0]
                if (environ["PATH_INFO"]) in ret and ret.split(
                        environ["PATH_INFO"])[1] == "":
                    query = parse_qs(environ["QUERY_STRING"])
                    sid = query["sid"][0]
                    came_from = self.outstanding_queries[sid]
            except:
                pass
            # remember the request
            self.outstanding_queries[_sid] = came_from

            if not ht_args["data"] and ht_args["headers"][0][0] == "Location":
                logger.debug('redirect to: %s' % ht_args["headers"][0][1])
                return HTTPSeeOther(headers=ht_args["headers"])
            else:
                return ht_args["data"]
Esempio n. 9
0
 def setup_class(self):
   self.x509_data = ds.X509Data()
Esempio n. 10
0
    def _create_signature(self):
        """Create an object that represents a SAML <Signature>.

        This must be filled with algorithms that the signing binary will apply
        in order to sign the whole message.
        Currently we enforce X509 signing.
        Example of the template::

        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
          <SignedInfo>
            <CanonicalizationMethod
              Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <SignatureMethod
              Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
            <Reference URI="#<Assertion ID>">
              <Transforms>
                <Transform
            Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
               <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
              </Transforms>
             <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
             <DigestValue />
            </Reference>
          </SignedInfo>
          <SignatureValue />
          <KeyInfo>
            <X509Data />
          </KeyInfo>
        </Signature>

        :return: XML <Signature> object

        """
        canonicalization_method = xmldsig.CanonicalizationMethod()
        canonicalization_method.algorithm = xmldsig.ALG_EXC_C14N
        signature_method = xmldsig.SignatureMethod(
            algorithm=xmldsig.SIG_RSA_SHA1)

        transforms = xmldsig.Transforms()
        envelope_transform = xmldsig.Transform(
            algorithm=xmldsig.TRANSFORM_ENVELOPED)

        c14_transform = xmldsig.Transform(algorithm=xmldsig.ALG_EXC_C14N)
        transforms.transform = [envelope_transform, c14_transform]

        digest_method = xmldsig.DigestMethod(algorithm=xmldsig.DIGEST_SHA1)
        digest_value = xmldsig.DigestValue()

        reference = xmldsig.Reference()
        reference.uri = '#' + self.assertion_id
        reference.digest_method = digest_method
        reference.digest_value = digest_value
        reference.transforms = transforms

        signed_info = xmldsig.SignedInfo()
        signed_info.canonicalization_method = canonicalization_method
        signed_info.signature_method = signature_method
        signed_info.reference = reference

        key_info = xmldsig.KeyInfo()
        key_info.x509_data = xmldsig.X509Data()

        signature = xmldsig.Signature()
        signature.signed_info = signed_info
        signature.signature_value = xmldsig.SignatureValue()
        signature.key_info = key_info

        return signature
Esempio n. 11
0
from saml2.extension.pefim import SPCertEnc
from saml2.samlp import Extensions
from saml2.samlp import authn_request_from_string
from saml2.sigver import read_cert_from_file
from pathutils import full_path

__author__ = 'roland'

conf = config.SPConfig()
conf.load_file("server_conf")
client = Saml2Client(conf)

# place a certificate in an authn request
cert = read_cert_from_file(full_path("test.pem"), "pem")

spcertenc = SPCertEnc(x509_data=ds.X509Data(
    x509_certificate=ds.X509Certificate(text=cert)))

extensions = Extensions(
    extension_elements=[element_to_extension_element(spcertenc)])

req_id, req = client.create_authn_request(
    "http://www.example.com/sso",
    "urn:mace:example.com:it:tek",
    nameid_format=saml.NAMEID_FORMAT_PERSISTENT,
    message_id="666",
    extensions=extensions)

print req

# Get a certificate from an authn request