コード例 #1
0
 /**
  * Verifies if the input xmlstring can be converted to an AttributeValue Element. If so, return
  * the element value.
  */
 private String validateAndGetAttributeValue(String value) throws SAML2Exception {
   Document doc = XMLUtils.toDOMDocument(value, SAML2SDKUtils.debug);
   if (doc == null) {
     if (SAML2SDKUtils.debug.messageEnabled()) {
       SAML2SDKUtils.debug.message(
           "AttributeImpl."
               + "validateAttributeValue:"
               + " could not obtain AttributeValue element.");
     }
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
   }
   Element element = doc.getDocumentElement();
   if (element == null) {
     if (SAML2SDKUtils.debug.messageEnabled()) {
       SAML2SDKUtils.debug.message("AttributeImpl." + "validateAttributeValue: Input is null.");
     }
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
   }
   // Make sure this is an AttributeValue.
   String tag = element.getLocalName();
   if ((tag == null) || (!tag.equals("AttributeValue"))) {
     if (SAML2SDKUtils.debug.messageEnabled()) {
       SAML2SDKUtils.debug.message(
           "AttributeImpl." + "validateAttributeValue: not AttributeValue.");
     }
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
   }
   return XMLUtils.getChildrenValue(element);
 }
コード例 #2
0
  /**
   * Constructor that uses DOM Element
   *
   * @param element the DOM representation of security token.
   * @throws com.sun.identity.wss.security.SecurityException
   */
  public FAMSecurityToken(Element element) throws SecurityException {
    if (element == null) {
      throw new SecurityException(WSSUtils.bundle.getString("nullInput"));
    }

    String localName = element.getLocalName();
    if (!"FAMToken".equals(localName)) {
      throw new SecurityException(WSSUtils.bundle.getString("invalidElement"));
    }

    NodeList nl = element.getChildNodes();
    int length = nl.getLength();
    if (length == 0) {
      throw new SecurityException(WSSUtils.bundle.getString("invalidElement"));
    }

    for (int i = 0; i < length; i++) {
      Node child = (Node) nl.item(i);
      if (child.getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }

      String childName = child.getLocalName();
      if (childName.equals("TokenValue")) {
        tokenID = XMLUtils.getElementValue((Element) child);
      } else if (childName.equals("AppTokenValue")) {
        appTokenID = XMLUtils.getElementValue((Element) child);
      } else if (childName.equals("TokenType")) {
        tokenType = XMLUtils.getElementValue((Element) child);
      }
    }
  }
コード例 #3
0
 /** Class constructor with <code>AttributeStatement</code> in xml string format. */
 public AttributeStatementImpl(String xmlString) throws SAML2Exception {
   Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
   if (doc == null) {
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
   }
   parseElement(doc.getDocumentElement());
 }
コード例 #4
0
ファイル: Attribute.java プロジェクト: aldaris/opensso
  /**
   * Returns a String representation of the <code>&lt;saml:Attribute&gt;</code> element.
   *
   * @param includeNS Determines whether or not the namespace qualifier is prepended to the Element
   *     when converted
   * @param declareNS Determines whether or not the namespace is declared within the Element.
   * @return A string containing the valid XML for this element
   */
  public String toString(boolean includeNS, boolean declareNS) {
    StringBuffer result = new StringBuffer(1000);
    String prefix = "";
    String uri = "";
    if (includeNS) {
      prefix = SAMLConstants.ASSERTION_PREFIX;
    }
    if (declareNS) {
      uri = SAMLConstants.assertionDeclareStr;
    }
    result
        .append("<")
        .append(prefix)
        .append("Attribute")
        .append(uri)
        .append(" AttributeName=\"")
        .append(_attributeName)
        .append("\" AttributeNamespace=\"")
        .append(_attributeNameSpace)
        .append("\">\n");

    Iterator iter = _attributeValue.iterator();
    while (iter.hasNext()) {
      result.append(XMLUtils.printAttributeValue((Element) iter.next(), prefix)).append("\n");
    }
    result.append("</").append(prefix).append("Attribute>\n");
    return result.toString();
  }
コード例 #5
0
 /**
  * Constructor creates <code>SPProvidedNameIdentifier</code> object from Document Element.
  *
  * @param spProvidedNameIdentifierElement the Document Element.
  * @throws FSMsgException on errors.
  */
 public SPProvidedNameIdentifier(Element spProvidedNameIdentifierElement) throws FSMsgException {
   Element elt = (Element) spProvidedNameIdentifierElement;
   String eltName = elt.getLocalName();
   if (eltName == null) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element): " + "local name missing");
     }
     throw new FSMsgException("nullInput", null);
   }
   if (!(eltName.equals("SPProvidedNameIdentifier"))) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element: " + "invalid root element");
     }
     throw new FSMsgException("invalidElement", null);
   }
   String read = elt.getAttribute("NameQualifier");
   if (read != null) {
     setNameQualifier(read);
   }
   read = elt.getAttribute("Format");
   if (read != null) {
     setFormat(read);
   }
   read = XMLUtils.getElementValue(elt);
   if ((read == null) || (read.length() == 0)) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element:  " + "null input specified");
     }
     throw new FSMsgException("nullInput", null);
   } else {
     setName(read);
   }
 }
コード例 #6
0
 /** Class constructor with <code>Attribute</code> in xml string format. */
 public AttributeImpl(String xmlString) throws com.sun.identity.saml2.common.SAML2Exception {
   Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
   if (doc == null) {
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
   }
   parseElement(doc.getDocumentElement());
 }
コード例 #7
0
ファイル: MessageProcessor.java プロジェクト: aldaris/opensso
  /**
   * Secures the SOAP Message response by adding necessary headers to the given SOAP Message and
   * also signs the message if it is required.
   *
   * @param soapMessage SOAP Message that needs to be secured.
   * @param sharedData Any shared data that may be needed between the request and response.
   * @return SOAPMessage Secured SOAP Message by adding liberty headers and also signs the message
   *     if configured.
   * @exception SOAPBindingException for any failure.
   */
  public SOAPMessage secureResponse(SOAPMessage soapMessage, Map sharedData)
      throws SOAPBindingException {

    WSSUtils.debug.message("MessageProcessor.secureResponse : Init");

    try {
      Message req = (Message) sharedData.get(SOAPBindingConstants.LIBERTY_REQUEST);
      addCorrelationHeader(soapMessage, req);

      if (_config.isResponseSignEnabled()) {
        soapMessage = signMessage(soapMessage, null, null);
      }

      if (WSSUtils.debug.messageEnabled()) {
        WSSUtils.debug.message(
            "MessageProcessor.secureResponse: "
                + com.sun.identity.shared.xml.XMLUtils.print(
                    soapMessage.getSOAPPart().getEnvelope()));
      }
      return soapMessage;
    } catch (Exception ex) {
      WSSUtils.debug.error(
          "MessageProcessor.secureResponse: " + "Failed in securing the response", ex);
      throw new SOAPBindingException(WSSUtils.bundle.getString("secureResponseFailed"));
    }
  }
