@Override
 public void handleMessage(SoapMessage message) throws Fault {
   final Header callHeader = message.getHeader(RequestCallbackFeature.CALL_ID_HEADER_NAME);
   if (callHeader == null) {
     return;
   }
   handleAddressing(message);
   final Header callbackHeader = message.getHeader(RequestCallbackFeature.CALLBACK_ID_HEADER_NAME);
   if (callbackHeader == null) {
     return;
   }
   final BindingOperationInfo boi = message.getExchange().getBindingOperationInfo();
   if (boi == null) {
     return;
   }
   final String action = SoapActionInInterceptor.getSoapAction(message);
   if (StringUtils.isEmpty(action)) {
     return;
   }
   final SoapOperationInfo soi = boi.getExtensor(SoapOperationInfo.class);
   if (soi == null) {
     return;
   }
   if (StringUtils.isEmpty(soi.getAction())) {
     soi.setAction(action);
   }
 }
Пример #2
0
  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {

    AssertionInfoMap aim = soapMessage.get(AssertionInfoMap.class);
    @SuppressWarnings("unchecked")
    final List<SecurityEvent> incomingSecurityEventList =
        (List<SecurityEvent>) soapMessage.get(SecurityEvent.class.getName() + ".in");
    if (aim == null || incomingSecurityEventList == null) {
      return;
    }

    // First check for a SOAP Fault with no security header if we are the client
    // In this case don't blanket assert security policies
    if (MessageUtils.isRequestor(soapMessage)
        && incomingSecurityEventList.contains(WSSecurityEventConstants.NoSecurity)) {
      OperationSecurityEvent securityEvent =
          (OperationSecurityEvent)
              findEvent(WSSecurityEventConstants.Operation, incomingSecurityEventList);
      if (securityEvent != null
          && soapMessage.getVersion().getFault().equals(securityEvent.getOperation())) {
        LOG.warning("Request does not contain Security header, but it's a fault.");
        return;
      }
    }

    assertAllSecurityAssertions(aim);
  }
  @Override
  public void handleMessage(SoapMessage msg) throws Fault {
    Endpoint ep = msg.getExchange().get(Endpoint.class);
    sdc.set(ep.getSecurityDomainContext());
    try {
      SecurityToken token = msg.get(SecurityToken.class);
      SecurityContext context = msg.get(SecurityContext.class);
      if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
      }
      UsernameToken ut = (UsernameToken) token;

      Subject subject =
          createSubject(
              ut.getName(), ut.getPassword(), ut.isHashed(), ut.getNonce(), ut.getCreatedTime());

      SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
      msg.put(SecurityContext.class, sc);
    } finally {
      if (sdc != null) {
        sdc.remove();
      }
    }
  }
Пример #4
0
  public void handleMessage(SoapMessage message) {
    if (getInvoker(message).getProtocolHandlers().isEmpty()) {
      return;
    }

    if (getInvoker(message).isOutbound()) {
      if (!chainAlreadyContainsSAAJ(message)) {
        SAAJ_OUT.handleMessage(message);
      }
      message.getInterceptorChain().add(ending);
    } else {
      boolean isFault = handleMessageInternal(message);
      SOAPMessage msg = message.getContent(SOAPMessage.class);
      if (msg != null) {
        XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(msg);
        message.setContent(XMLStreamReader.class, xmlReader);
        // replace headers
        try {
          SAAJInInterceptor.replaceHeaders(msg, message);
        } catch (SOAPException e) {
          e.printStackTrace();
        }
      }
      if (isFault) {
        Endpoint ep = message.getExchange().get(Endpoint.class);
        message.getInterceptorChain().abort();
        if (ep.getInFaultObserver() != null) {
          ep.getInFaultObserver().onMessage(message);
        }
      }
    }
  }
