private String getUTDerivedKey() throws WSSecurityException {

    List<WSHandlerResult> results =
        CastUtils.cast(
            (List<?>) message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));

    for (WSHandlerResult rResult : results) {
      List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

      for (WSSecurityEngineResult wser : wsSecEngineResults) {
        Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
        String utID = (String) wser.get(WSSecurityEngineResult.TAG_ID);
        if (actInt.intValue() == WSConstants.UT_NOPASSWORD) {
          if (utID == null || utID.length() == 0) {
            utID = wssConfig.getIdAllocator().createId("UsernameToken-", null);
          }
          Date created = new Date();
          Date expires = new Date();
          expires.setTime(created.getTime() + 300000);
          SecurityToken tempTok = new SecurityToken(utID, created, expires);

          byte[] secret = (byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET);
          tempTok.setSecret(secret);
          tokenStore.add(tempTok);

          return utID;
        }
      }
    }
    return null;
  }
  private String getEncryptedKey() {

    List<WSHandlerResult> results =
        CastUtils.cast(
            (List<?>) message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));

    for (WSHandlerResult rResult : results) {
      List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

      for (WSSecurityEngineResult wser : wsSecEngineResults) {
        Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
        String encryptedKeyID = (String) wser.get(WSSecurityEngineResult.TAG_ID);
        if (actInt.intValue() == WSConstants.ENCR
            && encryptedKeyID != null
            && encryptedKeyID.length() != 0) {
          Date created = new Date();
          Date expires = new Date();
          expires.setTime(created.getTime() + 300000);
          SecurityToken tempTok = new SecurityToken(encryptedKeyID, created, expires);
          tempTok.setSecret((byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET));
          tempTok.setSHA1(
              getSHA1((byte[]) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
          tokenStore.add(tempTok);

          return encryptedKeyID;
        }
      }
    }
    return null;
  }
Exemplo n.º 3
0
  /** Test the Bearer SAML1 case with a Lifetime element */
  @org.junit.Test
  public void testBearerSaml1Lifetime() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

    // Get a token
    SecurityToken token =
        requestSecurityTokenTTL(SAML1_TOKEN_TYPE, BEARER_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertTrue(SAML1_TOKEN_TYPE.equals(token.getTokenType()));
    assertTrue(token.getToken() != null);

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper) results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(assertion != null);
    assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && methods.size() > 0) {
      confirmMethod = methods.get(0);
    }
    assertTrue(confirmMethod.contains("bearer"));

    bus.shutdown(true);
  }
  private String setupEncryptedKey(TokenWrapper wrapper, Token sigToken)
      throws WSSecurityException {
    WSSecEncryptedKey encrKey = this.getEncryptedKeyBuilder(wrapper, sigToken);
    String id = encrKey.getId();
    byte[] secret = encrKey.getEphemeralKey();

    Date created = new Date();
    Date expires = new Date();
    expires.setTime(created.getTime() + 300000);
    SecurityToken tempTok =
        new SecurityToken(id, encrKey.getEncryptedKeyElement(), created, expires);

    tempTok.setSecret(secret);

    // Set the SHA1 value of the encrypted key, this is used when the encrypted
    // key is referenced via a key identifier of type EncryptedKeySHA1
    tempTok.setSHA1(getSHA1(encrKey.getEncryptedEphemeralKey()));

    tokenStore.add(tempTok);

    String bstTokenId = encrKey.getBSTTokenId();
    // If direct ref is used to refer to the cert
    // then add the cert to the sec header now
    if (bstTokenId != null && bstTokenId.length() > 0) {
      encrKey.prependBSTElementToHeader(secHeader);
    }
    return id;
  }
Exemplo n.º 5
0
 private SecurityToken getTransformedToken(TokenStore ts, int hash) {
   SecurityToken recoveredToken = ts.getToken(Integer.toString(hash));
   if (recoveredToken != null && recoveredToken.getTokenHash() == hash) {
     String transformedTokenId = recoveredToken.getTransformedTokenIdentifier();
     if (transformedTokenId != null) {
       return ts.getToken(transformedTokenId);
     }
   }
   return null;
 }
  /**
   * Returns the SAML token as a DOM Element.
   *
   * @return the SAML token as a DOM element or null if it doesn't exist
   */
  public Element getSAMLTokenAsElement() {
    if (reference) {
      LOGGER.warn("Attempting to return a SAML token without converting from a reference.");
      return null;
    }

    SecurityToken token = (SecurityToken) getCredentials();
    if (token != null) {
      return token.getToken();
    }
    return null;
  }