コード例 #8
0
ファイル: Attribute.java プロジェクト: aldaris/opensso
 /**
  * Adds <code>AttributeValue</code> to the Attribute.
  *
  * @param value A String representing <code>AttributeValue</code>.
  * @exception SAMLException
  */
 public void addAttributeValue(String value) throws SAMLException {
   if (value == null || value.length() == 0) {
     if (SAMLUtilsCommon.debug.messageEnabled()) {
       SAMLUtilsCommon.debug.message("addAttributeValue: Input is null");
     }
     throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
   }
   StringBuffer sb = new StringBuffer(300);
   sb.append("<")
       .append(SAMLConstants.ASSERTION_PREFIX)
       .append("AttributeValue")
       .append(SAMLConstants.assertionDeclareStr)
       .append(">")
       .append(value)
       .append("</")
       .append(SAMLConstants.ASSERTION_PREFIX)
       .append("AttributeValue>");
   try {
     Element ele =
         XMLUtils.toDOMDocument(sb.toString().trim(), SAMLUtilsCommon.debug).getDocumentElement();
     if (_attributeValue == null) {
       _attributeValue = new ArrayList();
     }
     if (!(_attributeValue.add(ele))) {
       if (SAMLUtilsCommon.debug.messageEnabled()) {
         SAMLUtilsCommon.debug.message(
             "Attribute: failed to " + "add to the attribute value list.");
       }
       throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError"));
     }
   } catch (Exception e) {
     SAMLUtilsCommon.debug.error("addAttributeValue error", e);
     throw new SAMLRequesterException("Exception in addAttributeValue" + e.getMessage());
   }
 }
コード例 #9
0
  /**
   * Parses an XML document.
   *
   * @param xmlin the XML document.
   * @return the ParseOutput object from walking and processing the node.
   * @throws Exception if there are IO or XML parsing exceptions.
   */
  public Object parse(InputStream xmlin) throws Exception {
    DocumentBuilder db = null;
    try {
      db = XMLUtils.getSafeDocumentBuilder(false);
    } catch (ParserConfigurationException e) {
      throw new Exception("DBG:Got ParserConfigurationException:" + e.toString());
    }

    Document doc = null;
    try {
      doc = db.parse(xmlin);
    } catch (SAXParseException e) {
      throw new Exception(
          "DBG:Got SAXParseException:"
              + e.toString()
              + "line:"
              + e.getLineNumber()
              + " col :"
              + e.getColumnNumber());
    } catch (SAXException e) {
      throw new Exception("DBG:Got SAXException:" + e.toString());
    } catch (IOException ex) {
      throw new Exception("DBG: Got IOException:" + ex.toString());
    }

    Element elem = doc.getDocumentElement();
    return (walkTree(elem));
  }
コード例 #10
0
ファイル: Utils.java プロジェクト: greaterwinner/OpenAM
  /**
   * Converts a JAXB object to a <code>org.w3c.dom.Element</code>.
   *
   * @param jaxbObj a JAXB object
   * @return a <code>org.w3c.dom.Element</code>
   * @throws JAXBException if an error occurs while converting JAXB object.
   * @supported.api
   */
  public static Element convertJAXBToElement(Object jaxbObj, boolean checkIdref)
      throws JAXBException {
    Marshaller m = jc.createMarshaller();
    try {
      m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());

    } catch (PropertyException ex) {
      debug.error("Utils.convertJAXBToElement", ex);
    }

    if (!checkIdref) {
      m.setEventHandler(
          new DefaultValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
              if (event instanceof NotIdentifiableEvent) {
                return true;
              }
              return super.handleEvent(event);
            }
          });
    }

    Document doc = null;
    try {
      doc = XMLUtils.newDocument();
    } catch (Exception ex) {
      debug.error("Utils.convertJAXBToElement:", ex);
    }
    m.marshal(jaxbObj, doc);
    return doc.getDocumentElement();
  }
コード例 #11
0
ファイル: IDPEntry.java プロジェクト: aldaris/opensso
 /**
  * Constructor creates <code>IDPEntry</code> Object from
  * Document Element.
  *
  * @param root Document Element of <code>IDPEntry<code> object.
  * @throws FSMsgException if <code>IDPEntry<code> cannot be created.
  */
 public IDPEntry(Element root) throws FSMsgException {
   if (root == null) {
     SAMLUtils.debug.message("IDPEntry.parseXML: null input.");
     throw new FSMsgException("nullInput", null);
   }
   String tag = null;
   if (((tag = root.getLocalName()) == null) || (!tag.equals("IDPEntry"))) {
     FSUtils.debug.message("IDPEntry.parseXML: wrong input.");
     throw new FSMsgException("wrongInput", null);
   }
   NodeList nl = root.getChildNodes();
   Node child;
   String nodeName;
   int length = nl.getLength();
   for (int i = 0; i < length; i++) {
     child = nl.item(i);
     if ((nodeName = child.getLocalName()) != null) {
       if (nodeName.equals("ProviderID")) {
         if (providerID != null) {
           if (FSUtils.debug.messageEnabled()) {
             FSUtils.debug.message("IDPEntry(Element): should" + "contain only one ProviderID");
           }
           throw new FSMsgException("wrongInput", null);
         }
         providerID = XMLUtils.getElementValue((Element) child);
       } else if (nodeName.equals("ProviderName")) {
         if (providerName != null) {
           if (FSUtils.debug.messageEnabled()) {
             FSUtils.debug.message("IDPEntry(Element): should" + "contain only one ProviderName");
           }
           throw new FSMsgException("wrongInput", null);
         }
         providerName = XMLUtils.getElementValue((Element) child);
       } else if (nodeName.equals("Loc")) {
         if (location != null) {
           if (FSUtils.debug.messageEnabled()) {
             FSUtils.debug.message("IDPEntry(Element): should" + "contain only one Loc");
           }
           throw new FSMsgException("wrongInput", null);
         }
         location = XMLUtils.getElementValue((Element) child);
       }
     }
   }
 }
コード例 #12
0
ファイル: Attribute.java プロジェクト: aldaris/opensso
 /**
  * Constructs an instance of <code>Attribute</code>.
  *
  * @param name The name of the attribute.
  * @param nameSpace The namespace in which <code>AttributeName</code> elements are interpreted.
  * @param attributeValue an <code>AttributeValue</code> object.
  * @exception SAMLException if there is an error in the sender or in the element definition.
  */
 public Attribute(String name, String nameSpace, String attributeValue) throws SAMLException {
   super(name, nameSpace);
   String escapeAttVal =
       SystemConfigurationUtil.getProperty(SAMLConstants.ESCAPE_ATTR_VALUE, "true");
   boolean escapeAtt = "true".equalsIgnoreCase(escapeAttVal) ? true : false;
   if (escapeAtt) {
     this.addAttributeValue(XMLUtils.escapeSpecialCharacters(attributeValue));
   } else {
     this.addAttributeValue(attributeValue);
   }
 }
