public static void showSession(HttpServletRequest req, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); out.println("Session id: " + session.getId()); out.println(" session.isNew(): " + session.isNew()); out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs"); out.println( " session.getCreationTime(): " + session.getCreationTime() + " (" + new Date(session.getCreationTime()) + ")"); out.println( " session.getLastAccessedTime(): " + session.getLastAccessedTime() + " (" + new Date(session.getLastAccessedTime()) + ")"); out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie()); out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL()); out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid()); out.println("Saved session Attributes:"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(" " + name + ": " + session.getAttribute(name) + "<BR>"); } }
/* good2() reverses the bodies in the if statement */ private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable { if (IO.static_returns_t()) { Logger tcLog = Logger.getLogger("cwe_testcases_logger"); if (request.getParameter("username") == null) { return; } String username = request.getParameter("username"); if (username.matches("[a-zA-Z0-9]*")) { HttpSession session = request.getSession(true); /* FIX: logged message does not contain session id */ tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId()); } else { response.getWriter().println("Invalid characters"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger tcLog = Logger.getLogger("cwe_testcases_logger"); if (request.getParameter("username") == null) { return; } String username = request.getParameter("username"); if (username.matches("[a-zA-Z0-9]*")) { HttpSession session = request.getSession(true); /* FLAW: leak session ID to debug log */ tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId()); } else { response.getWriter().println("Invalid characters"); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer) session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount); out.println( "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TR>" + "</TABLE>\n"); // the following two statements show how to retrieve parameters in // the request. The URL format is something like: // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li String myname = request.getParameter("myname"); if (myname != null) out.println("Hey " + myname + "<br><br>"); out.println("</BODY></HTML>"); }
public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer) session.getAttribute("snoop.count"); if (count == null) { count = 1; } else count = count + 1; session.setAttribute("snoop.count", count); out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()); out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>"); out.println("<BODY><H1>Session Snoop</H1>"); // Display the hit count for this page out.println( "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times.")); out.println("<P>"); out.println("<H3>Here is your saved session data:</H3>"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>"); } out.println("<H3>Here are some vital stats on your session:</H3>"); out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>"); out.println("New session: " + session.isNew() + "<BR>"); out.println("Timeout: " + session.getMaxInactiveInterval()); out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>"); out.println("Creation time: " + session.getCreationTime()); out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>"); out.println( "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>"); out.println("<H3>Test URL Rewriting</H3>"); out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println("</BODY></HTML>"); }
public static synchronized void sessionDestroyed(HttpSessionEvent ev) { HttpSession httpSession = ev.getSession(); String id = httpSession.getId(); synchronized (lookupSessionById) { lookupSessionById.remove(id); } // Forget HTTP-session: { lookupHttpSessionById.remove(id); } }
/** @service the servlet service request. called once for each servlet request. */ public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException { String name; String value[]; String val; servRes.setHeader("AUTHORIZATION", "user fred:mypassword"); ServletOutputStream out = servRes.getOutputStream(); HttpSession session = servReq.getSession(true); session.setAttribute("timemilis", new Long(System.currentTimeMillis())); if (session.isNew()) { out.println("<p> Session is new "); } else { out.println("<p> Session is not new "); } Long l = (Long) session.getAttribute("timemilis"); out.println("<p> Session id = " + session.getId()); out.println("<p> TimeMillis = " + l); out.println("<H2>Servlet Params</H2>"); Enumeration e = servReq.getParameterNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); value = servReq.getParameterValues(name); out.println(name + " : "); for (int i = 0; i < value.length; ++i) { out.println(value[i]); } out.println("<p>"); } out.println("<H2> Request Headers : </H2>"); e = servReq.getHeaderNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); val = (String) servReq.getHeader(name); out.println("<p>" + name + " : " + val); } try { BufferedReader br = servReq.getReader(); String line = null; while (null != (line = br.readLine())) { out.println(line); } } catch (IOException ie) { ie.printStackTrace(); } session.invalidate(); }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { System.out.println("COOKIE=" + cookies[i].getValue()); } } HttpSession session = req.getSession(false); if (session == null) { throw new ServletException("Unable to access login session"); } res.getWriter().println("JSESSIONID=" + session.getId()); }
public static synchronized void sessionCreated(HttpSessionEvent ev) { HttpSession httpSession = ev.getSession(); String id = httpSession.getId(); // Remember HTTP-session: { lookupHttpSessionById.put(id, httpSession); } AbstractSession session = null; synchronized (lookupSessionById) { session = lookupSessionById.get(id); } if (session == null) { Principal userPrincipal = null; Date timeCreation = new Date(httpSession.getCreationTime()); Date timeLastAccess = new Date(httpSession.getLastAccessedTime()); List<String> urisForLastRequests = null; Properties properties = null; session = new DefaultSession( id, userPrincipal, timeCreation, timeLastAccess, urisForLastRequests, properties); synchronized (lookupSessionById) { lookupSessionById.put(id, session); // Update 'sessionCountMax': { int sessionCount = lookupSessionById.size(); if (sessionCount > sessionCountMax) { sessionCountMax = sessionCount; sessionCountMaxTime = System.currentTimeMillis(); } } } } }
private void endHereCommon() throws BeanException { // save EJB object handle in property if (ejb != null) { try { hPubAccessHandle = ejb.getHandle(); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5955 " + this.getClass().getName() + ": ejb.getHandle(), ejb=" + ejb + ": " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // save ejb accessHandle and hpubLinkKey in HttpSession if ((oHttpServletRequest != null) && (outputProps != null)) { // a new HPubEjb2HttpSessionBindingListener object containing the ejb access // handle and hPubLinkKey for the connection is bound to the session using // a prefix and the ending connection state of the IO just processed. // This hPubLinkKey uniquely identifies the connection associated with the // IO chain for that HP Runtime JVM. // The ejb access handle is contained within the HPubEjb2HttpSessionBindingListener // object so that an ejb remove can be issued in the case where a session // timeout or session invalidation occurs for an incomplete IO chain. HttpSession theWebsession = oHttpServletRequest.getSession(true); if (theWebsession != null) { synchronized (theWebsession) { try { String theKey = KEY_WEBCONN + outputProps.getHPubEndChainName(); hPubLinkKey = outputProps.getHPubLinkKey(); theWebsession.setAttribute( theKey, new HPubEJB2HttpSessionBindingListener(hPubAccessHandle, hPubLinkKey)); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "theWebsession.setAttribute(" + theKey + ",new HPubEJB2HttpSessionBindingListener(" + hPubAccessHandle + ", " + hPubLinkKey + "))"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } if (auditing == true) { auditArgs[0] = "\n---\nIN:" + this.getClass().getName() + " " + theKey + " " + hPubAccessHandle + " " + hPubLinkKey + " " + theWebsession.getId(); auditArgs[1] = theWebsession; try { auditMethod.invoke(o, auditArgs); } catch (Exception x) { } } } catch (Exception e) { hPubLinkKey = null; // set to null to force following error logic } } } // if an error occurred throw an exception to cause ejb remove to be issued. if ((theWebsession == null) || (hPubLinkKey == null)) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5956 " + this.getClass().getName() + ": HttpServletRequest.getSession(true), hPubLinkKey=" + hPubLinkKey; System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // send Event to User indicating that the Query request is complete RequestCompleteEvent hPubEvent = new RequestCompleteEvent(this); fireHPubReqCompleteEvent(hPubEvent); return; }
/** all processing methods end up here */ private void startHereCommon() throws BeanException { // try to get the linkKey if already set in input properties try { hPubLinkKey = inputProps.getHPubLinkKey(); } catch (Exception e) { } // if running in Web environment and either the ejb access handle or // the linkKey are null, try to get them from the HttpSession if (oHttpServletRequest != null) { HttpSession theWebsession = oHttpServletRequest.getSession(false); if (theWebsession != null) { synchronized (theWebsession) { try { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getId()=" + theWebsession.getId(); try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } String theKey = KEY_WEBCONN + inputProps.getHPubStartChainName(); // if linkKey or access handle is null try to get it from Websession HPubEJB2HttpSessionBindingListener sbl = (HPubEJB2HttpSessionBindingListener) theWebsession.getAttribute(theKey); if ((hPubLinkKey == null) && (sbl != null)) { hPubLinkKey = sbl.getLinkKey(); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getAttribute(hPubLinkKey)=" + hPubLinkKey; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } inputProps.setHPubLinkKey(hPubLinkKey); } if ((hPubAccessHandle == null) && (sbl != null)) { hPubAccessHandle = sbl.getEjbHandle(); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getAttribute(hPubAccessHandle)=" + hPubAccessHandle; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } } // set the ejb handle to null before removing the Session Binding // Listener object if (auditing == true) { if (sbl != null) auditArgs[0] = "\n---\nOUT:" + this.getClass().getName() + " " + theKey + " " + hPubAccessHandle + " " + hPubLinkKey + " " + theWebsession.getId(); else // error - object not found in HttpSession auditArgs[0] = "\n---\nERR:" + this.getClass().getName() + " " + theKey + " " + theWebsession.getId(); auditArgs[1] = theWebsession; try { auditMethod.invoke(o, auditArgs); } catch (Exception x) { } } if (sbl != null) sbl.setEjbHandle(null); theWebsession.removeAttribute(theKey); } catch (IllegalStateException e) { } } } } // if either of required properties are still null then the ejb cannot // be accessed - throw an exception. if ((hPubAccessHandle == null) || (hPubLinkKey == null)) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5951 " + this.getClass().getName() + ": hPubAccessHandle==null || hPubLinkKey==null"; System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } else { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "hPubAccessHandle=" + hPubAccessHandle + ",hPubLinkKey=" + hPubLinkKey; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } } // get the EJB object from the handle try { ejb = (com.ibm.HostPublisher.EJB.HPubEJB2) javax.rmi.PortableRemoteObject.narrow( hPubAccessHandle.getEJBObject(), com.ibm.HostPublisher.EJB.HPubEJB2.class); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5952 " + this.getClass().getName() + ": getEJBObject(): " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } // if ejb handle, go invoke the HPubEJB's main business method. if (ejb != null) { try { outputProps = (CrownCounselIndexGetList_Properties) ejb.processIO(inputProps); inputProps = outputProps; inputProps.setInitialCall(false); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5953 " + this.getClass().getName() + ": processIO(" + inputProps.getClass().getName() + "): " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } endHereCommon(); return; }
public void getEnv(VariableTable vt) { Enumeration e = null; HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest()); HttpSession session = request.getSession(false); String db_charset = "gb2312"; String url_charset = null; vt.remove("SESSION.LOGINID"); vt.remove("SESSION.LOGINNAME"); vt.remove("SESSION.LOGINROLE"); if (vt.exists("WEBCHART.DB_CHARSET")) { db_charset = vt.getString("WEBCHART.DB_CHARSET"); } if (vt.exists("WEBCHART.URL_CHARSET")) { url_charset = vt.getString("WEBCHART.URL_CHARSET"); } if (session != null) { e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); Object value = session.getAttribute(name); vt.add(name, java.sql.Types.VARCHAR); if (value != null) vt.setValue(name, value.toString()); } vt.add("SESSION.ID", java.sql.Types.VARCHAR); vt.setValue("SESSION.ID", session.getId()); vt.add("SESSION.CREATE", java.sql.Types.VARCHAR); vt.setValue( "SESSION.CREATE", DBOperation.toString( new java.util.Date(session.getCreationTime()), "yyyy-MM-dd HH:mm:ss")); vt.add("SESSION.ACCESS", java.sql.Types.VARCHAR); vt.setValue( "SESSION.ACCESS", DBOperation.toString( new java.util.Date(session.getLastAccessedTime()), "yyyy-MM-dd HH:mm:ss")); } e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getParameter(name); ; String par_values[] = request.getParameterValues(name); name = name.toUpperCase(); if (name.equalsIgnoreCase("WEBCHART.SECURITY") || name.equalsIgnoreCase("WEBCHART.DEFAULTACCESS") || name.equalsIgnoreCase("WEBCHART.ALLOW") || name.equalsIgnoreCase("WEBCHART.DENY") || name.equalsIgnoreCase("WEBCHART.IPSECURITY") || name.equalsIgnoreCase("WEBCHART.IPACCESS") || name.equalsIgnoreCase("WEBCHART.IPALLOW") || name.equalsIgnoreCase("WEBCHART.IPDENY") || name.equalsIgnoreCase("WEBCHART.XSLDOC") || name.equalsIgnoreCase("WEBCHART.IMAGEONLY") || name.equalsIgnoreCase("WEBCHART.XMLDATA") || name.equalsIgnoreCase("WEBCHART.LOGSQL") || name.equalsIgnoreCase("WEBCHART.DATATYPE") || name.equalsIgnoreCase("WEBCHART.URLS") || name.equalsIgnoreCase("WEBCHART.TOPURLS") || name.equalsIgnoreCase("WEBCHART.TOPCURR") || name.equalsIgnoreCase("WEBCHART.LEFTURLS") || name.equalsIgnoreCase("WEBCHART.LEFTCURR") || name.equalsIgnoreCase("WEBCHART.INPUTS") || name.equalsIgnoreCase("WEBCHART.CACHE") || name.equalsIgnoreCase("WEBCHART.DATA") || name.equalsIgnoreCase("WEBCHART.CSS") || name.equalsIgnoreCase("WEBCHART.RELOAD") || name.equalsIgnoreCase("WEBCHART.EXPIRE") || name.equalsIgnoreCase("WEBCHART.DMLKEY") || name.equalsIgnoreCase("WEBCHART.ENGINE") || name.equalsIgnoreCase("WEBCHART.EXCELURL") || name.equalsIgnoreCase("WEBCHART.DBID") || name.equalsIgnoreCase("WEBCHART.DBIDSEED") || name.equalsIgnoreCase("WEBCHART.SECUREFIELDS") || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_IMAGE") || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_TIME") || name.startsWith("WEBCHART.SECUREMEMO") || name.startsWith("WEBCHART.QUERY_") || name.startsWith("WEBCHART.HEADHTML_") || name.startsWith("WEBCHART.DATAHTML_") || name.startsWith("WEBCHART.VARLIST_") || name.startsWith("WEBCHART.FORALL_") || name.startsWith("WEBCHART.XMLDATA_") || name.startsWith("WEBCHART.TABLE_") || name.startsWith("WEBCHART.COLUMN_") || name.startsWith("SESSION.")) continue; if (name.startsWith("WEBCHART.") && !name.equals("WEBCHART.DOCTYPE")) continue; vt.add(name, java.sql.Types.VARCHAR); if (par_values != null && par_values.length > 1) { StringBuffer temp = new StringBuffer(); for (int i = 0; i < par_values.length; i++) { if (par_values[i] != null && par_values[i].trim().length() > 0) { if (temp.length() > 0) { temp.append(","); } temp.append(par_values[i]); } } value = temp.toString(); } if (url_charset != null) { try { value = new String(value.getBytes(url_charset), db_charset); } catch (java.io.UnsupportedEncodingException uee) { } ; } vt.setValue(name, value); } vt.add("REQUEST.REMOTEADDR", java.sql.Types.VARCHAR); vt.setValue("REQUEST.REMOTEADDR", getClientIPAddr()); vt.add("REQUEST.REMOTEHOST", java.sql.Types.VARCHAR); vt.setValue("REQUEST.REMOTEHOST", request.getRemoteAddr()); vt.add("REQUEST.REFERER", java.sql.Types.VARCHAR); vt.setValue("REQUEST.REFERER", request.getHeader("Referer")); vt.add("REQUEST.QUERYSTRING", java.sql.Types.VARCHAR); vt.setValue("REQUEST.QUERYSTRING", request.getQueryString()); }