Exemplo n.º 7
0
  private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(
        token.getToken(), requestData, new WSDocInfo(token.getToken().getOwnerDocument()));
  }
  private String setupUTDerivedKey(UsernameToken sigToken) throws WSSecurityException {
    boolean useMac = hasSignedPartsOrElements();
    WSSecUsernameToken usernameToken = addDKUsernameToken(sigToken, useMac);
    String id = usernameToken.getId();
    byte[] secret = usernameToken.getDerivedKey();

    Date created = new Date();
    Date expires = new Date();
    expires.setTime(created.getTime() + 300000);
    SecurityToken tempTok =
        new SecurityToken(id, usernameToken.getUsernameTokenElement(), created, expires);
    tempTok.setSecret(secret);

    tokenStore.add(tempTok);

    return id;
  }
Exemplo n.º 9
0
  private String setupEncryptedKey(AbstractTokenWrapper wrapper, AbstractToken sigToken)
      throws WSSecurityException {

    Date created = new Date();
    Date expires = new Date();
    expires.setTime(created.getTime() + 300000L);
    SecurityToken tempTok = new SecurityToken(IDGenerator.generateID(null), created, expires);

    KeyGenerator keyGenerator =
        KeyUtils.getKeyGenerator(
            sbinding.getAlgorithmSuite().getAlgorithmSuiteType().getEncryption());
    SecretKey symmetricKey = keyGenerator.generateKey();
    tempTok.setKey(symmetricKey);
    tempTok.setSecret(symmetricKey.getEncoded());

    TokenStoreUtils.getTokenStore(message).add(tempTok);

    return tempTok.getId();
  }
Exemplo n.º 10
0
  /** Test the Symmetric Key SAML1 case */
  @org.junit.Test
  public void testSymmetricKeySaml1() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

    // Get a token
    SecurityToken token =
        requestSecurityToken(SAML1_TOKEN_TYPE, SYMMETRIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertTrue(token.getSecret() != null && token.getSecret().length > 0);
    assertTrue(SAML1_TOKEN_TYPE.equals(token.getTokenType()));
    assertTrue(token.getToken() != null);

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);

    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper) results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(assertion != null);
    assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && methods.size() > 0) {
      confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertTrue(subjectKeyInfo.getSecret() != null);

    bus.shutdown(true);
  }
  private WSSecBase doEncryption(
      TokenWrapper recToken,
      SecurityToken encrTok,
      boolean attached,
      List<WSEncryptionPart> encrParts,
      boolean atEnd) {
    // Do encryption
    if (recToken != null && recToken.getToken() != null && encrParts.size() > 0) {
      Token encrToken = recToken.getToken();
      policyAsserted(recToken);
      policyAsserted(encrToken);
      AlgorithmSuite algorithmSuite = sbinding.getAlgorithmSuite();
      if (encrToken.isDerivedKeys()) {
        return doEncryptionDerived(recToken, encrTok, encrToken, attached, encrParts, atEnd);
      } else {
        try {
          WSSecEncrypt encr = new WSSecEncrypt(wssConfig);
          String encrTokId = encrTok.getId();
          if (attached) {
            encrTokId = encrTok.getWsuId();
            if (encrTokId == null
                && (encrToken instanceof SecureConversationToken
                    || encrToken instanceof SecurityContextToken)) {
              encr.setEncKeyIdDirectId(true);
              encrTokId = encrTok.getId();
            } else if (encrTokId == null) {
              encrTokId = encrTok.getId();
            }
            if (encrTokId.startsWith("#")) {
              encrTokId = encrTokId.substring(1);
            }
          } else {
            encr.setEncKeyIdDirectId(true);
          }
          if (encrTok.getTokenType() != null) {
            encr.setCustomReferenceValue(encrTok.getTokenType());
          }
          encr.setEncKeyId(encrTokId);
          encr.setEphemeralKey(encrTok.getSecret());
          Crypto crypto = getEncryptionCrypto(recToken);
          if (crypto != null) {
            this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto);
            setEncryptionUser(encr, recToken, false, crypto);
          }

          encr.setDocument(saaj.getSOAPPart());
          encr.setEncryptSymmKey(false);
          encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());

          if (encrToken instanceof IssuedToken || encrToken instanceof SpnegoContextToken) {
            // Setting the AttachedReference or the UnattachedReference according to the flag
            Element ref;
            if (attached) {
              ref = encrTok.getAttachedReference();
            } else {
              ref = encrTok.getUnattachedReference();
            }

            String tokenType = encrTok.getTokenType();
            if (ref != null) {
              SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), false);
              encr.setSecurityTokenReference(secRef);
            } else if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
                || WSConstants.SAML_NS.equals(tokenType)) {
              encr.setCustomReferenceValue(WSConstants.WSS_SAML_KI_VALUE_TYPE);
              encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
                || WSConstants.SAML2_NS.equals(tokenType)) {
              encr.setCustomReferenceValue(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
              encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else {
              encr.setCustomReferenceValue(tokenType);
              encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            }
          } else if (encrToken instanceof UsernameToken) {
            encr.setCustomReferenceValue(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
          } else if (!isRequestor()) {
            if (encrTok.getSHA1() != null) {
              encr.setCustomReferenceValue(encrTok.getSHA1());
              encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
            } else {
              encr.setKeyIdentifierType(WSConstants.EMBED_SECURITY_TOKEN_REF);
            }
          }

          encr.prepare(saaj.getSOAPPart(), crypto);

          if (encr.getBSTTokenId() != null) {
            encr.prependBSTElementToHeader(secHeader);
          }

          Element refList = encr.encryptForRef(null, encrParts);
          if (atEnd) {
            this.insertBeforeBottomUp(refList);
          } else {
            this.addDerivedKeyElement(refList);
          }
          return encr;
        } catch (WSSecurityException e) {
          policyNotAsserted(recToken, e);
        }
      }
    }
    return null;
  }