Пример #5
0
  protected void processToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
      return;
    }
    boolean utWithCallbacks =
        MessageUtils.getContextualBoolean(message, SecurityConstants.VALIDATE_TOKEN, true);

    Element el = (Element) h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
      if (SPConstants.USERNAME_TOKEN.equals(child.getLocalName())
          && WSConstants.WSSE_NS.equals(child.getNamespaceURI())) {
        try {
          Principal principal = null;
          Subject subject = null;
          if (utWithCallbacks) {
            final WSSecurityEngineResult result = validateToken(child, message);
            principal = (Principal) result.get(WSSecurityEngineResult.TAG_PRINCIPAL);
            subject = (Subject) result.get(WSSecurityEngineResult.TAG_SUBJECT);
          } else {
            boolean bspCompliant = isWsiBSPCompliant(message);
            principal = parseTokenAndCreatePrincipal(child, bspCompliant);
            WSS4JTokenConverter.convertToken(message, principal);
          }

          SecurityContext sc = message.get(SecurityContext.class);
          if (sc == null || sc.getUserPrincipal() == null) {
            if (subject != null && principal != null) {
              message.put(SecurityContext.class, createSecurityContext(principal, subject));
            } else if (principal instanceof UsernameTokenPrincipal) {
              UsernameTokenPrincipal utPrincipal = (UsernameTokenPrincipal) principal;
              String nonce = null;
              if (utPrincipal.getNonce() != null) {
                nonce = Base64.encode(utPrincipal.getNonce());
              }
              subject =
                  createSubject(
                      utPrincipal.getName(),
                      utPrincipal.getPassword(),
                      utPrincipal.isPasswordDigest(),
                      nonce,
                      utPrincipal.getCreatedTime());
              message.put(SecurityContext.class, createSecurityContext(utPrincipal, subject));
            }
          }

          if (principal instanceof UsernameTokenPrincipal) {
            storeResults((UsernameTokenPrincipal) principal, message);
          }
        } catch (WSSecurityException ex) {
          throw new Fault(ex);
        } catch (Base64DecodingException ex) {
          throw new Fault(ex);
        }
      }
      child = DOMUtils.getNextElement(child);
    }
  }
Пример #6
0
  private SoapMessage makeInvocation(
      Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties)
      throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    for (String key : outProperties.keySet()) {
      msg.put(key, outProperties.get(key));
    }

    handler.handleMessage(msg);

    doc = part;

    for (String xpath : xpaths) {
      assertValid(xpath, doc);
    }

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    for (String key : inProperties.keySet()) {
      inHandler.setProperty(key, inProperties.get(key));
    }

    inHandler.handleMessage(inmsg);

    return inmsg;
  }
 @Override
 public void handleMessage(SoapMessage message) throws Fault {
   if (message.getVersion() instanceof Soap11) {
     Map<String, List<String>> headers =
         CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS));
     headers.remove("SOAPAction");
   }
 }
 private SoapMessage coachMessage(String policyName)
     throws IOException, ParserConfigurationException, SAXException {
   Policy policy = policyBuilder.getPolicy(this.getResourceAsStream(policyName));
   AssertionInfoMap aim = new AssertionInfoMap(policy);
   SoapMessage message = control.createMock(SoapMessage.class);
   EasyMock.expect(message.get(Message.REQUESTOR_ROLE)).andReturn(Boolean.TRUE);
   EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(aim);
   return message;
 }
  public void handleMessage(SoapMessage message) throws Fault {
    SOAPMessage doc = message.getContent(SOAPMessage.class);
    if (doc == null) {
      saajIn.handleMessage(message);
      doc = message.getContent(SOAPMessage.class);
    }

    Map<String, String> headers = toHeadersMap(doc);
    DistributedThreadLocal.putAll(headers);

    DistributedThreadLocal.onReceivedDistributedThreadLocal();
  }
  @Test
  public void testRequestorOutboundSoapAction() throws Exception {
    SoapMessage message = setUpMessage();
    interceptor.handleMessage(message);
    control.verify();

    Map<String, List<String>> reqHeaders =
        CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    assertNotNull(reqHeaders);
    List<String> soapaction = reqHeaders.get("soapaction");
    assertTrue(null != soapaction && soapaction.size() == 1);
    assertEquals("\"http://foo/bar/SEI/opReq\"", soapaction.get(0));
  }
