Example usage for javax.servlet.http HttpServletRequest getRemoteHost

List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteHost.

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.sipfoundry.conference.ConfRecordStatus.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String inString = request.getQueryString();

    LOG.info(String.format("ConfRecordStatus::doGet Conference Record string: " + inString));

    // The get command contains the required information
    String parmWavName = request.getParameter("wn");
    String parmOwnerName = request.getParameter("on");
    String parmBridgeContact = request.getParameter("bc");
    String synch = request.getParameter("synchronous");
    Boolean synchronous = (synch == null) ? false : new Boolean(synch);

    boolean stringsOK = ((parmWavName != null) && (parmOwnerName != null) && (parmBridgeContact != null)
            && (parmWavName.compareTo("") != 0) && (parmOwnerName.compareTo("") != 0)
            && (parmBridgeContact.compareTo("") != 0));

    response.setContentType(MessageSummaryContentType);
    // Use the OutputStream rather than the PrintWriter as this will cause Jetty
    // To NOT set the charset= parameter on the content type, which breaks
    // The status server doing this request.
    // The price is we aren't specifying the encoding of this message (sigh).
    OutputStream os = response.getOutputStream();

    // Just echo the bytes of the string.  No character encoding or nothing.
    os.write(formatConfRecord(parmWavName).getBytes());
    if (!synchronous) {
        os.close();//from   www .ja v a  2  s  .c o  m
    }

    // The WAV file is now the remote conference server
    // Stream the file to the local voicemail server
    if (stringsOK) {
        try {
            String confMailboxName = parmOwnerName;

            MailboxManager mailboxManager = (MailboxManager) request
                    .getAttribute(SipxIvrServletHandler.MAILBOX_MANAGER);
            ValidUsers validUsers = (ValidUsers) request.getAttribute(SipxIvrServletHandler.VALID_USERS_ATTR);

            TempMessage tempMessage = mailboxManager.createTempMessage(confMailboxName, parmBridgeContact,
                    true);
            String tempPath = tempMessage.getTempPath();

            tempMessage.setIsToBeStored(true);

            // Get the name of the server that sent us the request
            String remoteHost = request.getRemoteHost();

            URL url = new URL("http://" + remoteHost + ":8090/recordings/" + parmWavName);
            URLConnection urlC = url.openConnection();
            InputStream streamIn = urlC.getInputStream();
            OutputStream streamOut = new FileOutputStream(tempPath);
            IOUtils.copy(streamIn, streamOut);
            IOUtils.closeQuietly(streamIn);
            IOUtils.closeQuietly(streamOut);

            mailboxManager.store(validUsers.getUser(parmOwnerName), Folder.CONFERENCE, tempMessage,
                    MailboxManager.CONFERENCE_CALL);
            //cleanup temporary message
            if (tempMessage != null) {
                mailboxManager.deleteTempMessage(tempMessage);
            }
        } catch (IOException e) {
            LOG.error("ConfRecordStatus::Copy IO error ", e);
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

public WebMailSession(WebMailServer parent, Object parm, HTTPRequestHeader h)
        throws UserDataException, InvalidPasswordException, WebMailException {
    try {/*from   www  .  ja v a 2  s .  c  o m*/
        Class srvltreq = Class.forName("javax.servlet.http.HttpServletRequest");
        if (srvltreq.isInstance(parm)) {
            javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) parm;
            this.sess = req.getSession(false);
            session_code = ((javax.servlet.http.HttpSession) sess).getId();

            try {
                remote = InetAddress.getByName(req.getRemoteHost());
            } catch (UnknownHostException e) {
                try {
                    remote = InetAddress.getByName(req.getRemoteAddr());
                } catch (Exception ex) {
                    try {
                        remote = InetAddress.getByName("localhost");
                    } catch (Exception ex2) {
                    }
                }
            }
        } else {
            throw new Exception("Servlet class found but not running as servlet");
        }
    } catch (Throwable t) {
        this.remote = (InetAddress) parm;
        session_code = Helper.calcSessionCode(remote, h);
    }
    doInit(parent, h);
}

From source file:org.apache.openaz.xacml.rest.XACMLPapServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w  w  w  .j  a  v a 2  s  .c o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        XACMLRest.dumpRequest(request);

        // Is this from the Admin Console?
        String groupId = request.getParameter("groupId");
        if (groupId != null) {
            // this is from the Admin Console, so handle separately
            doACGet(request, response, groupId);
            return;
        }
        //
        // Get the PDP's ID
        //
        String id = this.getPDPID(request);
        logger.info("doGet from: " + id);
        //
        // Get the PDP Object
        //
        PDP pdp = this.papEngine.getPDP(id);
        //
        // Is it known?
        //
        if (pdp == null) {
            //
            // Check if request came from localhost
            //
            String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: "
                    + request.getLocalAddr();
            logger.info(message);
            if (request.getRemoteHost().equals("localhost") || request.getRemoteHost().equals("127.0.0.1") //NOPMD
                    || request.getRemoteHost().equals(request.getLocalAddr())) {
                //
                // Return status information - basically all the groups
                //
                Set<PDPGroup> groups = papEngine.getPDPGroups();

                // convert response object to JSON and include in the response
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), groups);
                response.setHeader("content-type", "application/json");
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Get the PDP's Group
        //
        PDPGroup group = this.papEngine.getPDPGroup(pdp);
        if (group == null) {
            String message = "No group associated with pdp " + pdp.getId();
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Which policy do they want?
        //
        String policyId = request.getParameter("id");
        if (policyId == null) {
            String message = "Did not specify an id for the policy";
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        PDPPolicy policy = group.getPolicy(policyId);
        if (policy == null) {
            String message = "Unknown policy: " + policyId;
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        //
        // Get its stream
        //
        try (InputStream is = policy.getStream(); OutputStream os = response.getOutputStream()) {
            //
            // Send the policy back
            //
            IOUtils.copy(is, os);

            response.setStatus(HttpServletResponse.SC_OK);
        } catch (PAPException e) {
            String message = "Failed to open policy id " + policyId;
            logger.error(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
        }
    } catch (PAPException e) {
        logger.error("GET exception: " + e, e);
        response.sendError(500, e.getMessage());
        return;
    }
}

From source file:org.lockss.servlet.LockssServlet.java

/** Common request handling. */
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resetState();//from ww w . j ava 2s . co m
    HttpSession session = req.getSession(false);
    try {
        this.req = req;
        this.resp = resp;
        if (log.isDebug()) {
            logParams();
        }
        resp.setContentType("text/html");

        if (!mayPageBeCached()) {
            resp.setHeader("pragma", "no-cache");
            resp.setHeader("Cache-control", "no-cache");
        }

        reqURL = new URL(UrlUtil.getRequestURL(req));
        clientAddr = getLocalIPAddr();

        // check that current user has permission to run this servlet
        if (!isServletAllowed(myServletDescr())) {
            displayWarningInLieuOfPage("You are not authorized to use " + myServletDescr().heading);
            return;
        }

        // check whether servlet is disabled
        String reason = ServletUtil.servletDisabledReason(myServletDescr().getServletName());
        if (reason != null) {
            displayWarningInLieuOfPage("This function is disabled. " + reason);
            return;
        }
        if (session != null) {
            session.setAttribute(SESSION_KEY_RUNNING_SERVLET, getHeading());
            String reqHost = req.getRemoteHost();
            String forw = req.getHeader(HttpFields.__XForwardedFor);
            if (!StringUtil.isNullString(forw)) {
                reqHost += " (proxies for " + forw + ")";
            }
            session.setAttribute(SESSION_KEY_REQUEST_HOST, reqHost);
        }
        reqStartTime = TimeBase.nowMs();
        lockssHandleRequest();
    } catch (ServletException e) {
        log.error("Servlet threw", e);
        throw e;
    } catch (IOException e) {
        log.error("Servlet threw", e);
        throw e;
    } catch (RuntimeException e) {
        log.error("Servlet threw", e);
        throw e;
    } finally {
        if (session != null) {
            session.setAttribute(SESSION_KEY_RUNNING_SERVLET, null);
            session.setAttribute(LockssFormAuthenticator.__J_AUTH_ACTIVITY, TimeBase.nowMs());
        }
        resetMyLocals();
        resetLocals();
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet.java

private void handleSAMLResponse(HttpServletRequest request, HttpServletResponse response) {
    Logger.info("handleSAMLResponse started");
    String pendingRequestID = null;

    try {/*from  w w w.j a v  a  2s.com*/
        Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
        Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));

        super.setNoCachingHeadersInHttpRespone(request, response);
        Logger.trace("No Caching headers set for HTTP response");

        //check if https or only http
        super.checkIfHTTPisAllowed(request.getRequestURL().toString());

        Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");

        //extract STORK Response from HTTP Request
        //Decodes SAML Response
        byte[] decSamlToken;
        try {
            decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
            Logger.debug("SAMLResponse: " + new String(decSamlToken));

        } catch (NullPointerException e) {
            Logger.error("Unable to retrieve STORK Response", e);
            throw new MOAIDException("stork.04", null);
        }

        //Get SAMLEngine instance
        STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");

        STORKAuthnResponse authnResponse = null;
        try {
            //validate SAML Token
            Logger.debug("Starting validation of SAML response");
            authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost());
            Logger.info("SAML response succesfully verified!");
        } catch (STORKSAMLEngineException e) {
            Logger.error("Failed to verify STORK SAML Response", e);
            throw new MOAIDException("stork.05", null);
        }

        Logger.info("STORK SAML Response message succesfully extracted");
        Logger.debug("STORK response: ");
        Logger.debug(authnResponse.toString());

        Logger.debug("Trying to find MOA Session-ID ...");
        //String moaSessionID = request.getParameter(PARAM_SESSIONID);
        //first use SAML2 relayState 
        String moaSessionID = request.getParameter("RelayState");

        // escape parameter strings
        moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

        //check if SAML2 relaystate includes a MOA sessionID
        if (StringUtils.isEmpty(moaSessionID)) {
            //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier

            moaSessionID = authnResponse.getInResponseTo();
            moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

            if (StringUtils.isEmpty(moaSessionID)) {
                //No authentication session has been started before
                Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
                Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
                throw new AuthenticationException("auth.02", new Object[] { moaSessionID });

            } else
                Logger.trace(
                        "Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");

        } else
            //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
            Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");

        /*INFO!!!!
         * SAML message IDs has an different format then MOASessionIDs
         * This is only a workaround because many PEPS does not support SAML2 relayState or
         * MOASessionID as AttributConsumerServiceURL GET parameter
         */
        //            if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
        //                throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");

        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);

        //load MOASession from database
        AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
        //change MOASessionID
        moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Found MOA sessionID: " + moaSessionID);

        String statusCodeValue = authnResponse.getStatusCode();

        if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
            Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
            throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
        }

        Logger.info("Got SAML response with authentication success message.");

        Logger.debug("MOA session is still valid");

        STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();

        if (storkAuthnRequest == null) {
            Logger.error(
                    "Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
            throw new MOAIDException("stork.07", null);
        }

        Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);

        ////////////// incorporate gender from parameters if not in stork response

        IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();

        // but first, check if we have a representation case
        if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
                || STORKResponseProcessor.hasAttribute("representative", attributeList)
                || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
            // in a representation case...
            moaSession.setUseMandate("true");

            // and check if we have the gender value
            PersonalAttribute gender = attributeList.get("gender");
            if (null == gender) {
                String gendervalue = (String) request.getParameter("gender");
                if (null != gendervalue) {
                    gender = new PersonalAttribute();
                    gender.setName("gender");
                    ArrayList<String> tmp = new ArrayList<String>();
                    tmp.add(gendervalue);
                    gender.setValue(tmp);

                    authnResponse.getPersonalAttributeList().add(gender);
                }
            }
        }

        //////////////////////////////////////////////////////////////////////////

        Logger.debug("Starting extraction of signedDoc attribute");
        //extract signed doc element and citizen signature
        String citizenSignature = null;
        try {
            PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().get("signedDoc");
            String signatureInfo = null;
            if (signedDoc != null) {
                signatureInfo = signedDoc.getValue().get(0);
                //should not occur
            } else {

                //store SAMLResponse
                moaSession.setSAMLResponse(request.getParameter("SAMLResponse"));
                //store authnResponse

                //moaSession.setAuthnResponse(authnResponse);//not serializable
                moaSession.setAuthnResponseGetPersonalAttributeList(authnResponse.getPersonalAttributeList());

                String authnContextClassRef = null;
                try {
                    authnContextClassRef = authnResponse.getAssertions().get(0).getAuthnStatements().get(0)
                            .getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef();
                } catch (Throwable e) {
                    Logger.warn(
                            "STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
                }

                moaSession.setAuthnContextClassRef(authnContextClassRef);
                moaSession.setReturnURL(request.getRequestURL());

                //load signedDoc
                String signRequest = moaSession.getSignedDoc();

                //session is implicit stored in changeSessionID!!!!
                String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

                //set return url to PEPSConnectorWithLocalSigningServlet and add newMOASessionID 
                //signRequest

                String issuerValue = AuthConfigurationProvider.getInstance().getPublicURLPrefix();
                String acsURL = issuerValue
                        + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN;

                String url = acsURL + "?moaSessionID=" + newMOASessionID;
                //redirect to OASIS module and sign there

                boolean found = false;
                try {
                    List<AttributeProviderPlugin> aps = AuthConfigurationProvider.getInstance()
                            .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs();
                    Logger.info("Found AttributeProviderPlugins:" + aps.size());
                    for (AttributeProviderPlugin ap : aps) {
                        Logger.info("Found AttributeProviderPlugin attribute:" + ap.getAttributes());
                        if (ap.getAttributes().equalsIgnoreCase("signedDoc")) {
                            // FIXME[tlenz]: A servlet's class field is not thread safe.
                            oasisDssWebFormURL = ap.getUrl();
                            found = true;
                            Logger.info("Loaded signedDoc attribute provider url from config:"
                                    + oasisDssWebFormURL);
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.error("Loading the signedDoc attribute provider url from config failed");
                }
                if (!found) {
                    Logger.error("Failed to load the signedDoc attribute provider url from config");
                }
                performRedirect(url, request, response, signRequest);

                return;
            }
            SignResponse dssSignResponse = (SignResponse) ApiUtils
                    .unmarshal(new StreamSource(new java.io.StringReader(signatureInfo)));

            citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);

            // memorize signature into authblock
            moaSession.setAuthBlock(citizenSignature);

            X509Certificate cert = getSignerCertificate(citizenSignature);
            moaSession.setSignerCertificate(cert);
            moaSession.setForeigner(true);

        } catch (Throwable e) {
            Logger.error("Could not extract citizen signature from C-PEPS", e);
            throw new MOAIDException("stork.09", null);
        }

        try {
            SZRGInsertion(moaSession, authnResponse.getPersonalAttributeList(),
                    authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext()
                            .getAuthnContextClassRef().getAuthnContextClassRef(),
                    citizenSignature);
        } catch (STORKException e) {
            // this is really nasty but we work against the system here. We are supposed to get the gender attribute from
            // stork. If we do not, we cannot register the person in the ERnP - we have to have the
            // gender for the represented person. So here comes the dirty hack. 
            if (e.getCause() instanceof STORKException
                    && e.getCause().getMessage().equals("gender not found in response")) {
                try {
                    Logger.trace("Initialize VelocityEngine...");

                    VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
                    Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
                    VelocityContext context = new VelocityContext();
                    context.put("SAMLResponse", request.getParameter("SAMLResponse"));
                    context.put("action", request.getRequestURL());

                    StringWriter writer = new StringWriter();
                    template.merge(context, writer);

                    response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
                } catch (Exception e1) {
                    Logger.error("Error sending gender retrival form.", e1);
                    //                  httpSession.invalidate();
                    throw new MOAIDException("stork.10", null);
                }

                return;
            }

            Logger.error("Error connecting SZR Gateway", e);
            throw new MOAIDException("stork.10", null);
        }

        Logger.debug("Add full STORK AuthnResponse to MOA session");
        moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));//TODO ask Florian/Thomas authnResponse?

        //session is implicit stored in changeSessionID!!!!
        String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);

        //redirect
        String redirectURL = null;
        redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
                ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
                newMOASessionID);
        redirectURL = response.encodeRedirectURL(redirectURL);

        response.setContentType("text/html");
        response.setStatus(302);
        response.addHeader("Location", redirectURL);
        Logger.info("REDIRECT TO: " + redirectURL);

    } catch (AuthenticationException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (MOAIDException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (Exception e) {
        Logger.error("PEPSConnector has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }

}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private Boolean isAuthorizedLockssCrawler(StudyFile file, HttpServletRequest req) {
    // is this a LOCKSS request?

    if (!isLockssCrawlRequest(req)) {
        return false;
    }/*from   w  ww . ja va2 s.c o  m*/

    // OK, it is.
    // Let's check if this address is authorized to download this file.

    String remoteAddress = req.getRemoteHost();

    if (remoteAddress == null || remoteAddress.equals("")) {
        return false;
    }
    Study study = null;
    VDC vdc = null;

    study = file.getStudy();

    if (study != null) {
        vdc = study.getOwner();
    }

    //return lockssAuthService.isAuthorizedLockssServer(vdc, req);
    return lockssAuthService.isAuthorizedLockssDownload(vdc, req, isRestrictedFile(file, study, vdc));
}

From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet.java

/**
 * Handles the reception of a STORK response message
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from   ww w . j  ava2s.  com*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pendingRequestID = null;

    try {

        Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

        Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
        Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));

        super.setNoCachingHeadersInHttpRespone(request, response);
        Logger.trace("No Caching headers set for HTTP response");

        //check if https or only http
        super.checkIfHTTPisAllowed(request.getRequestURL().toString());

        Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");

        //extract STORK Response from HTTP Request
        //Decodes SAML Response
        byte[] decSamlToken;
        try {
            decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
            Logger.debug("SAMLResponse: " + new String(decSamlToken));

        } catch (NullPointerException e) {
            Logger.error("Unable to retrieve STORK Response", e);
            throw new MOAIDException("stork.04", null);
        }

        //Get SAMLEngine instance
        STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");

        STORKAuthnResponse authnResponse = null;
        try {
            //validate SAML Token
            Logger.debug("Starting validation of SAML response");
            authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost());
            Logger.info("SAML response succesfully verified!");
        } catch (STORKSAMLEngineException e) {
            Logger.error("Failed to verify STORK SAML Response", e);
            throw new MOAIDException("stork.05", null);
        }

        Logger.info("STORK SAML Response message succesfully extracted");
        Logger.debug("STORK response: ");
        Logger.debug(authnResponse.toString());

        Logger.debug("Trying to find MOA Session-ID ...");
        //String moaSessionID = request.getParameter(PARAM_SESSIONID);
        //first use SAML2 relayState 
        String moaSessionID = request.getParameter("RelayState");

        // escape parameter strings
        moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

        //check if SAML2 relaystate includes a MOA sessionID
        if (StringUtils.isEmpty(moaSessionID)) {
            //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier

            moaSessionID = authnResponse.getInResponseTo();
            moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);

            if (StringUtils.isEmpty(moaSessionID)) {
                //No authentication session has been started before
                Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
                Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
                throw new AuthenticationException("auth.02", new Object[] { moaSessionID });

            } else
                Logger.trace(
                        "Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");

        } else
            //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
            Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");

        /*INFO!!!!
         * SAML message IDs has an different format then MOASessionIDs
         * This is only a workaround because many PEPS does not support SAML2 relayState or
         * MOASessionID as AttributConsumerServiceURL GET parameter
        */
        //            if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
        //                throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");

        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);

        //load MOASession from database
        AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
        //change MOASessionID
        moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Found MOA sessionID: " + moaSessionID);

        String statusCodeValue = authnResponse.getStatusCode();

        if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
            Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
            throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
        }

        Logger.info("Got SAML response with authentication success message.");

        Logger.debug("MOA session is still valid");

        STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();

        if (storkAuthnRequest == null) {
            Logger.error(
                    "Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
            throw new MOAIDException("stork.07", null);
        }

        OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
        //================== Check QAA level start ====================
        int reqQaa = -1;
        int authQaa = -1;
        String authQaaStr = null;
        try {
            reqQaa = storkAuthnRequest.getQaa();

            //TODO: found better solution, but QAA Level in response could be not supported yet
            try {

                authQaaStr = authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext()
                        .getAuthnContextClassRef().getAuthnContextClassRef();
                moaSession.setQAALevel(authQaaStr);

            } catch (Throwable e) {
                Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
                moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
                authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
            }
            if (authQaaStr != null)//Check value only if set
            {
                authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length()));
                //               authQaa = Integer.valueOf(authQaaStr);
                if (reqQaa > authQaa) {
                    Logger.warn("Requested QAA level does not match to authenticated QAA level");
                    throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

                }
            }
        } catch (MOAIDException e) {
            throw e;

        } catch (Exception e) {
            if (Logger.isDebugEnabled())
                Logger.warn("STORK QAA Level evaluation error", e);

            else
                Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" + e.getMessage() + ")");

            throw new MOAIDException("stork.21", new Object[] { reqQaa, authQaa });

        }
        //================== Check QAA level end ====================

        Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);

        ////////////// incorporate gender from parameters if not in stork response

        IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();

        // but first, check if we have a representation case
        if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
                || STORKResponseProcessor.hasAttribute("representative", attributeList)
                || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
            // in a representation case...
            moaSession.setUseMandate("true");

            // and check if we have the gender value
            PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if there is no representation case?
            if (null == gender) {
                String gendervalue = (String) request.getParameter("gender");
                if (null != gendervalue) {
                    gender = new PersonalAttribute();
                    gender.setName("gender");
                    ArrayList<String> tmp = new ArrayList<String>();
                    tmp.add(gendervalue);
                    gender.setValue(tmp);

                    authnResponse.getPersonalAttributeList().add(gender);
                }
            }
        }

        //////////////////////////////////////////////////////////////////////////

        Logger.debug("Starting extraction of signedDoc attribute");
        //extract signed doc element and citizen signature
        String citizenSignature = null;
        try {
            String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING

            Logger.debug("signatureInfo:" + signatureInfo);

            SignResponse dssSignResponse = (SignResponse) ApiUtils
                    .unmarshal(new StreamSource(new java.io.StringReader(signatureInfo)));

            // fetch signed doc
            DataSource ds = null;
            try {
                ds = LightweightSourceResolver.getDataSource(dssSignResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ds == null) {
                //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500 
                //which results in an exception and ds==null

                //try to load document from documentservice
                citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                //throw new ApiUtilsException("No datasource found in response");
            } else {
                InputStream incoming = ds.getInputStream();
                citizenSignature = IOUtils.toString(incoming);
                incoming.close();

                Logger.debug("citizenSignature:" + citizenSignature);
                if (isDocumentServiceUsed(citizenSignature) == true) {
                    citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
                    //               Logger.debug("Loading document from DocumentService.");
                    //               String url = getDtlUrlFromResponse(dssSignResponse);
                    //               //get Transferrequest
                    //               String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
                    //               //Load document from DocumentService
                    //               byte[] data = getDocumentFromDtl(transferRequest, url);
                    //               citizenSignature = new String(data, "UTF-8");
                    //               Logger.debug("Overridung citizenSignature with:"+citizenSignature);
                }
            }
            JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
            SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller()
                    .unmarshal(IOUtils.toInputStream(citizenSignature))).getValue();

            // memorize signature into authblock
            moaSession.setAuthBlock(citizenSignature);

            // extract certificate
            for (Object current : root.getKeyInfo().getContent())
                if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
                    for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
                            .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
                        if (casted.getName().getLocalPart().equals("X509Certificate")) {
                            moaSession.setSignerCertificate(
                                    new X509Certificate(((String) casted.getValue()).getBytes("UTF-8")));
                            break;
                        }
                    }
                }

        } catch (Throwable e) {
            Logger.error("Could not extract citizen signature from C-PEPS", e);
            throw new MOAIDException("stork.09", null);
        }
        Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
        Logger.debug("Citizen signature will be verified by SZR Gateway!");

        Logger.debug("fetching OAParameters from database");

        //         //read configuration paramters of OA
        //           AuthenticationSession moasession;
        //         try {
        //            moasession = AuthenticationSessionStoreage.getSession(moaSessionID);
        //         } catch (MOADatabaseException e2) {
        //            Logger.error("could not retrieve moa session");
        //            throw new AuthenticationException("auth.01", null);
        //         }
        //          OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
        //          if (oaParam == null)
        //                throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });

        // retrieve target
        //TODO: check in case of SSO!!!
        String targetType = null;
        if (oaParam.getBusinessService()) {
            String id = oaParam.getIdentityLinkDomainIdentifier();
            if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                targetType = id;
            else
                targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
        } else {
            targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
        }

        IdentityLink identityLink = null;
        try {
            AuthConfigurationProvider config = AuthConfigurationProvider.getInstance();
            if (config.isStorkFakeIdLActive()
                    && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
                // create fake IdL
                // - fetch IdL template from resources
                InputStream s = PEPSConnectorServlet.class
                        .getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml");
                Element idlTemplate = DOMUtils.parseXmlValidating(s);

                identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink();

                // replace data
                Element idlassertion = identityLink.getSamlAssertion();
                // - set bpk/wpbk;
                Node prIdentification = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH);
                if (!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList))
                    throw new STORKException("eIdentifier is missing");
                String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList,
                        false);
                prIdentification.getFirstChild().setNodeValue(eIdentifier);

                // - set last name
                Node prFamilyName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("surname", attributeList))
                    throw new STORKException("surname is missing");
                String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false);
                prFamilyName.getFirstChild().setNodeValue(familyName);

                // - set first name
                Node prGivenName = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH);
                if (!STORKResponseProcessor.hasAttribute("givenName", attributeList))
                    throw new STORKException("givenName is missing");
                String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false);
                prGivenName.getFirstChild().setNodeValue(givenName);

                // - set date of birth
                Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion,
                        IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH);
                if (!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList))
                    throw new STORKException("dateOfBirth is missing");
                String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList,
                        false);
                prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth);

                identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink();

                //resign IDL
                IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance();
                Element resignedilAssertion = identitylinkresigner.resignIdentityLink(
                        identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey());
                identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink();
            } else {
                //contact SZR Gateway
                Logger.debug("Starting connecting SZR Gateway");
                identityLink = STORKResponseProcessor.connectToSZRGateway(
                        authnResponse.getPersonalAttributeList(), oaParam.getFriendlyName(), targetType, null,
                        oaParam.getMandateProfiles(), citizenSignature);
            }
        } catch (STORKException e) {
            // this is really nasty but we work against the system here. We are supposed to get the gender attribute from
            // stork. If we do not, we cannot register the person in the ERnP - we have to have the
            // gender for the represented person. So here comes the dirty hack. 
            if (e.getCause() instanceof STORKException
                    && e.getCause().getMessage().equals("gender not found in response")) {
                try {
                    Logger.trace("Initialize VelocityEngine...");

                    VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
                    Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
                    VelocityContext context = new VelocityContext();
                    context.put("SAMLResponse", request.getParameter("SAMLResponse"));
                    context.put("action", request.getRequestURL());

                    StringWriter writer = new StringWriter();
                    template.merge(context, writer);

                    response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
                } catch (Exception e1) {
                    Logger.error("Error sending gender retrival form.", e1);
                    //                  httpSession.invalidate();
                    throw new MOAIDException("stork.10", null);
                }

                return;
            }

            Logger.error("Error connecting SZR Gateway", e);
            throw new MOAIDException("stork.10", null);
        }
        Logger.debug("SZR communication was successfull");

        if (identityLink == null) {
            Logger.error("SZR Gateway did not return an identity link.");
            throw new MOAIDException("stork.10", null);
        }
        moaSession.setForeigner(true);

        Logger.info("Received Identity Link from SZR Gateway");
        moaSession.setIdentityLink(identityLink);

        Logger.debug("Adding addtional STORK attributes to MOA session");
        moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList());

        Logger.debug("Add full STORK AuthnResponse to MOA session");
        moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));

        //We don't have BKUURL, setting from null to "Not applicable"
        moaSession.setBkuURL("Not applicable (STORK Authentication)");

        // free for single use
        moaSession.setAuthenticatedUsed(false);

        // stork did the authentication step
        moaSession.setAuthenticated(true);

        //         //TODO: found better solution, but QAA Level in response could be not supported yet
        //         try {
        //
        //            moaSession.setQAALevel(authnResponse.getAssertions().get(0).
        //                  getAuthnStatements().get(0).getAuthnContext().
        //                  getAuthnContextClassRef().getAuthnContextClassRef());
        //            
        //         } catch (Throwable e) {
        //            Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
        //            moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
        //            
        //         }

        //session is implicit stored in changeSessionID!!!!
        String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);

        Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);

        //redirect
        String redirectURL = null;
        redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
                ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
                newMOASessionID);
        redirectURL = response.encodeRedirectURL(redirectURL);

        //          response.setContentType("text/html");
        //          response.setStatus(302);
        //          response.addHeader("Location", redirectURL);
        response.sendRedirect(redirectURL);
        Logger.info("REDIRECT TO: " + redirectURL);

    } catch (AuthenticationException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (MOAIDException e) {
        handleError(null, e, request, response, pendingRequestID);

    } catch (Exception e) {
        Logger.error("PEPSConnector has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }

}

From source file:com.adito.security.actions.PromptForPrivateKeyPassphraseDispatchAction.java

/**
 * Commit the passphrase change./*from  w w w.j  av  a2 s  . c o  m*/
 * 
 * @param mapping mappng
 * @param form form
 * @param request request
 * @param response response
 * @return forward
 * @throws Exception
 */
public ActionForward commit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    PromptForPrivateKeyPassphraseForm f = (PromptForPrivateKeyPassphraseForm) form;
    SessionInfo session = getSessionInfo(request);
    UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(session.getUser().getRealm());
    if (!udb.checkPassword(session.getUser().getPrincipalName(), f.getPassphrase())) {
        // User has entered incorrect passphrase - go back
        ActionErrors errs = new ActionErrors();
        errs.add(Globals.ERROR_KEY,
                new ActionMessage("promptForPrivateKeyPassphrase.error.incorrectPassphrase"));
        saveErrors(request.getSession(), errs);
        return mapping.getInputForward();
    }

    // Now check to see if the password has been added to the authentication scheme
    AuthenticationScheme scheme = (AuthenticationScheme) getSessionInfo(request).getHttpSession()
            .getAttribute(Constants.AUTH_SESSION);
    if (LogonControllerFactory.getInstance().getPasswordFromCredentials(scheme) == null) {
        // No so lets add it
        scheme.addCredentials(new PasswordCredentials(getSessionInfo(request).getUser().getPrincipalName(),
                f.getPassphrase().toCharArray()));
    }

    try {
        PublicKeyStore.getInstance().verifyPrivateKey(getSessionInfo(request).getUser().getPrincipalName(),
                f.getPassphrase().toCharArray());
    } catch (UpdatePrivateKeyPassphraseException upkpe) {

        // LDP - This code was incorrectly adding a bad logon warning. What we actually have to 
        // do is redirect back again to the UpdatePrivateKeyPassphraseIntercerptListener
        CoreUtil.removePageInterceptListener(request.getSession(), "promptForPrivateKeyPassphrase");
        CoreUtil.addPageInterceptListener(request.getSession(),
                new DefaultLogonController.UpdatePrivateKeyPassphraseInterceptListener());

        // Force the forward back to /showHome.do so that the intercerpt functions correctly
        return new ActionForward("/showHome.do");
    }

    CoreUtil.removePageInterceptListener(request.getSession(), "promptForPrivateKeyPassphrase");
    CoreServlet.getServlet()
            .fireCoreEvent(new CoreEvent(this, CoreEventConstants.LOGON,
                    getSessionInfo(request).getCredentials(), getSessionInfo(request))
                            .addAttribute(CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                            .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost()));

    return mapping.findForward("success");
}

From source file:net.duckling.ddl.web.controller.LynxEmailResourceController.java

/**
 * ?email/*from  ww w  . j  ava  2s.c  om*/
 * @param request
 * @param response
 * @throws UnsupportedEncodingException 
 */
@RequestMapping
public void dealEmailFile(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    request.setCharacterEncoding("utf-8");
    if (!ClientValidator.validate(request)) {
        writeSenderError(response, NO_AUTH, "", "");
        return;
    }
    String fileName = "";
    if (StringUtils.isNotEmpty(request.getParameter("fileName"))) {
        fileName = URLDecoder.decode(request.getParameter("fileName"), "UTF-8");
    }
    String userEmail = request.getParameter("email");
    String mid = request.getParameter("mid");
    if (!EmailUtil.isValidEmail(userEmail)) {
        writeSenderError(response, EMAIL_ERROR, "", fileName);
        return;
    }
    try {
        Integer.parseInt(request.getParameter("clbId"));
        Long.parseLong(request.getParameter("fileSize"));
    } catch (RuntimeException e) {
        writeSenderError(response, CLB_ID_ERROR, "", fileName);
        return;
    }
    int tid = getSaveAttaTid(request, userEmail);
    try {
        FileVersion fileVersion = saveFile(tid, request);
        addFileTag(tid, fileVersion, userEmail);
        String attachmentURL = VWBContainerImpl.findContainer().getBaseURL()
                + urlGenerator.getURL(tid, UrlPatterns.T_VIEW_R, fileVersion.getRid() + "", null);

        emailAttachmentService.createEmailAttach(createEmailAttachment(userEmail, mid, fileVersion));
        eventDispatcher.sendFileUploadEvent(fileVersion.getTitle(), fileVersion.getRid(), userEmail, tid);
        if (SupportedFileFormatForOnLineViewer.isSupported(MimeType.getSuffix(fileVersion.getTitle()))) {
            resourceOperateService.sendPdfTransformEvent(fileVersion.getClbId(),
                    fileVersion.getClbVersion() + "");
        }

        LOG.info(request.getRemoteHost() + "ddl" + fileVersion.getTid() + "" + userEmail
                + "[" + fileVersion.getTitle() + "]?"
                + fileVersion.getSize());
        writeSenderError(response, NORMAL, attachmentURL, fileVersion.getTitle());
    } catch (RuntimeException e) {
        LOG.error("?email", e);
        writeSenderError(response, ERROR, "", fileName);
    }
}