Exemplo n.º 12
0
  public Credential validateWithSTS(Credential credential, Message message)
      throws WSSecurityException {

    try {
      SecurityToken token = new SecurityToken();
      Element tokenElement = null;
      int hash = 0;
      if (credential.getSamlAssertion() != null) {
        SamlAssertionWrapper assertion = credential.getSamlAssertion();
        byte[] signatureValue = assertion.getSignatureValue();
        if (signatureValue != null && signatureValue.length > 0) {
          hash = Arrays.hashCode(signatureValue);
        }
        tokenElement = credential.getSamlAssertion().getElement();
      } else if (credential.getUsernametoken() != null) {
        tokenElement = credential.getUsernametoken().getElement();
        hash = credential.getUsernametoken().hashCode();
      } else if (credential.getBinarySecurityToken() != null) {
        tokenElement = credential.getBinarySecurityToken().getElement();
        hash = credential.getBinarySecurityToken().hashCode();
      } else if (credential.getSecurityContextToken() != null) {
        tokenElement = credential.getSecurityContextToken().getElement();
        hash = credential.getSecurityContextToken().hashCode();
      }
      token.setToken(tokenElement);

      TokenStore ts = null;
      if (!disableCaching) {
        ts = getTokenStore(message);
        if (ts == null) {
          ts = tokenStore;
        }
        if (ts != null && hash != 0) {
          SecurityToken transformedToken = getTransformedToken(ts, hash);
          if (transformedToken != null && !transformedToken.isExpired()) {
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(transformedToken.getToken());
            credential.setPrincipal(new SAMLTokenPrincipalImpl(assertion));
            credential.setTransformedToken(assertion);
            return credential;
          }
        }
      }
      token.setTokenHash(hash);

      STSClient c = stsClient;
      if (c == null) {
        c = STSUtils.getClient(message, "sts");
      }

      synchronized (c) {
        System.setProperty("noprint", "true");

        SecurityToken returnedToken = null;

        if (useIssueBinding && useOnBehalfOf) {
          ElementCallbackHandler callbackHandler = new ElementCallbackHandler(tokenElement);
          c.setOnBehalfOf(callbackHandler);
          returnedToken = c.requestSecurityToken();
          c.setOnBehalfOf(null);
        } else if (useIssueBinding && !useOnBehalfOf && credential.getUsernametoken() != null) {
          c.getProperties()
              .put(SecurityConstants.USERNAME, credential.getUsernametoken().getName());
          c.getProperties()
              .put(SecurityConstants.PASSWORD, credential.getUsernametoken().getPassword());
          returnedToken = c.requestSecurityToken();
          c.getProperties().remove(SecurityConstants.USERNAME);
          c.getProperties().remove(SecurityConstants.PASSWORD);
        } else {
          List<SecurityToken> tokens = c.validateSecurityToken(token);
          returnedToken = tokens.get(0);
        }

        if (returnedToken != token) {
          SamlAssertionWrapper assertion = new SamlAssertionWrapper(returnedToken.getToken());
          credential.setTransformedToken(assertion);
          credential.setPrincipal(new SAMLTokenPrincipalImpl(assertion));
          if (!disableCaching && hash != 0 && ts != null) {
            ts.add(returnedToken);
            token.setTransformedTokenIdentifier(returnedToken.getId());
            ts.add(Integer.toString(hash), token);
          }
        }
        return credential;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new WSSecurityException(
          WSSecurityException.ErrorCode.FAILURE, e, "invalidSAMLsecurity");
    }
  }
Exemplo n.º 13
0
  // CHECKSTYLE:OFF
  @org.junit.Test
  public void testSAMLinWSSecToOtherRealm() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    CallbackHandler callbackHandler = new CommonCallbackHandler();

    // Create SAML token
    Element samlToken =
        createSAMLAssertion(
            WSConstants.WSS_SAML2_TOKEN_TYPE,
            crypto,
            "mystskey",
            callbackHandler,
            null,
            "alice",
            "a-issuer");

    String id = null;
    QName elName = DOMUtils.getElementQName(samlToken);
    if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion"))
        && samlToken.hasAttributeNS(null, "AssertionID")) {
      id = samlToken.getAttributeNS(null, "AssertionID");
    } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion"))
        && samlToken.hasAttributeNS(null, "ID")) {
      id = samlToken.getAttributeNS(null, "ID");
    }
    if (id == null) {
      id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id");
    }

    SecurityToken wstoken = new SecurityToken(id, samlToken, null, null);
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(SecurityConstants.TOKEN, wstoken);
    properties.put(SecurityConstants.TOKEN_ID, wstoken.getId());

    // Get a token

    SecurityToken token =
        requestSecurityToken(
            SAML2_TOKEN_TYPE,
            BEARER_KEYTYPE,
            null,
            bus,
            DEFAULT_ADDRESS,
            null,
            properties,
            "b-issuer",
            "Transport_SAML_Port");

    /*
    SecurityToken token =
            requestSecurityToken(SAML2_TOKEN_TYPE, BEARER_KEYTYPE, null,
                    bus, DEFAULT_ADDRESS, null, properties, "b-issuer", null);
                    */
    assertTrue(SAML2_TOKEN_TYPE.equals(token.getTokenType()));
    assertTrue(token.getToken() != null);

    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper) results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(assertion != null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && methods.size() > 0) {
      confirmMethod = methods.get(0);
    }
    assertTrue(confirmMethod.contains("bearer"));

    assertTrue("b-issuer".equals(assertion.getIssuerString()));
    String subjectName = assertion.getSaml2().getSubject().getNameID().getValue();
    assertTrue("Subject must be ALICE instead of " + subjectName, "ALICE".equals(subjectName));
  }
