Search in sources :

Example 1 with Assertion

use of org.opensaml.saml2.core.Assertion in project OpenAttestation by OpenAttestation.

the class SamlGenerator method createHostAttributes.

/*  works but not needed
        private List<Attribute> createStringAttributes(Map<String,String> attributes) throws ConfigurationException {
            ArrayList<Attribute> list = new ArrayList<Attribute>();
            for(Map.Entry<String,String> e : attributes.entrySet()) {
                Attribute attr = createStringAttribute(e.getKey(), e.getValue());
                list.add(attr);
            }
            return list;
        }
        * 
        */
// currently unused but probably works
/*
	private Attribute createComplexAttribute(String name, String xmlValue) throws ConfigurationException {
            SAMLObjectBuilder attrBuilder = (SAMLObjectBuilder)  builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME);
            Attribute attr = (Attribute) attrBuilder.buildObject();
            attr.setName(name);

            XMLObjectBuilder stringBuilder =  builderFactory.getBuilder(XSString.TYPE_NAME);
            XSAny attrValue = (XSAny) stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSAny.TYPE_NAME);
            attrValue.setTextContent(xmlValue);

            attr.getAttributeValues().add(attrValue);
            return attr;
	}
	*/
//        private final String DEFAULT_OID = "2.5.4.789.1";
private AttributeStatement createHostAttributes(TxtHost host, X509AttributeCertificate tagCertificate, Map<String, String> vmMetaData) throws ConfigurationException {
    // Builder Attributes
    SAMLObjectBuilder attrStatementBuilder = (SAMLObjectBuilder) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME);
    AttributeStatement attrStatement = (AttributeStatement) attrStatementBuilder.buildObject();
    // add host attributes (both for single host and multi-host assertions)
    attrStatement.getAttributes().add(createStringAttribute("Host_Name", host.getHostName().toString()));
    attrStatement.getAttributes().add(createStringAttribute("Host_Address", host.getIPAddress().toString()));
    //            attrStatement.getAttributes().add(createStringAttribute("Host_UUID", host.getUuid()));  
    //            attrStatement.getAttributes().add(createStringAttribute("Host_AIK_SHA1", host.getUuid()));  
    // Create the attribute statements that are trusted
    attrStatement.getAttributes().add(createBooleanAttribute("Trusted", host.isBiosTrusted() && host.isVmmTrusted()));
    attrStatement.getAttributes().add(createBooleanAttribute("Trusted_BIOS", host.isBiosTrusted()));
    if (host.isBiosTrusted()) {
        attrStatement.getAttributes().add(createStringAttribute("BIOS_Name", host.getBios().getName()));
        attrStatement.getAttributes().add(createStringAttribute("BIOS_Version", host.getBios().getVersion()));
        attrStatement.getAttributes().add(createStringAttribute("BIOS_OEM", host.getBios().getOem()));
    }
    attrStatement.getAttributes().add(createBooleanAttribute("Trusted_VMM", host.isVmmTrusted()));
    if (host.isVmmTrusted()) {
        attrStatement.getAttributes().add(createStringAttribute("VMM_Name", host.getVmm().getName()));
        attrStatement.getAttributes().add(createStringAttribute("VMM_Version", host.getVmm().getVersion()));
        attrStatement.getAttributes().add(createStringAttribute("VMM_OSName", host.getVmm().getOsName()));
        attrStatement.getAttributes().add(createStringAttribute("VMM_OSVersion", host.getVmm().getOsVersion()));
    }
    //}
    if (tagCertificate != null) {
        // add the asset tag attestation status and if the status is trusted, then add all the attributes. In order to uniquely
        // identify all the asset tags on the client side, we will just append the text ATAG for all of them.
        attrStatement.getAttributes().add(createBooleanAttribute("Asset_Tag", host.isAssetTagTrusted()));
        attrStatement.getAttributes().add(createStringAttribute("Asset_Tag_Certificate_Sha1", Sha1Digest.digestOf(tagCertificate.getEncoded()).toString()));
        if (host.isAssetTagTrusted()) {
            // get all microformat attributes
            List<UTF8NameValueMicroformat> microformatAttributes = tagCertificate.getAttributes(UTF8NameValueMicroformat.class);
            for (UTF8NameValueMicroformat microformatAttribute : microformatAttributes) {
                attrStatement.getAttributes().add(createStringAttribute(String.format("TAG[" + microformatAttribute.getName() + "]"), microformatAttribute.getValue()));
            }
            // get all name-valuesequence attributes
            List<UTF8NameValueSequence> nameValueSequenceAttributes = tagCertificate.getAttributes(UTF8NameValueSequence.class);
            for (UTF8NameValueSequence nameValueSequenceAttribute : nameValueSequenceAttributes) {
                attrStatement.getAttributes().add(createStringAttribute(String.format("TAG[" + nameValueSequenceAttribute.getName() + "]"), StringUtils.join(nameValueSequenceAttribute.getValues(), ",")));
            }
            // all attributes including above and any other custom attributes will be available directly via the certificate
            attrStatement.getAttributes().add(createBase64BinaryAttribute("TagCertificate", tagCertificate.getEncoded()));
        } else {
            log.debug("Since Asset tag is not verified, no attributes would be added");
        }
    } else {
        log.debug("Since asset tag is not provisioned, asset tag attribute will not be added to the assertion.");
    }
    if (host.getAikCertificate() != null) {
        attrStatement.getAttributes().add(createStringAttribute("AIK_Certificate", host.getAikCertificate()));
    //attrStatement.getAttributes().add(createStringAttribute("AIK_SHA1", host.getAikSha1()));
    }
    if (vmMetaData != null && !vmMetaData.isEmpty()) {
        for (Map.Entry<String, String> entry : vmMetaData.entrySet()) {
            attrStatement.getAttributes().add(createStringAttribute(entry.getKey(), entry.getValue()));
        }
    }
    return attrStatement;
}
Also used : UTF8NameValueSequence(com.intel.mtwilson.datatypes.UTF8NameValueSequence) SAMLObjectBuilder(org.opensaml.common.SAMLObjectBuilder) AttributeStatement(org.opensaml.saml2.core.AttributeStatement) XSString(org.opensaml.xml.schema.XSString) UTF8NameValueMicroformat(com.intel.mtwilson.datatypes.UTF8NameValueMicroformat)