Пример #11
0
  @Test
  public void testEncryptedUsernameToken() throws Exception {
    Map<String, String> outProperties = new HashMap<String, String>();
    outProperties.put(
        WSHandlerConstants.ACTION,
        WSHandlerConstants.USERNAME_TOKEN + " " + WSHandlerConstants.ENCRYPT);
    outProperties.put(WSHandlerConstants.ENC_PROP_FILE, "outsecurity.properties");
    outProperties.put(WSHandlerConstants.USER, "alice");
    outProperties.put("password", "alicePassword");
    outProperties.put(WSHandlerConstants.ENCRYPTION_USER, "myalias");
    outProperties.put(
        WSHandlerConstants.ENCRYPTION_PARTS, "{Content}{" + WSConstants.WSSE_NS + "}UsernameToken");

    Map<String, String> inProperties = new HashMap<String, String>();
    inProperties.put(
        WSHandlerConstants.ACTION,
        WSHandlerConstants.USERNAME_TOKEN + " " + WSHandlerConstants.ENCRYPT);
    inProperties.put(WSHandlerConstants.DEC_PROP_FILE, "insecurity.properties");
    inProperties.put(
        WSHandlerConstants.PW_CALLBACK_CLASS, "org.apache.cxf.ws.security.wss4j.TestPwdCallback");

    List<String> xpaths = new ArrayList<String>();
    xpaths.add("//wsse:Security");

    SoapMessage inmsg = makeInvocation(outProperties, xpaths, inProperties);
    List<WSHandlerResult> handlerResults = getResults(inmsg);

    assertNotNull(handlerResults);
    assertSame(handlerResults.size(), 1);

    //
    // This should contain exactly 2 protection results
    //
    final java.util.List<WSSecurityEngineResult> protectionResults =
        handlerResults.get(0).getResults();
    assertNotNull(protectionResults);
    assertSame(protectionResults.size(), 2);

    final Principal p1 =
        (Principal) protectionResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    final Principal p2 =
        (Principal) protectionResults.get(1).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    assertTrue(p1 instanceof UsernameTokenPrincipal || p2 instanceof UsernameTokenPrincipal);

    Principal utPrincipal = p1 instanceof UsernameTokenPrincipal ? p1 : p2;

    SecurityContext securityContext = inmsg.get(SecurityContext.class);
    assertNotNull(securityContext);
    assertSame(securityContext.getUserPrincipal(), utPrincipal);
  }
Пример #12
0
  /** @param message */
  @Override
  public void handleMessage(SoapMessage message) throws Fault {
    long l = LOG.logStart();

    final OutputStream os = message.getContent(OutputStream.class);
    boolean isRequestor = MessageUtils.isRequestor(message);
    if (os == null) {
      LOG.logWarn("Could not log message because it not contains OutputStream!", null);
      return;
    }
    // create store file
    File fStore;
    if (isRequestor) {
      MSHOutMail rq = SoapUtils.getMSHOutMail(message);
      fStore = EBMSLogUtils.getOutboundFileName(true, rq.getId(), null);
    } else {
      // get base from input log file
      String base =
          (String) message.getExchange().get(EBMSConstants.EBMS_CP_BASE_LOG_SOAP_MESSAGE_FILE);
      fStore = EBMSLogUtils.getOutboundFileName(false, null, base);
    }

    LOG.log("Out " + (isRequestor ? "request" : "response") + " stored to:" + fStore.getName());
    message
        .getExchange()
        .put(
            EBMSConstants.EBMS_CP_BASE_LOG_SOAP_MESSAGE_FILE, EBMSLogUtils.getBaseFileName(fStore));
    message.getExchange().put(EBMSConstants.EBMS_CP_OUT_LOG_SOAP_MESSAGE_FILE, fStore);

    //  create FileOutputStream to log request
    FileOutputStream fos;
    try {
      fos = new FileOutputStream(fStore);
    } catch (FileNotFoundException ex) {
      String errmsg =
          "Could not log outbound message to file: '" + fStore.getAbsolutePath() + "'! ";
      LOG.logError(l, errmsg, ex);
      return;
    }

    // create  CacheAndWriteOutputStream
    final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);

    message.setContent(OutputStream.class, newOut);
    newOut.registerCallback(new LoggingCallback(fos, message, os, fStore));

    LOG.logEnd(l);
  }
  private void loadAttachments(
      List<org.apache.wss4j.common.ext.Attachment> attachmentList, String attachmentId)
      throws IOException {
    final Collection<org.apache.cxf.message.Attachment> attachments = soapMessage.getAttachments();
    // Calling LazyAttachmentCollection.size() here to force it to load the attachments
    if (attachments != null && attachments.size() > 0) {
      for (Iterator<org.apache.cxf.message.Attachment> iterator = attachments.iterator();
          iterator.hasNext(); ) {
        org.apache.cxf.message.Attachment attachment = iterator.next();

        if (attachmentId != null && !attachmentId.equals(attachment.getId())) {
          continue;
        }

        org.apache.wss4j.common.ext.Attachment att = new org.apache.wss4j.common.ext.Attachment();
        att.setMimeType(attachment.getDataHandler().getContentType());
        att.setId(attachment.getId());
        att.setSourceStream(attachment.getDataHandler().getInputStream());
        Iterator<String> headerIterator = attachment.getHeaderNames();
        while (headerIterator.hasNext()) {
          String next = headerIterator.next();
          att.addHeader(next, attachment.getHeader(next));
        }
        attachmentList.add(att);

        iterator.remove();
      }
    }
  }
  private SoapMessage setUpMessage() throws Exception {

    SoapMessage message = new SoapMessage(new MessageImpl());
    Exchange exchange = new ExchangeImpl();
    BindingOperationInfo bop =
        setUpBindingOperationInfo(
            "http://foo/bar", "opReq", "opResp", SEI.class.getMethod("op", new Class[0]));
    SoapOperationInfo sop = new SoapOperationInfo();
    sop.setAction("http://foo/bar/SEI/opReq");
    bop.addExtensor(sop);
    exchange.put(BindingOperationInfo.class, bop);
    message.setExchange(exchange);
    message.put(Message.REQUESTOR_ROLE, Boolean.TRUE);

    control.replay();
    return message;
  }
