Ejemplo n.º 1
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);
  }
Ejemplo n.º 2
0
  public static String createToken(String audRestr, boolean saml2, boolean sign)
      throws WSSecurityException {
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
    samlCallbackHandler.setAudience(audRestr);
    if (!saml2) {
      samlCallbackHandler.setSaml2(false);
      samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
    }

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);

    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    if (samlCallback.isSignAssertion()) {
      samlAssertion.signAssertion(
          samlCallback.getIssuerKeyName(),
          samlCallback.getIssuerKeyPassword(),
          samlCallback.getIssuerCrypto(),
          samlCallback.isSendKeyValue(),
          samlCallback.getCanonicalizationAlgorithm(),
          samlCallback.getSignatureAlgorithm());
    }

    return samlAssertion.assertionToString();
  }
Ejemplo n.º 3
0
  public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper transformedToken = validatedCredential.getTransformedToken();
    if (transformedToken == null
        || transformedToken.getSaml2() == null
        || !"DoubleItSTSIssuer".equals(transformedToken.getIssuerString())) {
      throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    return validatedCredential;
  }
Ejemplo n.º 4
0
  public int doubleIt(int numberToDouble) {
    //
    // Get the transformed SAML Assertion from the STS and check it
    //
    MessageContext context = wsc.getMessageContext();
    final List<WSHandlerResult> handlerResults =
        CastUtils.cast((List<?>) context.get(WSHandlerConstants.RECV_RESULTS));
    WSSecurityEngineResult actionResult =
        WSSecurityUtil.fetchActionResult(handlerResults.get(0).getResults(), WSConstants.UT);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_TRANSFORMED_TOKEN);
    Assert.assertTrue(assertion != null && "DoubleItSTSIssuer".equals(assertion.getIssuerString()));

    return numberToDouble * 2;
  }
Ejemplo n.º 5
0
  /**
   * Find the index of the token corresponding to either the X509Certificate or PublicKey used to
   * sign the "signatureResult" argument.
   */
  private int findCorrespondingTokenIndex(
      WSSecurityEngineResult signatureResult, List<WSSecurityEngineResult> results) {
    // See what was used to sign this result
    X509Certificate cert =
        (X509Certificate) signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    PublicKey publicKey = (PublicKey) signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);

    for (int i = 0; i < results.size(); i++) {
      WSSecurityEngineResult token = results.get(i);
      Integer actInt = (Integer) token.get(WSSecurityEngineResult.TAG_ACTION);
      if (actInt == WSConstants.SIGN) {
        continue;
      }

      BinarySecurity binarySecurity =
          (BinarySecurity) token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
      PublicKey foundPublicKey = (PublicKey) token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
      if (binarySecurity instanceof X509Security || binarySecurity instanceof PKIPathSecurity) {
        X509Certificate foundCert =
            (X509Certificate) token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
        if (foundCert.equals(cert)) {
          return i;
        }
      } else if (actInt.intValue() == WSConstants.ST_SIGNED
          || actInt.intValue() == WSConstants.ST_UNSIGNED) {
        SamlAssertionWrapper assertionWrapper =
            (SamlAssertionWrapper) token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
        SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
        if (samlKeyInfo != null) {
          X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
          PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
          if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0]))
              || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
            return i;
          }
        }
      } else if (publicKey != null && publicKey.equals(foundPublicKey)) {
        return i;
      }
    }
    return -1;
  }
Ejemplo n.º 6
0
  public void handleMessage(Message message) throws Fault {
    try {
      SamlAssertionWrapper assertionWrapper = createAssertion(message);

      Document doc = DOMUtils.newDocument();
      Element assertionElement = assertionWrapper.toDOM(doc);
      String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

      Map<String, List<String>> headers = getHeaders(message);

      StringBuilder builder = new StringBuilder();
      builder.append("SAML").append(" ").append(encodedToken);
      headers.put(
          "Authorization",
          CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
      StringWriter sw = new StringWriter();
      ex.printStackTrace(new PrintWriter(sw));
      LOG.warning(sw.toString());
      throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }
  }
Ejemplo n.º 7
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);
  }
Ejemplo n.º 8
0
  protected void signToken(
      SamlAssertionWrapper assertion,
      RealmProperties samlRealm,
      STSPropertiesMBean stsProperties,
      KeyRequirements keyRequirements)
      throws Exception {
    // Initialise signature objects with defaults of STSPropertiesMBean
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    SignatureProperties signatureProperties = stsProperties.getSignatureProperties();
    String alias = stsProperties.getSignatureUsername();

    if (samlRealm != null) {
      // If SignatureCrypto configured in realm then
      // callbackhandler and alias of STSPropertiesMBean is ignored
      if (samlRealm.getSignatureCrypto() != null) {
        LOG.fine("SAMLRealm signature keystore used");
        signatureCrypto = samlRealm.getSignatureCrypto();
        callbackHandler = samlRealm.getCallbackHandler();
        alias = samlRealm.getSignatureAlias();
      }
      // SignatureProperties can be defined independently of SignatureCrypto
      if (samlRealm.getSignatureProperties() != null) {
        signatureProperties = samlRealm.getSignatureProperties();
      }
    }

    // Get the signature algorithm to use
    String signatureAlgorithm = keyRequirements.getSignatureAlgorithm();
    if (signatureAlgorithm == null) {
      // If none then default to what is configured
      signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
    } else {
      List<String> supportedAlgorithms = signatureProperties.getAcceptedSignatureAlgorithms();
      if (!supportedAlgorithms.contains(signatureAlgorithm)) {
        signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
        if (LOG.isLoggable(Level.FINE)) {
          LOG.fine("SignatureAlgorithm not supported, defaulting to: " + signatureAlgorithm);
        }
      }
    }

    // Get the c14n algorithm to use
    String c14nAlgorithm = keyRequirements.getC14nAlgorithm();
    if (c14nAlgorithm == null) {
      // If none then default to what is configured
      c14nAlgorithm = signatureProperties.getC14nAlgorithm();
    } else {
      List<String> supportedAlgorithms = signatureProperties.getAcceptedC14nAlgorithms();
      if (!supportedAlgorithms.contains(c14nAlgorithm)) {
        c14nAlgorithm = signatureProperties.getC14nAlgorithm();
        if (LOG.isLoggable(Level.FINE)) {
          LOG.fine("C14nAlgorithm not supported, defaulting to: " + c14nAlgorithm);
        }
      }
    }

    // If alias not defined, get the default of the SignatureCrypto
    if ((alias == null || "".equals(alias)) && (signatureCrypto != null)) {
      alias = signatureCrypto.getDefaultX509Identifier();
      if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Signature alias is null so using default alias: " + alias);
      }
    }
    // Get the password
    WSPasswordCallback[] cb = {new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)};
    LOG.fine("Creating SAML Token");
    callbackHandler.handle(cb);
    String password = cb[0].getPassword();

    LOG.fine("Signing SAML Token");
    boolean useKeyValue = signatureProperties.isUseKeyValue();
    assertion.signAssertion(
        alias,
        password,
        signatureCrypto,
        useKeyValue,
        c14nAlgorithm,
        signatureAlgorithm,
        signatureProperties.getDigestAlgorithm());
  }
Ejemplo n.º 9
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");
    }
  }
Ejemplo 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));
  }