Exemplo n.º 14
0
  /**
   * Parses the SecurityToken by wrapping within an AssertionWrapper.
   *
   * @param securityToken SecurityToken
   */
  private void parseToken(SecurityToken securityToken) {
    XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken());

    try {
      AttrStatement attributeStatement = null;
      AuthenticationStatement authenticationStatement = null;
      Attr attribute = null;
      int attrs = 0;
      while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();
        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case NameID.DEFAULT_ELEMENT_LOCAL_NAME:
                  name = xmlStreamReader.getElementText();
                  for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {
                    if (xmlStreamReader
                        .getAttributeLocalName(i)
                        .equals(NameID.FORMAT_ATTRIB_NAME)) {
                      nameIDFormat = xmlStreamReader.getAttributeValue(i);
                      break;
                    }
                  }
                  break;
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = new AttrStatement();
                  attributeStatements.add(attributeStatement);
                  break;
                case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  authenticationStatement = new AuthenticationStatement();
                  authenticationStatements.add(authenticationStatement);
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) {
                      authenticationStatement.setAuthnInstant(DateTime.parse(value));
                    }
                  }
                  break;
                case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME:
                  if (authenticationStatement != null) {
                    String classValue = xmlStreamReader.getText();
                    classValue = classValue.trim();
                    AuthenticationContextClassRef authenticationContextClassRef =
                        new AuthenticationContextClassRef();
                    authenticationContextClassRef.setAuthnContextClassRef(classValue);
                    AuthenticationContext authenticationContext = new AuthenticationContext();
                    authenticationContext.setAuthnContextClassRef(authenticationContextClassRef);
                    authenticationStatement.setAuthnContext(authenticationContext);
                  }
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = new Attr();
                  if (attributeStatement != null) {
                    attributeStatement.addAttribute(attribute);
                  }
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Attribute.NAME_ATTTRIB_NAME.equals(name)) {
                      attribute.setName(value);
                    } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) {
                      attribute.setNameFormat(value);
                    }
                  }
                  break;
                case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME:
                  XSString xsString = new XMLString();
                  xsString.setValue(xmlStreamReader.getElementText());
                  if (attribute != null) {
                    attribute.addAttributeValue(xsString);
                  }
                  break;
                case Issuer.DEFAULT_ELEMENT_LOCAL_NAME:
                  issuer = xmlStreamReader.getElementText();
                  break;
                case Conditions.DEFAULT_ELEMENT_LOCAL_NAME:
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) {
                      notBefore = DatatypeConverter.parseDateTime(value).getTime();
                    } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) {
                      notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime();
                    }
                  }
                  break;
              }
              break;
            }
          case XMLStreamConstants.END_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = null;
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = null;
                  break;
              }
              break;
            }
        }
      }
    } catch (XMLStreamException e) {
      LOGGER.error("Unable to parse security token.", e);
    } finally {
      try {
        xmlStreamReader.close();
      } catch (XMLStreamException ignore) {
        // ignore
      }
    }
  }