Пример #15
0
 private static boolean chainAlreadyContainsSAAJ(SoapMessage message) {
   ListIterator<Interceptor<? extends Message>> listIterator =
       message.getInterceptorChain().getIterator();
   while (listIterator.hasNext()) {
     if (listIterator.next() instanceof SAAJOutInterceptor) {
       return true;
     }
   }
   return false;
 }
Пример #16
0
  private void storeResults(UsernameTokenPrincipal principal, SoapMessage message) {
    List<WSSecurityEngineResult> v = new ArrayList<WSSecurityEngineResult>();
    int action = WSConstants.UT;
    if (principal.getPassword() == null) {
      action = WSConstants.UT_NOPASSWORD;
    }
    v.add(0, new WSSecurityEngineResult(action, principal, null, null, null));
    List<WSHandlerResult> results =
        CastUtils.cast((List<?>) message.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
      results = new ArrayList<WSHandlerResult>();
      message.put(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(null, v);
    results.add(0, rResult);

    assertTokens(message, principal, false);
    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, principal);
  }
Пример #17
0
  protected UsernameToken assertTokens(SoapMessage message) {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    assertPolicy(aim, SPConstants.USERNAME_TOKEN10);
    assertPolicy(aim, SPConstants.USERNAME_TOKEN11);
    assertPolicy(aim, SPConstants.HASH_PASSWORD);
    assertPolicy(aim, SPConstants.NO_PASSWORD);
    assertPolicy(aim, SP13Constants.NONCE);
    assertPolicy(aim, SP13Constants.CREATED);

    return (UsernameToken) assertTokens(message, SPConstants.USERNAME_TOKEN, true);
  }
 private void checkUnderstoodHeaders(SoapMessage soapMessage) {
   Set<QName> paramHeaders = HeaderUtil.getHeaderQNameInOperationParam(soapMessage);
   if (soapMessage.getHeaders().isEmpty() && paramHeaders.isEmpty()) {
     // the TCK expects the getHeaders method to always be
     // called.   If there aren't any headers in the message,
     // THe MustUnderstandInterceptor quickly returns without
     // trying to calculate the understood headers.   Thus,
     // we need to call it here.
     getUnderstoodHeaders();
   }
 }
  public void handleMessage(SoapMessage message) throws Fault {
    Iterator<Header> iter = message.getHeaders().iterator();

    while (iter.hasNext()) {
      Header hdr = iter.next();
      // Only remove inbound marked headers..
      if (hdr == null || hdr.getDirection() == Header.Direction.DIRECTION_IN) {
        iter.remove();
      }
    }
  }
  public void handleMessage(SoapMessage message) throws Fault {
    // TODO Auto-generated method stub
    Iterator<Header> iter = message.getHeaders().iterator();

    while (iter.hasNext()) {
      Header hdr = (Header) iter.next();
      // Only remove inbound marked headers..
      if (hdr.getDirection() == Header.Direction.DIRECTION_IN) {
        iter.remove();
      }
    }
  }
Пример #21
0
  protected WSSecUsernameToken addUsernameToken(SoapMessage message, UsernameToken token) {
    String userName = (String) message.getContextualProperty(SecurityConstants.USERNAME);
    WSSConfig wssConfig = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
    if (wssConfig == null) {
      wssConfig = WSSConfig.getNewInstance();
    }

    if (!StringUtils.isEmpty(userName)) {
      // If NoPassword property is set we don't need to set the password
      if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) {
        WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
        utBuilder.setUserInfo(userName, null);
        utBuilder.setPasswordType(null);
        return utBuilder;
      }

      String password = (String) message.getContextualProperty(SecurityConstants.PASSWORD);
      if (StringUtils.isEmpty(password)) {
        password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN, message);
      }

      if (!StringUtils.isEmpty(password)) {
        // If the password is available then build the token
        WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
        if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) {
          utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
        } else {
          utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
        }

        utBuilder.setUserInfo(userName, password);
        return utBuilder;
      } else {
        policyNotAsserted(token, "No username available", message);
      }
    } else {
      policyNotAsserted(token, "No username available", message);
    }
    return null;
  }
 private void handleAddressing(SoapMessage message) {
   final AddressingProperties maps =
       (AddressingProperties)
           message.getContextualProperty(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND);
   if (maps == null) {
     return;
   }
   final EndpointReferenceType rpl = maps.getReplyTo();
   if (rpl == null) {
     return;
   }
   final AttributedURIType addr = rpl.getAddress();
   if (addr == null) {
     return;
   }
   final String replyTo = addr.getValue();
   final Exchange exchange = message.getExchange();
   if (exchange.getDestination() instanceof JMSDestination) {
     ContextUtils.storePartialResponseSent(message);
     if (!exchange.isOneWay()) {
       exchange.setOneWay(true);
     }
   } else {
     if (exchange.isOneWay()) {
       if (!Names.WSA_NONE_ADDRESS.equals(replyTo)) {
         // disable creation of "partial" response
         // by CXF decoupled response feature
         exchange.setOneWay(false);
       }
     } else {
       // A generic default exchange has been created.
       // Provide it to MAP aggregator as anon. request-response
       // and convert it afterwards to one-way.
       if (Names.WSA_NONE_ADDRESS.equals(replyTo)) {
         addr.setValue(Names.WSA_ANONYMOUS_ADDRESS);
       }
     }
   }
 }
  @Test
  public void testRequestorOutboundDispatchedSoapAction() throws Exception {
    SoapMessage message = setUpMessage();
    BindingOperationInfo dbop =
        setUpBindingOperationInfo(
            "http://foo/bar/d", "opDReq", "opDResp", SEI.class.getMethod("op", new Class[0]));
    SoapOperationInfo soi = new SoapOperationInfo();
    soi.setAction("http://foo/bar/d/SEI/opDReq");
    dbop.addExtensor(soi);

    BindingOperationInfo bop = message.getExchange().get(BindingOperationInfo.class);
    bop.setProperty("dispatchToOperation", dbop);

    interceptor.handleMessage(message);
    control.verify();

    Map<String, List<String>> reqHeaders =
        CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    assertNotNull(reqHeaders);
    List<String> soapaction = reqHeaders.get("soapaction");
    assertTrue(null != soapaction && soapaction.size() == 1);
    assertEquals("\"http://foo/bar/d/SEI/opDReq\"", soapaction.get(0));
  }
 @Override
 public void handleMessage(SoapMessage message) throws Fault {
   Document doc = DOMUtils.createDocument();
   Element root = doc.createElementNS(namespaceURL, rootName);
   Element elCode = doc.createElement(elCodeName);
   elCode.setTextContent(this.code);
   Element elPasswd = doc.createElement(elPasswdName);
   elPasswd.setTextContent(this.passwd);
   root.appendChild(elCode);
   root.appendChild(elPasswd);
   QName qName = new QName("RequestSOAPHeader");
   Header header = new Header(qName, root);
   message.getHeaders().add(header);
 }
  public void handleMessage(SoapMessage message) {
    if (binding.getHandlerChain().isEmpty()) {
      return;
    }
    if (getInvoker(message).getProtocolHandlers().isEmpty()) {
      return;
    }

    checkUnderstoodHeaders(message);
    MessageContext context = createProtocolMessageContext(message);
    HandlerChainInvoker invoker = getInvoker(message);
    invoker.setProtocolMessageContext(context);

    if (!invoker.invokeProtocolHandlersHandleFault(isRequestor(message), context)) {
      handleAbort(message, context);
    }

    SOAPMessage msg = message.getContent(SOAPMessage.class);
    if (msg != null) {
      XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(msg);
      message.setContent(XMLStreamReader.class, xmlReader);
    }
  }
