Example #1
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;
 }
Example #2
0
 private static SecurityToken getToken(Message message) {
   TokenStore tokenStore = getTokenStore(message);
   SAMLTokenPrincipal principal =
       (SAMLTokenPrincipal) message.get(WSS4JInInterceptor.PRINCIPAL_RESULT);
   if (tokenStore != null && principal != null) {
     return tokenStore.getToken(principal.getId());
   } else {
     return null;
   }
 }
  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;
  }
  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;
  }
  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;
  }
Example #7
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");
    }
  }
  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 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);
    }
  }