コード例 #13
0
 /**
  * Constructs an <code>AudienceRestrictionCondition</code> element from an existing XML block.
  *
  * @param audienceRestrictionConditionElement A <code>org.w3c.dom.Element</code> representing DOM
  *     tree for <code>AudienceRestrictionCondition</code> object.
  * @exception SAMLException if it could not process the <code>org.w3c.dom.Element</code> properly,
  *     implying that there is an error in the sender or in the element definition.
  */
 public AudienceRestrictionCondition(org.w3c.dom.Element audienceRestrictionConditionElement)
     throws SAMLException {
   Element elt = (Element) audienceRestrictionConditionElement;
   String eltName = elt.getLocalName();
   if (eltName == null) {
     if (SAMLUtilsCommon.debug.messageEnabled()) {
       SAMLUtilsCommon.debug.message("AudienceRestrictionCondition: " + "null condition ");
     }
     throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
   }
   if (!(eltName.equals("AudienceRestrictionCondition"))) {
     if (!(eltName.equals("Condition"))) {
       if (SAMLUtilsCommon.debug.messageEnabled()) {
         SAMLUtilsCommon.debug.message(
             "AudienceRestrictionCondition: " + "unsupported condition ");
       }
       throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("unsupportedCondition"));
     }
   }
   if (eltName.equals("Condition")) { // seems like extension type
     String type = elt.getAttribute("xsi:type");
     if (!(type.equals("AudienceRestrictionCondition"))) {
       if (SAMLUtilsCommon.debug.messageEnabled()) {
         SAMLUtilsCommon.debug.message("AudienceRestrictionCondition: invalid condition");
       }
       throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("invalidElement"));
     }
   }
   NodeList nl = elt.getChildNodes();
   if (nl.getLength() <= 0) {
     if (SAMLUtilsCommon.debug.messageEnabled()) {
       SAMLUtilsCommon.debug.message(
           "AudienceRestrictionCondition: " + "no Audience in this Element");
     }
     throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("noElement"));
   }
   int length = nl.getLength();
   for (int n = 0; n < length; n++) {
     Node child = (Node) nl.item(n);
     if (child.getNodeType() != Node.ELEMENT_NODE) {
       continue;
     }
     String childName = child.getLocalName();
     if (childName.equals("Audience")) {
       _audience.add(XMLUtils.getElementValue((Element) child));
     } else {
       if (SAMLUtilsCommon.debug.messageEnabled()) {
         SAMLUtilsCommon.debug.message(
             "AudienceRestrictionCondition:" + "  invalid element found");
       }
       throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("invalidElement"));
     }
   }
 }
コード例 #14
0
ファイル: SubjectImpl.java プロジェクト: greaterwinner/OpenAM
 /**
  * This constructor is used to build <code>Subject</code> object from a XML string.
  *
  * @param xml A <code>java.lang.String</code> representing a <code>Subject</code> object
  * @exception XACMLException if it could not process the XML string
  */
 public SubjectImpl(String xml) throws XACMLException {
   Document document = XMLUtils.toDOMDocument(xml, XACMLSDKUtils.debug);
   if (document != null) {
     Element rootElement = document.getDocumentElement();
     processElement(rootElement);
     makeImmutable();
   } else {
     XACMLSDKUtils.debug.error("SubjectImpl.processElement(): invalid XML input");
     throw new XACMLException(
         XACMLSDKUtils.xacmlResourceBundle.getString("errorObtainingElement"));
   }
 }
コード例 #15
0
ファイル: ServiceManager.java プロジェクト: aldaris/opensso
 protected static boolean validateServiceSchema(Node serviceNode) throws SMSException {
   Node schemaRoot = XMLUtils.getChildNode(serviceNode, SMSUtils.SCHEMA);
   String[] schemaNames = {
     SMSUtils.GLOBAL_SCHEMA,
     SMSUtils.ORG_SCHEMA,
     SMSUtils.DYNAMIC_SCHEMA,
     SMSUtils.USER_SCHEMA,
     SMSUtils.POLICY_SCHEMA,
     SMSUtils.GROUP_SCHEMA,
     SMSUtils.DOMAIN_SCHEMA
   };
   for (int i = 0; i < schemaNames.length; i++) {
     Node childNode = XMLUtils.getChildNode(schemaRoot, schemaNames[i]);
     if (childNode != null) {
       ServiceSchemaImpl ssi = new ServiceSchemaImpl(null, childNode);
       Map attrs = ssi.getAttributeDefaults();
       ssi.validateAttributes(attrs, false);
     }
   }
   return (true);
 }
コード例 #16
0
  /**
   * Returns a <code>RemoveListenerRequest</code> object constructed from a XML.
   *
   * @param pNode the XML DOM node for the <code>RemoveListenerRequest</code> object.
   * @return constructed <code>RemoveListenerRequest</code> object.
   */
  public static RemoveListenerRequest parseXML(Node pNode) throws PolicyEvaluationException {
    RemoveListenerRequest removeListenerReq = new RemoveListenerRequest();
    String attr = XMLUtils.getNodeAttributeValue(pNode, SERVICE_NAME);

    if (attr == null) {
      debug.error("RemoveListenerRequest: missing attribute " + SERVICE_NAME);
      String objs[] = {SERVICE_NAME};
      throw new PolicyEvaluationException(ResBundleUtils.rbName, "missing_attribute", objs, null);
    }

    removeListenerReq.setServiceName(attr);

    attr = XMLUtils.getNodeAttributeValue(pNode, NOTIFICATION_URL);
    if (attr == null) {
      debug.error("RemoveListenerRequest: missing attribute " + NOTIFICATION_URL);
      String objs[] = {NOTIFICATION_URL};
      throw new PolicyEvaluationException(ResBundleUtils.rbName, "missing_attribute", objs, null);
    }

    removeListenerReq.setNotificationURL(attr);
    return removeListenerReq;
  }
コード例 #17
0
ファイル: Utils.java プロジェクト: greaterwinner/OpenAM
 /**
  * Converts a JAXB object to a <code>org.w3c.dom.Element</code>.
  *
  * @param jaxbObj a JAXB object
  * @return a <code>org.w3c.dom.Element</code>
  * @throws JAXBException if an error occurs while converting JAXB object.
  * @supported.api
  */
 public static Element convertJAXBToElement(Object jaxbObj) throws JAXBException {
   Marshaller m = jc.createMarshaller();
   try {
     m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());
   } catch (PropertyException ex) {
     debug.error("Utils.convertJAXBToElement", ex);
   }
   Document doc = null;
   try {
     doc = XMLUtils.newDocument();
   } catch (Exception ex) {
     debug.error("Utils.convertJAXBToElement:", ex);
   }
   m.marshal(jaxbObj, doc);
   return doc.getDocumentElement();
 }