Example 2 with Assertion

use of org.opensaml.saml2.core.Assertion in project cas by apereo.

the class WsFederationHelper method parseTokenFromString.

/**
     * parseTokenFromString converts a raw wresult and extracts it into an assertion.
     *
     * @param wresult the raw token returned by the IdP
     * @param config  the config
     * @return an assertion
     */
public Assertion parseTokenFromString(final String wresult, final WsFederationConfiguration config) {
    LOGGER.debug("Result token received from ADFS is [{}]", wresult);
    try (InputStream in = new ByteArrayInputStream(wresult.getBytes(StandardCharsets.UTF_8))) {
        LOGGER.debug("Parsing token into a document");
        final Document document = configBean.getParserPool().parse(in);
        final Element metadataRoot = document.getDocumentElement();
        final UnmarshallerFactory unmarshallerFactory = configBean.getUnmarshallerFactory();
        final Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
        if (unmarshaller == null) {
            throw new IllegalArgumentException("Unmarshaller for the metadata root element cannot be determined");
        }
        LOGGER.debug("Unmarshalling the document into a security token response");
        final RequestSecurityTokenResponse rsToken = (RequestSecurityTokenResponse) unmarshaller.unmarshall(metadataRoot);
        if (rsToken == null || rsToken.getRequestedSecurityToken() == null) {
            throw new IllegalArgumentException("Request security token response is null");
        }
        //Get our SAML token
        LOGGER.debug("Locating list of requested security tokens");
        final List<RequestedSecurityToken> rst = rsToken.getRequestedSecurityToken();
        if (rst.isEmpty()) {
            throw new IllegalArgumentException("No requested security token response is provided in the response");
        }
        LOGGER.debug("Locating the first occurrence of a requested security token in the list");
        final RequestedSecurityToken reqToken = rst.get(0);
        if (reqToken.getSecurityTokens() == null || reqToken.getSecurityTokens().isEmpty()) {
            throw new IllegalArgumentException("Requested security token response is not carrying any security tokens");
        }
        Assertion assertion = null;
        LOGGER.debug("Locating the first occurrence of a security token from the requested security token");
        XMLObject securityToken = reqToken.getSecurityTokens().get(0);
        if (securityToken instanceof EncryptedData) {
            try {
                LOGGER.debug("Security token is encrypted. Attempting to decrypt to extract the assertion");
                final EncryptedData encryptedData = EncryptedData.class.cast(securityToken);
                final Decrypter decrypter = buildAssertionDecrypter(config);
                LOGGER.debug("Built an instance of [{}]", decrypter.getClass().getName());
                securityToken = decrypter.decryptData(encryptedData);
            } catch (final Exception e) {
                throw new IllegalArgumentException("Unable to decrypt security token", e);
            }
        }
        if (securityToken instanceof Assertion) {
            LOGGER.debug("Security token is an assertion.");
            assertion = Assertion.class.cast(securityToken);
        }
        if (assertion == null) {
            throw new IllegalArgumentException("Could not extract or decrypt an assertion based on the security token provided");
        }
        LOGGER.debug("Extracted assertion successfully: [{}]", assertion);
        return assertion;
    } catch (final Exception ex) {
        LOGGER.warn(ex.getMessage());
        return null;
    }
}
Also used : RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Assertion(org.opensaml.saml.saml1.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) Document(org.w3c.dom.Document) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse)

