Ejemplo n.º 1
0
    def _do_test(self, resourceContentsStr, expected_status, expected_decision):
        """Constructs, sends and evaluates the response from a SAML SOAP request
        using the XACML-SAML profile, with specified resource contents.
        """
        # Load the AuthorisationServiceMiddleware and
        # SOAPQueryInterfaceMiddleware so that the authorisation service can be
        # called.
        self.__class__.INI_FILEPATH = os.path.join(self.__class__.THIS_DIR, 
                                                   self.__class__.INI_FILE)
        wsgiapp = loadapp('config:'+self.__class__.INI_FILEPATH)
        self.app = paste.fixture.TestApp(wsgiapp)

        # Construct a SOAP request.
        (header, request) = self._makeRequest(resourceContentsStr,
                                              issuer=self.ISSUER_DN)

        # Send the SOAP request to the authorisation service.
        httpResponse = self.app.post(self.AUTHZ_SERVICE_URI, 
                                          params=request,
                                          headers=header,
                                          status=200)
        log.debug("Response status=%d", httpResponse.status)

        # Parse the SOAP response.
        envelope = SOAPEnvelope()
        respFile = StringIO(httpResponse.body)
        envelope.parse(respFile)

        # Extract the SAML response.
        samlAuthzResponse = ResponseElementTree.fromXML(envelope.body.elem[0])

#        serialisedResponse = pickle.dumps(samlAuthzResponse)
#        response2 = pickle.loads(serialisedResponse)

        assertions = samlAuthzResponse.assertions
        (assertion,
         error_status,
         error_message) = XacmlSamlPepFilter._evaluate_assertions(assertions,
                                                        self.SUBJECT_ID,
                                                        self.RESOURCE_URI,
                                                        self.AUTHZ_SERVICE_URI)
        if expected_status is None:
            self.assertTrue(error_status is None,
                            ("Unexpected error %d: %s" %
                             (0 if error_status is None else error_status,
                              error_message)))

            self.assertEqual(
                assertion.statements[0].xacmlContextResponse.results[0
                                                            ].decision.value,
                expected_decision)
        else:
            self.assertEqual(error_status, expected_status)
Ejemplo n.º 2
0
 def fromXML(cls, elem, **kw):
     """Extend base method adding mapping for ESG Group/Role Attribute Value
      
     @type elem: ElementTree.Element
     @param elem: ESGF Group/Role attribute value as ElementTree.Element
     @rtype: ndg.security.common.saml_utils.etree.ESGFGroupRoleAttributeValue
     @return: ESGF Group/Role attribute value 
     """
     toSAMLTypeMap = kw.get('customToSAMLTypeMap', [])
     toSAMLTypeMap.append(
                     ESGFGroupRoleAttributeValueElementTree.factoryMatchFunc)
     kw['customToSAMLTypeMap'] = toSAMLTypeMap
     
     return ResponseElementTree.fromXML(elem, **kw)
 def _parseResponse(self, responseStr):
     """Helper to parse a response from a string"""
     soapResponse = SOAPEnvelope()
     
     responseStream = StringIO()
     responseStream.write(responseStr)
     responseStream.seek(0)
     
     soapResponse.parse(responseStream)
     
     print("Parsed response ...")
     print(soapResponse.serialize())
     
     response = ResponseElementTree.fromXML(soapResponse.body.elem[0])
     return response
Ejemplo n.º 4
0
 def _getSAMLResponse(self, responseBody):
     """Deserialise response string into ElementTree element"""
     soapResponse = SOAPEnvelope()
     
     responseStream = StringIO()
     responseStream.write(responseBody.decode())
     responseStream.seek(0)
     
     soapResponse.parse(responseStream)
     
     print("Parsed response ...")
     print((soapResponse.serialize()))
     
     response = ResponseElementTree.fromXML(soapResponse.body.elem[0])
     
     return response
Ejemplo n.º 5
0
    def _getSAMLResponse(self, responseBody):
        """Deserialise response string into ElementTree element"""
        soapResponse = SOAPEnvelope()

        responseStream = StringIO()
        responseStream.write(responseBody)
        responseStream.seek(0)

        soapResponse.parse(responseStream)

        print("Parsed response ...")
        print(soapResponse.serialize())
        #        print(prettyPrint(soapResponse.elem))

        response = ResponseElementTree.fromXML(soapResponse.body.elem[0])

        return response
Ejemplo n.º 6
0
    def test02_with_action_namespace(self):
        # Handle case where response has used an invalid namespace URI for the
        # action specified.  In the example below 'GET' is used which belongs
        # to the urn:oasis:names:tc:SAML:1.0:action:ghpp namespace.  However,
        # it has not been set so the parser should interpret it as the default
        # urn:oasis:names:tc:SAML:1.0:action:rwedc-negation -
        # 2.7.4.2 SAML 2 Core Spec. 15 March 2005
        saml_resp = '''
<samlp:Response ID="1a0c8a92-f408-4ab6-b352-dc9ae5f025cb" 
InResponseTo="d78f66ec-ddce-4a2a-81cf-6bb2bf5ea624" 
IssueInstant="2016-01-24T06:06:04.389161Z" Version="2.0" 
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:Issuer 
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName" 
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">/C=GB/O=NDG/CN=localhost
</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<saml:Assertion ID="41aaf9d3-b637-4d54-ac7f-0b35316c4558" 
IssueInstant="2016-01-24T06:06:04.586012Z" Version="2.0" 
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Issuer 
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName">
/C=GB/O=NDG/CN=localhost
</saml:Issuer>
<saml:Subject>
<saml:NameID Format="urn:esg:openid" /></saml:Subject>
<saml:Conditions NotBefore="2016-01-24T06:06:04.586012Z" 
NotOnOrAfter="2016-01-25T06:06:04.586012Z" />
<saml:AuthzDecisionStatement Decision="Deny" 
Resource="http://localhost:8000/resource.html" >
<saml:Action Namespace="urn:oasis:names:tc:SAML:1.0:action:ghpp">GET
</saml:Action>
</saml:AuthzDecisionStatement>
</saml:Assertion></samlp:Response>
'''
        authz_decision_response_stream = StringIO()
        authz_decision_response_stream.write(saml_resp)
        authz_decision_response_stream.seek(0)

        tree = ElementTree.parse(authz_decision_response_stream)
        elem = tree.getroot()
        resp = ResponseElementTree.fromXML(elem)
        self.assertIsInstance(resp, Response, 'Expecting SAML Response type')
