Exemplo n.º 1
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()));
  }
Exemplo n.º 2
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);
  }
  /**
   * 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.º 4
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);
  }
Exemplo n.º 5
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);
    }
  }
Exemplo n.º 8
0
 public static void logSecurityAssertionInfo(SecurityToken token) {
   if (SECURITY_LOGGER.isDebugEnabled() && token != null) {
     SECURITY_LOGGER.debug(getFormattedXml(token.getToken()));
   }
 }
Exemplo n.º 9
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.º 10
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));
  }