コード例 #18
0
ファイル: Utils.java プロジェクト: greaterwinner/OpenAM
  /**
   * Converts Document to SOAPMessage
   *
   * @param doc the source Document
   * @return SOAPMessage
   * @throws SOAPBindingException if an error occurs while converting the document
   * @supported.api
   */
  public static SOAPMessage DocumentToSOAPMessage(Document doc) throws SOAPBindingException {
    SOAPMessage msg = null;
    try {
      MimeHeaders mimeHeaders = new MimeHeaders();
      mimeHeaders.addHeader("Content-Type", "text/xml");

      String xmlstr = XMLUtils.print(doc);
      if (debug.messageEnabled()) {
        debug.message("Utils.DocumentToSOAPMessage: xmlstr = " + xmlstr);
      }
      msg =
          messageFactory.createMessage(
              mimeHeaders,
              new ByteArrayInputStream(xmlstr.getBytes(SOAPBindingConstants.DEFAULT_ENCODING)));
    } catch (Exception e) {
      debug.error("Utils.DocumentToSOAPMessage", e);
      throw new SOAPBindingException(e.getMessage());
    }
    return msg;
  }
コード例 #19
0
 /**
  * Convert the security token into DOM Object.
  *
  * @return the DOM Document Element.
  * @exception SecurityException if any failure is occured.
  */
 public Element toDocumentElement() throws SecurityException {
   StringBuffer sb = new StringBuffer();
   if ((appTokenID != null) && (appTokenID.length() != 0)) {
     sb.append("<fam:FAMToken xmlns:fam=\"")
         .append(STSConstants.FAM_TOKEN_NS)
         .append("\"")
         .append(">")
         .append("\n")
         .append("<fam:TokenValue>")
         .append(tokenID)
         .append("</fam:TokenValue>")
         .append("\n")
         .append("<fam:AppTokenValue>")
         .append(appTokenID)
         .append("</fam:AppTokenValue>")
         .append("\n")
         .append("<fam:TokenType>")
         .append(tokenType)
         .append("</fam:TokenType>")
         .append("\n")
         .append("</fam:FAMToken>");
   } else {
     sb.append("<fam:FAMToken xmlns:fam=\"")
         .append(STSConstants.FAM_TOKEN_NS)
         .append("\"")
         .append(">")
         .append("\n")
         .append("<fam:TokenValue>")
         .append(tokenID)
         .append("</fam:TokenValue>")
         .append("\n")
         .append("<fam:TokenType>")
         .append(tokenType)
         .append("</fam:TokenType>")
         .append("\n")
         .append("</fam:FAMToken>");
   }
   Document document = XMLUtils.toDOMDocument(sb.toString(), debug);
   return document.getDocumentElement();
 }
コード例 #20
0
ファイル: ServiceManager.java プロジェクト: aldaris/opensso
  /**
   * Registers one or more services, defined by the XML input stream that follows the SMS DTD.
   *
   * @param xmlServiceSchema the input stream of service metadata in XML conforming to SMS DTD.
   * @param decryptObj Object to decrypt the password in the XML.
   * @return set of registered service names.
   * @throws SMSException if an error occurred while performing the operation
   * @throws SSOException if the user's single sign on token is invalid or expired.
   */
  public Set registerServices(InputStream xmlServiceSchema, AMEncryption decryptObj)
      throws SMSException, SSOException {
    // Validate SSO Token
    SMSEntry.validateToken(token);
    Set sNames = new HashSet();
    List serviceNodes = new ArrayList();
    // Get the XML document and get the list of service nodes
    Document doc = SMSSchema.getXMLDocument(xmlServiceSchema);

    if (!validSMSDtdDocType(doc)) {
      throw new SMSException(
          IUMSConstants.UMS_BUNDLE_NAME, IUMSConstants.SMS_xml_invalid_doc_type, null);
    }

    // Before validating service schema, we need to check
    // for AttributeSchema having the syntax of "password"
    // and if present, encrypt the DefaultValues if any
    checkAndEncryptPasswordSyntax(doc, true, decryptObj);

    // Create service schema
    NodeList nodes = doc.getElementsByTagName(SMSUtils.SERVICE);
    for (int i = 0; (nodes != null) && (i < nodes.getLength()); i++) {
      Node serviceNode = nodes.item(i);
      String name = XMLUtils.getNodeAttributeValue(serviceNode, SMSUtils.NAME);
      String version = XMLUtils.getNodeAttributeValue(serviceNode, SMSUtils.VERSION);

      // Obtain the SMSSchema for Schema and PluginSchema
      SMSSchema smsSchema = new SMSSchema(name, version, doc);

      // Check if the schema element exists
      if (XMLUtils.getChildNode(serviceNode, SMSUtils.SCHEMA) != null) {
        validateServiceSchema(serviceNode);
        ServiceSchemaManager.createService(token, smsSchema);

        // Update the service name and version cached SMSEntry
        if (serviceNames == null) {
          serviceNames = CachedSubEntries.getInstance(token, serviceDN);
        }
        serviceNames.add(name);
        CachedSubEntries sVersions = (CachedSubEntries) serviceVersions.get(name);
        if (sVersions == null) {
          // Not present, hence create it and add it
          sVersions = CachedSubEntries.getInstance(token, getServiceNameDN(name));
          serviceVersions.put(name, sVersions);
        }
        sVersions.add(version);
        sNames.add(name);
      }

      // Check if PluginSchema nodes exists
      for (Iterator pluginNodes =
              XMLUtils.getChildNodes(serviceNode, SMSUtils.PLUGIN_SCHEMA).iterator();
          pluginNodes.hasNext(); ) {
        Node pluginNode = (Node) pluginNodes.next();
        PluginSchema.createPluginSchema(token, pluginNode, smsSchema);
      }

      if (XMLUtils.getChildNode(serviceNode, SMSUtils.CONFIGURATION) != null) {
        serviceNodes.add(serviceNode);
      }
    }

    if (serviceNodes.size() > 0) {
      clearCache();
    }
    /*
     * Need to do this after all the schema has been loaded
     */
    for (Iterator i = serviceNodes.iterator(); i.hasNext(); ) {
      Node svcNode = (Node) i.next();
      String name = XMLUtils.getNodeAttributeValue(svcNode, SMSUtils.NAME);
      String version = XMLUtils.getNodeAttributeValue(svcNode, SMSUtils.VERSION);
      Node configNode = XMLUtils.getChildNode(svcNode, SMSUtils.CONFIGURATION);
      /*
       * Store the configuration, will throw exception if
       * the service configuration already exists
       */
      CreateServiceConfig.createService(this, name, version, configNode, true, decryptObj);
    }
    return sNames;
  }