Ejemplo n.º 7
0
    def test06_deserialize_authz_decision_response(self):
        xmlOutput = self._serialize_authz_decision_query_response()
        
        authzDecisionResponseStream = StringIO()
        authzDecisionResponseStream.write(xmlOutput)
        authzDecisionResponseStream.seek(0)

        tree = ElementTree.parse(authzDecisionResponseStream)
        elem = tree.getroot()
        response = ResponseElementTree.fromXML(elem)
        
        self.assertTrue(response.assertions[0])
        self.assertTrue(response.assertions[0].authzDecisionStatements[0])
        self.assertTrue(response.assertions[0].authzDecisionStatements[0
            ].decision == DecisionType.PERMIT)
        self.assertTrue(response.assertions[0].authzDecisionStatements[0
            ].resource == SAMLUtil.RESOURCE_URI)
        self.assertTrue(response.assertions[0].authzDecisionStatements[0
            ].decision == DecisionType.PERMIT)
        self.assertTrue(response.assertions[0].authzDecisionStatements[0
            ].actions[-1].namespace == Action.GHPP_NS_URI)
        self.assertTrue(response.assertions[0].authzDecisionStatements[0
            ].actions[-1].value == Action.HTTP_GET_ACTION)
    def test01AttributeQuery(self):
        attributeQuery = AttributeQuery()
        attributeQuery.version = SAMLVersion(SAMLVersion.VERSION_20)
        attributeQuery.id = str(uuid4())
        attributeQuery.issueInstant = datetime.utcnow()
        
        attributeQuery.issuer = Issuer()
        attributeQuery.issuer.format = Issuer.X509_SUBJECT
        attributeQuery.issuer.value = \
                        "/O=NDG/OU=BADC/CN=attributeauthority.badc.rl.ac.uk"
                        
                        
        attributeQuery.subject = Subject()  
        attributeQuery.subject.nameID = NameID()
        attributeQuery.subject.nameID.format = SamlSoapBindingApp.NAMEID_FORMAT
        attributeQuery.subject.nameID.value = \
                                    "https://openid.localhost/philip.kershaw"
        
        # special case handling for 'FirstName' attribute
        fnAttribute = Attribute()
        fnAttribute.name = SamlSoapBindingApp.FIRSTNAME_ATTRNAME
        fnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string"
        fnAttribute.friendlyName = "FirstName"

        attributeQuery.attributes.append(fnAttribute)
    
        # special case handling for 'LastName' attribute
        lnAttribute = Attribute()
        lnAttribute.name = SamlSoapBindingApp.LASTNAME_ATTRNAME
        lnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string"
        lnAttribute.friendlyName = "LastName"

        attributeQuery.attributes.append(lnAttribute)
    
        # special case handling for 'LastName' attribute
        emailAddressAttribute = Attribute()
        emailAddressAttribute.name = SamlSoapBindingApp.EMAILADDRESS_ATTRNAME
        emailAddressAttribute.nameFormat = XMLConstants.XSD_NS+"#"+\
                                    XSStringAttributeValue.TYPE_LOCAL_NAME
        emailAddressAttribute.friendlyName = "emailAddress"

        attributeQuery.attributes.append(emailAddressAttribute)                                   
        
        elem = AttributeQueryElementTree.toXML(attributeQuery)
        soapRequest = SOAPEnvelope()
        soapRequest.create()
        soapRequest.body.elem.append(elem)
        
        request = soapRequest.serialize()
        
        header = {
            'soapAction': "http://www.oasis-open.org/committees/security",
            'Content-length': str(len(request)),
            'Content-type': 'text/xml'
        }
        response = self.app.post('/attributeauthority', 
                                 params=request, 
                                 headers=header, 
                                 status=200)
        print("Response status=%d" % response.status)

        soapResponse = SOAPEnvelope()
        
        responseStream = StringIO()
        responseStream.write(response.body)
        responseStream.seek(0)
        
        soapResponse.parse(responseStream)
        
        print("Parsed response ...")
        print(soapResponse.serialize())
#        print(prettyPrint(soapResponse.elem))
        
        response = ResponseElementTree.fromXML(soapResponse.body.elem[0])
        self.assert_(response.status.statusCode.value==StatusCode.SUCCESS_URI)
        self.assert_(response.inResponseTo == attributeQuery.id)
        self.assert_(response.assertions[0].subject.nameID.value == \
                     attributeQuery.subject.nameID.value)