/*
  * (non-Javadoc)
  *
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   StringBuilder result = new StringBuilder();
   result.append("Principal: " + getPrincipal() + ", Attributes: ");
   for (AttributeStatement attributeStatement : getAttributeStatements()) {
     for (Attribute attr : attributeStatement.getAttributes()) {
       result.append("[ ");
       result.append(attr.getName());
       result.append(" : ");
       for (int i = 0; i < attr.getAttributeValues().size(); i++) {
         result.append(((XSString) attr.getAttributeValues().get(i)).getValue());
       }
       result.append("] ");
     }
   }
   // add this back in when we support parsing this information
   result.append(", AuthnStatements: ");
   for (AuthnStatement authStatement : getAuthnStatements()) {
     result.append("[ ");
     result.append(authStatement.getAuthnInstant() + " : ");
     result.append(
         authStatement.getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
     result.append("] ");
   }
   //        result.append(", AuthzDecisionStatements: ");
   //        for (AuthzDecisionStatement authDecision : getAuthzDecisionStatements()) {
   //            result.append("[ ");
   //            result.append(authDecision.getDecision().toString());
   //            result.append(" ]");
   //        }
   return result.toString();
 }
 private Response buildMockResponse() throws Exception {
   Response samlMessage = new ResponseBuilder().buildObject();
   samlMessage.setID("foo");
   samlMessage.setVersion(SAMLVersion.VERSION_20);
   samlMessage.setIssueInstant(new DateTime(0));
   Issuer issuer = new IssuerBuilder().buildObject();
   issuer.setValue("MockedIssuer");
   samlMessage.setIssuer(issuer);
   Status status = new StatusBuilder().buildObject();
   StatusCode statusCode = new StatusCodeBuilder().buildObject();
   statusCode.setValue(StatusCode.SUCCESS_URI);
   status.setStatusCode(statusCode);
   samlMessage.setStatus(status);
   Assertion assertion = new AssertionBuilder().buildObject();
   Subject subject = new SubjectBuilder().buildObject();
   NameID nameID = new NameIDBuilder().buildObject();
   nameID.setValue("SOME-UNIQUE-ID");
   nameID.setFormat(NameIDType.PERSISTENT);
   subject.setNameID(nameID);
   assertion.setSubject(subject);
   AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
   authnStatement.setSessionIndex("Some Session String");
   assertion.getAuthnStatements().add(authnStatement);
   AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
   assertion.getAttributeStatements().add(attributeStatement);
   samlMessage.getAssertions().add(assertion);
   return samlMessage;
 }
 /*
  * (non-Javadoc)
  *
  * @see ddf.security.assertion.SecurityAssertion#getPrincipal()
  */
 @Override
 public Principal getPrincipal() {
   if (securityToken != null) {
     if (principal == null || !principal.getName().equals(name)) {
       String authMethod = null;
       if (authenticationStatements != null) {
         for (AuthnStatement authnStatement : authenticationStatements) {
           AuthnContext authnContext = authnStatement.getAuthnContext();
           if (authnContext != null) {
             AuthnContextClassRef authnContextClassRef = authnContext.getAuthnContextClassRef();
             if (authnContextClassRef != null) {
               authMethod = authnContextClassRef.getAuthnContextClassRef();
             }
           }
         }
       }
       if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authMethod)
           || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authMethod)
           || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authMethod)
           || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authMethod)
           || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authMethod)) {
         principal = new X500Principal(name);
       } else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_KERBEROS.equals(authMethod)) {
         principal = new KerberosPrincipal(name);
       } else if (principal instanceof GuestPrincipal
           || name.startsWith(GuestPrincipal.GUEST_NAME_PREFIX)) {
         principal = new GuestPrincipal(name);
       } else {
         principal = new AssertionPrincipal(name);
       }
     }
     return principal;
   }
   return null;
 }
  /**
   * Returns logout request message ready to be sent to the IDP.
   *
   * @param context message context
   * @param credential information about assertions used to log current user in
   * @param bindingService service used to deliver the request
   * @return logoutRequest to be sent to IDP
   * @throws SAMLException error creating the message
   * @throws MetadataProviderException error retrieving metadata
   */
  protected LogoutRequest getLogoutRequest(
      SAMLMessageContext context, SAMLCredential credential, Endpoint bindingService)
      throws SAMLException, MetadataProviderException {

    SAMLObjectBuilder<LogoutRequest> builder =
        (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    LogoutRequest request = builder.buildObject();
    buildCommonAttributes(context.getLocalEntityId(), request, bindingService);

    // Add session indexes
    SAMLObjectBuilder<SessionIndex> sessionIndexBuilder =
        (SAMLObjectBuilder<SessionIndex>)
            builderFactory.getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
    for (AuthnStatement statement : credential.getAuthenticationAssertion().getAuthnStatements()) {
      SessionIndex index = sessionIndexBuilder.buildObject();
      index.setSessionIndex(statement.getSessionIndex());
      request.getSessionIndexes().add(index);
    }

    if (request.getSessionIndexes().size() == 0) {
      throw new SAMLException("No session indexes to logout user for were found");
    }

    SAMLObjectBuilder<NameID> nameIDBuilder =
        (SAMLObjectBuilder<NameID>) builderFactory.getBuilder(NameID.DEFAULT_ELEMENT_NAME);
    NameID nameID = nameIDBuilder.buildObject();
    nameID.setFormat(credential.getNameID().getFormat());
    nameID.setNameQualifier(credential.getNameID().getNameQualifier());
    nameID.setSPNameQualifier(credential.getNameID().getSPNameQualifier());
    nameID.setSPProvidedID(credential.getNameID().getSPProvidedID());
    nameID.setValue(credential.getNameID().getValue());
    request.setNameID(nameID);

    return request;
  }
  /** {@inheritDoc} */
  protected void marshallAttributes(XMLObject samlObject, Element domElement)
      throws MarshallingException {
    AuthnStatement authnStatement = (AuthnStatement) samlObject;

    if (authnStatement.getAuthnInstant() != null) {
      String authnInstantStr =
          Configuration.getSAMLDateFormatter().print(authnStatement.getAuthnInstant());
      domElement.setAttributeNS(null, AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME, authnInstantStr);
    }

    if (authnStatement.getSessionIndex() != null) {
      domElement.setAttributeNS(
          null, AuthnStatement.SESSION_INDEX_ATTRIB_NAME, authnStatement.getSessionIndex());
    }

    if (authnStatement.getSessionNotOnOrAfter() != null) {
      String sessionNotOnOrAfterStr =
          Configuration.getSAMLDateFormatter().print(authnStatement.getSessionNotOnOrAfter());
      domElement.setAttributeNS(
          null, AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME, sessionNotOnOrAfterStr);
    }
  }
  private Assertion buildSAMLAssertion(
      SAMLSSOAuthnReqDTO authReqDTO, DateTime notOnOrAfter, String sessionId)
      throws IdentityException {
    try {
      DateTime currentTime = new DateTime();
      Assertion samlAssertion = new AssertionBuilder().buildObject();
      samlAssertion.setID(SAMLSSOUtil.createID());
      samlAssertion.setVersion(SAMLVersion.VERSION_20);
      samlAssertion.setIssuer(SAMLSSOUtil.getIssuer());
      samlAssertion.setIssueInstant(currentTime);
      Subject subject = new SubjectBuilder().buildObject();

      NameID nameId = new NameIDBuilder().buildObject();
      if (authReqDTO.getUseFullyQualifiedUsernameAsSubject()) {
        nameId.setValue(authReqDTO.getUsername());
        nameId.setFormat(NameIdentifier.EMAIL);
      } else {
        nameId.setValue(MultitenantUtils.getTenantAwareUsername(authReqDTO.getUsername()));
        nameId.setFormat(authReqDTO.getNameIDFormat());
      }

      subject.setNameID(nameId);

      SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject();
      subjectConfirmation.setMethod(SAMLSSOConstants.SUBJECT_CONFIRM_BEARER);

      SubjectConfirmationData scData = new SubjectConfirmationDataBuilder().buildObject();
      scData.setRecipient(authReqDTO.getAssertionConsumerURL());
      scData.setNotOnOrAfter(notOnOrAfter);
      scData.setInResponseTo(authReqDTO.getId());
      subjectConfirmation.setSubjectConfirmationData(scData);

      subject.getSubjectConfirmations().add(subjectConfirmation);

      samlAssertion.setSubject(subject);

      AuthnStatement authStmt = new AuthnStatementBuilder().buildObject();
      authStmt.setAuthnInstant(new DateTime());

      AuthnContext authContext = new AuthnContextBuilder().buildObject();
      AuthnContextClassRef authCtxClassRef = new AuthnContextClassRefBuilder().buildObject();
      authCtxClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
      authContext.setAuthnContextClassRef(authCtxClassRef);
      authStmt.setAuthnContext(authContext);
      if (authReqDTO.isDoSingleLogout()) {
        authStmt.setSessionIndex(sessionId);
      }
      samlAssertion.getAuthnStatements().add(authStmt);

      /*
       * If <AttributeConsumingServiceIndex> element is in the
       * <AuthnRequest> and
       * according to the spec 2.0 the subject MUST be in the assertion
       */
      Map<String, String> claims = SAMLSSOUtil.getAttributes(authReqDTO);
      if (claims != null) {
        samlAssertion.getAttributeStatements().add(buildAttributeStatement(claims));
      }

      AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject();
      Audience issuerAudience = new AudienceBuilder().buildObject();
      issuerAudience.setAudienceURI(authReqDTO.getIssuer());
      audienceRestriction.getAudiences().add(issuerAudience);
      if (authReqDTO.getRequestedAudiences() != null) {
        for (String requestedAudience : authReqDTO.getRequestedAudiences()) {
          Audience audience = new AudienceBuilder().buildObject();
          audience.setAudienceURI(requestedAudience);
          audienceRestriction.getAudiences().add(audience);
        }
      }
      Conditions conditions = new ConditionsBuilder().buildObject();
      conditions.setNotBefore(currentTime);
      conditions.setNotOnOrAfter(notOnOrAfter);
      conditions.getAudienceRestrictions().add(audienceRestriction);
      samlAssertion.setConditions(conditions);

      if (authReqDTO.getDoSignAssertions()) {
        SAMLSSOUtil.setSignature(
            samlAssertion,
            XMLSignature.ALGO_ID_SIGNATURE_RSA,
            new SignKeyDataHolder(authReqDTO.getUsername()));
      }

      return samlAssertion;
    } catch (Exception e) {
      log.error("Error when reading claim values for generating SAML Response", e);
      throw new IdentityException(
          "Error when reading claim values for generating SAML Response", e);
    }
  }
  public boolean processLogoutRequest(SAMLMessageContext context, SAMLCredential credential)
      throws SAMLException, MetadataProviderException, MessageEncodingException {

    SAMLObject message = context.getInboundSAMLMessage();

    // Verify type
    if (message == null || !(message instanceof LogoutRequest)) {
      log.warn("Received request is not of a LogoutRequest object type");
      throw new SAMLException("Error validating SAML request");
    }

    LogoutRequest logoutRequest = (LogoutRequest) message;

    // Make sure request was authenticated if required, authentication is done as part of the
    // binding processing
    if (!context.isInboundSAMLMessageAuthenticated()
        && context.getLocalExtendedMetadata().isRequireLogoutRequestSigned()) {
      log.warn(
          "Logout Request object is required to be signed by the entity policy: "
              + context.getInboundSAMLMessageId());
      Status status = getStatus(StatusCode.REQUEST_DENIED_URI, "Message signature is required");
      sendLogoutResponse(status, context);
      return false;
    }

    try {
      // Verify destination
      verifyEndpoint(context.getLocalEntityEndpoint(), logoutRequest.getDestination());
    } catch (SAMLException e) {
      log.warn(
          "Destination of the request {} does not match any singleLogout endpoint",
          logoutRequest.getDestination());
      Status status =
          getStatus(StatusCode.REQUEST_DENIED_URI, "Destination URL of the request is invalid");
      sendLogoutResponse(status, context);
      return false;
    }

    // Verify issuer
    if (logoutRequest.getIssuer() != null) {
      try {
        Issuer issuer = logoutRequest.getIssuer();
        verifyIssuer(issuer, context);
      } catch (SAMLException e) {
        log.warn(
            "Response issue time is either too old or with date in the future, id {}",
            context.getInboundSAMLMessageId());
        Status status =
            getStatus(StatusCode.REQUEST_DENIED_URI, "Issuer of the message is unknown");
        sendLogoutResponse(status, context);
        return false;
      }
    }

    // Verify issue time
    DateTime time = logoutRequest.getIssueInstant();
    if (!isDateTimeSkewValid(getResponseSkew(), time)) {
      log.warn(
          "Response issue time is either too old or with date in the future, id {}.",
          context.getInboundSAMLMessageId());
      Status status =
          getStatus(StatusCode.REQUESTER_URI, "Message has been issued too long time ago");
      sendLogoutResponse(status, context);
      return false;
    }

    // Check whether any user is logged in
    if (credential == null) {
      Status status = getStatus(StatusCode.UNKNOWN_PRINCIPAL_URI, "No user is logged in");
      sendLogoutResponse(status, context);
      return false;
    }

    // Find index for which the logout is requested
    boolean indexFound = false;
    if (logoutRequest.getSessionIndexes() != null && logoutRequest.getSessionIndexes().size() > 0) {
      for (AuthnStatement statement :
          credential.getAuthenticationAssertion().getAuthnStatements()) {
        String statementIndex = statement.getSessionIndex();
        if (statementIndex != null) {
          for (SessionIndex index : logoutRequest.getSessionIndexes()) {
            if (statementIndex.equals(index.getSessionIndex())) {
              indexFound = true;
            }
          }
        }
      }
    } else {
      indexFound = true;
    }

    // Fail if sessionIndex is not found in any assertion
    if (!indexFound) {

      // Check logout request still valid and store request
      if (logoutRequest.getNotOnOrAfter() != null) {
        // TODO store request for assertions possibly arriving later
      }

      Status status =
          getStatus(StatusCode.REQUESTER_URI, "The requested SessionIndex was not found");
      sendLogoutResponse(status, context);
      return false;
    }

    try {
      // Fail if NameId doesn't correspond to the currently logged user
      NameID nameID = getNameID(context, logoutRequest);
      if (nameID == null || !equalsNameID(credential.getNameID(), nameID)) {
        Status status =
            getStatus(StatusCode.UNKNOWN_PRINCIPAL_URI, "The requested NameID is invalid");
        sendLogoutResponse(status, context);
        return false;
      }
    } catch (DecryptionException e) {
      Status status = getStatus(StatusCode.RESPONDER_URI, "The NameID can't be decrypted");
      sendLogoutResponse(status, context);
      return false;
    }

    // Message is valid, let's logout
    Status status = getStatus(StatusCode.SUCCESS_URI, null);
    sendLogoutResponse(status, context);

    return true;
  }