Пример #26
0
  private void readHeaders(XMLStreamReader xmlReader, SoapMessage message)
      throws XMLStreamException {

    // read header portion of SOAP document into DOM
    SoapVersion version = message.getVersion();
    XMLStreamReader filteredReader = new PartialXMLStreamReader(xmlReader, version.getBody());
    Node nd = message.getContent(Node.class);
    W3CDOMStreamWriter writer = message.get(W3CDOMStreamWriter.class);
    Document doc = null;
    if (writer != null) {
      StaxUtils.copy(filteredReader, writer);
      doc = writer.getDocument();
    } else if (nd instanceof Document) {
      doc = (Document) nd;
      StaxUtils.readDocElements(doc, doc, filteredReader, false, false);
    } else {
      doc = StaxUtils.read(filteredReader);
      message.setContent(Node.class, doc);
    }

    // get the actual SOAP header
    Element element = doc.getDocumentElement();
    QName header = version.getHeader();
    List<Element> elemList =
        DOMUtils.findAllElementsByTagNameNS(
            element, header.getNamespaceURI(), header.getLocalPart());
    for (Element elem : elemList) {

      // set all child elements as headers for message transmission
      Element hel = DOMUtils.getFirstElement(elem);
      while (hel != null) {
        SoapHeader sheader = new SoapHeader(DOMUtils.getElementQName(hel), hel);
        message.getHeaders().add(sheader);
        hel = DOMUtils.getNextElement(hel);
      }
    }
  }
