public Assertion build(OMElement element, AssertionBuilderFactory factory)
      throws IllegalArgumentException {
    TransportBinding transportBinding = new TransportBinding(SPConstants.SP_V12);

    Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
    policy = (Policy) policy.normalize(false);

    for (List<PolicyComponent> alts : policy.getAlternatives()) {
      processAlternative(alts, transportBinding, factory);
      break;
    }

    return transportBinding;
  }
  public PolicyAssertion build(Element element) throws IllegalArgumentException {

    SPConstants consts =
        SP11Constants.SP_NS.equals(element.getNamespaceURI())
            ? SP11Constants.INSTANCE
            : SP12Constants.INSTANCE;

    SymmetricBinding symmetricBinding = new SymmetricBinding(consts);

    Policy policy = builder.getPolicy(DOMUtils.getFirstElement(element));
    policy = (Policy) policy.normalize(false);

    for (Iterator iterator = policy.getAlternatives(); iterator.hasNext(); ) {
      processAlternatives((List) iterator.next(), symmetricBinding, consts);

      /*
       * since there should be only one alternative ..
       */
      break;
    }
    return symmetricBinding;
  }
  public Assertion build(Element element, AssertionBuilderFactory factory)
      throws IllegalArgumentException {

    SPConstants consts =
        SP11Constants.SP_NS.equals(element.getNamespaceURI())
            ? SP11Constants.INSTANCE
            : SP12Constants.INSTANCE;

    RecipientSignatureToken recipientSignatureToken = new RecipientSignatureToken(consts, builder);
    recipientSignatureToken.setOptional(PolicyConstants.isOptional(element));
    recipientSignatureToken.setIgnorable(PolicyConstants.isIgnorable(element));

    Policy policy = builder.getPolicy(DOMUtils.getFirstElement(element));
    policy = policy.normalize(builder.getPolicyRegistry(), false);

    for (Iterator<List<Assertion>> iterator = policy.getAlternatives(); iterator.hasNext(); ) {
      processAlternative(iterator.next(), recipientSignatureToken);
      break; // TODO process all the token that must be set ..
    }

    return recipientSignatureToken;
  }
  public PolicyAssertion build(Element element) throws IllegalArgumentException {

    SPConstants consts =
        SP11Constants.SP_NS.equals(element.getNamespaceURI())
            ? SP11Constants.INSTANCE
            : SP12Constants.INSTANCE;

    RecipientToken recipientToken = new RecipientToken(consts);

    Policy policy = builder.getPolicy(DOMUtils.getFirstElement(element));
    policy = (Policy) policy.normalize(false);

    for (Iterator iterator = policy.getAlternatives(); iterator.hasNext(); ) {
      processAlternative((List) iterator.next(), recipientToken);

      /*
       * for the moment we will pick the first token specified in the policy
       */
      break;
    }

    return recipientToken;
  }
Esempio n. 5
0
  public Policy loadPolicy(String xmlPath, String clientKey) throws Exception {

    StAXOMBuilder builder = new StAXOMBuilder(xmlPath);
    Policy policy = PolicyEngine.getPolicy(builder.getDocumentElement());

    RampartConfig rc = new RampartConfig();

    rc.setUser("admin");
    rc.setUserCertAlias("wso2carbon");
    rc.setEncryptionUser("wso2carbon");
    rc.setPwCbClass(SecurityClient.class.getName());

    CryptoConfig sigCryptoConfig = new CryptoConfig();
    sigCryptoConfig.setProvider("org.apache.ws.security.components.crypto.Merlin");

    Properties prop1 = new Properties();
    prop1.put("org.apache.ws.security.crypto.merlin.keystore.type", "JKS");
    prop1.put("org.apache.ws.security.crypto.merlin.file", clientKey);
    prop1.put("org.apache.ws.security.crypto.merlin.keystore.password", "wso2carbon");
    sigCryptoConfig.setProp(prop1);

    CryptoConfig encrCryptoConfig = new CryptoConfig();
    encrCryptoConfig.setProvider("org.apache.ws.security.components.crypto.Merlin");

    Properties prop2 = new Properties();
    prop2.put("org.apache.ws.security.crypto.merlin.keystore.type", "JKS");
    prop2.put("org.apache.ws.security.crypto.merlin.file", clientKey);
    prop2.put("org.apache.ws.security.crypto.merlin.keystore.password", "wso2carbon");
    encrCryptoConfig.setProp(prop2);

    rc.setSigCryptoConfig(sigCryptoConfig);
    rc.setEncrCryptoConfig(encrCryptoConfig);

    policy.addAssertion(rc);
    return policy;
  }