Example 3 with Assertion

use of org.opensaml.saml2.core.Assertion in project cas by apereo.

the class WsFederationHelperTests method verifyValidateSignatureBadKey.

@Test
@DirtiesContext
public void verifyValidateSignatureBadKey() throws Exception {
    final List<Credential> signingWallet = new ArrayList<>();
    final WsFederationConfiguration cfg = new WsFederationConfiguration();
    cfg.setSigningCertificateResources(ctx.getResource("classpath:bad-signing.crt"));
    signingWallet.addAll(cfg.getSigningCertificates());
    final String wresult = testTokens.get(GOOD_TOKEN);
    final Assertion assertion = wsFederationHelper.parseTokenFromString(wresult, wsFedConfig);
    wsFedConfig.getSigningCertificates().clear();
    wsFedConfig.getSigningCertificates().addAll(signingWallet);
    final boolean result = wsFederationHelper.validateSignature(assertion, wsFedConfig);
    assertFalse("testValidateSignatureModifiedKey() - False", result);
}
Also used : Credential(org.opensaml.security.credential.Credential) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) ArrayList(java.util.ArrayList) Assertion(org.opensaml.saml.saml1.core.Assertion) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Example 4 with Assertion

use of org.opensaml.saml2.core.Assertion in project cas by apereo.

the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.

/**
     * Construct SAML response.
     * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
     *
     * @param service the service
     * @return the SAML response
     */
protected String constructSamlResponse(final GoogleAccountsService service) {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(service.getPrincipal(), service);
    final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    final String sessionIndex = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
    final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
    assertion.setConditions(conditions);
    final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId());
    assertion.setSubject(subject);
    response.getAssertions().add(assertion);
    final StringWriter writer = new StringWriter();
    this.samlObjectBuilder.marshalSamlXmlObject(response, writer);
    final String result = writer.toString();
    LOGGER.debug("Generated Google SAML response: [{}]", result);
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Assertion(org.opensaml.saml.saml2.core.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) SecureRandom(java.security.SecureRandom) Conditions(org.opensaml.saml.saml2.core.Conditions) Subject(org.opensaml.saml.saml2.core.Subject) StringWriter(java.io.StringWriter) ZonedDateTime(java.time.ZonedDateTime) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement)

Example 5 with Assertion

use of org.opensaml.saml2.core.Assertion in project cas by apereo.

the class BaseSamlProfileSamlResponseBuilder method build.

@Override
public T build(final AuthnRequest authnRequest, final HttpServletRequest request, final HttpServletResponse response, final org.jasig.cas.client.validation.Assertion casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final Assertion assertion = buildSamlAssertion(authnRequest, request, response, casAssertion, service, adaptor);
    final T finalResponse = buildResponse(assertion, casAssertion, authnRequest, service, adaptor, request, response);
    return encodeFinalResponse(request, response, service, adaptor, finalResponse);
}
Also used : EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)175 Test (org.junit.jupiter.api.Test)118 Response (org.opensaml.saml.saml2.core.Response)62 AssertionBuilder.anAssertion (uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion)61 EncryptedAssertion (org.opensaml.saml.saml2.core.EncryptedAssertion)58 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)43 Attribute (org.opensaml.saml.saml2.core.Attribute)25 DateTime (org.joda.time.DateTime)22 Element (org.w3c.dom.Element)22 NameID (org.opensaml.saml.saml2.core.NameID)20 XMLObject (org.opensaml.core.xml.XMLObject)19 PassthroughAssertion (uk.gov.ida.saml.core.domain.PassthroughAssertion)17 ValidatedResponse (uk.gov.ida.saml.security.validators.ValidatedResponse)15 Authentication (org.springframework.security.core.Authentication)14 SubjectConfirmation (org.opensaml.saml.saml2.core.SubjectConfirmation)13 Test (org.junit.Test)12 AuthnStatement (org.opensaml.saml.saml2.core.AuthnStatement)12 Conditions (org.opensaml.saml.saml2.core.Conditions)12 HashMap (java.util.HashMap)11 NameIDBuilder (org.opensaml.saml.saml2.core.impl.NameIDBuilder)11