コード例 #21
0
  /**
   * Signs the entity descriptor root element by the following rules:
   *
   * <ul>
   *   <li>Hosted Entity
   *       <ul>
   *         <li>If there is a signature already on the EntityDescriptor, removes it, then signs the
   *             EntityDescriptor.
   *         <li>Simply signs the EntityDescriptor otherwise.
   *       </ul>
   *   <li>Remote Entity
   *       <ul>
   *         <li>If there is a signature already on the EntityDescriptor, then does not change it,
   *             but returns the Document with the original signature.
   *         <li>Simply signs the EntityDescriptor otherwise
   *       </ul>
   * </ul>
   *
   * If there is no extended metadata for the entity, the entity is considered as remote.
   *
   * @param realm The realm where the EntityDescriptor belongs to.
   * @param descriptor The entity descriptor.
   * @return Signed <code>Document</code> for the entity descriptor or null if no metadata signing
   *     key is found in the configuration.
   * @throws SAML2MetaException if unable to sign the entity descriptor.
   * @throws JAXBException if the entity descriptor is invalid.
   */
  public static Document sign(String realm, EntityDescriptorElement descriptor)
      throws JAXBException, SAML2MetaException {
    if (descriptor == null) {
      throw new SAML2MetaException("Unable to sign null descriptor");
    }

    SAML2MetaManager metaManager = new SAML2MetaManager();
    EntityConfigElement cfgElem = metaManager.getEntityConfig(realm, descriptor.getEntityID());
    boolean isHosted;
    if (cfgElem == null) {
      // if there is no EntityConfig, this is considered as a remote entity
      isHosted = false;
    } else {
      isHosted = cfgElem.isHosted();
    }

    String signingCert = getRealmSetting(METADATA_SIGNING_KEY, realm);
    if (signingCert == null) {
      return null;
    }

    initializeKeyStore();

    String xmlstr = SAML2MetaUtils.convertJAXBToString(descriptor);
    xmlstr = formatBase64BinaryElement(xmlstr);

    Document doc = XMLUtils.toDOMDocument(xmlstr, debug);
    NodeList childNodes = doc.getDocumentElement().getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
      Node node = childNodes.item(i);
      if (node.getLocalName() != null
          && node.getLocalName().equals("Signature")
          && node.getNamespaceURI().equals(NS_XMLSIG)) {
        if (isHosted) {
          node.getParentNode().removeChild(node);
          break;
        } else {
          // one signature found for this remote entity on the root element,
          // in this case returning the entry with the original signature
          // as that may be judged more accurately
          return doc;
        }
      }
    }

    // we need to sign or re-sign the document, let's generate a new ID
    String descriptorId = SAMLUtils.generateID();
    doc.getDocumentElement().setAttribute(ATTR_ID, descriptorId);

    XMLSignatureManager sigManager = XMLSignatureManager.getInstance();
    try {
      String xpath =
          "//*[local-name()=\""
              + TAG_ENTITY_DESCRIPTOR
              + "\" and namespace-uri()=\""
              + NS_META
              + "\"]/*[1]";
      sigManager.signXMLUsingKeyPass(
          doc,
          signingCert,
          getRealmSetting(METADATA_SIGNING_KEY_PASS, realm),
          null,
          SAML2Constants.ID,
          descriptorId,
          true,
          xpath);
    } catch (XMLSignatureException xmlse) {
      if (debug.messageEnabled()) {
        debug.message("SAML2MetaSecurityUtils.sign:", xmlse);
      }
    }

    return doc;
  }
コード例 #22
0
ファイル: MessageProcessor.java プロジェクト: aldaris/opensso
  /**
   * Secures the request by getting the credential from the discovery service.
   *
   * @param offering Resource Offering of the discovery service.
   * @param credentials List of credentials that are required to access the discovery service.
   * @param serviceType Service Type that the discovery service should need to look for.
   * @param soapMessage SOAPMessage that needs to be secured.
   * @param sharedData Any shared data that may be used between the request and the response.
   * @return SOAPMessage Secured SOAP Message.
   * @exception SOAPBindingException for any failure.
   */
  public SOAPMessage secureRequest(
      ResourceOffering offering,
      List credentials,
      String serviceType,
      SOAPMessage soapMessage,
      Map sharedData)
      throws SOAPBindingException {

    WSSUtils.debug.message("MessageProcessor.secureRequest:Init");
    try {
      SOAPHeader header = addCorrelationHeader(soapMessage, null);
      QueryResponse discoResponse = getWebserviceOffering(offering, credentials, serviceType);

      if (WSSUtils.debug.messageEnabled()) {
        WSSUtils.debug.message(
            "MessageProcessor.secureRequest: " + "Discovery Response: " + discoResponse.toString());
      }

      List offerings = discoResponse.getResourceOffering();
      if (offerings == null || offerings.size() == 0) {
        WSSUtils.debug.error("MessageProcessor.secureRequest:: service " + "offerings are null.");
        throw new SOAPBindingException(WSSUtils.bundle.getString("noServiceOfferings"));
      }

      ResourceOffering serviceOffering =
          (ResourceOffering) discoResponse.getResourceOffering().get(0);

      List creds = discoResponse.getCredentials();

      String securityProfile = processResourceOffering(serviceOffering);

      // If the security profile is of SAML or Bearer insert a
      // security token for this profile.
      SecurityAssertion securityAssertion = null;
      if (securityProfile.equals(Message.NULL_SAML)
          || securityProfile.equals(Message.TLS_SAML)
          || securityProfile.equals(Message.CLIENT_TLS_SAML)
          || securityProfile.equals(Message.NULL_BEARER)
          || securityProfile.equals(Message.TLS_BEARER)
          || securityProfile.equals(Message.CLIENT_TLS_BEARER)
          || securityProfile.equals(Message.NULL_SAML_WSF11)
          || securityProfile.equals(Message.TLS_SAML_WSF11)
          || securityProfile.equals(Message.CLIENT_TLS_SAML_WSF11)
          || securityProfile.equals(Message.NULL_BEARER_WSF11)
          || securityProfile.equals(Message.TLS_BEARER_WSF11)
          || securityProfile.equals(Message.CLIENT_TLS_BEARER_WSF11)) {

        if (creds != null && creds.size() != 0) {
          securityAssertion = (SecurityAssertion) creds.get(0);
          securityAssertion.addToParent(header);
        }
      }

      if (securityProfile.equals(Message.NULL_SAML)
          || securityProfile.equals(Message.TLS_SAML)
          || securityProfile.equals(Message.CLIENT_TLS_SAML)
          || securityProfile.equals(Message.NULL_X509)
          || securityProfile.equals(Message.TLS_X509)
          || securityProfile.equals(Message.CLIENT_TLS_X509)
          || securityProfile.equals(Message.NULL_SAML_WSF11)
          || securityProfile.equals(Message.TLS_SAML_WSF11)
          || securityProfile.equals(Message.CLIENT_TLS_SAML_WSF11)
          || securityProfile.equals(Message.NULL_X509_WSF11)
          || securityProfile.equals(Message.TLS_X509_WSF11)
          || securityProfile.equals(Message.CLIENT_TLS_X509_WSF11)) {

        soapMessage = signMessage(soapMessage, securityProfile, securityAssertion);
      }

      if (WSSUtils.debug.messageEnabled()) {
        WSSUtils.debug.message(
            "MessageProcessor.secureRequest: "
                + com.sun.identity.shared.xml.XMLUtils.print(
                    soapMessage.getSOAPPart().getEnvelope()));
      }

      return soapMessage;

    } catch (Exception ex) {
      WSSUtils.debug.error(
          "MessageProcessor.secureRequest: Failure in " + "Securing the request.", ex);
      throw new SOAPBindingException(WSSUtils.bundle.getString("secureRequestFailed"));
    }
  }