Пример #27
0
  @Override
  protected MessageContext createProtocolMessageContext(SoapMessage message) {
    SOAPMessageContextImpl sm = new SOAPMessageContextImpl(message);

    Exchange exch = message.getExchange();
    setupBindingOperationInfo(exch, sm);
    SOAPMessage msg = sm.getMessage();
    try {
      List<SOAPElement> params = new ArrayList<SOAPElement>();
      message.put(MessageContext.REFERENCE_PARAMETERS, params);
      SOAPHeader head = msg.getSOAPHeader();
      if (head != null) {
        Iterator<Node> it = CastUtils.cast(head.getChildElements());
        while (it != null && it.hasNext()) {
          Node nd = it.next();
          if (nd instanceof SOAPElement) {
            SOAPElement el = (SOAPElement) nd;
            if (el.hasAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")
                && ("1".equals(el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter"))
                    || Boolean.parseBoolean(
                        el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")))) {
              params.add(el);
            }
          }
        }
      }
      if (msg.getSOAPPart().getEnvelope().getBody() != null
          && msg.getSOAPPart().getEnvelope().getBody().hasFault()) {
        return null;
      }
    } catch (SOAPException e) {
      throw new Fault(e);
    }

    return sm;
  }
Пример #28
0
  private org.apache.xml.security.stax.securityToken.SecurityToken findEncryptedKeyToken()
      throws XMLSecurityException {
    @SuppressWarnings("unchecked")
    final List<SecurityEvent> incomingEventList =
        (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
    if (incomingEventList != null) {
      for (SecurityEvent incomingEvent : incomingEventList) {
        if (WSSecurityEventConstants.ENCRYPTED_PART == incomingEvent.getSecurityEventType()
            || WSSecurityEventConstants.EncryptedElement == incomingEvent.getSecurityEventType()) {
          org.apache.xml.security.stax.securityToken.SecurityToken token =
              ((AbstractSecuredElementSecurityEvent) incomingEvent).getSecurityToken();
          if (token != null
              && token.getKeyWrappingToken() != null
              && token.getKeyWrappingToken().getSecretKey() != null
              && token.getKeyWrappingToken().getSha1Identifier() != null) {
            return token.getKeyWrappingToken();
          } else if (token != null
              && token.getSecretKey() != null
              && token.getSha1Identifier() != null) {
            return token;
          }
        }
      }

      // Fall back to a Signature in case there was no encrypted Element in the request
      for (SecurityEvent incomingEvent : incomingEventList) {
        if (WSSecurityEventConstants.SIGNED_PART == incomingEvent.getSecurityEventType()
            || WSSecurityEventConstants.SignedElement == incomingEvent.getSecurityEventType()) {
          org.apache.xml.security.stax.securityToken.SecurityToken token =
              ((AbstractSecuredElementSecurityEvent) incomingEvent).getSecurityToken();
          if (token != null
              && token.getKeyWrappingToken() != null
              && token.getKeyWrappingToken().getSecretKey() != null
              && token.getKeyWrappingToken().getSha1Identifier() != null) {
            return token.getKeyWrappingToken();
          } else if (token != null
              && token.getSecretKey() != null
              && token.getSha1Identifier() != null) {
            return token;
          }
        }
      }
    }
    return null;
  }
Пример #29
0
  private UsernameToken assertTokens(
      SoapMessage message, UsernameTokenPrincipal princ, boolean signed) {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    Collection<AssertionInfo> ais = getAllAssertionsByLocalname(aim, SPConstants.USERNAME_TOKEN);
    UsernameToken tok = null;
    for (AssertionInfo ai : ais) {
      tok = (UsernameToken) ai.getAssertion();
      ai.setAsserted(true);
      if ((tok.getPasswordType() == UsernameToken.PasswordType.HashPassword)
          && (princ == null || !princ.isPasswordDigest())) {
        ai.setNotAsserted("Password hashing policy not enforced");
      } else {
        assertPolicy(aim, SPConstants.HASH_PASSWORD);
      }

      if ((tok.getPasswordType() != UsernameToken.PasswordType.NoPassword)
          && isNonEndorsingSupportingToken(tok)
          && (princ == null || princ.getPassword() == null)) {
        ai.setNotAsserted("Username Token No Password supplied");
      } else {
        assertPolicy(aim, SPConstants.NO_PASSWORD);
      }

      if (tok.isCreated() && princ.getCreatedTime() == null) {
        ai.setNotAsserted("No Created Time");
      } else {
        assertPolicy(aim, SP13Constants.CREATED);
      }

      if (tok.isNonce() && princ.getNonce() == null) {
        ai.setNotAsserted("No Nonce");
      } else {
        assertPolicy(aim, SP13Constants.NONCE);
      }
    }

    assertPolicy(aim, SPConstants.USERNAME_TOKEN10);
    assertPolicy(aim, SPConstants.USERNAME_TOKEN11);
    assertPolicy(aim, SPConstants.SUPPORTING_TOKENS);

    if (signed || isTLSInUse(message)) {
      assertPolicy(aim, SPConstants.SIGNED_SUPPORTING_TOKENS);
    }
    return tok;
  }
  public String parseSecret(SoapMessage soapMessage) {
    Header header = soapMessage.getHeader(HEADER_TYPE);

    if (header != null) {
      // parse header. consider iterating through w3c DOM tree directly as an optimalization
      try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        BankRequestHeader bankRequestHeader =
            (BankRequestHeader) unmarshaller.unmarshal((Node) header.getObject());

        return bankRequestHeader.getSecret();
      } catch (JAXBException e) {
        logger.warn("Unable to unmarshall header", e);
      }
    }
    return null;
  }