diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth')
22 files changed, 1742 insertions, 141 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 971fbcef2..fcaa4f053 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -19,7 +19,6 @@ import iaik.pki.PKIException; import iaik.x509.X509Certificate; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Calendar; @@ -34,7 +33,6 @@ import java.util.Vector; import javax.xml.transform.TransformerException; -import org.apache.axis.AxisFault; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.AuthenticationException; @@ -90,7 +88,6 @@ import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.logging.LogMsg; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.BoolUtils; import at.gv.egovernment.moa.util.Constants; @@ -176,9 +173,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { if ((!authURL.startsWith("https:")) && (false == BoolUtils.valueOf(boolStr))) throw new AuthenticationException("auth.07", new Object[] { authURL + "*" }); if (isEmpty(authURL)) - throw new WrongParametersException("StartAuthentication", "AuthURL"); + throw new WrongParametersException("StartAuthentication", "AuthURL", "auth.5"); if (isEmpty(oaURL)) - throw new WrongParametersException("StartAuthentication", PARAM_OA); + throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.5"); ConnectionParameter bkuConnParam = AuthConfigurationProvider.getInstance().getBKUConnectionParameter(); @@ -193,7 +190,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { if (!oaParam.getBusinessService()) { if (isEmpty(target)) - throw new WrongParametersException("StartAuthentication", PARAM_TARGET); + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.5"); } else { if (!isEmpty(target)) { Logger.info("Ignoring target parameter thus application type is \"businessService\""); @@ -220,7 +217,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { // bkuSelectionType==HTMLSelect String bkuSelectTag; try { - bkuSelectTag = readBKUSelectTag(AuthConfigurationProvider.getInstance(), bkuConnParam); + bkuSelectTag = readBKUSelectTag(AuthConfigurationProvider.getInstance(), bkuConnParam); } catch (Throwable ex) { throw new AuthenticationException( "auth.11", @@ -273,9 +270,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { * <li>Creates an HTML form for querying the identity link from the * security layer implementation. * <br>Form parameters include - * <ul> + * <ul> * <li>the <code><InfoboxReadRequest></code></li> - * <li>the data URL where the security layer implementation sends it response to</li> + * <li>the data URL where the security layer implementation sends it response to</li> * </ul> * </ul> * @param authURL URL of the servlet to be used as data URL @@ -302,7 +299,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { if (isEmpty(sessionID)) { if (isEmpty(authURL)) - throw new WrongParametersException("StartAuthentication", "AuthURL"); + throw new WrongParametersException("StartAuthentication", "AuthURL", "auth.5"); //check if HTTP Connection may be allowed (through FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) String boolStr = @@ -311,7 +308,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { if ((!authURL.startsWith("https:")) && (false == BoolUtils.valueOf(boolStr))) throw new AuthenticationException("auth.07", new Object[] { authURL + "*" }); if (isEmpty(oaURL)) - throw new WrongParametersException("StartAuthentication", PARAM_OA); + throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.5"); } AuthenticationSession session; OAAuthParameter oaParam; @@ -327,7 +324,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { throw new AuthenticationException("auth.00", new Object[] { oaURL }); if (!oaParam.getBusinessService()) { if (isEmpty(target)) - throw new WrongParametersException("StartAuthentication", PARAM_TARGET); + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.5"); } else { target = null; } @@ -411,8 +408,8 @@ public class AuthenticationServer implements MOAIDAuthConstants { * <li>Verifies all additional infoboxes returned from the BKU</li> * <li>Creates an authentication block to be signed by the user</li> * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the - * security layer implementation</li> + * containg the authentication block, meant to be returned to the + * security layer implementation</li> * </ul> * * @param sessionID ID of associated authentication session data @@ -441,6 +438,23 @@ public class AuthenticationServer implements MOAIDAuthConstants { throw new AuthenticationException("auth.01", new Object[] { sessionID }); session.setTimestampIdentityLink(); AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + // check if an identity link was found + // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform (SL1.2)) + CharSequence se = "ErrorCode>2911".substring(0); + boolean b = xmlInfoboxReadResponse.contains(se); + if (b) { // no identity link found + Logger.info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als ausländische eID."); + return null; + } + // spezifikationsgemäßer (SL1.2) Errorcode + se = "ErrorCode>4002"; + b = xmlInfoboxReadResponse.contains(se); + if (b) { // Unbekannter Infoboxbezeichner + Logger.info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als ausländische eID."); + return null; + } + // parses the <InfoboxReadResponse> IdentityLink identityLink = new InfoboxReadResponseParser(xmlInfoboxReadResponse).parseIdentityLink(); @@ -495,6 +509,18 @@ public class AuthenticationServer implements MOAIDAuthConstants { if (authConf==null) authConf = AuthConfigurationProvider.getInstance(); if (oaParam==null) oaParam = AuthConfigurationProvider.getInstance(). getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + //BZ.., calculate bPK for signing to be already present in AuthBlock + IdentityLink identityLink = session.getIdentityLink(); + if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + // only compute bPK if online application is a public service and we have the Stammzahl + String bpkBase64 = new BPKBuilder().buildBPK( + identityLink.getIdentificationValue(), + session.getTarget()); + identityLink.setIdentificationValue(bpkBase64); + } + //..BZ + // builds the AUTH-block String authBlock = buildAuthenticationBlock(session); @@ -514,6 +540,186 @@ public class AuthenticationServer implements MOAIDAuthConstants { } /** + * Returns a CreateXMLSignatureRequest for the foreign ID.<br> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from + * the BKU + * @param cert The certificate of the foreign ID + * @return String representation of the <code><CreateXMLSignatureRequest></code> + */ + public String getCreateXMLSignatureRequestForeignID(String sessionID, Map infoboxReadResponseParameters, X509Certificate cert) + throws + AuthenticationException, + BuildException, + ParseException, + ConfigurationException, + ValidateException, + ServiceException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID}); + + + AuthenticationSession session = getSession(sessionID); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + OAAuthParameter oaParam = + AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + + + return getCreateXMLSignatureRequestForeignID(session, authConf, oaParam); + } + + public String getCreateXMLSignatureRequestForeignID(AuthenticationSession session, AuthConfigurationProvider authConf, OAAuthParameter oaParam) + throws + ConfigurationException, + BuildException, + ValidateException { + + + if (authConf==null) authConf = AuthConfigurationProvider.getInstance(); + if (oaParam==null) oaParam = AuthConfigurationProvider.getInstance(). + getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + //BZ.., calculate bPK for signing to be already present in AuthBlock +// IdentityLink identityLink = session.getIdentityLink(); +// if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { +// // only compute bPK if online application is a public service and we have the Stammzahl +// String bpkBase64 = new BPKBuilder().buildBPK( +// identityLink.getIdentificationValue(), +// session.getTarget()); +// identityLink.setIdentificationValue(bpkBase64); +// } + //..BZ + + + // builds the AUTH-block + String authBlock = buildAuthenticationBlock(session); +// session.setAuthBlock(authBlock); + // builds the <CreateXMLSignatureRequest> + String[] transformsInfos = oaParam.getTransformsInfos(); + if ((transformsInfos == null) || (transformsInfos.length == 0)) { + // no OA specific transforms specified, use default ones + transformsInfos = authConf.getTransformsInfos(); + } + String createXMLSignatureRequest = + new CreateXMLSignatureRequestBuilder().build(authBlock, + oaParam.getKeyBoxIdentifier(), + transformsInfos, + oaParam.getSlVersion12()); + return createXMLSignatureRequest; +} + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param createXMLSignatureResponseParameters The parameters from the response returned from + * the BKU including the <code><CreateXMLSignatureResponse></code> + */ + public X509Certificate verifyXMLSignature(String sessionID, Map createXMLSignatureResponseParameters) + throws + AuthenticationException, + BuildException, + ParseException, + ConfigurationException, + ValidateException, + ServiceException { + + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[] { REQ_GET_FOREIGN_ID, PARAM_SESSIONID}); + + + String xmlCreateXMLSignatureResponse = (String)createXMLSignatureResponseParameters.get(PARAM_XMLRESPONSE); + + System.out.println(xmlCreateXMLSignatureResponse); + + if (isEmpty(xmlCreateXMLSignatureResponse)) + throw new AuthenticationException("auth.10", new Object[] { REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE}); + + AuthenticationSession session = getSession(sessionID); + /*if (session.getTimestampIdentityLink() != null) + throw new AuthenticationException("auth.01", new Object[] { sessionID });*/ + //session.setTimestampIdentityLink(); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + + // parses the <CreateXMLSignatureResponse> + CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse); + CreateXMLSignatureResponse createXMLSignatureResponse = p.parseResponseDsig(); + + // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP + Element domVerifyXMLSignatureRequest = + new VerifyXMLSignatureRequestBuilder().buildDsig( + createXMLSignatureResponse, authConf.getMoaSpAuthBlockTrustProfileID()); + + // invokes the call + Element domVerifyXMLSignatureResponse = + new SignatureVerificationInvoker().verifyXMLSignature(domVerifyXMLSignatureRequest); + + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse verifyXMLSignatureResponse = + new VerifyXMLSignatureResponseParser(domVerifyXMLSignatureResponse).parseData(); + + + //int code = verifyXMLSignatureResponse.getSignatureCheckCode(); + + return verifyXMLSignatureResponse.getX509certificate(); + + } + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param readInfoboxResponseParameters The parameters from the response returned from + * the BKU including the <code><ReadInfoboxResponse></code> + */ + public X509Certificate getCertificate(String sessionID, Map readInfoboxResponseParameters) + throws + AuthenticationException, + BuildException, + ParseException, + ConfigurationException, + ValidateException, + ServiceException { + + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + + String xmlReadInfoboxResponse = (String)readInfoboxResponseParameters.get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlReadInfoboxResponse)) + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE}); + + // parses the <CreateXMLSignatureResponse> + InfoboxReadResponseParser p = new InfoboxReadResponseParser(xmlReadInfoboxResponse); + X509Certificate cert = p.parseCertificate(); + + return cert; + + } + + /** * Builds an authentication block <code><saml:Assertion></code> from given session data. * @param session authentication session * @@ -523,16 +729,19 @@ public class AuthenticationServer implements MOAIDAuthConstants { * to be appended to the AUTH-Block. */ private String buildAuthenticationBlock(AuthenticationSession session) throws BuildException { - IdentityLink identityLink = session.getIdentityLink(); - String issuer = identityLink.getName(); - String gebDat = identityLink.getDateOfBirth(); - String identificationValue = identityLink.getIdentificationValue(); - String identificationType = identityLink.getIdentificationType(); - String issueInstant = DateTimeUtils.buildDateTime(Calendar.getInstance()); + IdentityLink identityLink = session.getIdentityLink(); + String issuer = identityLink.getName(); + String gebDat = identityLink.getDateOfBirth(); + String identificationValue = identityLink.getIdentificationValue(); + String identificationType = identityLink.getIdentificationType(); + + String issueInstant = DateTimeUtils.buildDateTime(Calendar.getInstance()); session.setIssueInstant(issueInstant); String authURL = session.getAuthURL(); String target = session.getTarget(); - String oaURL = session.getPublicOAURLPrefix(); + //Bug #485 (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105) + //String oaURL = session.getPublicOAURLPrefix(); + String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); List extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); String authBlock = new AuthenticationBlockAssertionBuilder().buildAuthBlock( issuer, @@ -824,19 +1033,19 @@ public class AuthenticationServer implements MOAIDAuthConstants { * <li>Validates given <code><CreateXMLSignatureResponse></code></li> * <li>Parses <code><CreateXMLSignatureResponse></code> for error codes</li> * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></code></li> + * <code><CreateXMLSignatureResponse></code></li> * <li>Verifies authentication block by calling the MOA SP component</li> * <li>Creates authentication data</li> * <li>Creates a corresponding SAML artifact</li> * <li>Stores authentication data in the authentication data store - * indexed by the SAML artifact</li> + * indexed by the SAML artifact</li> * <li>Deletes authentication session</li> * <li>Returns the SAML artifact, encoded BASE64</li> * </ul> * * @param sessionID session ID of the running authentication session * @param xmlCreateXMLSignatureReadResponse String representation of the - * <code><CreateXMLSignatureResponse></code> + * <code><CreateXMLSignatureResponse></code> * @return SAML artifact needed for retrieving authentication data, encoded BASE64 */ public String verifyAuthenticationBlock( @@ -851,9 +1060,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { ValidateException { if (isEmpty(sessionID)) - throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); if (isEmpty(xmlCreateXMLSignatureReadResponse)) - throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); AuthenticationSession session = getSession(sessionID); AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); // parses <CreateXMLSignatureResponse> @@ -874,11 +1083,11 @@ public class AuthenticationServer implements MOAIDAuthConstants { String tpid = authConf.getMoaSpAuthBlockTrustProfileID(); Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, vtids, tpid); // debug output - + // invokes the call Element domVsresp = new SignatureVerificationInvoker().verifyXMLSignature(domVsreq); // debug output - + // parses the <VerifyXMLSignatureResponse> VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser(domVsresp).parseData(); @@ -1015,6 +1224,150 @@ public class AuthenticationServer implements MOAIDAuthConstants { "Anmeldedaten zu MOASession " + sessionID + " angelegt, SAML Artifakt " + samlArtifact); return samlArtifact; } + + /** + * Gets the foreign authentication data.<br> + * <ul> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store + * indexed by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @return SAML artifact needed for retrieving authentication data, encoded BASE64 + */ + public String getForeignAuthenticationData( + String sessionID) + throws + AuthenticationException, + BuildException, + ParseException, + ConfigurationException, + ServiceException, + ValidateException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + + AuthenticationSession session = getSession(sessionID); + //AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + try { + String serializedAssertion = DOMUtils.serializeNode(session.getIdentityLink().getSamlAssertion()); + session.setAuthBlock(serializedAssertion); + } catch (TransformerException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + } catch (IOException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + } + // post processing of the infoboxes + Iterator iter = session.getInfoboxValidatorIterator(); + boolean formpending = false; + if (iter != null) { + while (!formpending && iter.hasNext()) { + Vector infoboxValidatorVector = (Vector) iter.next(); + String identifier = (String) infoboxValidatorVector.get(0); + String friendlyName = (String) infoboxValidatorVector.get(1); + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector.get(2); + InfoboxValidationResult infoboxValidationResult = null; + try { + infoboxValidationResult = infoboxvalidator.validate(session.getIdentityLink().getSamlAssertion()); + } catch (ValidateException e) { + Logger.error("Error validating " + identifier + " infobox:" + e.getMessage()); + throw new ValidateException( + "validator.44", new Object[] {friendlyName}); + } + if (!infoboxValidationResult.isValid()) { + Logger.info("Validation of " + identifier + " infobox failed."); + throw new ValidateException( + "validator.40", new Object[] {friendlyName, infoboxValidationResult.getErrorMessage()}); + } + String form = infoboxvalidator.getForm(); + if (ParepUtils.isEmpty(form)) { + AddAdditionalSAMLAttributes(session, infoboxValidationResult.getExtendedSamlAttributes(), identifier, friendlyName); + } else { + return "Redirect to Input Processor"; + } + } + } + + // Exchange person data information by a mandate if needed + List oaAttributes = session.getExtendedSAMLAttributesOA(); + IdentityLink replacementIdentityLink = null; + if (session.isMandateCompatibilityMode() && oaAttributes != null && oaAttributes.size()>0) { + // look if we have a mandate + boolean foundMandate = false; + Iterator it = oaAttributes.iterator(); + while (!foundMandate && it.hasNext()) { + ExtendedSAMLAttribute samlAttribute = (ExtendedSAMLAttribute)it.next(); + if (ParepValidator.EXT_SAML_MANDATE_RAW.equals(samlAttribute.getName())) { + Object value = samlAttribute.getValue(); + if (value instanceof Element) { + Element mandate = (Element) value; + replacementIdentityLink = new IdentityLink(); + Element mandator = ParepUtils.extractMandator(mandate); + String dateOfBirth = ""; + Element prPerson = null; + String familyName = ""; + String givenName = ""; + String identificationType = ""; + String identificationValue = ""; + if (mandator != null) { + boolean physical = ParepUtils.isPhysicalPerson(mandator); + if (physical) { + familyName = ParepUtils.extractText(mandator, "descendant-or-self::pr:Name/pr:FamilyName/text()"); + givenName = ParepUtils.extractText(mandator, "descendant-or-self::pr:Name/pr:GivenName/text()"); + dateOfBirth = ParepUtils.extractMandatorDateOfBirth(mandator); + } else { + familyName = ParepUtils.extractMandatorFullName(mandator); + } + identificationType = ParepUtils.getIdentification(mandator, "Type"); + identificationValue = ParepUtils.extractMandatorWbpk(mandator); + prPerson = ParepUtils.extractPrPersonOfMandate(mandate); + if (physical && session.getBusinessService() && identificationType!=null && Constants.URN_PREFIX_BASEID.equals(identificationType)) { + // now we calculate the wbPK and do so if we got it from the BKU + identificationType = Constants.URN_PREFIX_WBPK + "+" + session.getDomainIdentifier(); + identificationValue = new BPKBuilder().buildWBPK(identificationValue, session.getDomainIdentifier()); + ParepUtils.HideStammZahlen(prPerson, true, null, null, true); + } + + } + replacementIdentityLink.setDateOfBirth(dateOfBirth); + replacementIdentityLink.setFamilyName(familyName); + replacementIdentityLink.setGivenName(givenName); + replacementIdentityLink.setIdentificationType(identificationType); + replacementIdentityLink.setIdentificationValue(identificationValue); + replacementIdentityLink.setPrPerson(prPerson); + try { + replacementIdentityLink.setSamlAssertion(session.getIdentityLink().getSamlAssertion()); + } catch (Exception e) { + throw new ValidateException("validator.64", null); + } + } else { + Logger.info("The type of Mandate SAML-Attribute is not \"org.w3c.dom.Element\""); + throw new ValidateException("validator.64", null); + } + } + } + } + + VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); + X509Certificate cert = session.getForeignSignerCertificate(); + vsresp.setX509certificate(cert); + AuthenticationData authData = buildAuthenticationData(session, vsresp, replacementIdentityLink); + String samlArtifact = + new SAMLArtifactBuilder().build(session.getAuthURL(), session.getSessionID()); + storeAuthenticationData(samlArtifact, authData); + + // invalidates the authentication session + sessionStore.remove(sessionID); + Logger.info( + "Anmeldedaten zu MOASession " + sessionID + " angelegt, SAML Artifakt " + samlArtifact); + return samlArtifact; + } + /** * Builds the AuthenticationData object together with the * corresponding <code><saml:Assertion></code> @@ -1076,13 +1429,17 @@ public class AuthenticationServer implements MOAIDAuthConstants { authData.setWBPK(identityLink.getIdentificationValue()); } else { authData.setBPK(identityLink.getIdentificationValue()); + + //BZ.., calculation of bPK already before sending AUTHBlock + /* if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { // only compute bPK if online application is a public service and we have the Stammzahl String bpkBase64 = new BPKBuilder().buildBPK( identityLink.getIdentificationValue(), session.getTarget()); authData.setBPK(bpkBase64); - } + }*/ + } String ilAssertion = oaParam.getProvideIdentityLink() @@ -1186,7 +1543,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @param id Session ID * @return AuthenticationSession created * @exception AuthenticationException - * thrown when an <code>AuthenticationSession</code> is running + * thrown when an <code>AuthenticationSession</code> is running * already for the given session ID */ private static AuthenticationSession newSession() throws AuthenticationException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index 5aa1bf45e..88859dc3f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -54,6 +54,10 @@ public interface MOAIDAuthConstants { public static final String REQ_START_AUTHENTICATION = "StartAuthentication"; /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet} is mapped to */ public static final String REQ_VERIFY_IDENTITY_LINK = "VerifyIdentityLink"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet} is mapped to */ + public static final String REQ_GET_FOREIGN_ID = "GetForeignID"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet} is mapped to */ + public static final String REQ_VERIFY_CERTIFICATE = "VerifyCertificate"; /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.ProcessValidatorInputServlet} is mapped to */ public static final String REQ_PROCESS_VALIDATOR_INPUT = "ProcessInput"; /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet} is mapped to */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/WrongParametersException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/WrongParametersException.java index 398a6731d..f4827c189 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/WrongParametersException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/WrongParametersException.java @@ -29,8 +29,10 @@ public class WrongParametersException extends MOAIDException { /** * Constructor */ - public WrongParametersException(String call, String parameter) { - super("auth.05", new Object[] {call, parameter}); + public WrongParametersException(String call, String parameter, String errorID) { + super(errorID, new Object[] {call, parameter}); + //super("auth.5", new Object[] {call, parameter}); + //super("auth.12", new Object[] {call, parameter}); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java index f9d8e7091..d684c16c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java @@ -18,11 +18,21 @@ package at.gv.egovernment.moa.id.auth.builder; import java.text.MessageFormat; import java.util.List; +import org.w3c.dom.Element; + import at.gv.egovernment.moa.id.BuildException; import at.gv.egovernment.moa.id.ParseException; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; +import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.StringUtils; /** * Builder for the authentication block <code><saml:Assertion></code> @@ -66,6 +76,13 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion " </saml:AttributeValue>" + NL + " </saml:Attribute>" + NL; + + private static String PR_IDENTIFICATION_ATTRIBUTE = + " <pr:Identification xmlns:pr=\"" + PD_NS_URI + "\">" + NL + + " <pr:Value>{0}</pr:Value>" + NL + + " <pr:Type>{1}</pr:Type>" + NL + + " </pr:Identification>" + NL; + /** * The number of SAML attributes included in this AUTH-Block (without the extended SAML attributes). */ @@ -123,20 +140,72 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion session.setSAMLAttributeGebeORwbpk(true); String gebeORwbpk = ""; String wbpkNSDeclaration = ""; + + //BZ.., reading OA parameters + OAAuthParameter oaParam; + try { + oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + } catch (ConfigurationException e) { + Logger.error("Error on building AUTH-Block: " + e.getMessage()); + throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()}); + } + //..BZ + + if (target == null) { // OA is a business application if (!Constants.URN_PREFIX_HPI.equals(identityLinkType)) { - // Only add wbPKs to AUTH-Block. HPIs can be added to the AUTH-Block by the corresponding Validator - gebeORwbpk = MessageFormat.format(WBPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType }); - wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\""; + // Only add wbPKs to AUTH-Block. HPIs can be added to the AUTH-Block by the corresponding Validator + gebeORwbpk = MessageFormat.format(WBPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType }); + wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\""; + + //BZ.., adding type of wbPK domain identifier + ExtendedSAMLAttribute idLinkDomainIdentifierTypeAttribute = + new ExtendedSAMLAttributeImpl("IdentityLinkDomainIdentifierType", oaParam.getIdentityLinkDomainIdentifierType(), Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY); + + extendedSAMLAttributes.add(idLinkDomainIdentifierTypeAttribute); + //..BZ + } else { - // We do not have a wbPK, therefore no SAML-Attribute is provided - session.setSAMLAttributeGebeORwbpk(false); + // We do not have a wbPK, therefore no SAML-Attribute is provided + session.setSAMLAttributeGebeORwbpk(false); } } else { - gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target }); + // OA is a govermental application + //BZ.. + String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); + //gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target }); + gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target + " (" + sectorName + ")" }); + //..BZ + + //BZ.., no business service, adding bPK + + Element bpkSamlValueElement; + try { + bpkSamlValueElement = DOMUtils.parseDocument(MessageFormat.format(PR_IDENTIFICATION_ATTRIBUTE, new Object[] { identityLinkValue, Constants.URN_PREFIX_BPK }), false, null, null).getDocumentElement(); + } catch (Exception e) { + Logger.error("Error on building AUTH-Block: " + e.getMessage()); + throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()}); + } + ExtendedSAMLAttribute bpkAttribute = + new ExtendedSAMLAttributeImpl("bPK", bpkSamlValueElement, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY); + + extendedSAMLAttributes.add(bpkAttribute); + //gebeORwbpk = gebeORwbpk + MessageFormat.format(BPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType }); + wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\""; + //..BZ } + //BZ.., adding friendly name of OA + String oaFriendlyName = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "" : oaParam.getFriendlyName(); + + ExtendedSAMLAttribute oaFriendlyNameAttribute = + new ExtendedSAMLAttributeImpl("oaFriendlyName", oaFriendlyName, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY); + + extendedSAMLAttributes.add(oaFriendlyNameAttribute); + //..BZ + String assertion; try { assertion = MessageFormat.format( diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java new file mode 100644 index 000000000..9227d5303 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java @@ -0,0 +1,126 @@ +package at.gv.egovernment.moa.id.auth.builder;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import at.gv.egovernment.moa.id.BuildException;
+
+
+/**
+ * Builder for CreateXMLSignatureRequest to sign data from a foreign
+ * eID card.
+ *
+ */
+
+public class CreateXMLSignatureRequestBuilderForeign extends Builder {
+
+ /** special tag in the XML template to be substituted for the KeyboxIdentifier */
+ private static final String KEYBOXID_TAG = "<KEYBOXID>";
+ /** special tag in the XML template to be substituted for the content */
+ private static final String XMLCONTENT_TAG = "<XMLContent>";
+ /** private static int all contains the representation to replace all tags*/
+ private static final int ALL = -1;
+
+ /** default HTML template */
+ private static final String DEFAULT_XML_TEMPLATE =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<sl:CreateXMLSignatureRequest xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">" +
+ "<sl:KeyboxIdentifier>" + KEYBOXID_TAG + "</sl:KeyboxIdentifier>" +
+ "<sl:DataObjectInfo Structure=\"enveloping\">" +
+ "<sl:DataObject>" +
+ "<sl:XMLContent>" + XMLCONTENT_TAG + "</sl:XMLContent>" +
+ "</sl:DataObject>" +
+ "<sl:TransformsInfo>" +
+ "<sl:FinalDataMetaInfo>" +
+ "<sl:MimeType>text/plain</sl:MimeType>" +
+ "</sl:FinalDataMetaInfo>" +
+ "</sl:TransformsInfo>" +
+ "</sl:DataObjectInfo>" +
+ "</sl:CreateXMLSignatureRequest>";
+
+ /** default HTML template */
+ private static final String DEFAULT_XHTML_TEMPLATE =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<sl:CreateXMLSignatureRequest xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">" +
+ "<sl:KeyboxIdentifier>" + KEYBOXID_TAG + "</sl:KeyboxIdentifier>" +
+ "<sl:DataObjectInfo Structure=\"enveloping\">" +
+ "<sl:DataObject>" +
+ "<sl:XMLContent>" + XMLCONTENT_TAG + "</sl:XMLContent>" +
+ "</sl:DataObject>" +
+ "<sl:TransformsInfo>" +
+ "<sl:FinalDataMetaInfo>" +
+ "<sl:MimeType>application/xhtml+xml</sl:MimeType>" +
+ "</sl:FinalDataMetaInfo>" +
+ "</sl:TransformsInfo>" +
+ "</sl:DataObjectInfo>" +
+ "</sl:CreateXMLSignatureRequest>";
+
+ /**
+ * Constructor for CreateXMLSignatureRequestBuilderForeign.
+ */
+ public CreateXMLSignatureRequestBuilderForeign() {
+ super();
+ }
+ /**
+ * Builds the XML request.
+ *
+ * @param xmlRequest XML Request to be sent as a parameter in the form
+ * @param bkuURL URL of the "Bürgerkartenumgebung" the form will be submitted to;
+ * may be <code>null</code>, in this case the default URL will be used
+ * @param dataURL DataURL to be sent as a parameter in the form
+ */
+ public String build(
+ String keyboxIdentifier,
+ String xmlContent)
+ throws BuildException
+ {
+ String xmlRequest = DEFAULT_XHTML_TEMPLATE;
+ xmlRequest = replaceTag(xmlRequest, KEYBOXID_TAG, keyboxIdentifier, true, ALL);
+ //htmlForm = replaceTag(htmlForm, XMLREQUEST_TAG, encodeParameter(xmlRequest), true, ALL);
+ xmlRequest = replaceTag(xmlRequest, XMLCONTENT_TAG, xmlContent, true, ALL);
+ return xmlRequest;
+ }
+ /**
+ * Encodes a string for inclusion as a parameter in the form.
+ * Double quotes are substituted by <code>"&quot;"</code>.
+ * @param s the string to be encoded
+ * @return the string encoded
+ * @throws BuildException on any exception encountered
+ */
+ public static String encodeParameter(String s) throws BuildException {
+ StringReader in = new StringReader(s);
+ StringWriter out = new StringWriter();
+ try {
+ for (int ch = in.read(); ch >= 0; ch = in.read()) {
+ if (ch == '"')
+ out.write(""");
+ else if (ch == '<')
+ out.write("<");
+ else if (ch == '>')
+ out.write(">");
+ else if (ch == 'ä')
+ out.write("ä");
+ else if (ch == 'ö')
+ out.write("ö");
+ else if (ch == 'ü')
+ out.write("ü");
+ else if (ch == 'Ä')
+ out.write("Ä");
+ else if (ch == 'Ö')
+ out.write("Ö");
+ else if (ch == 'Ü')
+ out.write("Ü");
+ else if (ch == 'ß')
+ out.write("ß");
+ else
+ out.write(ch);
+ }
+ }
+ catch (IOException ex) {
+ throw new BuildException("builder.00", new Object[] {"GetIdentityLinkForm", ex.toString()});
+ }
+ return out.toString();
+ }
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java new file mode 100644 index 000000000..60feb7d2f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java @@ -0,0 +1,94 @@ +/*
+* Copyright 2003 Federal Chancellery Austria
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.util.Constants;
+
+/**
+ * Builder for the <code><InfoboxReadRequest></code> structure
+ * used for requesting the identity link from the security layer implementation.
+ *
+ * @author Paul Ivancsics
+ * @version $Id: InfoboxReadRequestBuilder.java 1087 2008-08-28 07:55:59Z mcentner $
+ */
+public class InfoboxReadRequestBuilderCertificate implements Constants {
+
+
+ /**
+ * Constructor for InfoboxReadRequestBuilder.
+ */
+ public InfoboxReadRequestBuilderCertificate() {
+ }
+
+
+ /**
+ * Builds an <code><InfoboxReadRequest></code>.
+ *
+ * @param slVersion12 specifies whether the Security Layer version is
+ * version 1.2 or not
+ * @param businessService specifies whether the online application is a
+ * business service or not
+ * @param identityLinkDomainIdentifier the identification number of the business
+ * company; maybe <code>null</code> if the OA
+ * is a public service; must not be <code>null</code>
+ * if the OA is a business service
+ *
+ * @return <code><InfoboxReadRequest></code> as String
+ */
+ public String build(boolean slVersion12) {
+
+ String slPrefix;
+ String slNsDeclaration;
+
+ if (slVersion12) {
+ slPrefix = SL12_PREFIX;
+ slNsDeclaration = SL12_NS_URI;
+ } else {
+ slPrefix = SL10_PREFIX;
+ slNsDeclaration = SL10_NS_URI;
+ }
+
+ StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest xmlns:");
+ sb.append(slPrefix);
+ sb.append("=\"");
+ sb.append(slNsDeclaration);
+ sb.append("\">");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>Certificates</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":AssocArrayParameters>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":ReadValue Key=\"SecureSignatureKeypair\"/>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":AssocArrayParameters>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest>");
+
+ return sb.toString();
+
+ }
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java index ffe4ad9b6..a14d0325f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java @@ -217,5 +217,67 @@ public class VerifyXMLSignatureRequestBuilder { return requestElem_; } + + /** + * Builds a <code><VerifyXMLSignatureRequest></code> + * from the signed data with a known trustProfileID which + * has to exist in MOA-SP + * @param csr - signed AUTH-Block + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * @return Element - The complete request as Dom-Element + * @throws ParseException + */ + public Element buildDsig( + CreateXMLSignatureResponse csr, + String trustProfileID) + throws BuildException { //samlAssertionObject + + try { + // build the request +// requestElem_.setAttributeNS(Constants.XMLNS_NS_URI, "xmlns:" +// + Constants.XML_PREFIX, Constants.XMLNS_NS_URI); + + Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + + Element xmlContentElem = requestDoc_.createElementNS(MOA_NS_URI, "XMLContent"); + verifySignatureEnvironmentElem.appendChild(xmlContentElem); + xmlContentElem.setAttribute(Constants.XML_PREFIX + ":space", "preserve"); + + // insert the dsig:Signature + xmlContentElem.appendChild(requestDoc_.importNode(csr.getDsigSignature(), true)); + // specify the signature location + Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + Node signatureLocation = requestDoc_.createTextNode("/"+ DSIG + "Signature"); + verifySignatureLocationElem.appendChild(signatureLocation); + // signature manifest params + Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "true"); + // add the transform profile IDs + Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + + trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIDElem); + + } catch (Throwable t) { + throw new BuildException("builder.00", new Object[] { "VerifyXMLSignatureRequest" }, t); + } + + return requestElem_; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 969e628f4..eca02a77b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -15,6 +15,8 @@ */ package at.gv.egovernment.moa.id.auth.data; +import iaik.x509.X509Certificate; + import java.util.ArrayList; import java.util.Date; import java.util.Iterator; @@ -87,7 +89,11 @@ public class AuthenticationSession { * service or not */ private boolean businessService; - + + /** + * Signer certificate of the foreign citizen + */ + private X509Certificate signerCertificate; /** * SAML attributes from an extended infobox validation to be appended * to the SAML assertion delivered to the final online application. @@ -149,6 +155,14 @@ public class AuthenticationSession { infoboxValidators = new ArrayList(); } + public X509Certificate getForeignSignerCertificate() { + return signerCertificate; + } + + public void setForeignSignerCertificate(X509Certificate signerCertificate) { + this.signerCertificate = signerCertificate; + } + /** * Returns the identityLink. * @return IdentityLink diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/CreateXMLSignatureResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/CreateXMLSignatureResponse.java index 81dc2f736..fc3831161 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/CreateXMLSignatureResponse.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/CreateXMLSignatureResponse.java @@ -1,18 +1,3 @@ -/* -* Copyright 2003 Federal Chancellery Austria -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ package at.gv.egovernment.moa.id.auth.data; import org.w3c.dom.Element; @@ -35,6 +20,11 @@ private SAMLAttribute[] samlAttributes; * the original saml:Assertion-Element */ private Element samlAssertion; + + /** + * the original dsig:Signature-Element + */ + private Element dsigSignature; /** * Returns the samlAssertion. * @return Element @@ -44,6 +34,14 @@ public Element getSamlAssertion() { } /** + * Returns the dsig:Signature + * @return Element + */ +public Element getDsigSignature() { + return dsigSignature; +} + +/** * Returns the samlAttribute. * @return SAMLAttribute[] */ @@ -67,6 +65,10 @@ public void setSamlAssertion(Element samlAssertion) { this.samlAssertion = samlAssertion; } +public void setDsigSignature(Element dsigSignature) { + this.dsigSignature = dsigSignature; +} + /** * Sets the samlAttribute. * @param samlAttributes The samlAttributes to set diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java index 74bad617c..d5b6f9aa9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; +import org.w3c.dom.NodeList; import org.w3c.dom.traversal.NodeIterator; import at.gv.egovernment.moa.id.AuthenticationException; @@ -129,6 +130,31 @@ public class CreateXMLSignatureResponseParser { throw new ParseException("parser.01", new Object[] { t.toString()}, t); } } + + /** + * Unmarshalls the <@link sigResponse> to an + * <code><CreateXMLSignatureResponse></code> object. + * + * @return a <code><CreateXMLSignatureResponse></code> object + * @throws ParseException + */ + + public CreateXMLSignatureResponse parseResponseDsig() throws ParseException { + CreateXMLSignatureResponse cResp; + try { + cResp = new CreateXMLSignatureResponse(); + + NodeList list = sigResponse_.getElementsByTagNameNS(Constants.DSIG_NS_URI, "Signature"); + Element dsigSignatureNode = (Element) list.item(0); + + Element dsigSignatureElement = (Element) dsigSignatureNode; + cResp.setDsigSignature(dsigSignatureElement); + } + catch (Throwable t) { + throw new ParseException("parser.01", new Object[] { t.toString()}, t); + } + return cResp; + } /** * Unmarshalls the <@link sigResponse> to an diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java index 954488173..b53a1a2dc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java @@ -15,17 +15,31 @@ */ package at.gv.egovernment.moa.id.auth.parser; +import iaik.x509.X509Certificate; + import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.security.cert.CertificateException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.apache.axis.encoding.Base64; +import org.w3c.dom.Document; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.AuthenticationException; import at.gv.egovernment.moa.id.ParseException; import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.XPathUtils; +import com.sun.org.apache.xpath.internal.XPathAPI; + /** * Parses an <code><InfoboxReadResponse></code>. * @@ -175,6 +189,43 @@ public class InfoboxReadResponseParser { IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(samlAssertion); return ilParser.parseIdentityLink(); } + + /** + * Returns the certificate given in the InfoboxReadResponse + * @return + * @throws ParseException + */ + public X509Certificate parseCertificate() throws ParseException { + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.newDocument(); + + Element nameSpaceNode = doc.createElement("NameSpaceNode"); + nameSpaceNode.setAttribute("xmlns:" + Constants.PD_PREFIX, Constants.PD_NS_URI); + nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + nameSpaceNode.setAttribute("xmlns:" + Constants.SL12_PREFIX, Constants.SL12_NS_URI); + + Element base64ContentElement = (Element)XPathAPI.selectSingleNode(infoBoxElem_.getParentNode(), "//sl:Base64Content[1]", nameSpaceNode); + + if (base64ContentElement == null) { + throw new ParseException("parser.01", new Object[] { "Could not find Base64Content for X509Certificate."}); + } + + String base64Content = DOMUtils.getText(base64ContentElement); + + // Decode Base64 value to X509Certificate + byte[] content = Base64.decode(base64Content); + return new X509Certificate(content); + + } catch (ParserConfigurationException e) { + throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e); + } catch (TransformerException e) { + throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e); + } catch (CertificateException e) { + throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e); + } + + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index 0656d37d3..bff0a3fca 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -123,6 +123,7 @@ public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { * Logs all servlet parameters for debugging purposes. */ protected void logParameters(HttpServletRequest req) { + //@TODO Parameter? for (Enumeration params = req.getParameterNames(); params.hasMoreElements(); ) { String parname = (String)params.nextElement(); Logger.debug("Parameter " + parname + req.getParameter(parname)); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java new file mode 100644 index 000000000..0599c79bd --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -0,0 +1,287 @@ +package at.gv.egovernment.moa.id.auth.servlet;
+
+import iaik.pki.PKIException;
+import iaik.x509.X509Certificate;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.cert.CertificateEncodingException;
+import java.util.Map;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.axis.encoding.Base64;
+import org.apache.commons.fileupload.FileUploadException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Text;
+
+import at.gv.egovernment.moa.id.MOAIDException;
+import at.gv.egovernment.moa.id.ParseException;
+import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+import at.gv.egovernment.moa.id.auth.WrongParametersException;
+import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
+import at.gv.egovernment.moa.id.util.MOAIDMessageProvider;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.id.util.SSLUtils;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.URLEncoder;
+
+/**
+ * Servlet requested for getting the foreign eID
+ * provided by the security layer implementation.
+ * Utilizes the {@link AuthenticationServer}.
+ *
+ */
+public class GetForeignIDServlet extends AuthServlet {
+
+ /**
+ * Constructor for GetForeignIDServlet.
+ */
+ public GetForeignIDServlet() {
+ super();
+ }
+
+ /**
+ * GET requested by security layer implementation to verify
+ * that data URL resource is available.
+ * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
+ */
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+
+ Logger.debug("GET GetForeignIDServlet");
+
+
+ }
+
+ /**
+ * Verifies the identity link and responds with a new
+ * <code>CreateXMLSignatureRequest</code>.
+ * <br>
+ * Request parameters:
+ * <ul>
+ * <li>MOASessionID: ID of associated authentication session</li>
+ * <li>XMLResponse: <code><InfoboxReadResponse></code></li>
+ * </ul>
+ * Response:
+ * <ul>
+ * <li>Content type: <code>"text/xml"</code></li>
+ * <li>Content: see return value of {@link AuthenticationServer#verifyIdentityLink}</li>
+ * <li>Error status: <code>500</code>
+ * </ul>
+ * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
+ */
+ protected void doPost(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+
+ Logger.debug("POST GetForeignIDServlet");
+
+ Map parameters;
+ try
+ {
+ parameters = getParameters(req);
+ } catch (FileUploadException e)
+ {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
+ throw new IOException(e.getMessage());
+ }
+ String sessionID = req.getParameter(PARAM_SESSIONID);
+ String redirectURL = null;
+ X509Certificate cert = null;
+ AuthenticationSession session = null;
+ try {
+ // check parameter
+ if (!ParamValidatorUtils.isValidSessionID(sessionID))
+ throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12");
+
+ session = AuthenticationServer.getSession(sessionID);
+
+ cert = AuthenticationServer.getInstance().verifyXMLSignature(sessionID, parameters);
+
+// Element signature = AuthenticationServer.getInstance().getDsigElement
+// (sessionID, parameters);
+
+// if (signature == null) {
+ if (cert == null) {
+ handleError("Error retrieving signature from foreign eID card.", null, req, resp);
+ }
+ else {
+
+ // make SZR request
+ //Element samlAssertion = getIdentityLink(signature);
+ Element samlAssertion = getIdentityLink(cert);
+
+ IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(samlAssertion);
+ IdentityLink identitylink = ilParser.parseIdentityLink();
+ session.setIdentityLink(identitylink);
+
+ String samlArtifactBase64 =
+ AuthenticationServer.getInstance().getForeignAuthenticationData(sessionID);
+ if (!samlArtifactBase64.equals("Redirect to Input Processor")) {
+ redirectURL = session.getOAURLRequested();
+ if (!session.getBusinessService()) {
+ redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8"));
+ }
+ redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
+ redirectURL = resp.encodeRedirectURL(redirectURL);
+ } else {
+ redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID());
+ }
+ resp.setContentType("text/html");
+ resp.setStatus(302);
+ resp.addHeader("Location", redirectURL);
+ Logger.debug("REDIRECT TO: " + redirectURL);
+ }
+
+ }
+ catch (ParseException ex) {
+ handleError(null, ex, req, resp);
+ }
+ catch (MOAIDException ex) {
+ handleError(null, ex, req, resp);
+ }
+ catch (SZRGWClientException ex) {
+ handleError(null, ex, req, resp);
+ }
+ }
+
+ /**
+ * Adds a parameter to a URL.
+ * @param url the URL
+ * @param paramname parameter name
+ * @param paramvalue parameter value
+ * @return the URL with parameter added
+ */
+ private static String addURLParameter(String url, String paramname, String paramvalue) {
+ String param = paramname + "=" + paramvalue;
+ if (url.indexOf("?") < 0)
+ return url + "?" + param;
+ else
+ return url + "&" + param;
+ }
+
+ /**
+ * Does the request to the SZR-GW
+ * @param givenname
+ * @param familyname
+ * @param dateofbirth
+ * @return Identity link assertion
+ * @throws SZRGWClientException
+ */
+ /*private Element getIdentityLink(Element signature) throws SZRGWClientException {*/
+ private Element getIdentityLink(X509Certificate cert) throws SZRGWClientException {
+
+ SZRGWClient client = new SZRGWClient();
+
+ try {
+ AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance();
+ ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter();
+ //url = "http://localhost:8081/szr-gateway/services/IdentityLinkCreation";
+ Logger.debug("Connection Parameters: " + connectionParameters);
+ client.setAddress(connectionParameters.getUrl());
+ if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) {
+ Logger.debug("Initialisiere SSL Verbindung");
+ try {
+ client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters));
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (GeneralSecurityException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (PKIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")...");
+
+
+ }
+ catch (ConfigurationException e) {
+ Logger.warn(e);
+ Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null ));
+
+ }
+ // create request
+ Document doc = buildGetIdentityLinkRequest(cert);
+ Element request = doc.getDocumentElement();
+ CreateIdentityLinkResponse response = null;
+
+ //try {
+ response = client.createIdentityLinkResponse(request);
+ //} catch (SZRGWClientException e) {
+ // give him a second try - Nach dem Starten des Tomcat wird beim ersten Mal das Client-Zertifikat offenbar vom HTTPClient nicht mitgeschickt.
+ // client = new SZRGWClient(url);
+ // response = client.createIdentityLinkResponse(request);
+ // }
+
+
+ return response.getAssertion();
+
+ }
+
+ /**
+ * Builds the szrgw:GetIdentityLinkRequest für the SZR-GW
+ * @param givenname
+ * @param familyname
+ * @param birthday
+ * @return
+ */
+ private static Document buildGetIdentityLinkRequest(X509Certificate cert) {
+
+ try {
+ byte[] certbyte = cert.getEncoded();
+ String certstring = Base64.encode(certbyte);
+
+ DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document doc = builder.newDocument();
+
+ Element getIdentityLink = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:GetIdentityLinkRequest");
+ getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGWConstants.SZRGW_REQUEST_NS);
+ doc.appendChild(getIdentityLink);
+
+ Element x509certificate = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:X509Certificate");
+ getIdentityLink.appendChild(x509certificate);
+ Text certbase64 = doc.createTextNode(certstring);
+ x509certificate.appendChild(certbase64);
+
+ return doc;
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (CertificateEncodingException e) {
+ e.printStackTrace();
+ }
+ return null;
+
+ }
+
+ /**
+ * Checks a parameter.
+ * @param param parameter
+ * @return true if the parameter is null or empty
+ */
+ private boolean isEmpty(String param) {
+ return param == null || param.length() == 0;
+ }
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessValidatorInputServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessValidatorInputServlet.java index 894b05428..317af3e06 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessValidatorInputServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessValidatorInputServlet.java @@ -73,7 +73,7 @@ public class ProcessValidatorInputServlet extends AuthServlet { } catch (FileUploadException e) {
Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
throw new IOException(e.getMessage());
- }
+ } String sessionID = req.getParameter(PARAM_SESSIONID);
if (sessionID==null) sessionID = (String) req.getAttribute(PARAM_SESSIONID);
if (sessionID==null) sessionID = (String) parameters.get(PARAM_SESSIONID);
@@ -124,7 +124,8 @@ public class ProcessValidatorInputServlet extends AuthServlet { } catch (FileUploadException e) {
Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
throw new IOException(e.getMessage());
- }
+ } + //@TODO Parameter
String sessionID = req.getParameter(PARAM_SESSIONID);
if (sessionID==null) sessionID = (String) req.getAttribute(PARAM_SESSIONID);
if (sessionID==null) sessionID = (String) parameters.get(PARAM_SESSIONID);
@@ -142,13 +143,15 @@ public class ProcessValidatorInputServlet extends AuthServlet { String htmlForm = null;
boolean doInputProcessorSign = false; // If sign process should be within an extra form, provide a parameter. Otherwise transport through security layer is assumed
+ //@TODO Parameter String inputProcessorSignForm = req.getParameter("Sign_Form");
if (inputProcessorSignForm==null) inputProcessorSignForm = (String) req.getAttribute("Sign_Form");
if (inputProcessorSignForm==null) inputProcessorSignForm = (String) parameters.get("Sign_Form");
if (inputProcessorSignForm==null) inputProcessorSignForm = (String) parameters.get("Sign_Form_");
if (!ParepUtils.isEmpty(inputProcessorSignForm)) doInputProcessorSign = inputProcessorSignForm.equalsIgnoreCase("true");
if (doInputProcessorSign) {
- // Test if we have a user input form sign template
+ // Test if we have a user input form sign template + //@TODO Parameter
String inputProcessorSignTemplateURL = req.getParameter(PARAM_INPUT_PROCESSOR_SIGN_TEMPLATE);
String inputProcessorSignTemplate = null;
OAAuthParameter oaParam =
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SelectBKUServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SelectBKUServlet.java index 78c028767..09b3ae15f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SelectBKUServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SelectBKUServlet.java @@ -29,6 +29,7 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; import at.gv.egovernment.moa.id.auth.WrongParametersException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** @@ -74,6 +75,7 @@ public class SelectBKUServlet extends AuthServlet { authURL = authURL.concat(":" + req.getServerPort()); } authURL = authURL.concat(req.getContextPath() + "/"); + String target = req.getParameter(PARAM_TARGET); String oaURL = req.getParameter(PARAM_OA); String bkuSelectionTemplateURL = req.getParameter(PARAM_BKUTEMPLATE); @@ -84,6 +86,16 @@ public class SelectBKUServlet extends AuthServlet { resp.addHeader(HEADER_CACHE_CONTROL,HEADER_VALUE_CACHE_CONTROL_IE); try { + + // check parameter + if (!ParamValidatorUtils.isValidTarget(target)) + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); + if (!ParamValidatorUtils.isValidOA(oaURL)) + throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); + if (!ParamValidatorUtils.isValidTemplate(templateURL)) + throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); + + String returnValue = AuthenticationServer.getInstance().selectBKU( authURL, target, oaURL, bkuSelectionTemplateURL, templateURL); String bkuSelectionType = AuthConfigurationProvider.getInstance().getBKUSelectionType(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/StartAuthenticationServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/StartAuthenticationServlet.java index 961511ee7..8165f90f8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/StartAuthenticationServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/StartAuthenticationServlet.java @@ -28,6 +28,7 @@ import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; import at.gv.egovernment.moa.id.auth.WrongParametersException; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** @@ -61,18 +62,36 @@ public class StartAuthenticationServlet extends AuthServlet { authURL = authURL.concat(":" + req.getServerPort()); } authURL = authURL.concat(req.getContextPath() + "/"); - String target = req.getParameter(PARAM_TARGET); - String oaURL = req.getParameter(PARAM_OA); + + String target = req.getParameter(PARAM_TARGET); + String oaURL = req.getParameter(PARAM_OA); String bkuURL = req.getParameter(PARAM_BKU); String templateURL = req.getParameter(PARAM_TEMPLATE); String sessionID = req.getParameter(PARAM_SESSIONID); + resp.setHeader(HEADER_EXPIRES,HEADER_VALUE_EXPIRES); resp.setHeader(HEADER_PRAGMA,HEADER_VALUE_PRAGMA); resp.setHeader(HEADER_CACHE_CONTROL,HEADER_VALUE_CACHE_CONTROL); resp.addHeader(HEADER_CACHE_CONTROL,HEADER_VALUE_CACHE_CONTROL_IE); - try { + + + try { + // check parameter + if (!ParamValidatorUtils.isValidTarget(target)) + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); + if (!ParamValidatorUtils.isValidOA(oaURL)) + throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); + if (!ParamValidatorUtils.isValidBKUURI(bkuURL)) + throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12"); + if (!ParamValidatorUtils.isValidTemplate(templateURL)) + throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("StartAuthentication", PARAM_SESSIONID, "auth.12"); + + String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(authURL, target, oaURL, templateURL, bkuURL, sessionID, req.getScheme()); + resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = new PrintWriter(resp.getOutputStream()); out.print(getIdentityLinkForm); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java index 43947f6f0..824df9ca8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java @@ -16,9 +16,7 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; -import java.util.Iterator; import java.util.Map; -import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -28,11 +26,10 @@ import org.apache.commons.fileupload.FileUploadException; import at.gv.egovernment.moa.id.MOAIDException; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.WrongParametersException; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.data.InfoboxValidationResult; -import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; -import at.gv.egovernment.moa.id.auth.validator.ValidateException; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.URLEncoder; @@ -99,10 +96,16 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); throw new IOException(e.getMessage()); } + //@TODO Parameter String sessionID = req.getParameter(PARAM_SESSIONID); String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); String redirectURL = null; try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(sessionID, createXMLSignatureResponse); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java new file mode 100644 index 000000000..c9c1e794d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -0,0 +1,286 @@ +package at.gv.egovernment.moa.id.auth.servlet;
+
+import iaik.pki.PKIException;
+import iaik.x509.X509Certificate;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.cert.CertificateEncodingException;
+import java.util.Map;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.axis.encoding.Base64;
+import org.apache.commons.fileupload.FileUploadException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Text;
+
+import at.gv.egovernment.moa.id.MOAIDException;
+import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+import at.gv.egovernment.moa.id.auth.WrongParametersException;
+import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
+import at.gv.egovernment.moa.id.util.MOAIDMessageProvider;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.id.util.SSLUtils;
+import at.gv.egovernment.moa.id.util.ServletUtils;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * Servlet requested for getting the foreign eID
+ * provided by the security layer implementation.
+ * Utilizes the {@link AuthenticationServer}.
+ *
+ */
+public class VerifyCertificateServlet extends AuthServlet {
+
+ /**
+ * Constructor for VerifyCertificateServlet.
+ */
+ public VerifyCertificateServlet() {
+ super();
+ }
+
+ /**
+ * GET requested by security layer implementation to verify
+ * that data URL resource is available.
+ * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
+ */
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+
+ Logger.debug("GET VerifyCertificateServlet");
+
+
+ }
+
+ /**
+ * Gets the signer certificate from the InfoboxReadRequest and
+ * responds with a new
+ * <code>CreateXMLSignatureRequest</code>.
+ * <br>
+ * Request parameters:
+ * <ul>
+ * <li>MOASessionID: ID of associated authentication session</li>
+ * <li>XMLResponse: <code><InfoboxReadResponse></code></li>
+ * </ul>
+ * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
+ */
+ protected void doPost(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+
+ Logger.debug("POST VerifyCertificateServlet");
+
+ Map parameters;
+ try
+ {
+ parameters = getParameters(req);
+ } catch (FileUploadException e)
+ {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
+ throw new IOException(e.getMessage());
+ }
+ //@TODO Parameter
+ String sessionID = req.getParameter(PARAM_SESSIONID);
+ AuthenticationSession session = null;
+ try {
+ // check parameter
+ if (!ParamValidatorUtils.isValidSessionID(sessionID))
+ throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12");
+
+ session = AuthenticationServer.getSession(sessionID);
+
+ X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters);
+
+ System.out.println(cert);
+
+ String createXMLSignatureRequest = AuthenticationServer.getInstance().getCreateXMLSignatureRequestForeignID(sessionID, parameters, cert);
+
+ System.out.println(createXMLSignatureRequest);
+
+ // build dataurl (to the GetForeignIDSerlvet)
+ String dataurl =
+ new DataURLBuilder().buildDataURL(
+ session.getAuthURL(),
+ REQ_GET_FOREIGN_ID,
+ session.getSessionID());
+
+ ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl);
+
+
+// Logger.debug("Send CreateXMLSignatureRequest to BKU");
+// String keyboxIdentifier = "SecureSignatureKeypair";
+// //String keyboxIdentifier = "CertifiedKeypair";
+// String xmlContent = "<html xmlns=\"http://www.w3.org/1999/xhtml\"> " +
+// "<head><title>CreateXMLSignatureRequest</title>" +
+// "<style type=\"text/css\"/></head>" +
+// "<body>" +
+// "<p>I hereby request to access this e-government application by using my " +
+// "domestic electronic identity. </p>" +
+// "<p>I further affirm that I am not yet registered with the Austrian Central " +
+// "Residents Registry and that I am not obliged to register with the Austrian " +
+// "Central Residents Registry according to Austrian law.</p>" +
+// "<p>In the event I am not yet registered with the Supplementary Register, I " +
+// "explicitly grant to do so according to §6 (5) E-Government Act (EGovG, idF: " +
+// "BGBl. I Nr. 7/2008 und BGBl. I Nr. 59/2008).</p>" +
+// "</body></html>";
+//
+// // create the CreateXMLSignatureRequest
+// String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilderForeign().build(
+// keyboxIdentifier,
+// xmlContent);
+//
+// // build dataurl (to the GetForeignIDSerlvet)
+// String dataurl =
+// new DataURLBuilder().buildDataURL(
+// session.getAuthURL(),
+// REQ_GET_FOREIGN_ID,
+// session.getSessionID());
+//
+// ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl);
+//
+
+
+ }
+ catch (MOAIDException ex) {
+ handleError(null, ex, req, resp);
+ }
+ }
+
+ /**
+ * Adds a parameter to a URL.
+ * @param url the URL
+ * @param paramname parameter name
+ * @param paramvalue parameter value
+ * @return the URL with parameter added
+ */
+ private static String addURLParameter(String url, String paramname, String paramvalue) {
+ String param = paramname + "=" + paramvalue;
+ if (url.indexOf("?") < 0)
+ return url + "?" + param;
+ else
+ return url + "&" + param;
+ }
+
+ /**
+ * Does the request to the SZR-GW
+ * @param givenname
+ * @param familyname
+ * @param dateofbirth
+ * @return Identity link assertion
+ * @throws SZRGWClientException
+ */
+ /*private Element getIdentityLink(Element signature) throws SZRGWClientException {*/
+ private Element getIdentityLink(X509Certificate cert) throws SZRGWClientException {
+
+ SZRGWClient client = new SZRGWClient();
+
+ try {
+ AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance();
+ ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter();
+ //url = "http://localhost:8081/szr-gateway/services/IdentityLinkCreation";
+ Logger.debug("Connection Parameters: " + connectionParameters);
+ client.setAddress(connectionParameters.getUrl());
+ if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) {
+ Logger.debug("Initialisiere SSL Verbindung");
+ try {
+ client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters));
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (GeneralSecurityException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (PKIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")...");
+
+
+ }
+ catch (ConfigurationException e) {
+ Logger.warn(e);
+ Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null ));
+
+ }
+ // create request
+ Document doc = buildGetIdentityLinkRequest(cert);
+ Element request = doc.getDocumentElement();
+ CreateIdentityLinkResponse response = null;
+
+ //try {
+ response = client.createIdentityLinkResponse(request);
+ //} catch (SZRGWClientException e) {
+ // give him a second try - Nach dem Starten des Tomcat wird beim ersten Mal das Client-Zertifikat offenbar vom HTTPClient nicht mitgeschickt.
+ // client = new SZRGWClient(url);
+ // response = client.createIdentityLinkResponse(request);
+ // }
+
+
+ return response.getAssertion();
+
+ }
+
+ /**
+ * Builds the szrgw:GetIdentityLinkRequest für the SZR-GW
+ * @param givenname
+ * @param familyname
+ * @param birthday
+ * @return
+ */
+ private static Document buildGetIdentityLinkRequest(X509Certificate cert) {
+
+ try {
+ byte[] certbyte = cert.getEncoded();
+ String certstring = Base64.encode(certbyte);
+
+ DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document doc = builder.newDocument();
+
+ Element getIdentityLink = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:GetIdentityLinkRequest");
+ getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGWConstants.SZRGW_REQUEST_NS);
+ doc.appendChild(getIdentityLink);
+
+ Element x509certificate = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:X509Certificate");
+ getIdentityLink.appendChild(x509certificate);
+ Text certbase64 = doc.createTextNode(certstring);
+ x509certificate.appendChild(certbase64);
+
+ return doc;
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (CertificateEncodingException e) {
+ e.printStackTrace();
+ }
+ return null;
+
+ }
+
+ /**
+ * Checks a parameter.
+ * @param param parameter
+ * @return true if the parameter is null or empty
+ */
+ private boolean isEmpty(String param) {
+ return param == null || param.length() == 0;
+ }
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index 329749e96..4f98e85e2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -25,8 +25,13 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadException; import at.gv.egovernment.moa.id.MOAIDException; +import at.gv.egovernment.moa.id.ParseException; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.WrongParametersException; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; @@ -60,7 +65,8 @@ public class VerifyIdentityLinkServlet extends AuthServlet { /** * Verifies the identity link and responds with a new - * <code>CreateXMLSignatureRequest</code>. + * <code>CreateXMLSignatureRequest</code> or a new <code> + * InfoboxReadRequest</code> (in case of a foreign eID card). * <br> * Request parameters: * <ul> @@ -88,13 +94,56 @@ public class VerifyIdentityLinkServlet extends AuthServlet { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); throw new IOException(e.getMessage()); } + //@TODO Parameter String sessionID = req.getParameter(PARAM_SESSIONID); + + + try { - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(sessionID, parameters); - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(sessionID, parameters); + + if (createXMLSignatureRequestOrRedirect == null) { + + System.out.println("Send InfoboxReadRequest to BKU to get signer certificate."); + // no identity link found + try { + + Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); + + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the GetForeignIDSerlvet) + String dataurl = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate", dataurl); + + } + catch(Exception e) { + handleError(null, e, req, resp); + } + + } + else { + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); + } + + } + catch (ParseException ex) { + handleError(null, ex, req, resp); } + catch (MOAIDException ex) { handleError(null, ex, req, resp); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java index 99c49ca09..072b6c48f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java @@ -26,6 +26,7 @@ import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.data.SAMLAttribute; +import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.StringUtils; @@ -70,7 +71,7 @@ public class CreateXMLSignatureResponseValidator { * @throws ValidateException */ public void validate(CreateXMLSignatureResponse createXMLSignatureResponse, AuthenticationSession session) - throws ValidateException { + throws ValidateException { // A3.056: more then one /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:NameIdentifier @@ -123,57 +124,60 @@ public class CreateXMLSignatureResponseValidator { SAMLAttribute samlAttribute; if (session.getSAMLAttributeGebeORwbpk()) { - // check the first attribute ("Geschaeftsbereich" or "wbPK") - samlAttribute = samlAttributes[0]; - if (businessService) { - if (!samlAttribute.getName().equals("wbPK")) { - if (samlAttribute.getName().equals("Geschaeftsbereich")) { - throw new ValidateException("validator.26", null); - } else { - throw new ValidateException( - "validator.37", - new Object[] {samlAttribute.getName(), "wbPK", String.valueOf(1)}); - } - } - if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) { - foundWBPK = true; - try { - Element attrValue = (Element)samlAttribute.getValue(); - String value = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Value").item(0)).getFirstChild().getNodeValue(); - String type = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Type").item(0)).getFirstChild().getNodeValue(); - if (!value.equals(identityLink.getIdentificationValue())) { - throw new ValidateException("validator.28", null); - } - if (!type.equals(identityLink.getIdentificationType())) { - throw new ValidateException("validator.28", null); - } - } catch (Exception ex) { - throw new ValidateException("validator.29", null); - } - } else { - throw new ValidateException("validator.30", null); - } - } else { - if (!samlAttribute.getName().equals("Geschaeftsbereich")) { - if (samlAttribute.getName().equals("wbPK")) { - throw new ValidateException("validator.26", null); - } else { - throw new ValidateException( - "validator.37", - new Object[] {samlAttribute.getName(), "Geschaeftsbereich", String.valueOf(1)}); - } - } - if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) { - foundGB = true; - if (!gbTarget.equals((String)samlAttribute.getValue())) { - throw new ValidateException("validator.13", null); - } - } else { - throw new ValidateException("validator.12", null); - } - } + // check the first attribute ("Geschaeftsbereich" or "wbPK") + samlAttribute = samlAttributes[0]; + if (businessService) { + if (!samlAttribute.getName().equals("wbPK")) { + if (samlAttribute.getName().equals("Geschaeftsbereich")) { + throw new ValidateException("validator.26", null); + } else { + throw new ValidateException( + "validator.37", + new Object[] {samlAttribute.getName(), "wbPK", String.valueOf(1)}); + } + } + if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) { + foundWBPK = true; + try { + Element attrValue = (Element)samlAttribute.getValue(); + String value = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Value").item(0)).getFirstChild().getNodeValue(); + String type = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Type").item(0)).getFirstChild().getNodeValue(); + if (!value.equals(identityLink.getIdentificationValue())) { + throw new ValidateException("validator.28", null); + } + if (!type.equals(identityLink.getIdentificationType())) { + throw new ValidateException("validator.28", null); + } + } catch (Exception ex) { + throw new ValidateException("validator.29", null); + } + } else { + throw new ValidateException("validator.30", null); + } + } else { + if (!samlAttribute.getName().equals("Geschaeftsbereich")) { + if (samlAttribute.getName().equals("wbPK")) { + throw new ValidateException("validator.26", null); + } else { + throw new ValidateException( + "validator.37", + new Object[] {samlAttribute.getName(), "Geschaeftsbereich", String.valueOf(1)}); + } + } + if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) { + foundGB = true; + //BZ.. + gbTarget = gbTarget + " (" + TargetToSectorNameMapper.getSectorNameViaTarget(gbTarget) + ")"; + //..BZ + if (!gbTarget.equals((String)samlAttribute.getValue())) { + throw new ValidateException("validator.13", null); + } + } else { + throw new ValidateException("validator.12", null); + } + } } else { - offset--; + offset--; } // check the second attribute (must be "OA") @@ -234,11 +238,11 @@ public class CreateXMLSignatureResponseValidator { Object actualValue = samlAttribute.getValue(); try { if (expectedValue instanceof String) { - // replace \r\n because text might be base64-encoded - String expValue = StringUtils.replaceAll((String)expectedValue,"\r",""); - expValue = StringUtils.replaceAll(expValue,"\n",""); - String actValue = StringUtils.replaceAll((String)actualValue,"\r",""); - actValue = StringUtils.replaceAll(actValue,"\n",""); + // replace \r\n because text might be base64-encoded + String expValue = StringUtils.replaceAll((String)expectedValue,"\r",""); + expValue = StringUtils.replaceAll(expValue,"\n",""); + String actValue = StringUtils.replaceAll((String)actualValue,"\r",""); + actValue = StringUtils.replaceAll(actValue,"\n",""); if (!expValue.equals(actValue)) { throw new ValidateException( "validator.38", diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java new file mode 100644 index 000000000..6448f9392 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw;
+
+
+import org.apache.xpath.XPathAPI;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+
+/**
+ * This class implements a SZR-gateway GetIdentityLink Response.
+ *
+ */
+public class CreateIdentityLinkResponse {
+
+ private Element assertion;
+
+ public Element getAssertion() {
+ return assertion;
+ }
+
+ public void setAssertion(Element assertion) {
+ this.assertion = assertion;
+ }
+
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java index 6c367594b..0c84a9b18 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java @@ -16,20 +16,20 @@ package at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-
-import javax.net.ssl.SSLSocketFactory;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils;
-import at.gv.egovernment.moa.logging.Logger;
+import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.protocol.Protocol; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; +import at.gv.egovernment.moa.logging.Logger; /**
@@ -41,7 +41,6 @@ import at.gv.egovernment.moa.logging.Logger; * <li>Detailed Request</li>
* </ol>
*
- * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
*/
public class SZRGWClient {
/**
@@ -136,6 +135,110 @@ public class SZRGWClient { //e.printStackTrace();
throw new SZRGWClientException(e);
}
+ } + + /** + * Gets a identity link. + * + * @param reqElem the request. + * @return a SZR-gateway response containing the result + * @throws SZRGWException when an error occurs creating the mandate. + */ + public CreateIdentityLinkResponse createIdentityLinkResponse(Element reqElem) throws SZRGWClientException { + + Logger.info("Connecting to SZR-gateway."); + try { + if (address == null) { + throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); + } + HttpClient client = new HttpClient(); + PostMethod method = new PostMethod(address); + method.setRequestHeader("SOAPAction", ""); + + + // ssl settings + if (sSLSocketFactory != null) { + SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); + Protocol.registerProtocol("https", new Protocol("https", fac, 443)); + } + + // create soap body + Element soapBody = getSOAPBody(); + Document doc = soapBody.getOwnerDocument(); + soapBody.appendChild(doc.importNode(reqElem, true)); + Element requestElement = soapBody.getOwnerDocument().getDocumentElement(); + + //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml")); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ParepUtils.serializeElementAsDocument(requestElement, bos); + + method.setRequestBody(new ByteArrayInputStream(bos.toByteArray())); + client.executeMethod(method); + CreateIdentityLinkResponse response = new CreateIdentityLinkResponse(); + + bos = new ByteArrayOutputStream(); + doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream()); + + //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml")); + + //check if errorresponse + boolean isError = checkErrorResponse(doc.getDocumentElement()); + + if (isError) { + String error = getErrorCodeandMessage(doc.getDocumentElement()); + throw new SZRGWClientException(error); + } + else { + response.setAssertion(doc.getDocumentElement()); + } + + return response; + } catch(Exception e) { + e.printStackTrace(); + throw new SZRGWClientException(e); + } + + } + + /** + * Returns an errorstring containing errorcode and info from SZR-GW error response + * @param element + * @return + */ + private String getErrorCodeandMessage(Element element) { + String error = "Fehler im SZR-Gateway: "; + + String code = ""; + NodeList list = element.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorCode"); + for (int i = 0; i < list.getLength(); i++) { + Element elem = (Element)list.item(i); + code += elem.getTextContent() + "/"; + } + + String info = ""; + list = element.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "Info"); + for (int i = 0; i < list.getLength(); i++) { + Element elem = (Element)list.item(i); + info += elem.getTextContent() + "/"; + } + + error += code + " " + info; + return error; + } + + /** + * Checks if response from SZR-GW is errorresponse or not + * @param element + * @return + */ + private boolean checkErrorResponse(Element element) { + + NodeList list = element.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorResponse"); + + if (list.getLength() == 0) + return false; + else + return true; }
/*
|