diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java')
-rw-r--r-- | id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java | 1682 |
1 files changed, 870 insertions, 812 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index b79b99a65..908c7e7b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -22,47 +22,31 @@ */ package at.gv.egovernment.moa.id.auth.builder; -import iaik.x509.X509Certificate; - -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.security.PrivateKey; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeQuery; -import org.opensaml.saml2.core.AuthnStatement; import org.opensaml.saml2.core.Response; import org.opensaml.ws.soap.common.SOAPException; import org.opensaml.xml.XMLObject; -import org.opensaml.xml.security.SecurityException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.w3c.dom.Node; +import org.w3c.dom.NodeList; -import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; -import at.gv.e_government.reference.namespace.mandates._20040701_.Mandator; -import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; -import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType.Value; -import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType; -import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; -import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; @@ -70,40 +54,36 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.DynamicOABuildException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; -import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.data.Pair; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; @@ -111,38 +91,41 @@ import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.XPathUtils; import at.gv.util.client.szr.SZRClient; import at.gv.util.config.EgovUtilPropertiesConfiguration; -import at.gv.util.ex.EgovUtilException; import at.gv.util.wsdl.szr.SZRException; import at.gv.util.xsd.szr.PersonInfoType; +import iaik.x509.X509Certificate; /** * @author tlenz * */ +@Service("AuthenticationDataBuilder") public class AuthenticationDataBuilder extends MOAIDAuthConstants { - public static IAuthData buildAuthenticationData(IRequest protocolRequest, - AuthenticationSession session, List<Attribute> reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - - - String oaID = protocolRequest.getOAURL(); - if (oaID == null) { - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - } - - // check parameter - if (!ParamValidatorUtils.isValidOA(oaID)) - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired protected AuthConfiguration authConfig; + @Autowired private AttributQueryBuilder attributQueryBuilder; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + return buildAuthenticationData(pendingReq, session, pendingReq.getOnlineApplicationConfiguration()); + } + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session, IOAAuthParameters oaParam) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { AuthenticationData authdata = null; + //only needed for SAML1 legacy support try { - Object saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); + //check if SAML1 authentication module is in Classpath + Class<?> saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); - if (protocolRequest.getClass().isInstance(saml1Requst)) { - //request is SAML1 + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + //request is SAML1 --> invoke SAML1 protocol specific methods if (session.getExtendedSAMLAttributesOA() == null) { saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList<ExtendedSAMLAttribute>()); @@ -156,727 +139,700 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authdata = new AuthenticationData(); } - - + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { authdata = new AuthenticationData(); } - - //reuse some parameters if it is a reauthentication - OASessionStore activeOA = AuthenticationSessionStoreage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); + + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + //reuse authentication information in case of service-provider reauthentication if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); authdata.setNameID(activeOA.getUserNameID()); authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); - - //mark AttributeQuery as used - if ( protocolRequest instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) protocolRequest).getRequest() instanceof MOARequest && - ((PVPTargetConfiguration) protocolRequest).getRequest().getInboundMessage() instanceof AttributeQuery) { - try { - activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); - - } - } - } - - InterfederationSessionStore interfIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); - - IOAAuthParameters oaParam = null; - if (reqAttributes == null) { - //get OnlineApplication from MOA-ID-Auth configuration - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaID); - - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway - if (oaParam.isSTORKPVPGateway()) - oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, protocolRequest); - } else { - //build OnlineApplication dynamic from requested attributes - oaParam = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes, interfIDP); - } - if (interfIDP != null ) { - //IDP is a chained interfederated IDP and Authentication is requested - if (oaParam.isInderfederationIDP() && protocolRequest instanceof PVPTargetConfiguration && - !(((PVPTargetConfiguration)protocolRequest).getRequest() instanceof AttributeQuery)) { - //only set minimal response attributes - authdata.setQAALevel(interfIDP.getQAALevel()); - authdata.setBPK(interfIDP.getUserNameID()); - - } else { - //get attributes from interfederated IDP - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); - getAuthDataFromInterfederation(authdata, session, oaParam, protocolRequest, interfIDP, idp, reqAttributes); + //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + if (oaParam.isSTORKPVPGateway()) + oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - //mark attribute request as used - try { - interfIDP.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(interfIDP); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); - - } - } - + Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( + PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); + if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { + //only set minimal response attributes + authdata.setQAALevel( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); + authdata.setBPK( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); + } else { //build AuthenticationData from MOASession - buildAuthDataFormMOASession(authdata, session, oaParam, protocolRequest); - + buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + } return authdata; } /** - * @param req - * @param session - * @param reqAttributes - * @return - * @throws WrongParametersException - * @throws ConfigurationException - * @throws BuildException - * @throws DynamicOABuildException + * Get PVP authentication attributes by using a SAML2 AttributeQuery + * + * @param reqQueryAttr List of PVP attributes which are requested + * @param userNameID SAML2 UserNameID of the user for which attributes are requested + * @param idpConfig Configuration of the IDP, which is requested + * @return + * @return PVP attribute DAO, which contains all received information + * @throws MOAIDException */ - public static IAuthData buildAuthenticationData(IRequest req, - AuthenticationSession session) throws WrongParametersException, ConfigurationException, BuildException, DynamicOABuildException { - return buildAuthenticationData(req, session, null); - } - - /** - * @param authdata - * @param session - * @param oaParam - * @param protocolRequest - * @param interfIDP - * @param idp - * @param reqQueryAttr - * @throws ConfigurationException - */ - private static void getAuthDataFromInterfederation( - AuthenticationData authdata, AuthenticationSession session, - IOAAuthParameters oaParam, IRequest req, - InterfederationSessionStore interfIDP, OAAuthParameter idp, List<Attribute> reqQueryAttr) throws BuildException, ConfigurationException{ + public AssertionAttributeExtractor getAuthDataFromAttributeQuery(List<Attribute> reqQueryAttr, + String userNameID, IOAAuthParameters idpConfig ) throws MOAIDException{ + String idpEnityID = idpConfig.getPublicURLPrefix(); try { - List<Attribute> attributs = null; - - //IDP is a chained interfederated IDP and request is of type AttributQuery - if (oaParam.isInderfederationIDP() && req instanceof PVPTargetConfiguration && - (((PVPTargetConfiguration)req).getRequest() instanceof AttributeQuery) && - reqQueryAttr != null) { - attributs = reqQueryAttr; - - //IDP is a service provider IDP and request interfederated IDP to collect attributes - } else { - //get PVP 2.1 attributes from protocol specific requested attributes - attributs = req.getRequestedAttributes(); + Logger.debug("Starting AttributeQuery process ..."); + //collect attributes by using BackChannel communication + String endpoint = idpConfig.getIDPAttributQueryServiceURL(); + if (MiscUtil.isEmpty(endpoint)) { + Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); + throw new ConfigurationException("config.26", new Object[]{idpEnityID}); } - - Response intfResp = (Response) req.getInterfederationResponse().getResponse(); - AssertionAttributeExtractor extractor = - new AssertionAttributeExtractor(intfResp); - - if (!extractor.containsAllRequiredAttributes()) { - Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); - //collect attributes by using BackChannel communication - String endpoint = idp.getIDPAttributQueryServiceURL(); - if (MiscUtil.isEmpty(endpoint)) { - Logger.error("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix()); - throw new ConfigurationException("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix(), null); - } - //build attributQuery request - AttributeQuery query = - AttributQueryBuilder.buildAttributQueryRequest(interfIDP.getUserNameID(), endpoint, attributs); + //build attributQuery request + AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(userNameID, endpoint, reqQueryAttr); - //build SOAP request - List<XMLObject> xmlObjects = MOASAMLSOAPClient.send(endpoint, query); + //build SOAP request + List<XMLObject> xmlObjects = MOASAMLSOAPClient.send(endpoint, query); + + if (xmlObjects.size() == 0) { + Logger.error("Receive emptry AttributeQuery response-body."); + throw new AttributQueryException("auth.27", + new Object[]{idpEnityID, "Receive emptry AttributeQuery response-body."}); - if (xmlObjects.size() == 0) { - Logger.error("Receive emptry AttributeQuery response-body."); - throw new AttributQueryException("Receive emptry AttributeQuery response-body.", null); - - } + } + + Response intfResp; + if (xmlObjects.get(0) instanceof Response) { + intfResp = (Response) xmlObjects.get(0); - if (xmlObjects.get(0) instanceof Response) { - intfResp = (Response) xmlObjects.get(0); - - //validate PVP 2.1 response - try { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifyResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); - - SAMLVerificationEngine.validateAssertion(intfResp, false); - - } catch (Exception e) { - Logger.warn("PVP 2.1 assertion validation FAILED.", e); - throw new AssertionValidationExeption("PVP 2.1 assertion validation FAILED.", null, e); - } - - } else { - Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); - throw new AttributQueryException("Receive AttributeQuery response-body include no PVP 2.1 response.", null); - + //validate PVP 2.1 response + try { + samlVerificationEngine.verifyIDPResponse(intfResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine( + MOAMetadataProvider.getInstance())); + + //create assertion attribute extractor from AttributeQuery response + return new AssertionAttributeExtractor(intfResp); + + } catch (Exception e) { + Logger.warn("PVP 2.1 assertion validation FAILED.", e); + throw new AssertionValidationExeption("auth.27", + new Object[]{idpEnityID, e.getMessage()}, e); } - - //create assertion attribute extractor from AttributeQuery response - extractor = new AssertionAttributeExtractor(intfResp); - + } else { - Logger.info("Interfedation response include all attributes with are required. Skip AttributQuery request step. "); - - } - //parse response information to authData - buildAuthDataFormInterfederationResponse(authdata, session, extractor, oaParam, req); + Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); + throw new AttributQueryException("auth.27", + new Object[]{idpEnityID, "Receive AttributeQuery response-body include no PVP 2.1 response"}); + } + } catch (SOAPException e) { throw new BuildException("builder.06", null, e); } catch (SecurityException e) { throw new BuildException("builder.06", null, e); - - } catch (AttributQueryException e) { - throw new BuildException("builder.06", null, e); - - } catch (BuildException e) { - throw new BuildException("builder.06", null, e); - - } catch (AssertionValidationExeption e) { - throw new BuildException("builder.06", null, e); - - } catch (AssertionAttributeExtractorExeption e) { - throw new BuildException("builder.06", null, e); + + } catch (org.opensaml.xml.security.SecurityException e1) { + throw new BuildException("builder.06", null, e1); } } - - private static void buildAuthDataFormInterfederationResponse( - AuthenticationData authData, - AuthenticationSession session, - AssertionAttributeExtractor extractor, - IOAAuthParameters oaParam, - IRequest req) - throws BuildException, AssertionAttributeExtractorExeption { - - Logger.debug("Build AuthData from assertion starts ...."); - authData.setIsBusinessService(oaParam.getBusinessService()); + private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, + IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { + + Collection<String> includedToGenericAuthData = null; + if (session.getGenericSessionDataStorage() != null && + !session.getGenericSessionDataStorage().isEmpty()) + includedToGenericAuthData = session.getGenericSessionDataStorage().keySet(); + else + includedToGenericAuthData = new ArrayList<String>(); - authData.setFamilyName(extractor.getSingleAttributeValue(PVPConstants.PRINCIPAL_NAME_NAME)); - authData.setGivenName(extractor.getSingleAttributeValue(PVPConstants.GIVEN_NAME_NAME)); - authData.setDateOfBirth(extractor.getSingleAttributeValue(PVPConstants.BIRTHDATE_NAME)); - authData.setCcc(extractor.getSingleAttributeValue(PVPConstants.EID_ISSUING_NATION_NAME)); - authData.setBkuURL(extractor.getSingleAttributeValue(PVPConstants.EID_CCS_URL_NAME)); - authData.setIdentificationValue(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_NAME)); - authData.setIdentificationType(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_TYPE_NAME)); + try { + //#################################################### + //set general authData info's + authData.setIssuer(protocolRequest.getAuthURL()); + authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); + authData.setIsBusinessService(oaParam.getBusinessService()); - if (extractor.containsAttribute(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - String bpkType = extractor.getSingleAttributeValue(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME); - if (bpkType.startsWith(Constants.URN_PREFIX_CDID) && - !bpkType.substring(Constants.URN_PREFIX_CDID.length(), - Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { - Logger.warn("Receive uncorrect encoded bBKType attribute " + bpkType + " Starting attribute value correction ... "); - bpkType = Constants.URN_PREFIX_CDID + "+" + bpkType.substring(Constants.URN_PREFIX_CDID.length() + 1); - - } - - authData.setBPKType(bpkType); - } - - if (extractor.containsAttribute(PVPConstants.BPK_NAME)) { - String pvpbPK = extractor.getSingleAttributeValue(PVPConstants.BPK_NAME); + //#################################################### + //parse user info's from identityLink + IdentityLink idlFromPVPAttr = null; + IdentityLink identityLink = session.getIdentityLink(); + if (identityLink != null) { + parseBasicUserInfosFromIDL(authData, identityLink, includedToGenericAuthData); - if (pvpbPK.startsWith("bPK:")) { - Logger.warn("Attribute " + PVPConstants.BPK_NAME - + " contains a not standardize prefix! Staring attribute value correction process ..."); - pvpbPK = pvpbPK.substring("bPK:".length()); + } else { + // identityLink is not direct in MOASession + String pvpAttrIDL = session.getGenericDataFromSession(PVPConstants.EID_IDENTITY_LINK_NAME, String.class); + //find PVP-Attr. which contains the IdentityLink + if (MiscUtil.isNotEmpty(pvpAttrIDL)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME + + " --> Parse basic user info's from that attribute."); + InputStream idlStream = null; + try { + idlStream = Base64Utils.decodeToStream(pvpAttrIDL, false); + idlFromPVPAttr = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); + parseBasicUserInfosFromIDL(authData, idlFromPVPAttr, includedToGenericAuthData); + + } catch (ParseException e) { + Logger.error("Received IdentityLink is not valid", e); + + } catch (Exception e) { + Logger.error("Received IdentityLink is not valid", e); + + } finally { + try { + includedToGenericAuthData.remove(PVPConstants.EID_IDENTITY_LINK_NAME); + if (idlStream != null) + idlStream.close(); + + } catch (IOException e) { + Logger.fatal("Close InputStream FAILED.", e); + + } + + } + + } + //if no basic user info's are set yet, parse info's single PVP-Attributes + if (MiscUtil.isEmpty(authData.getFamilyName())) { + Logger.debug("No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); + authData.setFamilyName(session.getGenericDataFromSession(PVPConstants.PRINCIPAL_NAME_NAME, String.class)); + authData.setGivenName(session.getGenericDataFromSession(PVPConstants.GIVEN_NAME_NAME, String.class)); + authData.setDateOfBirth(session.getGenericDataFromSession(PVPConstants.BIRTHDATE_NAME, String.class)); + authData.setIdentificationValue(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_NAME, String.class)); + authData.setIdentificationType(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_TYPE_NAME, String.class)); + + //remove corresponding keys from genericSessionData if exists + includedToGenericAuthData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); + } + } - String[] spitted = pvpbPK.split(":"); - authData.setBPK(spitted[1]); - if (MiscUtil.isEmpty(authData.getBPKType())) { - Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + - "Starting target extraction from bPK/wbPK prefix ..."); - //exract bPK/wbPK type from bpk attribute value prefix if type is - //not transmitted as single attribute - Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); - Matcher matcher = pattern.matcher(spitted[0]); - if (matcher.matches()) { - //find public service bPK - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); - Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); - - } else { - //find business service wbPK - authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); - Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); - - } - } - } - - boolean foundEncryptedbPKForOA = false; - if (extractor.containsAttribute(PVPConstants.ENC_BPK_LIST_NAME)) { - List<String> encbPKList = Arrays.asList( - extractor.getSingleAttributeValue(PVPConstants.ENC_BPK_LIST_NAME).split(";")); - authData.setEncbPKList(encbPKList); - for (String fullEncbPK : encbPKList) { - int index = fullEncbPK.indexOf("|"); - if (index >= 0) { - String encbPK = fullEncbPK.substring(index+1); - String second = fullEncbPK.substring(0, index); - int secIndex = second.indexOf("+"); - if (secIndex >= 0) { - if (oaParam.getTarget().equals(second.substring(secIndex+1))) { - Logger.debug("Found encrypted bPK for online-application " - + oaParam.getPublicURLPrefix() - + " Start decryption process ..."); - PrivateKey privKey = oaParam.getBPKDecBpkDecryptionKey(); - foundEncryptedbPKForOA = true; - if (privKey != null) { - try { - String bPK = BPKBuilder.decryptBPK(encbPK, oaParam.getTarget(), privKey); - if (MiscUtil.isNotEmpty(bPK)) { - if (MiscUtil.isEmpty(authData.getBPK())) { - authData.setBPK(bPK); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); - Logger.info("bPK decryption process finished successfully."); - } - - } else { - Logger.error("bPK decryption FAILED."); - - } - } catch (BuildException e) { - Logger.error("bPK decryption FAILED.", e); - - } - - } else { - Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + if (authData.getIdentificationType() != null && + !authData.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + Logger.trace("IdentificationType is not a baseID --> clear it. "); + authData.setBPK(authData.getIdentificationValue()); + authData.setBPKType(authData.getIdentificationType()); + + authData.setIdentificationValue(null); + authData.setIdentificationType(null); - } - - } else { - Logger.info("Found encrypted bPK but " + - "encrypted bPK target does not match to online-application target"); - - } - } - } - } - } - - if (MiscUtil.isEmpty(authData.getIdentificationValue()) && - MiscUtil.isEmpty(authData.getBPK()) && - !foundEncryptedbPKForOA) { - Logger.info("Federated assertion include no bPK, encrypted bPK or baseID"); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME - + " or " + PVPConstants.ENC_BPK_LIST_NAME); + } - } - - //check if received bPK matchs to online application configuration - //and no encrypted bPK is found for this oa - if (!matchsReceivedbPKToOnlineApplication(oaParam, authData) - && !foundEncryptedbPKForOA) { - Logger.info("Received bPK/wbPK does not match to online application"); - if (MiscUtil.isEmpty(authData.getIdentificationValue())) { - Logger.info("No baseID found. Connect SZR to reveive baseID ..."); - try { - EgovUtilPropertiesConfiguration eGovClientsConfig = AuthConfigurationProviderFactory.getInstance().geteGovUtilsConfig(); - if (eGovClientsConfig != null) { - SZRClient szrclient = new SZRClient(eGovClientsConfig); - - Logger.debug("Create SZR request to get baseID ... "); - PersonInfoType personInfo = new PersonInfoType(); - at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); - personInfo.setPerson(person); - at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); - person.setName(name); - at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); - person.setIdentification(idValue); + //#################################################### + //set BKU URL + includedToGenericAuthData.remove(PVPConstants.EID_CCS_URL_NAME); + if (MiscUtil.isNotEmpty(session.getBkuURL())) + authData.setBkuURL(session.getBkuURL()); + else + authData.setBkuURL(session.getGenericDataFromSession(PVPConstants.EID_CCS_URL_NAME, String.class)); - //set bPK or wbPK - idValue.setValue(authData.getBPK()); - idValue.setType(authData.getBPKType()); + + //#################################################### + //set QAA level + includedToGenericAuthData.remove(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME); + if (MiscUtil.isNotEmpty(session.getQAALevel())) + authData.setQAALevel(session.getQAALevel()); + + else { + String qaaLevel = session.getGenericDataFromSession(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, String.class); + if (MiscUtil.isNotEmpty(qaaLevel)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME + + " --> Parse QAA-Level from that attribute."); - //set person information - name.setGivenName(authData.getGivenName()); - name.setFamilyName(authData.getFamilyName()); - if (authData.getDateOfBirth() != null) - person.setDateOfBirth(authData.getFormatedDateOfBirth()); + if (qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { + authData.setQAALevel(qaaLevel); - //request szr and store baseID - authData.setIdentificationValue(szrclient.getStammzahl(personInfo)); - authData.setIdentificationType(Constants.URN_PREFIX_BASEID); - } else { - Logger.warn("No SZR clieht configuration found. Interfederation SSO login not possible."); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - + Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); + String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); + if (MiscUtil.isNotEmpty(mappedQAA)) + authData.setQAALevel(mappedQAA); + } - - } catch (ConfigurationException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - - } catch (EgovUtilException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - - } catch (SZRException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - } } - //build OA specific bPK/wbPK information - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); + //if no QAA level is set in MOASession then set default QAA level + if (MiscUtil.isEmpty(authData.getQAALevel())) { + Logger.info("No QAA level found. Set to default level " + PVPConstants.STORK_QAA_PREFIX + "1"); + authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + + } + - } - - if (MiscUtil.isEmpty(authData.getBPK())) { - Logger.debug("Calcutlate bPK from baseID"); - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); + //#################################################### + //set signer certificate + includedToGenericAuthData.remove(PVPConstants.EID_SIGNER_CERTIFICATE_NAME); + if (session.getEncodedSignerCertificate() != null) + authData.setSignerCertificate(session.getEncodedSignerCertificate()); - } - - - try { - String qaaLevel = extractor.getQAALevel(); - if (MiscUtil.isNotEmpty(qaaLevel) && - qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { - authData.setQAALevel(qaaLevel); + else { + String pvpAttrSignerCert = session.getGenericDataFromSession(PVPConstants.EID_SIGNER_CERTIFICATE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrSignerCert)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SIGNER_CERTIFICATE_FRIENDLY_NAME); + try { + authData.setSignerCertificate(Base64Utils.decode(pvpAttrSignerCert, false)); + + } catch (IOException e) { + Logger.error("SignerCertificate received via federated IDP is NOT valid", e); + + } + } else + Logger.info("NO SignerCertificate in MOASession."); + + } + + + //#################################################### + //set authBlock + includedToGenericAuthData.remove(PVPConstants.EID_AUTH_BLOCK_NAME); + if (MiscUtil.isNotEmpty(session.getAuthBlock())) { + authData.setAuthBlock(session.getAuthBlock()); } else { - Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); - String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - authData.setQAALevel(mappedQAA); + String pvpAttrAuthBlock = session.getGenericDataFromSession(PVPConstants.EID_AUTH_BLOCK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrAuthBlock)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_AUTH_BLOCK_FRIENDLY_NAME); + try { + byte[] authBlock = Base64Utils.decode(pvpAttrAuthBlock, false); + authData.setAuthBlock(new String(authBlock, "UTF-8")); + + } catch (IOException e) { + Logger.error("AuthBlock received via federated IDP is NOT valid", e); + + } + + } else + Logger.info("NO AuthBlock in MOASession."); - else - throw new AssertionAttributeExtractorExeption("PVP SecClass not mappable"); + } + + + //#################################################### + //set isForeigner flag + //TODO: change to new eIDAS-token attribute identifier + if (session.getGenericDataFromSession(PVPConstants.EID_STORK_TOKEN_NAME) != null) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME + + " --> Set 'isForeigner' flag to TRUE"); + authData.setForeigner(true); + + } else { + authData.setForeigner(session.isForeigner()); } - - } catch (AssertionAttributeExtractorExeption e) { - Logger.warn("No QAA level found in <RequestedAuthnContext> element of interfederated assertion. " + - "(ErrorHeader=" + e.getMessage() + ")"); - if (extractor.containsAttribute(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)) { - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + - extractor.getSingleAttributeValue(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)); - } else { - Logger.info("No QAA level found. Set to default level " + - PVPConstants.STORK_QAA_PREFIX + "1"); - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + + //#################################################### + //set citizen country-code + includedToGenericAuthData.remove(PVPConstants.EID_ISSUING_NATION_NAME); + String pvpCCCAttr = session.getGenericDataFromSession(PVPConstants.EID_ISSUING_NATION_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpCCCAttr)) { + authData.setCcc(pvpCCCAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME); + } else { + if (authData.isForeigner()) { + try { + if (authData.getSignerCertificate() != null) { + //TODO: replace with TSL lookup when TSL is ready! + X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); + if (certificate != null) { + LdapName ln = new LdapName(certificate.getIssuerDN() + .getName()); + for (Rdn rdn : ln.getRdns()) { + if (rdn.getType().equalsIgnoreCase("C")) { + Logger.info("C is: " + rdn.getValue()); + authData.setCcc(rdn.getValue().toString()); + break; + } + } + } + + } else + Logger.warn("NO PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_NAME + + " and NO SignerCertificate in MOASession -->" + + " Can NOT extract citizen-country of foreign person."); + + + } catch (Exception e) { + Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); + + } + + } else { + authData.setCcc(COUNTRYCODE_AUSTRIA); + + } } - - } - - if (extractor.containsAttribute(PVPConstants.EID_AUTH_BLOCK_NAME)) { - try { - byte[] authBlock = Base64Utils.decode(extractor.getSingleAttributeValue(PVPConstants.EID_AUTH_BLOCK_NAME), false); - authData.setAuthBlock(new String(authBlock, "UTF-8")); - } catch (IOException e) { - Logger.error("Received AuthBlock is not valid", e); + + //#################################################### + //set max. SSO session time + includedToGenericAuthData.remove(AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO); + Date validToFromFederatedIDP = session.getGenericDataFromSession( + AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO, Date.class); + if (validToFromFederatedIDP != null) { + authData.setSsoSessionValidTo(validToFromFederatedIDP); + Logger.debug("Use idToken validTo periode from federated IDP response."); + } else { + if (authData.isSsoSession()) { + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; + Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); + authData.setSsoSessionValidTo(ssoSessionValidTo); + + } else { + //set valid to 5 min + Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); + authData.setSsoSessionValidTo(ssoSessionValidTo); + + } } - } - - if (extractor.containsAttribute(PVPConstants.EID_SIGNER_CERTIFICATE_NAME)) { - try { - authData.setSignerCertificate(Base64Utils.decode( - extractor.getSingleAttributeValue(PVPConstants.EID_SIGNER_CERTIFICATE_NAME), false)); + + //mandate functionality + MISMandate misMandate = null; + if (session.isMandateUsed()) { + //#################################################### + //set Mandate reference value + includedToGenericAuthData.remove(PVPConstants.MANDATE_REFERENCE_VALUE_NAME); + if (MiscUtil.isNotEmpty(session.getMandateReferenceValue())) + authData.setMandateReferenceValue(session.getMandateReferenceValue()); - } catch (IOException e) { - Logger.error("Received SignerCertificate is not valid", e); + else { + String pvpMandateRefAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_REFERENCE_VALUE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpMandateRefAttr)) { + authData.setMandateReferenceValue(pvpMandateRefAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME); + } + } - } - } - if (extractor.containsAttribute(PVPConstants.EID_IDENTITY_LINK_NAME)) { - try { - InputStream idlStream = Base64Utils.decodeToStream(extractor.getSingleAttributeValue(PVPConstants.EID_IDENTITY_LINK_NAME), false); - IdentityLink idl = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); - idlStream.close(); - buildOAspecificIdentityLink(oaParam, authData, idl); - - } catch (ParseException e) { - Logger.error("Received IdentityLink is not valid", e); + /* TODO: Support SSO Mandate MODE! + * Insert functionality to translate mandates in case of SSO + */ - } catch (Exception e) { - Logger.error("Received IdentityLink is not valid", e); + //#################################################### + //set Full-mandate + misMandate = session.getMISMandate(); + if (misMandate != null ) { + //set MIS mandate to authdata + authData.setMISMandate(misMandate); + authData.setUseMandate(session.isMandateUsed()); + + } else { + String pvpFullMandateAttr = session.getGenericDataFromSession( + PVPConstants.MANDATE_FULL_MANDATE_NAME, String.class); + //check if full-mandate is available as PVP attribute + if (MiscUtil.isNotEmpty(pvpFullMandateAttr)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_FULL_MANDATE_FRIENDLY_NAME); + try { + byte[] mandate = Base64Utils.decode(pvpFullMandateAttr, false); + misMandate = new MISMandate(); + misMandate.setMandate(mandate); + + //read Organwalter OID + String pvpRepOIDAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_PROF_REP_OID_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpRepOIDAttr)) { + misMandate.setProfRep(pvpRepOIDAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_PROF_REP_OID_NAME); + + } + + //read Organwalter bPK from full-mandate + NodeList mandateElements = misMandate.getMandateDOM().getChildNodes(); + for (int i=0; i<mandateElements.getLength(); i++) { + Element mandateEl = (Element) mandateElements.item(i); + if (mandateEl.hasAttribute("OWbPK")) { + misMandate.setOWbPK(mandateEl.getAttribute("OWbPK")); + session.setOW(true); + + } + } + + authData.setMISMandate(misMandate); + authData.setUseMandate(true); + + } catch (IOException e) { + Logger.error("Base64 decoding of PVP-Attr:"+ PVPConstants.MANDATE_FULL_MANDATE_FRIENDLY_NAME + + " FAILED.", e); + + } + + } else { + Logger.debug("No full MIS-Mandate found --> Use single PVP attributes for mandate information."); + //check if ELGA mandates exists + String mandateType = session.getGenericDataFromSession(PVPConstants.MANDATE_TYPE_NAME, String.class); + if (MiscUtil.isNotEmpty(mandateType)) { + //switch to mandate-mode for authdata generation, because mandate-information + // is directly included in MOA-Session as PVP attributes + Logger.info("AuthDataBuilder find directly included 'MandateType' PVP-attribute." + + " --> Switch to mandate-mode for authdata generation."); + authData.setUseMandate(true); + + } + } + } + //remove PVP attributes with mandate information, because full-mandate exists + if (authData.getMISMandate() != null) { + includedToGenericAuthData.remove(PVPConstants.MANDATE_FULL_MANDATE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BPK_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_DESC_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_OID_NAME); + } } - } - // set mandate attributes - authData.setMandateReferenceValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_REFERENCE_VALUE_NAME)); - - if (extractor.containsAttribute(PVPConstants.MANDATE_FULL_MANDATE_NAME)) { - try { - byte[] mandate = Base64Utils.decode( - (extractor.getSingleAttributeValue(PVPConstants.MANDATE_FULL_MANDATE_NAME)), false); + + + + //#################################################### + // set bPK and IdentityLink for Organwalter --> + // Organwalter has a special bPK is received from MIS + if (authData.isUseMandate() && session.isOW() && misMandate != null + && MiscUtil.isNotEmpty(misMandate.getOWbPK())) { + //TODO: if full-mandate is removed in OPB --> OWbPK functionality needs an update!!! + authData.setBPK(misMandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + Logger.trace("Authenticated User is OW: " + misMandate.getOWbPK()); - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setMandate(mandate); - authData.getMISMandate().setFullMandateIncluded(true); - authData.setUseMandate(true); - - } catch (Exception e) { - Logger.error("Received Mandate is not valid", e); - throw new AssertionAttributeExtractorExeption(PVPConstants.MANDATE_FULL_MANDATE_NAME); - } - } - - //TODO: build short mandate if full mandate is no included. - if (authData.getMISMandate() == null && - (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME)) ) { - Logger.info("Federated assertion contains no full mandate. Start short mandate generation process ... "); - - MISMandate misMandate = new MISMandate(); - misMandate.setFullMandateIncluded(false); - - Mandate mandateObject = new Mandate(); - Mandator mandator = new Mandator(); - mandateObject.setMandator(mandator); + //TODO: check in case of mandates for business services + if (identityLink != null) + authData.setIdentityLink(identityLink); - //build legal person short mandate - if (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)) { - Logger.debug("Build short mandate for legal person ..."); - CorporateBodyType legalperson = new CorporateBodyType(); - IdentificationType legalID = new IdentificationType(); - Value idvalue = new Value(); - legalID.setValue(idvalue ); - legalperson.getIdentification().add(legalID ); - mandator.setCorporateBody(legalperson ); - - legalperson.setFullName(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME)); - legalID.setType(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)); - idvalue.setValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME)); - - //build natural person short mandate - } else if ( (extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME) || - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME)) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME)) { - Logger.debug("Build short mandate for natural person ..."); - PhysicalPersonType physPerson = new PhysicalPersonType(); - PersonNameType persName = new PersonNameType(); - mandator.setPhysicalPerson(physPerson ); - physPerson.setName(persName ); - FamilyName familyName = new FamilyName(); - persName.getFamilyName().add(familyName ); - IdentificationType persID = new IdentificationType(); - physPerson.getIdentification().add(persID ); - Value idValue = new Value(); - persID.setValue(idValue ); - - String[] pvp2GivenName = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME).split(" "); - for(int i=0; i<pvp2GivenName.length; i++) - persName.getGivenName().add(pvp2GivenName[i]); - familyName.setValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME)); - physPerson.setDateOfBirth(extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME)); + else if (idlFromPVPAttr != null){ + authData.setIdentityLink(idlFromPVPAttr); + Logger.debug("Set IdentityLink received from federated IDP for Organwalter"); + + } else + Logger.info("Can NOT set Organwalter IdentityLink. Msg: No IdentityLink found"); + - if (extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME)) { - persID.setType(Constants.URN_PREFIX_BASEID); - idValue.setValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME)); + //set bPK and IdenityLink for all other + } else { + //build bPK + String pvpbPKValue = getbPKValueFromPVPAttribute(session); + String pvpbPKTypeAttr = getbPKTypeFromPVPAttribute(session); + Pair<String, String> pvpEncbPKAttr = getEncryptedbPKFromPVPAttribute(session, authData, oaParam); + + //check if a unique ID for this citizen exists + if (MiscUtil.isEmpty(authData.getIdentificationValue()) && + MiscUtil.isEmpty(pvpbPKValue) && MiscUtil.isEmpty(authData.getBPK()) && + pvpEncbPKAttr == null) { + Logger.info("Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); + + } + + // baseID is in MOASesson --> calculate bPK directly + if (MiscUtil.isNotEmpty(authData.getIdentificationValue())) { + Logger.debug("Citizen baseID is in MOASession --> calculate bPK from this."); + Pair<String, String> result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); + + //check if bPK already added to AuthData matches OA + } else if (MiscUtil.isNotEmpty(authData.getBPK()) + && matchsReceivedbPKToOnlineApplication(oaParam, authData.getBPKType()) ) { + Logger.debug("Correct bPK is already included in AuthData."); + + //check if bPK received by PVP-Attribute matches OA + } else if (MiscUtil.isNotEmpty(pvpbPKValue) && + matchsReceivedbPKToOnlineApplication(oaParam, pvpbPKTypeAttr)) { + Logger.debug("Receive correct bPK from PVP-Attribute"); + authData.setBPK(pvpbPKValue); + authData.setBPKType(pvpbPKTypeAttr); + //check if decrypted bPK exists + } else if (pvpEncbPKAttr != null) { + Logger.debug("Receive bPK as encrypted bPK and decryption was possible."); + authData.setBPK(pvpEncbPKAttr.getFirst()); + authData.setBPKType(pvpEncbPKAttr.getSecond()); + + //ask SZR to get bPK } else { - String[] pvp2bPK = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME).split(":"); - if (pvp2bPK.length == 2) { - idValue.setValue(pvp2bPK[1]); + String notValidbPK = authData.getBPK(); + String notValidbPKType = authData.getBPKType(); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + notValidbPK = pvpbPKValue; + notValidbPKType = pvpbPKTypeAttr; - Pattern pattern = Pattern.compile(MOAIDAuthConstants.REGEX_PATTERN_TARGET); - Matcher matcher = pattern.matcher(pvp2bPK[0]); - if (matcher.matches()) - persID.setType(Constants.URN_PREFIX_CDID + "+" + pvp2bPK[0]); - else - persID.setType(Constants.URN_PREFIX_WBPK + "+" + pvp2bPK[0]); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + Logger.fatal("No bPK in MOASession. THIS error should not occur any more."); + throw new NullPointerException("No bPK in MOASession. THIS error should not occur any more."); + } + } + + Pair<String, String> baseIDFromSZR = getbaseIDFromSZR(authData, notValidbPK, notValidbPKType); + if (baseIDFromSZR != null) { + Logger.info("Receive citizen baseID from SRZ. Authentication can be completed"); + authData.setIdentificationValue(baseIDFromSZR.getFirst()); + authData.setIdentificationType(baseIDFromSZR.getSecond()); + Pair<String, String> result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); } else { - Logger.warn("Receive mandator bPK from federation with an unsupported format. " + extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME)); - throw new AssertionAttributeExtractorExeption("Receive mandator bPK from federation with an unsupported format."); + Logger.warn("Can not build authData, because moaSession include no valid bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No valid " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); } } - - } else { - Logger.error("Short mandate could not generated. Assertion contains not all attributes which are necessary."); - throw new AssertionAttributeExtractorExeption("Assertion contains not all attributes which are necessary for mandate generation", null); - - } - - try { - JAXBContext jc = JAXBContext.newInstance("at.gv.e_government.reference.namespace.mandates._20040701_"); - Marshaller m = jc.createMarshaller(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - m.marshal(mandateObject, stream); - misMandate.setMandate(Base64Utils.encode(stream.toByteArray()).getBytes()); - stream.close(); + + //build IdentityLink + if (identityLink != null) + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, identityLink, authData.getBPK(), authData.getBPKType())); - } catch (JAXBException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); + else if (idlFromPVPAttr != null) { + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, idlFromPVPAttr, authData.getBPK(), authData.getBPKType())); + Logger.debug("Set IdentityLink received from federated IDP"); - } catch (IOException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); - - } - authData.setUseMandate(true); + } else { + Logger.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); + + } + } - } - - - if (extractor.containsAttribute(PVPConstants.MANDATE_PROF_REP_OID_NAME)) { - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setProfRep( - extractor.getSingleAttributeValue(PVPConstants.MANDATE_PROF_REP_OID_NAME)); - } - - //set PVP role attribute - if (extractor.containsAttribute(PVPConstants.ROLES_NAME)) { - String pvpRoles = extractor.getSingleAttributeValue(PVPConstants.ROLES_NAME); - if (MiscUtil.isNotEmpty(pvpRoles)) { - List<String> roles = Arrays.asList(pvpRoles.split(";")); + //################################################################### + //set PVP role attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.ROLES_NAME); + String pvpAttrRoles = session.getGenericDataFromSession(PVPConstants.ROLES_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrRoles)) { + List<String> roles = Arrays.asList(pvpAttrRoles.split(";")); for (String role : roles) { authData.addAuthenticationRole(AuthenticationRoleFactory.buildFormPVPole(role)); - } - } - } - - //set PVP OU attribute - if (extractor.containsAttribute(PVPConstants.OU_NAME)) { - authData.setPvpAttribute_OU(extractor.getSingleAttributeValue(PVPConstants.OU_NAME)); - Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - - } - - //set STORK attributes - if (extractor.containsAttribute(PVPConstants.EID_STORK_TOKEN_NAME)) { - try { - authData.setGenericData(AuthenticationSessionStorageConstants.STORK_RESPONSE, - extractor.getSingleAttributeValue(PVPConstants.EID_STORK_TOKEN_NAME)); - authData.setForeigner(true); - } catch (SessionDataStorageException e) { - Logger.warn("STORK Response can not stored into generic authData.", e); + } + } + + + //################################################################### + //set PVP OU attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.OU_NAME); + String pvpAttrOUName = session.getGenericDataFromSession(PVPConstants.OU_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrOUName)) { + authData.setPvpAttribute_OU(pvpAttrOUName); + Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - } + } - } - -// if (!extractor.getSTORKAttributes().isEmpty()) { -// authData.setStorkAttributes(extractor.getSTORKAttributes()); -// authData.setForeigner(true); -// -// } + //#################################################################### + //parse AuthBlock signature-verification response + //INFO: this parameters are only required for SAML1 auth. protocol + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + if (verifyXMLSigResp != null) { + authData.setQualifiedCertificate(verifyXMLSigResp + .isQualifiedCertificate()); + authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); + authData.setPublicAuthorityCode(verifyXMLSigResp + .getPublicAuthorityCode()); - authData.setSsoSession(true); - authData.setInterfederatedSSOSession(true); - - if (extractor.getFullAssertion().getAuthnStatements() != null - && extractor.getFullAssertion().getAuthnStatements().size() > 0) { - for (AuthnStatement el : extractor.getFullAssertion().getAuthnStatements()) { - if (el.getSessionNotOnOrAfter() != null) { - authData.setSsoSessionValidTo(el.getSessionNotOnOrAfter().toDate()); - break; - } + } else { + //set parameters in respect to QAA level + Logger.info("No authBlock signature-verfication response found. Maybe IDP federation is in use."); + if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) + authData.setQualifiedCertificate(true); + else + authData.setQualifiedCertificate(false); + authData.setPublicAuthority(false); + + } + + //#################################################################### + //copy all generic authentication information, which are not processed before to authData + Iterator<String> copyInterator = includedToGenericAuthData.iterator(); + while (copyInterator.hasNext()) { + String elementKey = copyInterator.next(); + try { + authData.setGenericData(elementKey, session.getGenericDataFromSession(elementKey)); + + } catch (SessionDataStorageException e) { + Logger.warn("Can not add generic authData with key:" + elementKey, e); + + } } - } else { - authData.setSsoSessionValidTo(extractor.getFullAssertion().getConditions().getNotOnOrAfter().toDate()); + } catch (BuildException e) { + throw e; - } + } catch (Throwable ex) { + throw new BuildException("builder.00", new Object[]{ + "AuthenticationData", ex.toString()}, ex); + } - //only for SAML1 - if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) - authData.setQualifiedCertificate(true); - else - authData.setQualifiedCertificate(false); - authData.setPublicAuthority(false); } - + /** - * @param oaParam - * @param authData - * @return + * Check a bPK-Type against a Service-Provider configuration <br> + * If bPK-Type is <code>null</code> the result is <code>false</code>. + * + * @param oaParam Service-Provider configuration, never null + * @param bPKType bPK-Type to check + * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false */ - private static boolean matchsReceivedbPKToOnlineApplication( - IOAAuthParameters oaParam, AuthenticationData authData) { - + private boolean matchsReceivedbPKToOnlineApplication(IOAAuthParameters oaParam, String bPKType) { String oaTarget = null; if (oaParam.getBusinessService()) { - if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK) || - oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_STORK)) - oaTarget = oaParam.getIdentityLinkDomainIdentifier(); - - else { - Logger.warn("BusinessIdentifier can not be clearly assigned, because it starts without a prefix."); - return false; - - } - + oaTarget = oaParam.getIdentityLinkDomainIdentifier(); + } else { oaTarget = Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget(); } - - - if (oaTarget.equals(authData.getBPKType())) + + if (oaTarget.equals(bPKType)) return true; else return false; } - private static void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, - IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { - - IdentityLink identityLink = session.getIdentityLink(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - - authData.setIssuer(session.getAuthURL()); - + private void parseBasicUserInfosFromIDL(AuthenticationData authData, IdentityLink identityLink, Collection<String> includedGenericSessionData) { //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO authData.setIdentificationValue(identityLink.getIdentificationValue()); authData.setIdentificationType(identityLink.getIdentificationType()); @@ -885,144 +841,238 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authData.setFamilyName(identityLink.getFamilyName()); authData.setDateOfBirth(identityLink.getDateOfBirth()); - if (verifyXMLSigResp != null) { - authData.setQualifiedCertificate(verifyXMLSigResp - .isQualifiedCertificate()); - authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); - authData.setPublicAuthorityCode(verifyXMLSigResp - .getPublicAuthorityCode()); + //remove corresponding keys from genericSessionData if exists + includedGenericSessionData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.GIVEN_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.BIRTHDATE_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); + + } + + /** + * @param authData + * @param notValidbPK + * @param notValidbPKType + * @return + */ + private Pair<String, String> getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, + String notValidbPKType) { + try { + EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); + if (eGovClientsConfig != null) { + Logger.info("bPK in MOASession (bPK-Type:" + notValidbPKType + + " does no match to Service-Provider configuration. --> Request SZR to get correct bPK."); + + SZRClient szrclient = new SZRClient(eGovClientsConfig); + + Logger.debug("Create SZR request to get baseID ... "); + PersonInfoType personInfo = new PersonInfoType(); + at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); + personInfo.setPerson(person); + at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); + person.setName(name); + at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); + person.setIdentification(idValue); + + //set bPK or wbPK + idValue.setValue(authData.getBPK()); + idValue.setType(authData.getBPKType()); + + //set person information + name.setGivenName(authData.getGivenName()); + name.setFamilyName(authData.getFamilyName()); + if (authData.getDateOfBirth() != null) + person.setDateOfBirth(authData.getFormatedDateOfBirth()); + + //request szr and store baseID + return Pair.newInstance(szrclient.getStammzahl(personInfo), + Constants.URN_PREFIX_BASEID); + + } else { + Logger.debug("No SZR clieht configuration found."); + return null; + + } + + } catch (SZRException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - } else { - Logger.warn("No signature verfication response found!"); + } catch (at.gv.util.ex.EgovUtilException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); } - authData.setBkuURL(session.getBkuURL()); - - //copy all generic authentication information to authData - if (session.getGenericSessionDataStorage() != null && - !session.getGenericSessionDataStorage().isEmpty()) { - Iterator<Entry<String, Object>> copyInterator = session.getGenericSessionDataStorage().entrySet().iterator(); - while (copyInterator.hasNext()) { - Entry<String, Object> element = copyInterator.next(); - try { - authData.setGenericData(element.getKey(), element.getValue()); - - } catch (SessionDataStorageException e) { - Logger.warn("Can not add generic authData with key:" + element.getKey(), e); - - } - } - } + return null; + } + + /** + * Add encrypted bPKs from PVP Attribute 'ENC_BPK_LIST_NAME', which could be exist in + * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class)</code></pre> + * to <code>authData</code> + * + * @param session MOASession, but never null + * @param authData AuthenticationData DAO + * @param spConfig Service-Provider configuration + * + * @return Pair<bPK, bPKType> which was received by PVP-Attribute and could be decrypted for this Service Provider, + * or <code>null</code> if no attribute exists or can not decrypted + */ + private Pair<String, String> getEncryptedbPKFromPVPAttribute(AuthenticationSession session, + AuthenticationData authData, IOAAuthParameters spConfig) { + //set List of encrypted bPKs to authData DAO + String pvpEncbPKListAttr = session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpEncbPKListAttr)) { + List<String> encbPKList = Arrays.asList(pvpEncbPKListAttr.split(";")); + authData.setEncbPKList(encbPKList); + + //check if one of this encrypted bPK could be decrypt for this Service-Provider + for (String fullEncbPK : encbPKList) { + int index = fullEncbPK.indexOf("|"); + if (index >= 0) { + String encbPK = fullEncbPK.substring(index+1); + String second = fullEncbPK.substring(0, index); + int secIndex = second.indexOf("+"); + if (secIndex >= 0) { + if (spConfig.getTarget().equals(second.substring(secIndex+1))) { + Logger.debug("Found encrypted bPK for online-application " + + spConfig.getPublicURLPrefix() + + " Start decryption process ..."); + PrivateKey privKey = spConfig.getBPKDecBpkDecryptionKey(); + if (privKey != null) { + try { + String bPK = BPKBuilder.decryptBPK(encbPK, spConfig.getTarget(), privKey); + if (MiscUtil.isNotEmpty(bPK)) { + Logger.info("bPK decryption process finished successfully."); + return Pair.newInstance(bPK, Constants.URN_PREFIX_CDID + "+" + spConfig.getTarget()); + + } else { + Logger.error("bPK decryption FAILED."); + + } + } catch (BuildException e) { + Logger.error("bPK decryption FAILED.", e); + + } - authData.setSignerCertificate(session.getEncodedSignerCertificate()); - authData.setAuthBlock(session.getAuthBlock()); + } else { + Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + + } + + } else { + Logger.info("Found encrypted bPK but " + + "encrypted bPK target does not match to online-application target"); + + } + } + } + } + } - authData.setForeigner(session.isForeigner()); - authData.setQAALevel(session.getQAALevel()); + return null; + } - authData.setIsBusinessService(oaParam.getBusinessService()); - - if (session.isForeigner()) { - try { - //TODO: replace with TSL lookup when TSL is ready! - X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); - if (certificate != null) { - LdapName ln = new LdapName(certificate.getIssuerDN() - .getName()); - for (Rdn rdn : ln.getRdns()) { - if (rdn.getType().equalsIgnoreCase("C")) { - Logger.info("C is: " + rdn.getValue()); - authData.setCcc(rdn.getValue().toString()); - break; - } - } - } - - } catch (Exception e) { - Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); + /** + * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in + * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)</code></pre> + * + * @param session MOASession, but never null + * @return bPK, which was received by PVP-Attribute, or <code>null</code> if no attribute exists + */ + private String getbPKValueFromPVPAttribute(AuthenticationSession session) { + String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKValueAttr)) { + + //fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations + if (pvpbPKValueAttr.startsWith("bPK:")) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + + " contains a not standardize prefix! Staring attribute value correction process ..."); + pvpbPKValueAttr = pvpbPKValueAttr.substring("bPK:".length()); } - if (MiscUtil.isEmpty(authData.getCcc())) { - String storkCCC = authData.getGenericData( - AuthenticationSessionStorageConstants.STORK_CCC, String.class); + String[] spitted = pvpbPKValueAttr.split(":"); + if (spitted.length != 2) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + " has a wrong encoding and can NOT be USED!" + + " Value:" + pvpbPKValueAttr); + return null; - if (MiscUtil.isNotEmpty(storkCCC)) { - authData.setCcc(storkCCC); - Logger.info("Can not extract country from certificate -> Use country:" + storkCCC + " from STORK request."); - - } - } - - } else { - authData.setCcc("AT"); + Logger.debug("Find PVP-Attr: " + PVPConstants.BPK_FRIENDLY_NAME); + return spitted[1]; } - try { - authData.setSsoSession(AuthenticationSessionStoreage.isSSOSession(session.getSessionID())); + return null; + } + + /** + * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in + * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)</code></pre> + * + * @param session MOASession, but never null + * @return bPKType, which was received by PVP-Attribute, or <code>null</code> if no attribute exists + */ + private String getbPKTypeFromPVPAttribute(AuthenticationSession session) { + String pvpbPKTypeAttr = session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKTypeAttr)) { - //set max. SSO session time - if (authData.isSsoSession()) { - long maxSSOSessionTime = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; - Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); - authData.setSsoSessionValidTo(ssoSessionValidTo); - - } else { - //set valid to 5 min - Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); - authData.setSsoSessionValidTo(ssoSessionValidTo); + //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations + if (pvpbPKTypeAttr.startsWith(Constants.URN_PREFIX_CDID) && + !pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length(), + Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { + Logger.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting attribute value correction ... "); + pvpbPKTypeAttr = Constants.URN_PREFIX_CDID + "+" + pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length() + 1); } - - - /* TODO: Support SSO Mandate MODE! - * Insert functionality to translate mandates in case of SSO - */ + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); + return pvpbPKTypeAttr; + } + + return null; - - MISMandate mandate = session.getMISMandate(); - authData.setMISMandate(mandate); - authData.setUseMandate(session.getUseMandate()); - authData.setMandateReferenceValue(session.getMandateReferenceValue()); - - if (session.getUseMandate() && session.isOW() - && mandate != null && MiscUtil.isNotEmpty(mandate.getOWbPK())) { - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - - //TODO: check in case of mandates for business services - authData.setIdentityLink(identityLink); - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - } else { - buildOAspecificbPK(protocolRequest, oaParam, authData, - identityLink.getIdentificationValue(), - identityLink.getIdentificationType()); - - buildOAspecificIdentityLink(oaParam, authData, identityLink); - - } - - - } catch (Throwable ex) { - throw new BuildException("builder.00", new Object[]{ - "AuthenticationData", ex.toString()}, ex); - } + /* + * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', + * because the prefix of BPK_NAME attribute contains the postfix of the bPKType + * + * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' + * PVP attributes + */ +// String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); +// String[] spitted = pvpbPKValueAttr.split(":"); +// if (MiscUtil.isEmpty(authData.getBPKType())) { +// Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + +// "Starting target extraction from bPK/wbPK prefix ..."); +// //exract bPK/wbPK type from bpk attribute value prefix if type is +// //not transmitted as single attribute +// Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); +// Matcher matcher = pattern.matcher(spitted[0]); +// if (matcher.matches()) { +// //find public service bPK +// authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); +// Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); +// +// } else { +// //find business service wbPK +// authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); +// Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); +// +// } +// } } - - private static void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { + + private IdentityLink buildOAspecificIdentityLink(IOAAuthParameters oaParam, IdentityLink idl, String bPK, String bPKType) throws MOAIDException { if (oaParam.getBusinessService()) { Element idlassertion = idl.getSamlAssertion(); //set bpk/wpbk; Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(authData.getBPK()); + prIdentification.getFirstChild().setNodeValue(bPK); //set bkp/wpbk type Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); + prIdentificationType.getFirstChild().setNodeValue(bPKType); IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); IdentityLink businessServiceIdl = idlparser.parseIdentityLink(); @@ -1031,68 +1081,76 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); Element resignedilAssertion; - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - if (config.isIdentityLinkResigning()) { - resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), config.getIdentityLinkResigningKey()); + if (authConfig.isIdentityLinkResigning()) { + resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), authConfig.getIdentityLinkResigningKey()); } else { resignedilAssertion = businessServiceIdl.getSamlAssertion(); } IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); - IdentityLink resignedIDL = resignedIDLParser.parseIdentityLink(); + return resignedIDLParser.parseIdentityLink(); - authData.setIdentityLink(resignedIDL); - } else - authData.setIdentityLink(idl); + return idl; } - - private static void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { - - if (oaParam.getBusinessService()) { - //since we have foreigner, wbPK is not calculated in BKU - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); - authData.setBPK(new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr)); - authData.setBPKType(registerAndOrdNr); - - } else { - authData.setBPK(baseID); - authData.setBPKType(baseIDType); - } - - Logger.trace("Authenticate user with wbPK " + authData.getBPK()); - - } else { - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - // only compute bPK if online application is a public service and we have the Stammzahl - String target = null; - Object saml1Requst = null; - try { - saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException ex) { - - - } - - if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getTarget(); - else - target = oaParam.getTarget(); - - String bpkBase64 = new BPKBuilder().buildBPK(baseID, target); - authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + target); - } + private Pair<String, String> buildOAspecificbPK(IRequest pendingReq, IOAAuthParameters oaParam, AuthenticationData authData) throws BuildException { + + String bPK; + String bPKType; - Logger.trace("Authenticate user with bPK " + authData.getBPK()); - } + String baseID = authData.getIdentificationValue(); + String baseIDType = authData.getIdentificationType(); + + String eIDASOutboundCountry = pendingReq.getGenericData(RequestImpl.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class); + if (Constants.URN_PREFIX_BASEID.equals(baseIDType)) { + if (MiscUtil.isNotEmpty(eIDASOutboundCountry) && !COUNTRYCODE_AUSTRIA.equals(eIDASOutboundCountry)) { + Pair<String, String> eIDASID = new BPKBuilder().buildeIDASIdentifer(baseIDType, baseID, + COUNTRYCODE_AUSTRIA, eIDASOutboundCountry); + Logger.debug("Authenticate user with bPK:" + eIDASID.getFirst() + " Type:" + eIDASID.getSecond()); + return eIDASID; + + } else if (oaParam.getBusinessService()) { + //is Austrian private-service application + String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); + bPK = new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr); + bPKType = registerAndOrdNr; + + } else { + // only compute bPK if online application is a public service and we have the Stammzahl + String target = null; + Class<?> saml1RequstTemplate = null; + try { + saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + target = (String) pendingReq.getClass().getMethod("getTarget").invoke(pendingReq); + + } + + } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException | InvocationTargetException | NoSuchMethodException ex) { } + + if (MiscUtil.isEmpty(target)) + target = oaParam.getTarget(); + + bPK = new BPKBuilder().buildBPK(baseID, target); + bPKType = Constants.URN_PREFIX_CDID + "+" + target; + + } + + } else { + Logger.warn("!!!baseID-element does not include a baseID. This should not be happen any more!!!"); + bPK = baseID; + bPKType = baseIDType; + + } + Logger.trace("Authenticate user with bPK:" + bPK + " Type:" + bPKType); + return Pair.newInstance(bPK, bPKType); + } } |