コード例 #23
0
ファイル: FSSOAPService.java プロジェクト: aldaris/opensso
  /*
   * Parses the SOAPMessage and return the Element
   * corresponding to the liberty message(request/response).
   * @param message the <code>SOAPMessage</code> to be parsed
   * @return Element corresponding to liberty request/response
   */
  public Element parseSOAPMessage(SOAPMessage message) {
    FSUtils.debug.message("FSSOAPService.parseSOAPMessage: Called");
    ByteArrayOutputStream bop = null;
    String xmlString = null;

    // first check if there was any soap error during verifyHost()
    try {
      // check the SOAP message for any SOAP
      // related errros before passing control to SAM processor
      bop = new ByteArrayOutputStream();
      message.writeTo(bop);
      xmlString = bop.toString(IFSConstants.DEFAULT_ENCODING);
      Document doc = XMLUtils.toDOMDocument(xmlString, FSUtils.debug);
      Element root = doc.getDocumentElement();
      String rootName = root.getLocalName();
      if ((rootName == null) || (rootName.length() == 0)) {
        FSUtils.debug.error(
            "FSSOAPService.parseSOAPMessage: "
                + "Local name of the SOAPElement in  the"
                + " SOAPMessage passed seems to be missing");
        return null;
      }
      if (!(rootName.equals("Envelope"))
          || (!(root.getNamespaceURI().equals(IFSConstants.SOAP_URI)))) {
        FSUtils.debug.error(
            "FSSOAPService.parseSOAPMessage: Could not"
                + "parse SOAPMessage, either root element is not Envelope"
                + " or invalid name space");
        return null;
      }
      NodeList nlbody = root.getChildNodes();
      int blength = nlbody.getLength();
      if (blength <= 0) {
        FSUtils.debug.error("FSSOAPService.parseSOAPMessage: Message " + "does not have body");
        return null;
      }
      Node child = null;
      boolean found = false;
      for (int i = 0; i < blength; i++) {
        child = (Node) nlbody.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE) {
          continue;
        }
        String childName = child.getLocalName();
        if (childName.equals("Body")) {
          found = true;
          break; // found the message body
        }
      }
      if (!found) {
        FSUtils.debug.error("FSSOAPService.parseSOAPMessage: Message " + "does not have body1");
        return null;
      }
      Element body = (Element) child;
      // Is soap-env:Fault
      NodeList nl = body.getElementsByTagNameNS(IFSConstants.SOAP_URI, "Fault");
      int length = nl.getLength();

      if (length > 1) {
        return null;
      }
      if (length != 0) {
        child = (Node) nl.item(0);
        if (child.getNodeType() != Node.ELEMENT_NODE) {
          return null;
        }
        if (child.getLocalName().equalsIgnoreCase("Fault")) {
          if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message(
                "FSSOAPService."
                    + " parseSOAPMessage soap-env:Fault found in the "
                    + "SOAPMessage");
          }
          return (Element) child;
        }
      }

      try {
        // Is samlp:Request
        child = getSAMLElement(body, "Request");
        if (child != null) {
          return (Element) child;
        }
        // Is samlp:Response
        child = getSAMLElement(body, "Response");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:AuthnResponseEnvelope
        child = getFederationElement(body, "AuthnResponseEnvelope");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:AuthnRequest
        child = getFederationElement(body, "AuthnRequest");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:RegisterNameIdentifierRequest
        child = getFederationElement(body, "RegisterNameIdentifierRequest");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:RegisterNameIdentifierResponse
        child = getFederationElement(body, "RegisterNameIdentifierResponse");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:FederationTerminationNotification
        child = getFederationElement(body, "FederationTerminationNotification");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:LogoutRequest
        child = getFederationElement(body, "LogoutRequest");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:LogoutResponse
        child = getFederationElement(body, "LogoutResponse");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:NameIdentifierMappingRequest
        child = getFederationElement(body, "NameIdentifierMappingRequest");
        if (child != null) {
          return (Element) child;
        }
        // Is lib:NameIdentifierMappingResponse
        child = getFederationElement(body, "NameIdentifierMappingResponse");
        if (child != null) {
          return (Element) child;
        }
        FSUtils.debug.error("FSSOAPService.parseMessage:Invalid message type.");
      } catch (FSException e) {
        if (FSUtils.debug.messageEnabled()) {
          FSUtils.debug.message(
              "SOAPService.parseSOAPMessage: " + "Couldn't object protocol message element.");
        }
      }
      return null;
    } catch (Exception e) {
      FSUtils.debug.error("FSSOAPService.parseSOAPMessage: Exception ", e);
      return null;
    }
  }
コード例 #24
0
ファイル: MessageProcessor.java プロジェクト: aldaris/opensso
  /**
   * Signs the message.
   *
   * @param soapMessage SOAPMessage that needs to be signed.
   * @param profile Security profile that needs to be used for signing.
   * @param assertion Security Assertion
   * @return SOAPMessage signed SOAPMessage.
   */
  private SOAPMessage signMessage(
      SOAPMessage soapMessage, String profile, SecurityAssertion assertion)
      throws SOAPBindingException {
    try {
      SOAPHeader soapHeader = soapMessage.getSOAPPart().getEnvelope().getHeader();
      if (soapHeader == null) {
        soapMessage.getSOAPPart().getEnvelope().addHeader();
      }
      SOAPBody soapBody = soapMessage.getSOAPPart().getEnvelope().getBody();
      if (soapBody == null) {
        throw new SOAPBindingException(WSSUtils.bundle.getString("nullSOAPBody"));
      }

      String bodyId = SAMLUtils.generateID();
      soapBody.setAttributeNS(WSSEConstants.NS_WSU_WSF11, WSSEConstants.WSU_ID, bodyId);
      List ids = new ArrayList();
      ids.add(bodyId);
      if (correlationId != null) {
        ids.add(correlationId);
      }

      Certificate cert = null;
      Element sigElem = null;
      ByteArrayInputStream bin = null;
      ByteArrayOutputStream bop = new ByteArrayOutputStream();
      Document doc = null;
      if (profile == null
          || profile.equals(Message.NULL_X509)
          || profile.equals(Message.TLS_X509)
          || profile.equals(Message.CLIENT_TLS_X509)
          || profile.equals(Message.NULL_X509_WSF11)
          || profile.equals(Message.TLS_X509_WSF11)
          || profile.equals(Message.CLIENT_TLS_X509_WSF11)) {

        BinarySecurityToken binaryToken = addBinaryToken(soapMessage);
        cert = SecurityUtils.getCertificate(binaryToken);
        soapMessage.writeTo(bop);
        bin = new ByteArrayInputStream(bop.toByteArray());
        doc = XMLUtils.toDOMDocument(bin, WSSUtils.debug);
        sigElem =
            SecurityUtils.getSignatureManager()
                .signWithWSSX509TokenProfile(
                    doc, cert, "", ids, SOAPBindingConstants.WSF_11_VERSION);

      } else if (profile.equals(Message.NULL_SAML)
          || profile.equals(Message.TLS_SAML)
          || profile.equals(Message.CLIENT_TLS_SAML)
          || profile.equals(Message.NULL_SAML_WSF11)
          || profile.equals(Message.TLS_SAML_WSF11)
          || profile.equals(Message.CLIENT_TLS_SAML_WSF11)) {

        cert = SecurityUtils.getCertificate(assertion);
        soapMessage.writeTo(bop);
        new ByteArrayInputStream(bop.toByteArray());
        bin = new ByteArrayInputStream(bop.toByteArray());
        doc = XMLUtils.toDOMDocument(bin, WSSUtils.debug);
        sigElem =
            SecurityUtils.getSignatureManager()
                .signWithWSSSAMLTokenProfile(
                    doc,
                    cert,
                    assertion.getAssertionID(),
                    "",
                    ids,
                    SOAPBindingConstants.WSF_11_VERSION);
      }

      if (sigElem == null) {
        WSSUtils.debug.error("MessageProcessor.signMessage: " + "SigElement is null");
        throw new SOAPBindingException(WSSUtils.bundle.getString("cannotSignMessage"));
      }

      Element securityHeader = getSecurityHeader(soapMessage);
      securityHeader.appendChild(securityHeader.getOwnerDocument().importNode(sigElem, true));

      return Utils.DocumentToSOAPMessage(sigElem.getOwnerDocument());

    } catch (Exception ex) {
      WSSUtils.debug.error("MessageProcessor.signMessage: " + "Signing failed.", ex);
      throw new SOAPBindingException(WSSUtils.bundle.getString("cannotSignMessage"));
    }
  }