Esempio n. 6
0
  private void run() {
    try {
      loadConfigurations();

      // set the trust store as a system property for communication over
      // TLS.
      System.setProperty("javax.net.ssl.trustStore", keystorePath);
      System.setProperty("javax.net.ssl.trustStorePassword", keystorePwd);

      // create configuration context
      ConfigurationContext configCtx =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(repoPath);

      // create STS client
      STSClient stsClient = new STSClient(configCtx);
      stsClient.setRstTemplate(getRSTTemplate());

      String action = null;
      String responseTokenID = null;

      action =
          TrustUtil.getActionValue(RahasConstants.VERSION_05_02, RahasConstants.RST_ACTION_ISSUE);
      stsClient.setAction(action);

      // request the security token from STS.
      Token responseToken;

      Policy stsPolicy = loadPolicy(stsPolicyPath);

      // add rampart config assertion to the ws-sec policies
      RampartConfig rampartConfig = buildRampartConfig();
      stsPolicy.addAssertion(rampartConfig);

      responseToken = stsClient.requestSecurityToken(null, stsEPR, stsPolicy, relyingPartyEPR);

      // store the obtained token in token store to be used in future
      // communication.
      TokenStorage store = TrustUtil.getTokenStore(configCtx);
      responseTokenID = responseToken.getId();
      store.add(responseToken);

      // print token
      System.out.println(responseToken.getToken().toString());
      // sending token renew request
      String renewedTokenID = null;
      if (enableRenewing) {
        System.out.println("Renewing " + tokenType);
        String TokenProfile = null;
        if (tokenType.equals(ClientConstants.SAML_TOKEN_TYPE_11)) {
          TokenProfile = RahasConstants.TOK_TYPE_SAML_10;
        } else if (tokenType.equals(ClientConstants.SAML_TOKEN_TYPE_20)) {
          TokenProfile = RahasConstants.TOK_TYPE_SAML_20;
        }

        stsClient.setRstTemplate(getRSTTemplate());
        boolean tokenRenewed =
            stsClient.renewToken(responseTokenID, TokenProfile, stsEPR, stsPolicy, store);
        System.out.println("tokenRenewed : " + tokenRenewed);

        Token renewedToken = store.getRenewedTokens()[0];
        renewedTokenID = renewedToken.getId();
        System.out.println("Renewed Token : \n" + renewedToken.getToken().toString());
      }
      // Validate the token
      if (enableValidateBinding) {
        // validating the token.
        stsClient = new STSClient(configCtx);
        action =
            TrustUtil.getActionValue(
                RahasConstants.VERSION_05_02, RahasConstants.RST_ACTION_VALIDATE);
        stsClient.setAction(action);
        String tokenID = null;
        if (renewedTokenID != null) {
          tokenID = renewedTokenID;
        } else {
          tokenID = responseTokenID;
        }
        boolean isValid = stsClient.validateToken(tokenID, stsEPR, stsPolicy);

        if (isValid) {
          if (enableRenewing) {
            System.out.println("Renewed SAML " + tokenType + " Token is valid");
          } else {
            System.out.println("Response SAML " + tokenType + " Token is valid");
          }
        } else {
          if (enableRenewing) {
            System.out.println("Renewed SAML " + tokenType + " Token is invalid");
          } else {
            System.out.println("Response SAML " + tokenType + " Token is invalid");
          }
        }
      }

      // Send the token to relying party
      if (enableRelyingParty) {
        /* Invoke secured service using the obtained token */
        OMElement responseElem = null;

        // create service client
        ServiceClient serClient = new ServiceClient(configCtx, null);

        // engage modules
        serClient.engageModule("addressing");
        serClient.engageModule("rampart");

        // load policy of secured service
        Policy sec_policy = loadPolicy(relyingPartyPolicyPath);

        // add rampart config to the ws-sec policies
        sec_policy.addAssertion(rampartConfig);

        // set in/out security policies in client opts
        serClient.getOptions().setProperty(RampartMessageData.KEY_RAMPART_POLICY, sec_policy);

        // Set the token id as a property in the Axis2 client scope, so
        // that this will be picked up when creating the secure message to
        // invoke
        // the endpoint.
        serClient
            .getOptions()
            .setProperty(RampartMessageData.KEY_CUSTOM_ISSUED_TOKEN, renewedTokenID);

        // set action of the Hello Service to be invoked.
        serClient.getOptions().setAction("urn:echoString");
        serClient.getOptions().setTo(new EndpointReference(relyingPartyEPR));

        // invoke the service
        // System.out.println(serClient.sendReceive(getPayload(echoRequestMsg)).toString());
        responseElem = serClient.sendReceive(getPayload(echoRequestMsg));
        // cleanup transports
        serClient.getOptions().setCallTransportCleanup(true);

        System.out.println(responseElem.toString());

        System.exit(0);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      System.exit(0);
    }
  }
Esempio n. 7
0
  public void processListService(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    String url;
    try {
      url = req.getRequestURL().toString();
    } catch (Throwable t) {
      log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t);
      url = req.getRequestURI();
    }
    String serviceName = extractServiceName(url);
    HashMap services = configContext.getAxisConfiguration().getServices();
    String query = req.getQueryString();
    int wsdl2 = query.indexOf("wsdl2");
    int wsdl = query.indexOf("wsdl");
    int xsd = query.indexOf("xsd");
    int policy = query.indexOf("policy");

    if ((services != null) && !services.isEmpty()) {
      Object serviceObj = services.get(serviceName);
      if (serviceObj != null) {
        boolean isHttp = "http".equals(req.getScheme());
        if (wsdl2 >= 0) {
          res.setContentType("text/xml");
          String ip = extractHostAndPort(url, isHttp);
          String wsdlName = req.getParameter("wsdl2");
          if (wsdlName != null && wsdlName.length() > 0) {
            InputStream in =
                ((AxisService) serviceObj)
                    .getClassLoader()
                    .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName);
            if (in != null) {
              OutputStream out = res.getOutputStream();
              out.write(IOUtils.getStreamAsByteArray(in));
              out.flush();
              out.close();
            } else {
              res.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
          } else {
            OutputStream out = res.getOutputStream();
            ((AxisService) serviceObj).printWSDL2(out, ip);
            out.flush();
            out.close();
          }
          return;
        } else if (wsdl >= 0) {
          OutputStream out = res.getOutputStream();
          res.setContentType("text/xml");
          String ip = extractHostAndPort(url, isHttp);
          String wsdlName = req.getParameter("wsdl");

          if (wsdlName != null && wsdlName.length() > 0) {
            AxisService axisServce = (AxisService) serviceObj;
            axisServce.printUserWSDL(out, wsdlName);
            out.flush();
            out.close();
          } else {
            ((AxisService) serviceObj).printWSDL(out, ip);
            out.flush();
            out.close();
          }
          return;
        } else if (xsd >= 0) {
          res.setContentType("text/xml");
          int ret =
              ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd"));
          if (ret == 0) {
            // multiple schemas are present and the user specified
            // no name - in this case we cannot possibly pump a schema
            // so redirect to the service root
            res.sendRedirect("");
          } else if (ret == -1) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND);
          }
          return;
        } else if (policy >= 0) {

          ExternalPolicySerializer serializer = new ExternalPolicySerializer();
          serializer.setAssertionsToFilter(
              configContext.getAxisConfiguration().getLocalPolicyAssertions());

          // check whether Id is set
          String idParam = req.getParameter("id");

          if (idParam != null) {
            // Id is set

            Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj);

            if (targetPolicy != null) {
              XMLStreamWriter writer;

              try {
                OutputStream out = res.getOutputStream();
                writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                res.setContentType("application/wspolicy+xml");
                targetPolicy.serialize(writer);
                writer.flush();

              } catch (XMLStreamException e) {
                throw new ServletException("Error occured when serializing the Policy", e);

              } catch (FactoryConfigurationError e) {
                throw new ServletException("Error occured when serializing the Policy", e);
              }

            } else {

              OutputStream out = res.getOutputStream();
              res.setContentType("text/html");
              String outStr = "<b>No policy found for id=" + idParam + "</b>";
              out.write(outStr.getBytes());
            }

          } else {

            PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude();
            Policy effecPolicy = policyInclude.getEffectivePolicy();

            if (effecPolicy != null) {
              XMLStreamWriter writer;

              try {
                OutputStream out = res.getOutputStream();
                writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                res.setContentType("application/wspolicy+xml");
                effecPolicy.serialize(writer);
                writer.flush();

              } catch (XMLStreamException e) {
                throw new ServletException("Error occured when serializing the Policy", e);

              } catch (FactoryConfigurationError e) {
                throw new ServletException("Error occured when serializing the Policy", e);
              }
            } else {

              OutputStream out = res.getOutputStream();
              res.setContentType("text/html");
              String outStr = "<b>No effective policy for " + serviceName + " servcie</b>";
              out.write(outStr.getBytes());
            }
          }

          return;
        } else {
          try {
            req.getSession().setAttribute(Constants.SINGLE_SERVICE, serviceObj);
          } catch (Throwable t) {
            log.info("Old Servlet API :" + t);
          }
        }
      } else {
        try {
          req.getSession().setAttribute(Constants.SINGLE_SERVICE, null);
        } catch (Throwable t) {
          log.info("Old Servlet API :" + t);
        }

        res.sendError(HttpServletResponse.SC_NOT_FOUND, url);
      }
    }

    renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res);
  }
  public void serialize(XMLStreamWriter writer) throws XMLStreamException {

    String localname = getRealName().getLocalPart();
    String namespaceURI = getRealName().getNamespaceURI();
    String prefix;

    String writerPrefix = writer.getPrefix(namespaceURI);

    if (writerPrefix == null) {
      prefix = getRealName().getPrefix();
      writer.setPrefix(prefix, namespaceURI);
    } else {
      prefix = writerPrefix;
    }

    // <sp:SecureConversationToken>
    writer.writeStartElement(prefix, localname, namespaceURI);

    if (writerPrefix == null) {
      // xmlns:sp=".."
      writer.writeNamespace(prefix, namespaceURI);
    }

    String inclusion;

    inclusion = constants.getAttributeValueFromInclusion(getInclusion());

    if (inclusion != null) {
      writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion);
    }

    if (issuerEpr != null) {
      // <sp:Issuer>
      writer.writeStartElement(prefix, SPConstants.ISSUER, namespaceURI);

      StaxUtils.copy(issuerEpr, writer);

      writer.writeEndElement();
    }

    if (isDerivedKeys()
        || isRequireExternalUriRef()
        || isSc10SecurityContextToken()
        || bootstrapPolicy != null) {

      String wspNamespaceURI = SPConstants.POLICY.getNamespaceURI();

      String wspPrefix;

      String wspWriterPrefix = writer.getPrefix(wspNamespaceURI);

      if (wspWriterPrefix == null) {
        wspPrefix = SPConstants.POLICY.getPrefix();
        writer.setPrefix(wspPrefix, wspNamespaceURI);

      } else {
        wspPrefix = wspWriterPrefix;
      }

      // <wsp:Policy>
      writer.writeStartElement(wspPrefix, SPConstants.POLICY.getLocalPart(), wspNamespaceURI);

      if (wspWriterPrefix == null) {
        // xmlns:wsp=".."
        writer.writeNamespace(wspPrefix, wspNamespaceURI);
      }

      if (isDerivedKeys()) {
        // <sp:RequireDerivedKeys />
        writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI);
      }

      if (isRequireExternalUriRef()) {
        // <sp:RequireExternalUriReference />
        writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_URI_REFERENCE, namespaceURI);
      }

      if (isSc10SecurityContextToken()) {
        // <sp:SC10SecurityContextToken />
        writer.writeEmptyElement(prefix, SPConstants.SC10_SECURITY_CONTEXT_TOKEN, namespaceURI);
      }

      if (bootstrapPolicy != null) {
        // <sp:BootstrapPolicy ..>
        writer.writeStartElement(prefix, SPConstants.BOOTSTRAP_POLICY, namespaceURI);
        bootstrapPolicy.serialize(writer);
        writer.writeEndElement();
      }

      // </wsp:Policy>
      writer.writeEndElement();
    }

    // </sp:SecureConversationToken>
    writer.writeEndElement();
  }
 public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
   if (log.isDebugEnabled()) {
     log.debug("UnifiedEndpointModule applying policy: " + policy.getName());
   }
 }