Exemplo n.º 15
0
 public static void logSecurityAssertionInfo(SecurityToken token) {
   if (SECURITY_LOGGER.isDebugEnabled() && token != null) {
     SECURITY_LOGGER.debug(getFormattedXml(token.getToken()));
   }
 }
  private void doEncryptBeforeSign() {
    try {
      TokenWrapper encryptionWrapper = getEncryptionToken();
      Token encryptionToken = encryptionWrapper.getToken();
      List<WSEncryptionPart> encrParts = getEncryptedParts();
      List<WSEncryptionPart> sigParts = getSignedParts();

      // if (encryptionToken == null && encrParts.size() > 0) {
      // REVISIT - nothing to encrypt?
      // }

      if (encryptionToken != null && encrParts.size() > 0) {
        // The encryption token can be an IssuedToken or a
        // SecureConversationToken
        String tokenId = null;
        SecurityToken tok = null;
        if (encryptionToken instanceof IssuedToken
            || encryptionToken instanceof KerberosToken
            || encryptionToken instanceof SecureConversationToken
            || encryptionToken instanceof SecurityContextToken
            || encryptionToken instanceof SpnegoContextToken) {
          tok = getSecurityToken();
        } else if (encryptionToken instanceof X509Token) {
          if (isRequestor()) {
            tokenId = setupEncryptedKey(encryptionWrapper, encryptionToken);
          } else {
            tokenId = getEncryptedKey();
          }
        } else if (encryptionToken instanceof UsernameToken) {
          if (isRequestor()) {
            tokenId = setupUTDerivedKey((UsernameToken) encryptionToken);
          } else {
            tokenId = getUTDerivedKey();
          }
        }
        if (tok == null) {
          // if (tokenId == null || tokenId.length() == 0) {
          // REVISIT - no tokenId?   Exception?
          // }
          if (tokenId != null && tokenId.startsWith("#")) {
            tokenId = tokenId.substring(1);
          }

          /*
           * Get hold of the token from the token storage
           */
          tok = tokenStore.getToken(tokenId);
        }

        boolean attached = false;

        if (includeToken(encryptionToken.getInclusion())) {
          Element el = tok.getToken();
          this.addEncryptedKeyElement(cloneElement(el));
          attached = true;
        } else if (encryptionToken instanceof X509Token && isRequestor()) {
          Element el = tok.getToken();
          this.addEncryptedKeyElement(cloneElement(el));
          attached = true;
        }

        WSSecBase encr = doEncryption(encryptionWrapper, tok, attached, encrParts, true);

        handleEncryptedSignedHeaders(encrParts, sigParts);

        if (timestampEl != null) {
          WSEncryptionPart timestampPart = convertToEncryptionPart(timestampEl.getElement());
          sigParts.add(timestampPart);
        }

        if (isRequestor()) {
          this.addSupportingTokens(sigParts);
        } else {
          addSignatureConfirmation(sigParts);
        }

        // Sign the message
        // We should use the same key in the case of EncryptBeforeSig
        if (sigParts.size() > 0) {
          signatures.add(
              this.doSignature(sigParts, encryptionWrapper, encryptionToken, tok, attached));
        }

        if (isRequestor()) {
          this.doEndorse();
        }

        // Check for signature protection and encryption of UsernameToken
        if (sbinding.isSignatureProtection() || encryptedTokensList.size() > 0 && isRequestor()) {
          List<WSEncryptionPart> secondEncrParts = new ArrayList<WSEncryptionPart>();

          // Now encrypt the signature using the above token
          if (sbinding.isSignatureProtection()) {
            if (this.mainSigId != null) {
              WSEncryptionPart sigPart = new WSEncryptionPart(this.mainSigId, "Element");
              sigPart.setElement(bottomUpElement);
              secondEncrParts.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
              secondEncrParts.addAll(sigConfList);
            }
          }

          if (isRequestor()) {
            secondEncrParts.addAll(encryptedTokensList);
          }

          Element secondRefList = null;

          if (encryptionToken.isDerivedKeys() && !secondEncrParts.isEmpty()) {
            secondRefList = ((WSSecDKEncrypt) encr).encryptForExternalRef(null, secondEncrParts);
            this.addDerivedKeyElement(secondRefList);
          } else if (!secondEncrParts.isEmpty()) {
            // Encrypt, get hold of the ref list and add it
            secondRefList = ((WSSecEncrypt) encr).encryptForRef(null, encrParts);
            this.addDerivedKeyElement(secondRefList);
          }
        }
      }
    } catch (RuntimeException ex) {
      throw ex;
    } catch (Exception ex) {
      throw new Fault(ex);
    }
  }
  private void doSignBeforeEncrypt() {
    TokenWrapper sigTokenWrapper = getSignatureToken();
    Token sigToken = sigTokenWrapper.getToken();

    String sigTokId = null;
    Element sigTokElem = null;

    try {
      SecurityToken sigTok = null;
      if (sigToken != null) {
        if (sigToken instanceof SecureConversationToken
            || sigToken instanceof SecurityContextToken
            || sigToken instanceof IssuedToken
            || sigToken instanceof KerberosToken
            || sigToken instanceof SpnegoContextToken) {
          sigTok = getSecurityToken();
        } else if (sigToken instanceof X509Token) {
          if (isRequestor()) {
            sigTokId = setupEncryptedKey(sigTokenWrapper, sigToken);
          } else {
            sigTokId = getEncryptedKey();
          }
        } else if (sigToken instanceof UsernameToken) {
          if (isRequestor()) {
            sigTokId = setupUTDerivedKey((UsernameToken) sigToken);
          } else {
            sigTokId = getUTDerivedKey();
          }
        }
      } else {
        policyNotAsserted(sbinding, "No signature token");
        return;
      }

      if (sigTok == null && StringUtils.isEmpty(sigTokId)) {
        policyNotAsserted(sigTokenWrapper, "No signature token id");
        return;
      } else {
        policyAsserted(sigTokenWrapper);
      }
      if (sigTok == null) {
        sigTok = tokenStore.getToken(sigTokId);
      }
      // if (sigTok == null) {
      // REVISIT - no token?
      // }

      boolean tokIncluded = true;
      if (includeToken(sigToken.getInclusion())) {
        Element el = sigTok.getToken();
        sigTokElem = cloneElement(el);
        this.addEncryptedKeyElement(sigTokElem);
      } else if (isRequestor() && sigToken instanceof X509Token) {
        Element el = sigTok.getToken();
        sigTokElem = cloneElement(el);
        this.addEncryptedKeyElement(sigTokElem);
      } else {
        tokIncluded = false;
      }

      // Add timestamp
      List<WSEncryptionPart> sigs = getSignedParts();
      if (timestampEl != null) {
        WSEncryptionPart timestampPart = convertToEncryptionPart(timestampEl.getElement());
        sigs.add(timestampPart);
      }

      if (isRequestor()) {
        addSupportingTokens(sigs);
        if (!sigs.isEmpty()) {
          signatures.add(doSignature(sigs, sigTokenWrapper, sigToken, sigTok, tokIncluded));
        }
        doEndorse();
      } else {
        // confirm sig
        assertSupportingTokens(sigs);
        addSignatureConfirmation(sigs);
        if (!sigs.isEmpty()) {
          doSignature(sigs, sigTokenWrapper, sigToken, sigTok, tokIncluded);
        }
      }

      // Encryption
      TokenWrapper encrTokenWrapper = getEncryptionToken();
      Token encrToken = encrTokenWrapper.getToken();
      SecurityToken encrTok = null;
      if (sigToken.equals(encrToken)) {
        // Use the same token
        encrTok = sigTok;
      } else {
        policyNotAsserted(sbinding, "Encryption token does not equal signature token");
        return;
      }

      List<WSEncryptionPart> enc = getEncryptedParts();

      // Check for signature protection
      if (sbinding.isSignatureProtection()) {
        if (mainSigId != null) {
          WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
          sigPart.setElement(bottomUpElement);
          enc.add(sigPart);
        }
        if (sigConfList != null && !sigConfList.isEmpty()) {
          enc.addAll(sigConfList);
        }
      }

      if (isRequestor()) {
        enc.addAll(encryptedTokensList);
      }
      doEncryption(encrTokenWrapper, encrTok, tokIncluded, enc, false);
    } catch (Exception e) {
      throw new Fault(e);
    }
  }
  private byte[] doSignature(
      List<WSEncryptionPart> sigs,
      TokenWrapper policyTokenWrapper,
      Token policyToken,
      SecurityToken tok,
      boolean included)
      throws WSSecurityException {
    if (policyToken.isDerivedKeys()) {
      return doSignatureDK(sigs, policyTokenWrapper, policyToken, tok, included);
    } else {
      WSSecSignature sig = new WSSecSignature(wssConfig);
      sig.setWsConfig(wssConfig);
      // If a EncryptedKeyToken is used, set the correct value type to
      // be used in the wsse:Reference in ds:KeyInfo
      int type =
          included ? WSConstants.CUSTOM_SYMM_SIGNING : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
      if (policyToken instanceof X509Token) {
        if (isRequestor()) {
          sig.setCustomTokenValueType(
              WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE);
          sig.setKeyIdentifierType(type);
        } else {
          // the tok has to be an EncryptedKey token
          sig.setEncrKeySha1value(tok.getSHA1());
          sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
        }
      } else if (policyToken instanceof UsernameToken) {
        sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        sig.setKeyIdentifierType(type);
      } else {
        // Setting the AttachedReference or the UnattachedReference according to the flag
        Element ref;
        if (included) {
          ref = tok.getAttachedReference();
        } else {
          ref = tok.getUnattachedReference();
        }

        if (ref != null) {
          SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), false);
          sig.setSecurityTokenReference(secRef);
          sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else {
          String tokenType = tok.getTokenType();
          if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
              || WSConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
          } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
              || WSConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
          } else {
            sig.setCustomTokenValueType(tokenType);
            sig.setKeyIdentifierType(type);
          }
        }
      }

      String sigTokId;
      if (included) {
        sigTokId = tok.getWsuId();
        if (sigTokId == null) {
          if (policyToken instanceof SecureConversationToken
              || policyToken instanceof SecurityContextToken) {
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
          }
          sigTokId = tok.getId();
        }
        if (sigTokId.startsWith("#")) {
          sigTokId = sigTokId.substring(1);
        }
      } else {
        sigTokId = tok.getId();
      }

      if (included && sbinding.isTokenProtection()) {
        sigs.add(new WSEncryptionPart(sigTokId));
      }

      sig.setCustomTokenId(sigTokId);
      sig.setSecretKey(tok.getSecret());
      sig.setSignatureAlgorithm(sbinding.getAlgorithmSuite().getSymmetricSignature());
      Crypto crypto = null;
      if (sbinding.getProtectionToken() != null) {
        crypto = getEncryptionCrypto(sbinding.getProtectionToken());
      } else {
        crypto = getSignatureCrypto(policyTokenWrapper);
      }
      this.message.getExchange().put(SecurityConstants.SIGNATURE_CRYPTO, crypto);
      sig.prepare(saaj.getSOAPPart(), crypto, secHeader);
      sig.setParts(sigs);
      List<Reference> referenceList = sig.addReferencesToSign(sigs, secHeader);

      // Do signature
      if (bottomUpElement == null) {
        sig.computeSignature(referenceList, false, null);
      } else {
        sig.computeSignature(referenceList, true, bottomUpElement);
      }
      bottomUpElement = sig.getSignatureElement();

      this.mainSigId = sig.getId();
      return sig.getSignatureValue();
    }
  }
  private byte[] doSignatureDK(
      List<WSEncryptionPart> sigs,
      TokenWrapper policyTokenWrapper,
      Token policyToken,
      SecurityToken tok,
      boolean included)
      throws WSSecurityException {
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);
    if (policyTokenWrapper.getToken().getSPConstants() == SP12Constants.INSTANCE) {
      dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }

    // Check for whether the token is attached in the message or not
    boolean attached = false;
    if (includeToken(policyToken.getInclusion())) {
      attached = true;
    }

    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
      ref = tok.getAttachedReference();
    } else {
      ref = tok.getUnattachedReference();
    }

    if (ref != null) {
      dkSign.setExternalKey(tok.getSecret(), cloneElement(ref));
    } else if (!isRequestor() && policyToken.isDerivedKeys() && tok.getSHA1() != null) {
      // If the Encrypted key used to create the derived key is not
      // attached use key identifier as defined in WSS1.1 section
      // 7.7 Encrypted Key reference
      SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
      if (tok.getSHA1() != null) {
        tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
        String tokenType = tok.getTokenType();
        if (tokenType == null) {
          tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
        }
        tokenRef.addTokenType(tokenType);
      }
      dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    } else {
      if ((!attached && !isRequestor())
          || policyToken instanceof SecureConversationToken
          || policyToken instanceof SecurityContextToken) {
        dkSign.setTokenIdDirectId(true);
      }
      dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }

    // Set the algo info
    dkSign.setSignatureAlgorithm(sbinding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setDerivedKeyLength(sbinding.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
      // Set the value type of the reference
      String tokenType = tok.getTokenType();
      if (tokenType == null) {
        tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
      }
      dkSign.setCustomValueType(tokenType);
    } else {
      String tokenType = tok.getTokenType();
      if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
          || WSConstants.SAML_NS.equals(tokenType)) {
        dkSign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        dkSign.setCustomValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
      } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
          || WSConstants.SAML2_NS.equals(tokenType)) {
        dkSign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        dkSign.setCustomValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
      } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
      } else {
        dkSign.setCustomValueType(tokenType);
      }
    }

    try {
      dkSign.prepare(doc, secHeader);
    } catch (ConversationException e) {
      throw new WSSecurityException(e.getMessage(), e);
    }

    if (sbinding.isTokenProtection()) {
      String sigTokId = tok.getId();
      if (included) {
        sigTokId = tok.getWsuId();
        if (sigTokId == null) {
          sigTokId = tok.getId();
        }
        if (sigTokId.startsWith("#")) {
          sigTokId = sigTokId.substring(1);
        }
      }
      sigs.add(new WSEncryptionPart(sigTokId));
    }

    dkSign.setParts(sigs);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigs, secHeader);

    // Add elements to header
    Element el = dkSign.getdktElement();
    addDerivedKeyElement(el);

    // Do signature
    if (bottomUpElement == null) {
      dkSign.computeSignature(referenceList, false, null);
    } else {
      dkSign.computeSignature(referenceList, true, bottomUpElement);
    }
    bottomUpElement = dkSign.getSignatureElement();

    this.mainSigId = dkSign.getSignatureId();

    return dkSign.getSignatureValue();
  }
  private WSSecBase doEncryptionDerived(
      TokenWrapper recToken,
      SecurityToken encrTok,
      Token encrToken,
      boolean attached,
      List<WSEncryptionPart> encrParts,
      boolean atEnd) {
    try {
      WSSecDKEncrypt dkEncr = new WSSecDKEncrypt(wssConfig);
      if (recToken.getToken().getSPConstants() == SP12Constants.INSTANCE) {
        dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
      }

      if (attached && encrTok.getAttachedReference() != null) {
        dkEncr.setExternalKey(encrTok.getSecret(), cloneElement(encrTok.getAttachedReference()));
      } else if (encrTok.getUnattachedReference() != null) {
        dkEncr.setExternalKey(encrTok.getSecret(), cloneElement(encrTok.getUnattachedReference()));
      } else if (!isRequestor() && encrTok.getSHA1() != null) {
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef = new SecurityTokenReference(saaj.getSOAPPart());
        tokenRef.setKeyIdentifierEncKeySHA1(encrTok.getSHA1());
        String tokenType = encrTok.getTokenType();
        if (tokenType == null) {
          tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
        }
        tokenRef.addTokenType(tokenType);
        dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());
      } else {
        if (attached) {
          String id = encrTok.getWsuId();
          if (id == null
              && (encrToken instanceof SecureConversationToken
                  || encrToken instanceof SecurityContextToken)) {
            dkEncr.setTokenIdDirectId(true);
            id = encrTok.getId();
          } else if (id == null) {
            id = encrTok.getId();
          }
          if (id.startsWith("#")) {
            id = id.substring(1);
          }
          dkEncr.setExternalKey(encrTok.getSecret(), id);
        } else {
          dkEncr.setTokenIdDirectId(true);
          dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
        }
      }

      if (encrTok.getSHA1() != null) {
        String tokenType = encrTok.getTokenType();
        if (tokenType == null) {
          tokenType = WSConstants.WSS_ENC_KEY_VALUE_TYPE;
        }
        dkEncr.setCustomValueType(tokenType);
      } else {
        String tokenType = encrTok.getTokenType();
        if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML_NS.equals(tokenType)) {
          dkEncr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
          dkEncr.setCustomValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML2_NS.equals(tokenType)) {
          dkEncr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
          dkEncr.setCustomValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
        } else if (encrToken instanceof UsernameToken) {
          dkEncr.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        } else {
          dkEncr.setCustomValueType(tokenType);
        }
      }

      dkEncr.setSymmetricEncAlgorithm(sbinding.getAlgorithmSuite().getEncryption());
      dkEncr.setDerivedKeyLength(sbinding.getAlgorithmSuite().getEncryptionDerivedKeyLength() / 8);
      dkEncr.prepare(saaj.getSOAPPart());
      Element encrDKTokenElem = null;
      encrDKTokenElem = dkEncr.getdktElement();
      addDerivedKeyElement(encrDKTokenElem);
      Element refList = dkEncr.encryptForExternalRef(null, encrParts);
      if (atEnd) {
        this.insertBeforeBottomUp(refList);
      } else {
        this.addDerivedKeyElement(refList);
      }
      return dkEncr;
    } catch (Exception e) {
      policyNotAsserted(recToken, e);
    }
    return null;
  }