コード例 #25
0
ファイル: QueryClient.java プロジェクト: aldaris/opensso
 /**
  * Returns SAMLv2 <code>Response</code> object. The <code>Response</code> object is created from
  * the String representation of the object.
  *
  * @param xmlString the String representation of the object.
  * @return the <code>Response</code> object.
  * @exception <code>IOException</code> if there is an error processing the response.
  * @exception <code>SAML2Exception</code> if there is an error processing the response.
  */
 private static Response getSAMLResponse(String xmlString) throws IOException, SAML2Exception {
   String classMethod = "QueryClient:getSAMLResponse";
   if (xmlString == null || xmlString.length() == 0) {
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullResponse"));
   }
   if (debug.messageEnabled()) {
     debug.message(classMethod + "Response String : " + xmlString);
   }
   Response samlResponse = null;
   Document doc = XMLUtils.toDOMDocument(xmlString, debug);
   Element root = doc.getDocumentElement();
   String rootName = root.getLocalName();
   if (!(rootName.equals("Envelope"))
       || (!(root.getNamespaceURI().equals(SOAPConstants.URI_NS_SOAP_ENVELOPE)))) {
     SAML2SDKUtils.debug.error("Wrong Envelope tag or namespace.");
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("serverError"));
   }
   // examine the child element of <SOAP-ENV:Envelope>
   NodeList nodes = root.getChildNodes();
   int nodeCount = nodes.getLength();
   if (nodeCount <= 0) {
     SAML2SDKUtils.debug.error("Envelope does not contain a SOAP body.");
     throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingSOAPBody"));
   }
   String tagName = null;
   String ctagName = null;
   Node currentNode = null;
   Node cnode = null;
   for (int i = 0; i < nodeCount; i++) {
     currentNode = nodes.item(i);
     if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
       tagName = currentNode.getLocalName();
       if ((tagName == null) || tagName.length() == 0) {
         SAML2SDKUtils.debug.error(classMethod + "Child element is missing tag name");
         throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingChildTagName"));
       }
       if (tagName.equals("Body")) {
         NodeList cNodes = currentNode.getChildNodes();
         int cnodeCount = cNodes.getLength();
         for (int j = 0; j < cnodeCount; j++) {
           cnode = cNodes.item(j);
           if (cnode.getNodeType() == Node.ELEMENT_NODE) {
             ctagName = cnode.getLocalName();
             if ((ctagName == null) || ctagName.length() == 0) {
               SAML2SDKUtils.debug.error(
                   "Missing tag name " + "of child element of <SOAP-ENV:Body>");
               throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingChildTagName"));
             }
             if (ctagName.equals("Fault")) {
               SAML2SDKUtils.debug.error("SOAPFault error.");
               throw new SAML2Exception(XMLUtils.print(cnode));
             } else if (ctagName.equals("Response")) {
               samlResponse = ProtocolFactory.getInstance().createResponse((Element) cnode);
               break;
             } else {
               SAML2SDKUtils.debug.error("Invalid child  " + "element in SOAPBody");
               throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidSOAPBody"));
             }
           }
         } // end of for(int j=0; j <cnodeCount; j++)
       } else if (tagName.equals("Header")) {
         if (SAML2SDKUtils.debug.messageEnabled()) {
           SAML2SDKUtils.debug.message("SOAP Header in Response");
         }
       } else {
         SAML2SDKUtils.debug.error("Invalid element in Envelope");
         throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidSOAPElement"));
       }
     } // end of if (currentNode.getNodeType() == Node.ELEMENT_NODE)
   } // end of for (int i = 0; i < nodeCount; i++)
   return samlResponse;
 }
コード例 #26
0
  // used by the constructors.
  private void parseElement(Element element) throws SAML2Exception {
    // make sure that the input xml block is not null
    if (element == null) {
      if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message("AttributeImpl.parseElement: " + "Input is null.");
      }
      throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    // Make sure this is an Attribute.
    String tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("Attribute"))) {
      if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message("AttributeImpl.parseElement: " + "not Attribute.");
      }
      throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
    }

    // handle the attributes of <Attribute> element
    NamedNodeMap atts = ((Node) element).getAttributes();
    if (atts != null) {
      int length = atts.getLength();
      for (int i = 0; i < length; i++) {
        Attr attr = (Attr) atts.item(i);
        String attrName = attr.getName();
        String attrValue = attr.getValue().trim();
        if (attrName.equals("Name")) {
          name = attrValue;
        } else if (attrName.equals("NameFormat")) {
          nameFormat = attrValue;
        } else if (attrName.equals("FriendlyName")) {
          friendlyName = attrValue;
        } else {
          if (!attrValue.equals(SAML2Constants.ASSERTION_NAMESPACE_URI)) {
            if (anyMap == null) {
              anyMap = new HashMap();
            }
            anyMap.put(attrName, attrValue);
          }
        }
      }
    }

    // handle AttributeValue
    NodeList nl = element.getChildNodes();
    Node child;
    String childName;
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
      child = nl.item(i);
      if ((childName = child.getLocalName()) != null) {
        if (childName.equals("AttributeValue")) {
          if (attrValues == null) {
            attrValues = new ArrayList();
          }
          attrValues.add(XMLUtils.print(child));
          if (valueStrings == null) {
            valueStrings = new ArrayList();
          }
          valueStrings.add(XMLUtils.getChildrenValue((Element) child));
        } else {
          if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message(
                "Attributempl.parseElement" + ": Invalid element:" + childName);
          }
          throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
        }
      }
    }

    if (name == null || name.trim().length() == 0) {
      if (SAML2SDKUtils.debug.messageEnabled()) {
        SAML2SDKUtils.debug.message("AttributeImpl.parseElement:" + " missing Name attribute.");
      }
      throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingAttribute"));
    }

    if (attrValues != null) {
      attrValues = Collections.unmodifiableList(attrValues);
    }
    if (valueStrings != null) {
      valueStrings = Collections.unmodifiableList(valueStrings);
    }
    if (anyMap != null) {
      anyMap = Collections.unmodifiableMap(anyMap);
    }
    mutable = false;
  }
