perfsonar-dev - perfsonar: r4909 - in branches/simple-service-with-base2/src/main/java/org/perfsonar: base2/service/authn/tokens base2/service/messages service/authService
Subject: perfsonar development work
List archive
perfsonar: r4909 - in branches/simple-service-with-base2/src/main/java/org/perfsonar: base2/service/authn/tokens base2/service/messages service/authService
Chronological Thread
- From:
- To:
- Subject: perfsonar: r4909 - in branches/simple-service-with-base2/src/main/java/org/perfsonar: base2/service/authn/tokens base2/service/messages service/authService
- Date: Tue, 27 Jan 2009 07:14:37 -0500
Author: rodriguez
Date: 2009-01-27 07:14:37 -0500 (Tue, 27 Jan 2009)
New Revision: 4909
Added:
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AttrServiceEngine.java
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthNServiceEngine.java
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthRServiceEngine.java
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/GenericServiceEngine.java
Log:
- AS 1.2 100% functional with pSbase2
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
===================================================================
---
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
2009-01-26 12:31:52 UTC (rev 4908)
+++
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
2009-01-27 12:14:37 UTC (rev 4909)
@@ -5,11 +5,14 @@
import java.net.URLDecoder;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Vector;
import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
@@ -19,6 +22,7 @@
import net.geant.edugain.base.BaseDefinitions;
+import org.apache.axiom.om.impl.dom.TextImpl;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axiom.soap.SOAPHeaderBlock;
@@ -37,11 +41,14 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class SecTokenSOAPManager implements SecTokenManager {
private final String
WSSECHEADER_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private final String WSSECHEADER="Security";
+ protected final String
SOAPENV_NS="http://schemas.xmlsoap.org/soap/envelope/";
+ protected final String WSSECHEADER_ACTOR="actor";
private static final String URN_USER_FED = ":user:";
protected static final Logger logger =
Logger.getLogger(SecTokenSOAPManager.class.getName());
@@ -73,10 +80,18 @@
}
public Object getSTValue() throws PerfSONARException {
- if (!hasSTInRequest())
+ logger.debug("SecTokenSOAPManager (a)");
+ if (!hasSTInRequest()) {
+ logger.debug("SecTokenSOAPManager (b)");
return null;
+ }
+ logger.debug("SecTokenSOAPManager (c)");
Object res=null;
- SOAPHeaderBlock shb=(SOAPHeaderBlock)getSTFromRequest();
+ logger.debug("SecTokenSOAPManager (d)");
+ SOAPHeader sh = (SOAPHeader)getSTFromRequest();
+ ArrayList<?> list = sh.getHeaderBlocksWithNSURI(WSSECHEADER_NS);
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
+ logger.debug("SecTokenSOAPManager (e)");
/* Iterator it=sh.examineAllHeaderElements();
while (it.hasNext()) {
SOAPHeaderElement he=(SOAPHeaderElement)it.next();
@@ -96,35 +111,74 @@
}
if (res==null) { */
try {
+ logger.debug("SecTokenSOAPManager (1)");
MessageContext
mc=MessageContext.getCurrentMessageContext();
+ logger.debug("SecTokenSOAPManager (2)");
SOAPEnvelope se = mc.getEnvelope();
+ logger.debug("SecTokenSOAPManager (3)");
Document
doc=Axis2Util.getDocumentFromSOAPEnvelope(se, true);
+ logger.debug("SecTokenSOAPManager (4)");
Crypto crypto = new DynamicCrypto();
+ logger.debug("SecTokenSOAPManager (5)");
WSSecurityEngine secEngine = new
WSSecurityEngine();
- // If there is any problem validating the
SOAP header, it throws an exception
- secEngine.processSecurityHeader(doc, null,
null, crypto);
+ logger.debug("SecTokenSOAPManager (6)");
+ String actor=shb.getAttribute(new
QName(SOAPENV_NS, WSSECHEADER_ACTOR)).getAttributeValue();
+ logger.debug("SecTokenSOAPManager (7)");
+ Vector resultSignature =
secEngine.processSecurityHeader(doc, actor, null, crypto);
+ logger.debug("SecTokenSOAPManager (8)");
+ if (resultSignature==null) {
+ logger.debug("SecTokenSOAPManager
(8-)");
+ throw new
PerfSONARException("error.authn.wssec","Null response checking the
signature");
+ }
+ logger.debug("SecTokenSOAPManager (9)");
XPathFactory factory =
XPathFactory.newInstance();
+ logger.debug("SecTokenSOAPManager (10)");
XPath xpath = factory.newXPath();
+ logger.debug("SecTokenSOAPManager (11)");
xpath.setNamespaceContext(new
WSSENamespaceContext());
+ logger.debug("SecTokenSOAPManager (12)");
XPathExpression expr =
xpath.compile("//wsse:BinarySecurityToken");
+ logger.debug("SecTokenSOAPManager (13)");
Object result = expr.evaluate(doc,
XPathConstants.NODESET);
+ logger.debug("SecTokenSOAPManager (14)");
NodeList nodes = (NodeList) result;
+ logger.debug("SecTokenSOAPManager (15)");
for (int i = 0; i < nodes.getLength(); i++) {
+ logger.debug("SecTokenSOAPManager
(16): "+i);
Element e=(Element)nodes.item(i);
+ logger.debug("SecTokenSOAPManager
(17)");
if
(e.getAttribute("ValueType").equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"))
{
- byte[]
bytes=Base64.decode(e.getTextContent());
+
logger.debug("SecTokenSOAPManager (17 a)");
+ NodeList listNodes =
e.getChildNodes();
+
logger.debug("SecTokenSOAPManager (17 b)");
+ Node n1 = listNodes.item(0);
+
logger.debug("SecTokenSOAPManager (17 c)");
+ TextImpl ti = (TextImpl) n1;
+
logger.debug("SecTokenSOAPManager (18): "+ti.getData());
+ byte[]
bytes=Base64.decode(ti.getData());
+
logger.debug("SecTokenSOAPManager (19)");
ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
+
logger.debug("SecTokenSOAPManager (20)");
X509Certificate
cert=crypto.loadCertificate(bais);
+
logger.debug("SecTokenSOAPManager (21)");
res=cert;
+
logger.debug("SecTokenSOAPManager (22)");
}
else if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
+
logger.debug("SecTokenSOAPManager (23)");
byte[]
bytes=Base64.decode(e.getTextContent());
+
logger.debug("SecTokenSOAPManager (24)");
ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
+
logger.debug("SecTokenSOAPManager (25)");
SAMLAssertion as=new
SAMLAssertion(bais);
+
logger.debug("SecTokenSOAPManager (26)");
res=as;
+
logger.debug("SecTokenSOAPManager (27)");
}
+ logger.debug("SecTokenSOAPManager
(28)");
}
+ logger.debug("SecTokenSOAPManager (29)");
} catch (Throwable t) {
logger.error("SecTokenSOAPManager:
"+t.getMessage());
throw new
PerfSONARException("authn_getting_sec_token");
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
===================================================================
---
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
2009-01-26 12:31:52 UTC (rev 4908)
+++
branches/simple-service-with-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
2009-01-27 12:14:37 UTC (rev 4909)
@@ -42,13 +42,13 @@
}
- protected ServiceEngine getServiceEngine(String serviceEngineClassName)
+ protected ServiceEngine getServiceEngine(String serviceEngineClassName)
throws Exception {
ServiceEngine se = (ServiceEngine)Class.forName(
serviceEngineClassName ).newInstance();
- return se;
+ return se;
}
@@ -74,7 +74,7 @@
} catch (Exception ex) {
- PerfSONARException pse = new
PerfSONARException("no_service_engine",
+ PerfSONARException pse = new
PerfSONARException("no_service_engine",
"Cannot find ServiceEngine ["+serviceEngineClassName +
"] for message type ["+messageType+"], nested exception
was:"+
ex.toString());
@@ -120,7 +120,7 @@
//just in case of unexpected runtime exception such as
//null, indexoutofbounds, classcast, etc.
throw new PerfSONARException(
- "runtime_exception",
+ "runtime_exception",
"Runtime exception in ServiceEngine: "
+rex.getMessage());
}
@@ -287,14 +287,14 @@
/**
* Find metadata chain for metadata ID (the last metadata in chain)
- *
+ *
* @param inputMessage message to process (won't be changed)
* @param lastMetadataId id of metadata which is last in chain
* @return map <id,metadata>
* @throws NoSuchMetadataException thrown if there is no metadata with
given ID
*/
protected Map<String,Metadata> getChaining(
- Message inputMessage, String metadataId, Map<String,Metadata>
metadatas)
+ Message inputMessage, String metadataId, Map<String,Metadata>
metadatas)
throws NoSuchMetadataException {
if (metadataId == null) throw new NoSuchMetadataException();
@@ -324,7 +324,7 @@
//get other chain, prevent endless loop
if ( (chainedMetadataId!=null)&&
!("".equals(chainedMetadataId))&&
- !(metadata.getId().equals(chainedMetadataId))) {
+ !(metadata.getId().equals(chainedMetadataId))) {
getChaining(inputMessage, chainedMetadataId, metadatas);
}
@@ -345,10 +345,10 @@
/**
- * Exception thrown when Metadata could not be found. It's internal
+ * Exception thrown when Metadata could not be found. It's internal
* Message Handler
* exception.
- *
+ *
* @author Maciej Glowiak
*
*/
Added:
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AttrServiceEngine.java
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthNServiceEngine.java
===================================================================
---
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthNServiceEngine.java
2009-01-26 12:31:52 UTC (rev 4908)
+++
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthNServiceEngine.java
2009-01-27 12:14:37 UTC (rev 4909)
@@ -1,47 +1,11 @@
package org.perfsonar.service.authService;
-import java.io.ByteArrayOutputStream;
-import java.io.FileInputStream;
-import java.io.PrintWriter;
-import java.security.KeyStore;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.Properties;
-import java.util.Vector;
-
-import javax.xml.namespace.QName;
-
-import net.geant.edugain.base.Configurator;
-import net.geant.edugain.validation.ComponentID;
-import net.geant.edugain.validation.Validator;
-
-import org.apache.axiom.om.impl.llom.OMElementImpl;
-import org.apache.axiom.soap.SOAPEnvelope;
-import org.apache.axiom.soap.SOAPHeaderBlock;
-import org.apache.axis2.context.MessageContext;
import org.apache.log4j.Logger;
-import org.apache.rampart.util.Axis2Util;
-import org.apache.ws.security.WSSecurityEngine;
-import org.apache.ws.security.WSSecurityException;
-import org.apache.ws.security.components.crypto.Crypto;
-import org.opensaml.SAMLAssertion;
-import org.opensaml.SAMLAuthenticationStatement;
-import org.opensaml.SAMLStatement;
-import org.opensaml.SAMLSubject;
-import org.perfsonar.base2.service.authn.component.DynamicCrypto;
-import org.perfsonar.base2.service.authn.tokens.SecTokenManagerFactory;
-import org.perfsonar.base2.service.authn.tokens.SecurityToken;
-import org.perfsonar.base2.service.configuration.Configuration;
-import org.perfsonar.base2.service.configuration.ConfigurationManager;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.perfsonar.base2.service.requesthandler.ServiceEngine;
import org.perfsonar.base2.service.requesthandler.ServiceMessage;
import org.perfsonar.base2.service.util.ResultCodesUtil;
import org.perfsonar.base2.xml.nmwg.Message;
-import org.perfsonar.base2.xml.nmwg.Metadata;
-import org.w3c.dom.Document;
public class AuthNServiceEngine extends GenericServiceEngine implements
ServiceEngine {
@@ -50,313 +14,27 @@
private static final Logger logger =
Logger.getLogger(AuthNServiceEngine.class.getName());
- public static final String
X509_ID="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- public static final String
SAML_ID="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
-
- protected final String
WSSECHEADER_TIMESTAMP_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
- protected final String
SOAPENV_NS="http://schemas.xmlsoap.org/soap/envelope/";
- protected final String
WSSECHEADER_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
- protected final String WSSECHEADER_TIMESTAMP="Timestamp";
- protected final String WSSECHEADER="Security";
- protected final String WSSECHEADER_ACTOR="actor";
-
protected static String TYPE_RESPONSE = "AuthNEEResponse";
protected static String EVENT_TYPE_SUCCESS = "success.as.authn";
- protected static String SEC_TOKEN_PARAM = "SecurityToken";
- protected Configuration configuration;
- protected ConfigurationManager configurationManager;
- protected Properties props;
- protected Validator val;
- protected Configurator cfg;
- protected Crypto tsCrypto;
-
- static final WSSecurityEngine secEngine = new WSSecurityEngine();
-
public AuthNServiceEngine() throws PerfSONARException {
- //get configuration
- configurationManager = ConfigurationManager.getInstance();
- configuration = configurationManager.getConfiguration();
+ super();
- //init as
- loadConfiguration();
- loadKeyStore();
+ logger.info("AuthN Service Engine started");
}
- private void loadKeyStore() throws PerfSONARException {
- try {
- String truststoreFile =
configuration.getExtensionOption("auth-engine", "service.as.truststore_file");
- String truststorePass =
configuration.getExtensionOption("auth-engine",
"service.as.truststore_password");
- KeyStore ks = KeyStore.getInstance("jks");
- ks.load(new FileInputStream(truststoreFile),
truststorePass.toCharArray());
- tsCrypto=new DynamicCrypto(ks);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PerfSONARException("error.as.crypto",e);
- }
-
- }
-
- private void loadConfiguration() throws PerfSONARException {
- props=new Properties();
- String
maxTtlToken=configuration.getExtensionOption("auth-engine",
"service.as.maxttl");
- if (maxTtlToken!=null) {
- try {
- int max=Integer.parseInt(maxTtlToken);
- props.put("service.as.maxttl",
String.valueOf(max));
- logger.debug("AuthNServiceEngine: setting max
ttl of token to "+max);
- } catch (NumberFormatException e) {
- logger.error("AuthNServiceEngine: value of
the parameter service.as.maxttl is not valid. Disabled this feature");
- }
- }
- props.put("provider",
configuration.getExtensionOption("auth-engine", "service.as.crypt_provider"));
- props.put(Configurator.PROPS_TRUSTSTORE_PASSWD,
configuration.getExtensionOption("auth-engine",
"service.as.truststore_password"));
-
props.put(Configurator.PROPS_TRUSTSTORE_FILE,configuration.getExtensionOption("auth-engine",
"service.as.truststore_file"));
-
props.put(Configurator.PROPS_VALID_COMPONENTS,configuration.getExtensionOption("auth-engine",
"service.as.valid_components"));
- try {
- logger.debug("AuthNServiceEngine: getting the eduGAIN
config object...");
- cfg = Configurator.getInstance(props);
- logger.debug("AuthNServiceEngine: getting the eduGAIN
validator object...");
- val=new Validator(props);
- } catch (Throwable e) {
- e.printStackTrace();
- String error="";
- ByteArrayOutputStream baos=new
ByteArrayOutputStream();
- PrintWriter pw=new PrintWriter(baos);
- e.printStackTrace(pw);
- error=baos.toString();
- pw.close();
- String m = "AuthNAction: There is a problem
initiating the eduGAIN environment: "+e.toString()+". Print Stack Trace:
"+error;
- logger.fatal(m);
- throw new PerfSONARException("error.authn.edugain",m);
- }
- }
-
public void takeAction(ServiceMessage serviceRequest, ServiceMessage
serviceResponse)
throws PerfSONARException {
//extract message
Message request = serviceRequest.getMessageElement();
- logger.debug("AuthN Service Engine started");
-
- SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
- if (!st.hasSecTokenInRequest()) {
- String m = "AuthNAction: The request has not sent a
valid Security Token";
- logger.info(m);
- throw new
PerfSONARException("error.authn.not_sectoken",m);
- }
- else {
- Metadata
metadata=getFirstMetadataFromRequest(request);
- String
sentSecToken=getParameterFromKey(metadata,SEC_TOKEN_PARAM);
- logger.info("Security Token: "+sentSecToken);
- if (sentSecToken!=null&&
- sentSecToken!=null&&
-
sentSecToken.equals(AuthNServiceEngine.X509_ID)) {
- checkWSSecHeader(tsCrypto);
- checkTimeStampInfo();
- if (processX509AuthN(request)) {
- Message response =
getValidAuthNMessage(request);
- serviceResponse.setElement(response);
- }
- }
- else if (sentSecToken!=null&&
- sentSecToken!=null&&
-
sentSecToken.equals(AuthNServiceEngine.SAML_ID)) {
- checkWSSecHeader(tsCrypto);
- checkTimeStampInfo();
- if (processSAMLAuthN(request)) {
- Message response =
getValidAuthNMessage(request);
- serviceResponse.setElement(response);
- }
- }
- else {
- String m = "AuthNAction: Wrong parameter in
metadata";
- logger.info(m);
- throw new
PerfSONARException("error.authn.wrong_params",m);
- }
- }
- }
-
- protected void checkTimeStampInfo() throws PerfSONARException {
- Calendar now=Calendar.getInstance();
- String maxttl=props.getProperty("service.as.maxttl");
- if (maxttl!=null) {
- int max=Integer.parseInt(maxttl);
-
- MessageContext
mc=MessageContext.getCurrentMessageContext();
- SOAPEnvelope se = mc.getEnvelope();
- Document doc = null;
- try {
- doc =
Axis2Util.getDocumentFromSOAPEnvelope(se, true);
- } catch (WSSecurityException e) {
- doc = null;
- } finally {
- if (doc == null) {
- String m = "AuthNServiceEngine:
Cannot process the Security Token";
- logger.error(m);
- throw new
PerfSONARException("error.authn.not_sectoken",m);
- }
- }
-
- try {
- boolean found = false;
- ArrayList<?> list =
se.getHeader().getHeaderBlocksWithNSURI(WSSECHEADER_NS);
- SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
- Iterator<?> it = shb.getChildrenWithName(new
QName(WSSECHEADER_TIMESTAMP_NS, WSSECHEADER_TIMESTAMP));
- while (it.hasNext()) {
- OMElementImpl node =
(OMElementImpl)it.next();
- if
(node.getLocalName().equals(WSSECHEADER_TIMESTAMP)) {
- found = true;
- long start = 0;
- long end = 0;
- Iterator<?> it2 =
node.getChildrenWithName(new QName(WSSECHEADER_TIMESTAMP_NS,"Created"));
- if (it2.hasNext()) {
- OMElementImpl node2 =
(OMElementImpl) it2.next();
- java.text.DateFormat
df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-
df.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
- java.util.Date date =
df.parse(node2.getText());
- start =
date.getTime();
-
- }
- it2 =
node.getChildrenWithName(new QName(WSSECHEADER_TIMESTAMP_NS,"Expires"));
- if (it2.hasNext()) {
- OMElementImpl node2 =
(OMElementImpl) it2.next();
- java.text.DateFormat
df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-
df.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
- java.util.Date date =
df.parse(node2.getText());
- end = date.getTime();
- }
- if
(now.before(start)||now.after(end)) {
-
logger.error("AuthNAction: security token not valid. The token was created
before or after right now");
-
logger.error("AuthNAction: **** Security token ("+start+","+end+") vs now
("+now.getTimeInMillis()+")");
- if
(now.before(start)) {
- throw new
PerfSONARException("error.authn.timestamp","Security token not valid. The
token was created after right now");
- }
- else {
- throw new
PerfSONARException("error.authn.timestamp","Security token not valid. The
token was expired before right now");
- }
- }
- if ((end-start)>max) {
-
logger.error("AuthNAction: security token not valid. The valid period of time
of the token is too long. Max allowed is "+max);
- throw new
PerfSONARException("error.authn.timestamp","The valid period of time of the
token is too long. Max allowed is "+max);
- }
- }
- }
- if (found==false) {
- logger.error("AuthNAction: security
token not valid. It's not included the timestamp information");
- throw new
PerfSONARException("error.authn.timestamp","AuthNAction: It's not included
the timestamp information");
- }
- } catch (PerfSONARException e) {
- throw e;
- } catch (Exception e) {
- e.printStackTrace();
- String m = "AuthNAction: Error getting the
SOAP envelope of the authN request";
- logger.error(m);
- throw new PerfSONARException("error.authn.soap", m,
e);
- }
- }
- }
-
- protected void checkWSSecHeader(Crypto tsCrypto) throws
PerfSONARException {
- MessageContext mc=MessageContext.getCurrentMessageContext();
- try {
- SOAPEnvelope se = mc.getEnvelope();
- Document
doc=Axis2Util.getDocumentFromSOAPEnvelope(se, true);
- Crypto crypto = new DynamicCrypto();
- ArrayList<?> list =
se.getHeader().getHeaderBlocksWithNSURI(WSSECHEADER_NS);
- SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
- String actor=shb.getAttribute(new QName(SOAPENV_NS,
WSSECHEADER_ACTOR)).getAttributeValue();
- Vector result = secEngine.processSecurityHeader(doc,
actor, null, crypto);
-
- logger.info("AuthNAction: result=
'"+(result!=null)+"'");
- if (result==null) {
- throw new
PerfSONARException("error.authn.wssec","Null response checking the
signature");
- }
- } catch (PerfSONARException e) {
- e.printStackTrace();
- String m = "Null response checking the signature";
- logger.error(m);
- throw e;
- } catch (WSSecurityException e) {
- logger.error("WSSecurityException: "+e.getMessage());
- String errorCode="error.authn.wssec";
- if
((e.getErrorCode()==WSSecurityException.INVALID_SECURITY)&&
-
(e.getMessage().contains("(WSSecurityEngine: Invalid timestamp The security
semantics of message have expired)"))) {
- // This means the timestamp has expired
- errorCode="error.authn.timestamp";
- }
- throw new
PerfSONARException(errorCode,e.getMessage(),e);
- } catch (Exception e) {
- e.printStackTrace();
- String m = "Error getting the SOAP envelope of the
authN request";
- logger.error(m);
- throw new PerfSONARException("error.authn.soap", m);
- }
- }
-
- protected boolean processSAMLAuthN(Message request) throws
PerfSONARException {
- logger.debug("AuthNAction: Processing the authN using the
SAML assertion");
- SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
- st.setSecTokenFromRequest();
- Object stValue=st.getSecTokenValue();
- if (stValue==null) {
- String m = "AuthNAction: the SAML assertion is not
included";
- logger.info(m);
- throw new
PerfSONARException("error.authn.assertion_not_included",m);
+ if (checkAuthNInformation(tsCrypto, request)) {
+ Message response = getValidAuthNMessage(request);
+ serviceResponse.setElement(response);
}
- logger.debug("AuthNAction: Getting the SAML assertion");
- try {
- SAMLAssertion assertion=(SAMLAssertion)stValue;
- String issuer=assertion.getIssuer();
- Iterator it=assertion.getStatements();
- while (it.hasNext()) {
- SAMLStatement
statement=(SAMLStatement)it.next();
- if (statement instanceof
SAMLAuthenticationStatement) {
- SAMLAuthenticationStatement
authSt=(SAMLAuthenticationStatement)statement;
- SAMLSubject
subject=authSt.getSubject();
- logger.info("AuthNAction: the issuer
'"+issuer+"' has sent an authN statement about
'"+subject.getNameIdentifier().getName()+"'");
- }
- }
- logger.info("AuthNAction: Validating SAML assertion");
- val.validate(assertion);
- } catch (Throwable e) {
- e.printStackTrace();
- String m = "AuthNAction: the SAML assertion is not
valid";
- logger.info(m);
- throw new
PerfSONARException("error.authn.assertion_not_valid",m,e);
- }
- logger.info("AuthNAction: the SAML assertion is valid");
- return true;
}
- protected boolean processX509AuthN(Message request) throws
PerfSONARException {
- SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
- st.setSecTokenFromRequest();
- Object stValue=st.getSecTokenValue();
- if (stValue==null) {
- String m = "AuthNAction: the X509 certificate is not
included";
- logger.info(m);
- throw new
PerfSONARException("error.authn.x509_not_included",m);
- }
- logger.debug("AuthNAction: Getting the X509 certificate");
- try {
- X509Certificate cert=(X509Certificate)stValue;
- logger.info("AuthNAction: subject DN:
'"+cert.getSubjectDN().toString()+"' issuer DN:
'"+cert.getIssuerDN().toString()+"'");
- logger.info("AuthNAction: Validating X509
certificate");
- ComponentID theUri=val.validate(cert);
- logger.info("AuthNAction: cId: "+theUri.getURN());
- } catch (Throwable e) {
- e.printStackTrace();
- String m = "AuthNAction: the X509 certificate is not
valid";
- logger.info(m);
- throw new
PerfSONARException("error.authn.x509_not_valid",m,e);
- }
- logger.info("AuthNAction: the X509 certificate is valid");
-
- return true;
- }
-
protected Message getValidAuthNMessage(Message request) {
Message response = new Message();
response.setType(TYPE_RESPONSE);
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthRServiceEngine.java
===================================================================
---
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthRServiceEngine.java
2009-01-26 12:31:52 UTC (rev 4908)
+++
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/AuthRServiceEngine.java
2009-01-27 12:14:37 UTC (rev 4909)
@@ -1,16 +1,159 @@
package org.perfsonar.service.authService;
+import java.util.Collection;
+import java.util.Iterator;
+
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+
+import net.geant.authr.pap.PolicyManager;
+import net.geant.authr.pap.PolicyManagerFactory;
+import net.geant.authr.pdp.Evaluator;
+import net.geant.authr.pdp.EvaluatorFactory;
+import net.geant.authr.pep.RequestFactory;
+import net.geant.authr.pep.SimpleRequest;
+import net.geant.authr.pep.SimpleResponse;
+import net.geant.authr.pep.exceptions.PEPException;
+
+import org.apache.log4j.Logger;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.perfsonar.base2.service.requesthandler.ServiceEngine;
import org.perfsonar.base2.service.requesthandler.ServiceMessage;
+import org.perfsonar.base2.xml.Element;
+import org.perfsonar.base2.xml.nmwg.Data;
+import org.perfsonar.base2.xml.nmwg.EventType;
+import org.perfsonar.base2.xml.nmwg.Message;
+import org.perfsonar.base2.xml.nmwg.Metadata;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
-public class AuthRServiceEngine extends GenericServiceEngine implements
- ServiceEngine {
+public class AuthRServiceEngine extends GenericServiceEngine implements
ServiceEngine {
+ protected static String METADATA_ID = "authRmetadata";
+ protected static String TYPE_AUTHR_RESPONSE = "AuthREEResponse";
+ protected static String EVENT_TYPE_SUCCESS = "success.as.authr";
- public void takeAction(ServiceMessage request, ServiceMessage
response)
- throws PerfSONARException {
- // TODO Auto-generated method stub
+ private static final Logger logger =
Logger.getLogger(AuthRServiceEngine.class.getName());
+ private PolicyManager policyManager;
+ private Evaluator evaluator;
+
+ private XPath xpath;
+
+ public AuthRServiceEngine() throws PerfSONARException {
+ super();
+
+ loadAuthRConfiguration();
+
+ XPathFactory xfactory = XPathFactory.newInstance();
+ xpath = xfactory.newXPath();
}
+ private void loadAuthRConfiguration() throws PerfSONARException {
+ String policyFile = configuration.getExtensionOption("authr-engine",
"service.as.authr_policy");
+ logger.debug("Loading policy '"+policyFile+"'");
+ if (policyFile!=null&&!policyFile.equals("")) {
+ policyManager =
PolicyManagerFactory.getDefaultPolicyManager();
+ policyManager.loadPolicies(new String[]{policyFile});
+ }
+ else {
+ String m = "AuthRAction: Policy '"+policyFile+"' has
not found!";
+ logger.error(m);
+ throw new
PerfSONARException("error.authr.not_policy",m);
+ }
+ logger.debug("AuthRAction: Loading evaluator");
+ evaluator = EvaluatorFactory.getDefaultEvaluator();
+ evaluator.setPolicyManager(policyManager);
+ }
+
+ public void takeAction(ServiceMessage serviceRequest, ServiceMessage
serviceResponse) throws PerfSONARException {
+ //extract message
+ Message request = serviceRequest.getMessageElement();
+
+ if (checkAuthNInformation(tsCrypto, request)) {
+ logger.info("Authentication data valid");
+ SimpleRequest authRRequest =
getSimpleRequestFromMessage(request);
+ logger.info("AuthRAction: Received request:
("+authRRequest.getSubject()+","+authRRequest.getResource()+","+authRRequest.getAction()+")");
+ SimpleResponse authRResponse =
evaluator.evaluateRequest(authRRequest);
+
+ if (authRResponse.getDecision()==SimpleResponse.PERMIT) {
+ logger.debug("AuthRAction: Authorization response:
PERMIT ("+authRResponse.getDecision()+")");
+ Message response = getValidAuthRMessage(request);
+ serviceResponse.setElement(response);
+ }
+ else if (authRResponse.getDecision()==SimpleResponse.DENY) {
+ logger.debug("AuthRAction: Authorization response:
DENY ("+authRResponse.getDecision()+")");
+ String m = "AuthRAction: The authorization request
has been denied";
+ logger.info(m);
+ throw new PerfSONARException("error.authr.denied",m);
+ }
+ else if
(authRResponse.getDecision()==SimpleResponse.INDETERMINATE) {
+ logger.debug("AuthRAction: Authorization response:
INDETERMINATE ("+authRResponse.getDecision()+")");
+ String m = "AuthRAction: The result of the
authorization request is indeterminate";
+ logger.info(m);
+ throw new
PerfSONARException("error.authr.indeterminate",m);
+ }
+ else {
+ logger.debug("AuthRAction: Authorization response:
NOT_APPLICABLE ("+authRResponse.getDecision()+")");
+ String m = "AuthRAction: The authorization request is
not applicable";
+ logger.info(m);
+ throw new
PerfSONARException("error.authr.not_applicable",m);
+ }
+ }
+ }
+
+ private SimpleRequest getSimpleRequestFromMessage(Message request)
throws PerfSONARException {
+ Metadata md = getFirstMetadataFromRequest(request);
+ Collection<Element> list = md.getChildren("subject",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/authr/1.0/");
+ Iterator<Element> it = list.iterator();
+ Element e = it.next();
+ String authRmessage = e.getText();
+ Document doc = getDocumentFromString(authRmessage);
+
+ SimpleRequest sr=null;
+ NodeList nodes = null;
+ try {
+ XPathExpression expression =
xpath.compile("//Request/Subject/Attribute[@AttributeId='urn:geant:edugain:protocol:delegatedclient']");
+ nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
+ } catch (XPathExpressionException ex) {
+ ex.printStackTrace();
+ String m = "AuthRAction: There is an error processing
the request";
+ throw new PerfSONARException("error.authr.subject",
m, ex);
+ }
+ if (nodes!=null&&nodes.getLength()>0) {
+ sr=RequestFactory.getDefaultSimpleDelegatedRequest();
+ }
+ else {
+ sr=RequestFactory.getDefaultSimpleRequest();
+ }
+ try {
+ sr.setRequestFromMessage(authRmessage);
+
+ return sr;
+ } catch (PEPException ex) {
+ ex.printStackTrace();
+ String m = "AuthRAction: There is an error processing
the subject";
+ throw new PerfSONARException("error.authr.subject",
m, ex);
+ }
+ }
+
+ protected Message getValidAuthRMessage(Message request) {
+ Message response = new Message();
+ response.setType(TYPE_AUTHR_RESPONSE);
+
+ Metadata responseMetadata=new Metadata();
+ EventType et=new EventType();
+ responseMetadata.setEventType(et);
+ et.setEventType(EVENT_TYPE_SUCCESS);
+
+ Data responseData = new Data();
+ responseData.setMetadataIdRef(responseMetadata.getId());
+ response.addChild(responseData);
+ response.setMetadata(responseMetadata);
+
+ return response;
+ }
+
}
Modified:
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/GenericServiceEngine.java
===================================================================
---
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/GenericServiceEngine.java
2009-01-26 12:31:52 UTC (rev 4908)
+++
branches/simple-service-with-base2/src/main/java/org/perfsonar/service/authService/GenericServiceEngine.java
2009-01-27 12:14:37 UTC (rev 4909)
@@ -1,13 +1,142 @@
package org.perfsonar.service.authService;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.io.PrintWriter;
+import java.net.URLDecoder;
+import java.security.KeyStore;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import net.geant.edugain.base.BaseDefinitions;
+import net.geant.edugain.base.Configurator;
+import net.geant.edugain.validation.ComponentID;
+import net.geant.edugain.validation.Validator;
+
+import org.apache.axiom.om.impl.llom.OMElementImpl;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axiom.soap.SOAPHeaderBlock;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.util.Base64;
+import org.apache.log4j.Logger;
+import org.apache.rampart.util.Axis2Util;
+import org.apache.ws.security.WSSecurityEngine;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.opensaml.SAMLAssertion;
+import org.opensaml.SAMLAuthenticationStatement;
+import org.opensaml.SAMLStatement;
+import org.opensaml.SAMLSubject;
+import org.perfsonar.base2.service.authn.component.DynamicCrypto;
+import org.perfsonar.base2.service.authn.tokens.SecTokenManagerFactory;
+import org.perfsonar.base2.service.authn.tokens.SecurityToken;
+import org.perfsonar.base2.service.configuration.Configuration;
+import org.perfsonar.base2.service.configuration.ConfigurationManager;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.perfsonar.base2.service.requesthandler.ServiceEngine;
import org.perfsonar.base2.xml.Element;
import org.perfsonar.base2.xml.nmwg.Message;
import org.perfsonar.base2.xml.nmwg.Metadata;
+import org.w3c.dom.Document;
public abstract class GenericServiceEngine implements ServiceEngine {
+ private static final Logger logger =
Logger.getLogger(GenericServiceEngine.class.getName());
+ public static final String
X509_ID="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ public static final String
SAML_ID="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
+
+ protected final String
WSSECHEADER_TIMESTAMP_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
+ protected final String
SOAPENV_NS="http://schemas.xmlsoap.org/soap/envelope/";
+ protected final String
WSSECHEADER_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+ protected final String WSSECHEADER_TIMESTAMP="Timestamp";
+ protected final String WSSECHEADER_BINARY = "BinarySecurityToken";
+ protected final String WSSECHEADER="Security";
+ protected final String WSSECHEADER_ACTOR="actor";
+ protected final String SEC_TOKEN_PARAM = "SecurityToken";
+
+ protected static String PREFIX_BE = "urn:geant:edugain:component:be:";
+ protected static String PREFIX_GIDP_BE =
"urn:geant:edugain:component:be:gidp:user:";
+
+ protected Configuration configuration;
+ protected ConfigurationManager configurationManager;
+ protected Properties props;
+ protected Validator val;
+ protected Configurator cfg;
+ protected Crypto tsCrypto;
+
+ static final WSSecurityEngine secEngine = new WSSecurityEngine();
+
+ public GenericServiceEngine() throws PerfSONARException {
+ //get configuration
+ configurationManager = ConfigurationManager.getInstance();
+ configuration = configurationManager.getConfiguration();
+
+ //init as
+ loadConfiguration();
+ loadKeyStore();
+ }
+
+ private void loadKeyStore() throws PerfSONARException {
+ try {
+ String truststoreFile =
configuration.getExtensionOption("auth-engine", "service.as.truststore_file");
+ String truststorePass =
configuration.getExtensionOption("auth-engine",
"service.as.truststore_password");
+ KeyStore ks = KeyStore.getInstance("jks");
+ ks.load(new FileInputStream(truststoreFile),
truststorePass.toCharArray());
+ tsCrypto=new DynamicCrypto(ks);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new PerfSONARException("error.as.crypto",e);
+ }
+
+ }
+
+ private void loadConfiguration() throws PerfSONARException {
+ props=new Properties();
+ String
maxTtlToken=configuration.getExtensionOption("auth-engine",
"service.as.maxttl");
+ if (maxTtlToken!=null) {
+ try {
+ int max=Integer.parseInt(maxTtlToken);
+ props.put("service.as.maxttl",
String.valueOf(max));
+ logger.debug("GenericServiceEngine: setting
max ttl of token to "+max);
+ } catch (NumberFormatException e) {
+ logger.error("GenericServiceEngine: value of
the parameter service.as.maxttl is not valid. Disabled this feature");
+ }
+ }
+ props.put("provider",
configuration.getExtensionOption("auth-engine", "service.as.crypt_provider"));
+ props.put(Configurator.PROPS_TRUSTSTORE_PASSWD,
configuration.getExtensionOption("auth-engine",
"service.as.truststore_password"));
+
props.put(Configurator.PROPS_TRUSTSTORE_FILE,configuration.getExtensionOption("auth-engine",
"service.as.truststore_file"));
+
props.put(Configurator.PROPS_VALID_COMPONENTS,configuration.getExtensionOption("auth-engine",
"service.as.valid_components"));
+ try {
+ logger.debug("GenericServiceEngine: getting the
eduGAIN config object...");
+ cfg = Configurator.getInstance(props);
+ logger.debug("GenericServiceEngine: getting the
eduGAIN validator object...");
+ val=new Validator(props);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ String error="";
+ ByteArrayOutputStream baos=new
ByteArrayOutputStream();
+ PrintWriter pw=new PrintWriter(baos);
+ e.printStackTrace(pw);
+ error=baos.toString();
+ pw.close();
+ String m = "GenericServiceEngine: There is a problem
initiating the eduGAIN environment: "+e.toString()+". Print Stack Trace:
"+error;
+ logger.fatal(m);
+ throw new PerfSONARException("error.authn.edugain",m);
+ }
+ }
+
protected String extractEventType(Message request) {
//find eventType in the metadatas
@@ -55,8 +184,13 @@
for (Element params : requestMetadata.getChildren("parameters"))
{
for (Element p : params.getChildren("parameter")) {
String nameAttr = p.getAttribute("name");
+ logger.debug("Param: "+nameAttr);
if (nameAttr.equals(parameterName)) {
String parameterValue = p.getText().trim();
+ if
(parameterValue==null||parameterValue.equals("")) {
+ parameterValue =
p.getAttribute("value");
+ }
+ logger.debug("ParamValue: "+parameterValue);
return parameterValue; //if key has keyId and
}
}
@@ -64,5 +198,376 @@
return null;
}
+ protected boolean checkAuthNInformation(Crypto tsCrypto,Message request)
throws PerfSONARException {
+ SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ String m = "GenericServiceEngine: The request has not
sent a valid Security Token";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.not_sectoken",m);
+ }
+ else {
+ Metadata
metadata=getFirstMetadataFromRequest(request);
+ String
sentSecToken=getParameterFromKey(metadata,SEC_TOKEN_PARAM);
+ logger.info("Security Token: "+sentSecToken);
+ if (sentSecToken!=null&&
+ sentSecToken!=null&&
+
sentSecToken.equals(GenericServiceEngine.X509_ID)) {
+ logCertificate(tsCrypto);
+ checkWSSecHeader(tsCrypto);
+ checkTimeStampInfo();
+ return processX509AuthN(request);
+ }
+ else if (sentSecToken!=null&&
+ sentSecToken!=null&&
+
sentSecToken.equals(GenericServiceEngine.SAML_ID)) {
+ logCertificate(tsCrypto);
+ checkWSSecHeader(tsCrypto);
+ checkTimeStampInfo();
+ return processSAMLAuthN(request);
+ }
+ else {
+ String m = "GenericServiceEngine: Wrong
parameter in metadata";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.wrong_params",m);
+ }
+ }
+ }
+ protected void logCertificate(Crypto tsCrypto) throws PerfSONARException
{
+ MessageContext mc=MessageContext.getCurrentMessageContext();
+ SOAPEnvelope se = mc.getEnvelope();
+ Document doc = null;
+ try {
+ doc = Axis2Util.getDocumentFromSOAPEnvelope(se, true);
+ } catch (WSSecurityException e) {
+ doc = null;
+ } finally {
+ if (doc == null) {
+ String m = "GenericServiceEngine: Cannot
process the Security Token";
+ logger.error(m);
+ throw new
PerfSONARException("error.authn.not_sectoken",m);
+ }
+ }
+
+ try {
+ ArrayList<?> list =
se.getHeader().getHeaderBlocksWithNSURI(WSSECHEADER_NS);
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
+ Iterator<?> it = shb.getChildrenWithName(new
QName(WSSECHEADER_NS, WSSECHEADER_BINARY));
+ while (it.hasNext()) {
+ OMElementImpl node = (OMElementImpl)it.next();
+ if
(node.getLocalName().equals(WSSECHEADER_BINARY)) {
+ String encodedValue =
node.getTrimmedText();
+ byte[] dataCert =
Base64.decode(encodedValue);
+ ByteArrayInputStream in = new
ByteArrayInputStream(dataCert);
+ CertificateFactory cf =
tsCrypto.getCertificateFactory();
+ X509Certificate cert =
(X509Certificate)cf.generateCertificate(in);
+ logger.info("AuthNEERequest signed by
"+cert.getSubjectDN().getName()+" issued by "+cert.getIssuerDN().getName());
+ }
+ }
+ } catch (Exception e) {
+ }
+
+ }
+
+ protected void checkTimeStampInfo() throws PerfSONARException {
+ Calendar now=Calendar.getInstance();
+ String maxttl=props.getProperty("service.as.maxttl");
+ if (maxttl!=null) {
+ int max=Integer.parseInt(maxttl);
+
+ MessageContext
mc=MessageContext.getCurrentMessageContext();
+ SOAPEnvelope se = mc.getEnvelope();
+ Document doc = null;
+ try {
+ doc =
Axis2Util.getDocumentFromSOAPEnvelope(se, true);
+ } catch (WSSecurityException e) {
+ doc = null;
+ } finally {
+ if (doc == null) {
+ String m = "GenericServiceEngine:
Cannot process the Security Token";
+ logger.error(m);
+ throw new
PerfSONARException("error.authn.not_sectoken",m);
+ }
+ }
+
+ try {
+ boolean found = false;
+ ArrayList<?> list =
se.getHeader().getHeaderBlocksWithNSURI(WSSECHEADER_NS);
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
+ Iterator<?> it = shb.getChildrenWithName(new
QName(WSSECHEADER_TIMESTAMP_NS, WSSECHEADER_TIMESTAMP));
+ while (it.hasNext()) {
+ OMElementImpl node =
(OMElementImpl)it.next();
+ if
(node.getLocalName().equals(WSSECHEADER_TIMESTAMP)) {
+ found = true;
+ long start = 0;
+ long end = 0;
+ Iterator<?> it2 =
node.getChildrenWithName(new QName(WSSECHEADER_TIMESTAMP_NS,"Created"));
+ if (it2.hasNext()) {
+ OMElementImpl node2 =
(OMElementImpl) it2.next();
+ java.text.DateFormat
df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+
df.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
+ java.util.Date date =
df.parse(node2.getText());
+ start =
date.getTime();
+
+ }
+ it2 =
node.getChildrenWithName(new QName(WSSECHEADER_TIMESTAMP_NS,"Expires"));
+ if (it2.hasNext()) {
+ OMElementImpl node2 =
(OMElementImpl) it2.next();
+ java.text.DateFormat
df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+
df.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
+ java.util.Date date =
df.parse(node2.getText());
+ end = date.getTime();
+ }
+ if
(now.before(start)||now.after(end)) {
+
logger.error("GenericServiceEngine: security token not valid. The token was
created before or after right now");
+
logger.error("GenericServiceEngine: **** Security token ("+start+","+end+")
vs now ("+now.getTimeInMillis()+")");
+ if
(now.before(start)) {
+ throw new
PerfSONARException("error.authn.timestamp","Security token not valid. The
token was created after right now");
+ }
+ else {
+ throw new
PerfSONARException("error.authn.timestamp","Security token not valid. The
token was expired before right now");
+ }
+ }
+ if ((end-start)>max) {
+
logger.error("GenericServiceEngine: security token not valid. The valid
period of time of the token is too long. Max allowed is "+max);
+ throw new
PerfSONARException("error.authn.timestamp","The valid period of time of the
token is too long. Max allowed is "+max);
+ }
+ }
+ }
+ if (found==false) {
+ logger.error("GenericServiceEngine:
security token not valid. It's not included the timestamp information");
+ throw new
PerfSONARException("error.authn.timestamp","AuthNAction: It's not included
the timestamp information");
+ }
+ } catch (PerfSONARException e) {
+ throw e;
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "GenericServiceEngine: Error
getting the SOAP envelope of the authN request";
+ logger.error(m);
+ throw new PerfSONARException("error.authn.soap", m,
e);
+ }
+ }
+ }
+
+ protected void checkWSSecHeader(Crypto tsCrypto) throws
PerfSONARException {
+ MessageContext mc=MessageContext.getCurrentMessageContext();
+ try {
+ SOAPEnvelope se = mc.getEnvelope();
+ Document
doc=Axis2Util.getDocumentFromSOAPEnvelope(se, true);
+ Crypto crypto = new DynamicCrypto();
+ ArrayList<?> list =
se.getHeader().getHeaderBlocksWithNSURI(WSSECHEADER_NS);
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
+ String actor=shb.getAttribute(new QName(SOAPENV_NS,
WSSECHEADER_ACTOR)).getAttributeValue();
+ Vector result = secEngine.processSecurityHeader(doc,
actor, null, crypto);
+
+ logger.info("GenericServiceEngine: result=
'"+(result!=null)+"'");
+ if (result==null) {
+ throw new
PerfSONARException("error.authn.wssec","Null response checking the
signature");
+ }
+ } catch (PerfSONARException e) {
+ e.printStackTrace();
+ String m = "Null response checking the signature";
+ logger.error(m);
+ throw e;
+ } catch (WSSecurityException e) {
+ logger.error("WSSecurityException: "+e.getMessage());
+ String errorCode="error.authn.wssec";
+ if
((e.getErrorCode()==WSSecurityException.INVALID_SECURITY)&&
+
(e.getMessage().contains("(GenericServiceEngine: Invalid timestamp The
security semantics of message have expired)"))) {
+ // This means the timestamp has expired
+ errorCode="error.authn.timestamp";
+ }
+ throw new
PerfSONARException(errorCode,e.getMessage(),e);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "Error getting the SOAP envelope of the
authN request";
+ logger.error(m);
+ throw new PerfSONARException("error.authn.soap", m);
+ }
+ }
+
+ protected boolean processSAMLAuthN(Message request) throws
PerfSONARException {
+ logger.debug("GenericServiceEngine: Processing the authN
using the SAML assertion");
+ SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ st.setSecTokenFromRequest();
+ Object stValue=st.getSecTokenValue();
+ if (stValue==null) {
+ String m = "GenericServiceEngine: the SAML assertion
is not included";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.assertion_not_included",m);
+ }
+ logger.debug("GenericServiceEngine: Getting the SAML
assertion");
+ try {
+ SAMLAssertion assertion=(SAMLAssertion)stValue;
+ String issuer=assertion.getIssuer();
+ Iterator it=assertion.getStatements();
+ while (it.hasNext()) {
+ SAMLStatement
statement=(SAMLStatement)it.next();
+ if (statement instanceof
SAMLAuthenticationStatement) {
+ SAMLAuthenticationStatement
authSt=(SAMLAuthenticationStatement)statement;
+ SAMLSubject
subject=authSt.getSubject();
+ logger.info("GenericServiceEngine:
the issuer '"+issuer+"' has sent an authN statement about
'"+subject.getNameIdentifier().getName()+"'");
+ }
+ }
+ logger.info("GenericServiceEngine: Validating SAML
assertion");
+ val.validate(assertion);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ String m = "GenericServiceEngine: the SAML assertion
is not valid";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.assertion_not_valid",m,e);
+ }
+ logger.info("GenericServiceEngine: the SAML assertion is
valid");
+
+ return true;
+ }
+
+ protected boolean processX509AuthN(Message request) throws
PerfSONARException {
+ SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ st.setSecTokenFromRequest();
+ Object stValue=st.getSecTokenValue();
+ if (stValue==null) {
+ String m = "GenericServiceEngine: the X509
certificate is not included";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.x509_not_included",m);
+ }
+ logger.debug("GenericServiceEngine: Getting the X509
certificate");
+ try {
+ X509Certificate cert=(X509Certificate)stValue;
+ logger.info("GenericServiceEngine: subject DN:
'"+cert.getSubjectDN().toString()+"' issuer DN:
'"+cert.getIssuerDN().toString()+"'");
+ logger.info("GenericServiceEngine: Validating X509
certificate");
+ ComponentID theUri=val.validate(cert);
+ logger.info("GenericServiceEngine: cId:
"+theUri.getURN());
+ } catch (Throwable e) {
+ e.printStackTrace();
+ String m = "GenericServiceEngine: the X509
certificate is not valid";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.x509_not_valid",m,e);
+ }
+ logger.info("GenericServiceEngine: the X509 certificate is
valid");
+
+ return true;
+ }
+
+ protected String getURNUser(Message request) throws
PerfSONARException {
+ SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ String m = "GenericServiceEngine: The request has not
sent a valid Security Token";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.not_sectoken",m);
+ }
+ else {
+ st.setSecTokenFromRequest();
+ Metadata
metadata=getFirstMetadataFromRequest(request);
+ String
sentSecToken=getParameterFromKey(metadata,SEC_TOKEN_PARAM);
+ logger.info("Security Token: "+sentSecToken);
+ if (sentSecToken!=null&&
+ sentSecToken!=null&&
+
sentSecToken.equals(GenericServiceEngine.X509_ID)) {
+ X509Certificate
cert=(X509Certificate)st.getSecTokenValue();
+ logger.info("AttrRequest signed by
"+cert.getSubjectDN().getName()+" issued by "+cert.getIssuerDN().getName());
+ try {
+ Collection subjectAltNames =
cert.getSubjectAlternativeNames();
+ if (subjectAltNames != null) {
+ Iterator names = subjectAltNames.iterator();
+ while (names.hasNext()) {
+ List<?> values = (List<?>)names.next();
+ if (values.size() == 2) {
+ Integer type = (Integer)values.get(0);
+ String name = (String)values.get(1);
+ if ((type == 6) &&
(name.startsWith(BaseDefinitions.EDUGAIN_CID_RESOLVER))) {
+ String componentName =
URLDecoder.decode(name.substring(name.indexOf('=')+1),"UTF-8");
+ return componentName;
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new
PerfSONARException("error.authn.x509_not_valid","GenericServiceEngine: Cannot
get a valid component ID from the certificate");
+ }
+ throw new
PerfSONARException("error.authn.x509_not_valid","GenericServiceEngine: Cannot
get a valid component ID from the certificate");
+ }
+ else if (sentSecToken!=null&&
+ sentSecToken!=null&&
+
sentSecToken.equals(GenericServiceEngine.SAML_ID)) {
+ try {
+ SAMLAssertion
assertion=(SAMLAssertion)st.getSecTokenValue();
+ Iterator<SAMLStatement>
it=assertion.getStatements();
+ while (it.hasNext()) {
+ SAMLStatement
statement=it.next();
+ if (statement instanceof
SAMLAuthenticationStatement) {
+
SAMLAuthenticationStatement
authStatement=(SAMLAuthenticationStatement)statement;
+ org.w3c.dom.Element
confData=authStatement.getSubject().getConfirmationData();
+ String idpIssuer = "";
+ for (int i=0;
i<confData.getChildNodes().getLength(); i++) {
+
org.w3c.dom.Element
elem=(org.w3c.dom.Element)confData.getChildNodes().item(i);
+ if
(elem.getNodeName().equals("Assertion")) {
+
SAMLAssertion assertionUser=new SAMLAssertion(elem);
+
idpIssuer = assertionUser.getIssuer();
+
Iterator<SAMLStatement> it2=assertionUser.getStatements();
+ while
(it2.hasNext()) {
+
SAMLStatement statement2=it2.next();
+
if (statement2 instanceof SAMLAuthenticationStatement) {
+
SAMLAuthenticationStatement
authStatement2=(SAMLAuthenticationStatement)statement;
+
String componentID =
idpIssuer+":user:"+authStatement2.getSubject().getNameIdentifier().getName();
+
return componentID;
+
}
+ }
+ }
+ }
+ }
+ }
+ } catch (Throwable e) {
+ e.printStackTrace();
+ throw new
PerfSONARException("error.authn.assertion_not_valid","GenericServiceEngine:
the SAML assertion is not valid");
+ }
+ throw new
PerfSONARException("error.authn.assertion_not_valid","GenericServiceEngine:
the SAML assertion is not valid. Cannot get a valid issuer");
+ }
+ else {
+ String m = "GenericServiceEngine: Wrong
parameter in metadata";
+ logger.info(m);
+ throw new
PerfSONARException("error.authn.wrong_params",m);
+ }
+ }
+
+ }
+
+ protected String getDomainUser(Message request) throws
PerfSONARException {
+ String componentName = getURNUser(request);
+ if (componentName.startsWith(PREFIX_GIDP_BE)) {
+ String userdomain =
componentName.substring(componentName.indexOf("-")+1);
+ logger.info("AttrAction: getDomainUser(\""+componentName+"\")
= "+userdomain);
+ return userdomain;
+ }
+ else if (componentName.startsWith(PREFIX_BE)) {
+ String userfed = componentName.substring(PREFIX_BE.length());
+ if (userfed.indexOf(':')>0) {
+ userfed = userfed.substring(0,userfed.indexOf(':'));
+ }
+ logger.info("AttrAction: getDomainUser(\""+componentName+"\")
= "+userfed);
+ return userfed;
+ }
+ return "";
+ }
+
+
+ protected Document getDocumentFromString(String message) {
+ try {
+ Document request = null;
+ DocumentBuilderFactory factory =
DocumentBuilderFactory
+ .newInstance();
+ factory.setNamespaceAware(true);
+
+ DocumentBuilder builder =
factory.newDocumentBuilder();
+ request = builder
+ .parse(new
ByteArrayInputStream(message.getBytes()));
+
+ return request;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
}
- perfsonar: r4909 - in branches/simple-service-with-base2/src/main/java/org/perfsonar: base2/service/authn/tokens base2/service/messages service/authService, svnlog, 01/27/2009
Archive powered by MHonArc 2.6.16.