コード例 #27
0
ファイル: PolicyRequest.java プロジェクト: wadahiro/OpenAM
  /**
   * Returns a <code>PolicyRequest</code> object constructed from a XML.
   *
   * @param pNode the XML DOM node for the <code>PolicyRequest</code> object.
   * @return constructed <code>PolicyRequest</code> object
   */
  public static PolicyRequest parseXML(Node pNode) throws PolicyEvaluationException {
    PolicyRequest preq = new PolicyRequest();

    String attr = XMLUtils.getNodeAttributeValue(pNode, APP_SSOTOKEN);
    if (attr == null) {
      debug.error("PolicyRequestparseXML(Node): missing attribute " + APP_SSOTOKEN);
      String objs[] = {APP_SSOTOKEN};
      throw new PolicyEvaluationException(ResBundleUtils.rbName, "missing_attribute", objs, null);
    }
    preq.setAppSSOToken(attr);
    attr = XMLUtils.getNodeAttributeValue(pNode, REQUEST_ID);

    if (attr == null) {
      debug.error("PolicyRequest.parseXML(Node): missing attribute " + REQUEST_ID);
      String objs[] = {REQUEST_ID};
      throw new PolicyEvaluationException(ResBundleUtils.rbName, "missing_attribute", objs, null);
    }
    preq.setRequestId(attr);

    Node node = XMLUtils.getChildNode(pNode, GET_RESOURCE_RESULTS);
    if (node != null) {
      ResourceResultRequest resourceResultReq = null;
      try {
        resourceResultReq = ResourceResultRequest.parseXML(node);
      } catch (PolicyEvaluationException pe) {
        throw new PolicyEvaluationException(pe, preq.getRequestId());
      }
      preq.setResourceResultRequest(resourceResultReq);
      preq.setMethodID(POLICY_REQUEST_GET_RESOURCE_RESULTS);
      return preq;
    }

    node = XMLUtils.getChildNode(pNode, ADD_POLICY_LISTENER);
    if (node != null) {
      PolicyListenerRequest plr = null;
      try {
        plr = PolicyListenerRequest.parseXML(node);
      } catch (PolicyEvaluationException pe) {
        throw new PolicyEvaluationException(pe, preq.getRequestId());
      }
      preq.setPolicyListenerRequest(plr);
      preq.setMethodID(POLICY_REQUEST_ADD_POLICY_LISTENER);
      return preq;
    }

    node = XMLUtils.getChildNode(pNode, REMOVE_POLICY_LISTENER);
    if (node != null) {
      RemoveListenerRequest rmListenerReq = null;
      try {
        rmListenerReq = RemoveListenerRequest.parseXML(node);
      } catch (PolicyEvaluationException pe) {
        throw new PolicyEvaluationException(pe, preq.getRequestId());
      }
      preq.setRemoveListenerRequest(rmListenerReq);
      preq.setMethodID(POLICY_REQUEST_REMOVE_POLICY_LISTENER);
      return preq;
    }

    node = XMLUtils.getChildNode(pNode, ADVICES_HANDLEABLE_BY_AM_REQUEST);
    if (node != null) {
      preq.setAdvicesHandleableByAMRequest(new AdvicesHandleableByAMRequest());
      preq.setMethodID(POLICY_REQUEST_ADVICES_HANDLEABLE_BY_AM_REQUEST);
      return preq;
    }

    /*
     * We reach here, there is no valid method name specified in
     * the xml docuemnt. Throw exception.
     */
    debug.error("PolicyRequest: invalid method specified");
    throw new PolicyEvaluationException(
        ResBundleUtils.rbName, "invalid_policy_request_method", null, null);
  }
コード例 #28
0
ファイル: ServiceManager.java プロジェクト: aldaris/opensso
  protected static void checkAndEncryptPasswordSyntax(
      Document doc, boolean encrypt, AMEncryption encryptObj) throws SMSException {
    // Get the node list of all AttributeSchema
    NodeList nl = doc.getElementsByTagName(SMSUtils.SCHEMA_ATTRIBUTE);
    for (int i = 0; i < nl.getLength(); i++) {
      Node node = nl.item(i);
      // Check if the "syntax" attribute is "password"
      String syntax = XMLUtils.getNodeAttributeValue(node, SMSUtils.ATTRIBUTE_SYNTAX);
      if (syntax.equals(AttributeSchema.Syntax.PASSWORD.toString())) {
        if (debug.messageEnabled()) {
          debug.message("ServiceManager: encrypting password syntax");
        }
        // Get the DefaultValues and encrypt then
        Node defaultNode;
        if ((defaultNode = XMLUtils.getChildNode(node, SMSUtils.ATTRIBUTE_DEFAULT_ELEMENT))
            != null) {
          // Get NodeList of "Value" nodes and encrypt them
          for (Iterator items =
                  XMLUtils.getChildNodes(defaultNode, SMSUtils.ATTRIBUTE_VALUE).iterator();
              items.hasNext(); ) {
            Node valueNode = (Node) items.next();
            String value = XMLUtils.getValueOfValueNode(valueNode);
            String encValue;

            if (encrypt) {
              if (encryptObj != null) {
                value = (String) AccessController.doPrivileged(new DecodeAction(value, encryptObj));
                if (value.equals("&amp;#160;")) {
                  try {
                    byte[] b = new byte[1];
                    b[0] = -96;
                    value = new String(b, "ISO-8859-1");
                  } catch (UnsupportedEncodingException e) {
                    // ignore
                  }
                }
              }
              encValue = (String) AccessController.doPrivileged(new EncodeAction(value));
            } else {
              encValue = (String) AccessController.doPrivileged(new DecodeAction(value));

              try {
                // this is catch the whitespace for password
                byte[] b = encValue.getBytes("ISO-8859-1");
                if ((b.length == 1) && (b[0] == -96)) {
                  encValue = "&amp;#160;";
                }
              } catch (UnsupportedEncodingException e) {
                // ignore
              }
              if (encryptObj != null) {
                encValue =
                    (String) AccessController.doPrivileged(new EncodeAction(encValue, encryptObj));
              }
            }

            // Construct the encrypted "Value" node
            StringBuffer sb = new StringBuffer(100);
            sb.append(AttributeSchema.VALUE_BEGIN)
                .append(encValue)
                .append(AttributeSchema.VALUE_END);
            Document newDoc = SMSSchema.getXMLDocument(sb.toString(), false);
            Node newValueNode = XMLUtils.getRootNode(newDoc, SMSUtils.ATTRIBUTE_VALUE);
            // Replace the node
            Node nValueNode = doc.importNode(newValueNode, true);
            defaultNode.replaceChild(nValueNode, valueNode);
          }
        }
      }
    }
  }