Session Management and Vulnerabilities
Lecture notes
Goal of the chapter
The goal of this chapter is to illustrate how session is tracked. This also
explains the session vulnerabilities and how session data can be misused
by an attacker.
Acknowledgement and further reading
The content of this chapter has been extracted from:
• Book: Professional Java for Web Applications, Author- Nicholas
S. Williams Published by Wrox Publications
• Book: Java 2: Web Developer Certification Study Guide : Exam
310-080,Levi, Natalie, and Philip Heller. John Wiley and Sons,
• https://cheatsheetseries.owasp.org/cheatsheets/
Session_Management_Cheat_Sheet.html
1 What is a session
A session is defined as a conversation between a server and a client. When a
sequence of request and response from the same client to the server happens, the
server cannot identify from which client the requests are coming of the sequence
of requests, since, HTTP is a stateless protocol. Therefore, when there is a need
to maintain the conversational state, session tracking is mandatory as HTTP
protocol cannot do this.1
1 Book: Professional Java for Web Applications, Author- Nicholas S. Williams Published
by Wrox Publications
1
1.1 Maintaining conversational state (Source Reference 2 )
Sessions are used to maintain state between one request and the next. HTTP
requests are completely stateless on their own. From the server’s perspective,
the request begins when the user’s web browser opens a socket to the server,
and it ends when the server sends the last packet back to the client and closes
the connection. At that point there is no longer a link between the user’s
browser and the server, and when the next connection comes in, there is no
way to tie the new request to the previous request. Applications often cannot
function correctly in such a stateless manner. A classic example is the online
shopping website. Nearly every online shopping site these days requires you to
create a username and password before purchasing, but consider even the few
that don’t. When browsing the store, you find a product you like, so you add
that product to your shopping cart. You continue browsing the store and find
another product you like. You add it to your shopping cart as well. When you
view your shopping cart, you see that both products you added remain in your
shopping cart. Somehow, between every request you made, the website knew
those requests were coming from the same browser on the same computer and
associated that with your shopping cart. Nobody else can see your shopping
cart or the items in it — it is exclusively tied to your computer and browser.
This scenario is an analogy to a real-life shopping experience. You enter your
favorite grocery store, and as you walk in the door, you grab a shopping cart
or basket. (You get a session from the server.) You walk through the store and
pick up items as you go, placing them in your cart (adding them to the session).
When you get to the cash register, you remove the items from the cart and give
them to the cashier, who scans them and takes your money. (You check out
using your session.) As you walk out the door, you return your shopping cart
or basket. (You close your browser or log out, ending your session.) In this
example, the cart or basket maintains your state as you walk through the store.
Without the cart, neither you nor the store could keep up with everything you
needed to purchase. If no state were maintained between requests, you would
have to “walk in,” grab one item, pay for it, “walk out” (end the request), and
repeat the entire process again for each item you wanted to purchase. Sessions
are the engine behind maintaining state between requests, and without them
the web would be a very different place.
3
1.2 Tracking Sessions. (Source Reference)
A session object is usually created when a client makes its first request to an
application. It is unique to a client and can exist longer than a single request
or even longer than the life of a client. It is an object used to track client-
specific data for the duration of the conversation or a specified period of time.
2 Book: Professional Java for Web Applications, Author- Nicholas S. Williams Published
by Wrox Publications
3 Book: Java 2: Web Developer Certification Study Guide : Exam 310-080,Levi, Natalie,
and Philip Heller. John Wiley Sons,
2
What distinguishes one session from another is its unique ID (session ID/ JSES-
SIONID). In fact, the container uses this session ID to map an incoming request
to the correct session object, which in turn is associated to a particular client.
The actual client information can be transferred by using one of three session
processes:
• Using hidden form fields
• Rewriting the URL
• Using cookies
• HttpSession Object
1.2.1 Tracking Sessions:HttpSession object
The servlet creates an HttpSession object to maintain data for the entire du-
ration of a transaction. An HttpSession object is created when the client first
accesses a web application. Data can then be written to or retrieved from
this object. The container (e.g.Tomcat) determines the method used to trans-
mit/propagate the session ID between the client and server (whether it used
cookies or URL rewriting).
To access a session object, use the HttpServletRequest method:
public HttpSession getSession()
The method returns the HttpSession object tied to the client requesting
the current servlet. If the object does not exist, the getSession() method will
automatically create a new HttpSession instance.
The other method used to access a session object is as follows:
public HttpSession getSession(boolean create)
This method differs from the previous version in that it requires a boolean
value:
• A true value creates a new session object if one does not already exist.
• A false value prevents a session object from being created if one does not
exist.
A false value is really what distinguishes this method from its overloaded get-
Session() method. Instead of creating a new session without further validation,
the developer might want to redirect the user back to a login page before a
session is created. Once created, the session object will continue to accumulate
stored data until the session is terminated
1.2.2 Storing and retrieving data HttpSession object
Data is stored to an HttpSession object as attributes by the following method:
public void setAttribute(String name, Object value)
3
The setAttribute() method binds a Java object to a specified key name.
Another servlet can then use the HttpSession object and access its data by
using the following method:
public Object getAttribute(String name)
The getAttribute() method uses the key name to find and return the asso-
ciated object.
1.2.3 Invalidating Sessions
A session can be invalidated in multiple ways. It can expire automatically, after
a specified or default period of inactivity, or a servlet can explicitly invalidate
a session through method calls. It is important to understand the effects on
the application and client when a session is nullified. Basically, all the attribute
data is lost when the session is invalidated. You would expect a session object
to terminate when the client is done with an application. You would expect this
to occur when the client leaves the site/ Logs out, terminates the browser, or
simply walks away from the application for a period of time.
To modifying the life of a session, The HttpSession interface provides the
following methods:
public void setMaxInactiveInterval(int secs)
public void invalidate() throws IllegalStateException
The invalidate() method can be called to close the session and unbind all
associated objects. If the session is already invalidated, then an IllegalStateEx-
ception object is thrown.
2 Session vulnerabilities: (Source Reference 4 )
Sessions are not without their vulnerabilities. These vulnerabilities can cause
serious problems for your users, and if you transact sensitive or personal in-
formation (such as credit card numbers or healthcare data) it can mean huge
penalties for your business. So it’s the act of stealing a customer’s session ID,
by which attacker can access your web application as if they’re that customer.
2.0.1 Session vulnerabilities: Session Fixation
An attacker might go to some website known to accept session IDs embedded in
the URL. The attacker will obtain a session ID in this manner (either through
a URL or by examining the browser’s cookies) and then send a URL containing
that session ID to a victim, through a forum or (most often) an e-mail. At this
point, when the user clicks the link to go to the website, his session ID is fixed
to what was in the URL — a session ID the attacker knows about. If the user
then logs in to the website during this session, the attacker will also be logged
in because he shares the session ID, giving him access to the user’s account.
4 Book: Professional Java for Web Applications, Author- Nicholas S. Williams Published
by Wrox Publications
4
2.0.2 Session vulnerabilities: Cross-Site Request Forgery
CSRF exploits the session vulnerabilities that allow an attacker to force an un-
suspecting user’s browser to send malicious requests. User/victim logs into a
trusted site with a new session. Trusted site store session identifier and prop-
agate using aforementioned method of Tracking Sessions. Attacker sends a
phishing email requests to trick user, so user click on the link and making a
request to a malicious site. That allow attacker to send a malicious request to
the trusted site from the user’s/victim’s browser using the active session of the
victim. This malicious request may steal information or modify information for
victim stored in the trusted server.
2.1 Vulnerable code to session hijacking
The user story of this vulnerable application is as follows. The application refers
to webapp 08-session management.
• The user is presented with a login form (plain-login.jsp).
• If the user provide a correct combination username and password, then
we let the user access the coach’s advice (workout.jsp).
• While in workout.jsp, the user can request many workouts. The user can
also logout to close the session.
1. Create the page plain-login.jsp for the user to send their credentials.
2. Tell the application to use plain-login.jsp as the entry point.
3. Create a controller to handle the login information. If successful, a piece
of data identifying the user will be added to the session.
4. Tell the Coach controller that the user identifier will be found as part of
the session data.
5. Create a database and table where to store the user’s credentials and
workout.
6. Provide a DAO interface to manipulate the database as needed.
7. Update workout.jsp by adding a button to get another workout, and an-
other button to logout.
2.1.1 Create the login page
Create a JSP page called plain-login.jsp with the following content.
5
1 <% @ taglib prefix = " form " uri = " http :// www . sp ri n gf ra me w or k . org / tags / form
" %>
2
3
4 < html >
5
6 < head >
7 < title > Custom Login Page </ title >
8
9 < style >
10 . failed {
11 color : red ;
12 }
13 </ style >
14
15 </ head >
16
17 < body >
18
19 < h3 > Please Login </ h3 >
20
21 < form : form action = " $ { pageContext . request . contextPath }/
authenticateTheUser "
22 method = " POST " >
23
24 <p >
25 User name : < input type = " text " name = " username " / >
26 </ p >
27
28 <p >
29 Password : < input type = " password " name = " password " / >
30 </ p >
31
32 <! -- Check for login error -- >
33
34 < div >
35 <i class = " failed " >$ { errorMessage } </ i >
36 </ div >
37
38 < input type = " submit " value = " Login " / >
39
40 </ form : form >
41
42 </ body >
43
44 </ html >
2.1.2 Use plain-login.jsp as the entry point
Update index.jsp with the following code.
1 <% response . sendRedirect ( " showLogin " ) ; % >
This request will be handle by the LoginController, which we will implement
next.
6
7
2.1.3 Create a controller to handle the login information
1 package edu . deakin . sit218 . coachwebapp . controller ;
2
3
4 import javax . servlet . http . H t t p S e r v l e t R e q u e s t ;
5 import javax . servlet . http . HttpSession ;
6 import javax . validation . Valid ;
7
8 import org . s pr i ng fr am e wo rk . stereotype . Controller ;
9 import org . s pr i ng fr am e wo rk . ui . Model ;
10 import org . s pr i ng fr am e work . validation . BindingResult ;
11 import org . s pr i ng fr am e work . web . bind . annotation . ModelA ttribute ;
12 import org . s pr i ng fr am e work . web . bind . annotation . R eq u e s t A t t r i b u t e ;
13 import org . s pr i ng fr am e work . web . bind . annotation . Reques tMapping ;
14 import org . s pr i ng fr am e work . web . bind . annotation . RequestParam ;
15 import javax . servlet . http . Cookie ;
16
17 import edu . deakin . sit218 . coachwebapp . dao . ClientDAO ;
18 import edu . deakin . sit218 . coachwebapp . dao . ClientDAOImpl ;
19 import edu . deakin . sit218 . coachwebapp . entity . Client ;
20 import org . s pr i ng fr am e work . web . bind . annotation . CookieValue ;
21 import javax . servlet . http . H t t p S e r v l e t R e s p o n s e ;
22
23 @Controller
24 public class L og in Co n tr ol l er {
25 @ Re qu es t Ma pp in g ( " / showLogin " )
26 public String login () {
27 return " plain - login " ;
28 }
29 @ Re qu e st Ma pp i ng ( " / logOut " )
30 public String logOut ( H t t p S e r v l e t R e q u e s t request , H t t p S e r v l e t R e s p o n s e
response ) {
31 HttpSession session = request . getSession ( false ) ;
32 if ( session != null ) {
33 session . invalidate () ;
34 // model . addAttribute (" message " , " You are a hacker ! get
out from here ") ;// Added
35 // return " workout ";// Added
36 }
37 return " plain - login " ;
38 }
39 @ Re qu e st Ma pp i ng ( " / a u t h e n t i c a t e T h e U s e r " )
40 public String a u t h e n t i c a t e T h e U s e r (
41 @RequestParam ( " username " ) String username ,
42 @RequestParam ( " password " ) String password ,
43 Model model , H t t p S e r v l e t R e q u e s t request , H t t p S e r v l e t R e s p o n s e
response ) {
44 ClientDAO dao = new ClientDAOImpl () ;
45 if ( dao . a r e C r e d e n t i a l s C o r r e c t ( username , password ) ) {
46 // Logic for when the client is exists
47 Client client = dao . re trieveC lient ( username ) ;
48 // Now that the client is authenticated
49 // We handle the logic to the Co a ch Co n tr ol le r .
50 Cookie foo = new Cookie ( " foo " , " bar " ) ;
51 foo . setHttpOnly ( true ) ;
52 response . addCookie ( foo ) ;
53 // DEfault is true and if session does not exist , it will create one
54 HttpSession session = request . getSession () ;
55
56 // setting session to expiry in 5 mins
57 session . s e t M a x I n a c t i v e I n t e r v a l (5*60) ;
58 // storing data to you session
59 session . setAttribute ( " user " , client . getUsername () ) ;
60 return " redirect :/ workout " ;
61 // return " redirect :/ workout ? user ="+ client . getId () ;
62 }
63 else {
64 // Logic for when the client doesn ’t exist
65 model . addAttribute ( " errorMessage8" , " Wrong combination of password
and username " ) ;
66 return " plain - login " ;
67 }
68 }
69
70 }
The method login just directs the application to the plain-login.jsp page.
The method authenticateTheUser is called by the login form, which provides
the username and password as parameters of the HttpRequest. The logic of
the method is rather straightforward. If the credentials are correct, then the
client is retrieved from the database. To keep track of the client throughout
different requests, the method adds the client’s identifier as a parameter to the
response: return "redirect:/workout;. Recall that ’redirect’ instruct the
DispatcherServlet to find the appropriate controller for the request /workout,
rather than rendering the view page workout.jsp. As the user logs in, HttpSes-
sion session = request.getSession(); it will create a new session if session does
not exist, session.setMaxInactiveInterval(5*60); This sets session to expiry in 5
mins. session.setAttribute(”user”, client.getUsername()); Storing data to your
session.
9
10
2.1.4 Create a CoachController class with the workout logic
1 package edu . deakin . sit218 . coachwebapp . controller ;
2 import javax . servlet . http . Cookie ;
3
4 import java . util . logging . Level ;
5
6 import javax . servlet . http . H t t p S e r v l e t R e q u e s t ;
7 import javax . servlet . http . H t t p S e r v l e t R e s p o n s e ;
8 import javax . validation . Valid ;
9
10 import org . s pr i ng fr am e work . stereotype . Controller ;
11 import org . s pr i ng fr am e work . ui . Model ;
12 import org . s pr i ng fr am e work . validation . BindingResult ;
13 import org . s pr i ng fr am e work . web . bind . annotation . E xc e p t i o n H a n d l e r ;
14 import org . s pr i ng fr am e work . web . bind . annotation . ModelA ttribute ;
15 import org . s pr i ng fr am e work . web . bind . annotation . Reques tMapping ;
16 import org . s pr i ng fr am e work . web . bind . annotation . RequestParam ;
17
18 import edu . deakin . sit218 . coachwebapp . dao . ClientDAO ;
19 import edu . deakin . sit218 . coachwebapp . dao . ClientDAOImpl ;
20 import edu . deakin . sit218 . coachwebapp . entity . Client ;
21 import javax . servlet . http . HttpSession ;
22
23
24
25 @Controller
26 public class C oa ch Co n tr ol l er {
27
28 private String referer1 ;
29 private String referer2 ;
30 @ Re qu e st Ma pp i ng ( " / workout " )
31 public String workout (
32 Model model , H t t p S e r v l e t R e q u e s t request , H t t p S e r v l e t R e s p o n s e
response ) {
33
34
35 HttpSession session = request . getSession ( false ) ;
36
37
38 if ( session == null )
39 {
40
41 // Logic for when the client doesn ’t exist , it has expired
42 model . addAttribute ( " errorMessage " , " Login First . Session has
expired ! " ) ;
43 return " plain - login " ;
44 }
45
46 // reyrieving data from your session
47 String uname = ( String ) session . getAttribute ( " user " ) ;
48
49
50 // Get jsessionID // session . getId ()
51 String jessionID = null ;
52 Cookie [] cookies = request . getCookies () ;
53 if ( cookies != null ) {
54 for ( Cookie cookie : cookies ) {
55 if ( cookie . getName () . equals ( " JSESSIONID " ) ) {
56 jessionID = " JSESSIONID = " + cookie . getValue () ;
57 break ;
58 }
59 }
60 }
61
62 //
63
64 // Get the referrer
65
66
67
11
// this . referer1 = request . getHeader (" referer ") ;
68
69 // code for ccomparison ====
70 String ref ;
71 String ctxpath ;
72 ref = request . getHeader ( " referer " ) ;
73 ctxpath = request . getCon textPath () ;
74 this . referer1 = ref . substring (0 , ref . indexOf ( ctxpath ) + ctxpath .
length () ) ;
75
76 // code for comparison ====
1 // Rest part Co ac hC o nt ro ll e r
2 ClientDAO dao = new ClientDAOImpl () ;
3 Client client = dao . re trieveC lient ( uname ) ;
4 // Retrieve Client object from database
5 g i v e W o r k o u t T o C l i e n t ( client , model , jessionID ) ;
6 // Return the View
7 return " workout " ;
8 }
9 private void g i v e W o r k o u t T o C l i e n t ( Client client , Model model , String
jessionID ) {
10 if ( client . getUsername () . equals ( " Rolando " ) ) {
11 model . addAttribute ( " message " , " Rolando never workouts " ) ;
12 }
13 else if ( client . getAge () < 40) {
14 model . addAttribute ( " message " , " Hey , " + client . getUsername () +
15 " you are still too young , no need to work out ! " ) ;
16 }
17 else {
18 model . addAttribute ( " message " , client . getUsername () +
19 " , please , run for 30 min . " +
20 System . lineSeparator () +
21 " You have worked out " + client . getWorkouts () +
22 " times . " + jessionID ) ;
23 client . addWorkout () ;
24 ClientDAO dao = new ClientDAOImpl () ;
25 dao . updateClient ( client ) ;
26 }
27 }
28 @ Re qu e st Ma pp i ng ( " / change " )
29 public String changeAge ( @RequestParam ( " age " ) int age ,
30 Model model , H t t p S e r v l e t R e q u e s t request , H t t p S e r v l e t R e s p o n s e
response ) {
31 HttpSession session = request . getSession ( false ) ;
32 if ( session == null )
33 {
34 // Logic for when the client doesn ’t exist , it has expired
35 model . addAttribute ( " errorMessage " , " Login First . Session has
expired ! " ) ;
36 return " plain - login " ;
37 }
38 // code for correct comparison =====
39 String ref , ctxpath ;
40 ref = request . getHeader ( " referer " ) ;
41 ctxpath = request . getCont extPath () ;
42 this . referer2 = ref . substring (0 , ref . indexOf ( ctxpath ) + ctxpath
. length () ) ;
43
44 // if ( this . referer1 != this . referer2 )
45 if (! this . referer2 . equals ( this . referer1 ) )
46 {
47 // HttpSession session = request . getSession ( false ) ;
48 if ( session != null ) {
49 session . invalidate () ;
50 model . addAttribute ( " message " , " You are a hacker ! get
out from here " ) ; // Added
51 return " workout " ; // Added
52 }
53 }
54 // code for correct comparison ========
55 // System . out . println ( referer ) ;
56 ClientDAO dao = new ClientDAOImpl () ;
57 // HttpSession session = request . getSession () ;
58 // Get jsessionID
59 String jessionID = null ;
60 Cookie [] cookies = request . getCookies () ;
61 if ( cookies != null ) {
62 for ( Cookie cookie : cookies ) {
63 if ( cookie . getName () . equals ( " JSESSIONID " ) ) {
64 jessionID = " JSESSIONID = " + cookie . getValue () ;
65 break ;
66 } 12
67 }
68 }
69 // Get jsessionID
70 String uname = ( String ) session . getAttribute ( " user " ) ;
71 Client client = dao . re trieveC lient ( uname ) ;
72 client . setAge ( age ) ;
73 dao . updateClient ( client ) ;
74 model . addAttribute ( " message " , " You age has been updated " +
jessionID ) ;
75 return " workout " ;
76 }
The following code in @RequestMapping(”/change”) finds the session ID
which is propagated using cookies.
1
2 // Get jsessionID
3 String jessionID = null ;
4 Cookie [] cookies = request . getCookies () ;
5 if ( cookies != null ) {
6 for ( Cookie cookie : cookies ) {
7 if ( cookie . getName () . equals ( " JSESSIONID " ) ) {
8 jessionID = " JSESSIONID = " + cookie . getValue () ;
9 break ;
10 }
11 }
12 }
13 // Get jsessionID
The following code in @RequestMapping(”/change”) prevents CSRF attack.
Without this code, the app is vulnerable to CSRF attack
1
2 String ref , ctxpath ;
3 ref = request . getHeader ( " referer " ) ;
4 ctxpath = request . getCont extPath () ;
5 this . referer2 = ref . substring (0 , ref . indexOf ( ctxpath ) + ctxpath
. length () ) ;
6
7 // if ( this . referer1 != this . referer2 )
8 if (! this . referer2 . equals ( this . referer1 ) )
9 {
10 // HttpSession session = request . getSession ( false ) ;
11 if ( session != null ) {
12 session . invalidate () ;
13 model . addAttribute ( " message " , " You are a hacker ! get
out from here " ) ; // Added
14 return " workout " ; // Added
15 }
16 }
The following code in @RequestMapping(”/change”) force user to login
again if session expires.
1 HttpSession session = request . getSession ( false ) ;
2
3
4 if ( session == null )
5 {
6
7 // Logic for when the client doesn ’t exist , it has expired
8 model . addAttribute ( " errorMessage " , " Login First . Session has
expired ! " ) ;
9 return " plain - login " ;
10 }
11
13
2.1.5 Create a database and table where to store the user’s data
For authentication purposes we will need clients to have a password. Let’s create
a new MySQL schema by using the following script. The table is already created
for you in the VM for you. The code is given for information.
1 -- MySQL Workbench Forward Engineering
2
3 SET @ O L D _ U N I Q U E _ C H E C K S = @@UNIQUE_CHECKS , UNIQUE_CHECKS =0;
4 SET @ O L D _ F O R E I G N _ K E Y _ C H E C K S = @@FOREIGN_KEY_CHECKS , F O R E I G N _ K E Y _ C H E C K S
=0;
5 SET @OLD_SQL_MODE = @@SQL_MODE ,
6 SQL_MODE = ’ ONLY_FULL_GROUP_BY , STRICT_TRANS_TABLES , NO_ZERO_IN_DATE ,
NO_ZERO_DATE , ERROR_FOR_DIVISION_BY_ZERO , N O _ E N G I N E _ S U B S T I T U T I O N ’;
7
8 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
9 -- Schema sessiondb
10 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
11
12 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
13 -- Schema sessiondb
14 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
15 CREATE SCHEMA IF NOT EXISTS ‘ sessiondb ‘ DEFAULT CHARACTER SET utf8 ;
16 USE ‘ sessiondb ‘ ;
17
18 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
19 -- Table ‘ sessiondb ‘. ‘ user ‘
20 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
21 CREATE TABLE IF NOT EXISTS ‘ sessiondb ‘. ‘ user ‘ (
22 ‘ iduser ‘ INT NOT NULL AUTO_INCREMENT ,
23 ‘ username ‘ VARCHAR (45) NULL ,
24 ‘ password ‘ VARCHAR (45) NULL ,
25 ‘age ‘ INT ,
26 ‘ workouts ‘ INT ,
27 PRIMARY KEY ( ‘ iduser ‘) )
28 ENGINE = InnoDB ;
29
30 CREATE USER ’ admin ’ IDENTIFIED BY ’ admin ’;
31
32 GRANT ALL ON ‘ sessiondb ‘.* TO ’ admin ’;
33
34 SET SQL_MODE = @OLD_SQL_MODE ;
35 SET F O R E I G N _ K E Y _ C H E C K S = @ O L D _ F O R E I G N _ K E Y _ C H E C K S ;
36 SET UNIQUE_CHECKS = @ O L D _ U N I Q U E _ C H E C K S ;
With respect to the schema we have been using in previous chapters, this
new MySQL schema, called sessiondb, adds a password field.
Let’s populate this table by using the following script.
1 INSERT INTO ‘ sessiondb ‘. ‘ user ‘ ( ‘ iduser ‘ , ‘ username ‘ , ‘ password ‘ , ‘
workouts ‘ ,
2 ‘age ‘) VALUES ( ’1 ’ , ’ Bob ’ , ’ bob ’ , ’0 ’ , ’ 23 ’) ;
3 INSERT INTO ‘ sessiondb ‘. ‘ user ‘ ( ‘ iduser ‘ , ‘ username ‘ , ‘ password ‘ , ‘
workouts ‘ ,
4 ‘age ‘) VALUES ( ’ 11 ’ , ’ Alice ’ , ’ alice ’ , ’0 ’ , ’ 33 ’) ;
5 INSERT INTO ‘ sessiondb ‘. ‘ user ‘ ( ‘ iduser ‘ , ‘ username ‘ , ‘ password ‘ , ‘
workouts ‘ ,
6 ‘age ‘) VALUES ( ’ 111 ’ , ’ John ’ , ’ john ’ , ’0 ’ , ’ 43 ’) ;
14
We also need to update our Client class by adding the password field. Next
I provide a extract of the main changes. At this point you should already be
able to generate the getters and setters of the new attributes.
1 @Entity
2 @Table ( name = " user " )
3 public class Client {
4
5 @Id
6 @ Ge ne r at ed Va l ue ( strategy = Gen erationT ype . IDENTITY )
7 @Column ( name = " iduser " )
8 protected int id ;
9
10 public int getId () {
11 return id ;
12 }
13
14 public void setId ( int id ) {
15 this . id = id ;
16 }
17
18 @Pattern ( regexp = " ^[ A - Z ][ a - z ]* " , message = " A name should start with
a "
19 + " capital letter and be followed by lower case letters " )
20 @Column ( name = " username " )
21 protected String username ;
22
23 @NotNull ( message = " is required " )
24 @Size ( min = 1 , message = " is required " )
25 @Column ( name = " password " )
26 protected String password ;
27
28 @Min ( value = 18 , message = " You must be 18 years old or older " )
29 @Max ( value = 120 , message = " Vampires are not allowed " )
30 @Column ( name = " age " )
31 protected int age ;
32
33 @Column ( name = " workouts " )
34 protected int workouts = 0;
Finally, we need to configure hibernate to access the database. We are doing
this by using the file hibernate.cfg.xml.
1 < session - factory >
2
3 <! -- JDBC Database connection settings -- >
4 < property
5 name = " connection . driver_class " > com . mysql . cj . jdbc . Driver </ property >
6 < property
7 name = " connection . url " > jdbc : mysql :// localhost :3306/ sessiondb </
property >
8 < property name = " connection . username " > admin </ property >
9 < property name = " connection . password " > admin </ property >
10 .
11 .
12 .
13 .
14 .
15
2.1.6 Provide a DAO interface to manipulate the database as needed
Our ClientDAO looks now as follows.
1 package edu . deakin . sit218 . coachwebapp . dao ;
2
3 import edu . deakin . sit218 . coachwebapp . entity . Client ;
4
5 public interface ClientDAO {
6
7 public void updateClient ( Client client ) ;
8
9 public void insertClient ( Client client ) ;
10
11 public boolean a r e C r e d e n t i a l s C o r r e c t ( String username , String password
);
12
13 public boolean existsClient ( String username ) ;
14
15 public Client retrie veClien t ( String username ) ;
16
17 public Client r e t r i e v e C l i e n t B y I D ( int userId ) ;
18
19 }
16
2.1.7 Update workout.jsp
1 <% @ page language = " java " contentType = " text / html ; charset = ISO -8859 -1 "
2 pageEncoding = " ISO -8859 -1 " % >
3 <! DOCTYPE html >
4 < html >
5 < head >
6 < meta charset = " ISO -8859 -1 " >
7 < title > sit218 Secure Coding - First Spring - based dynamic web app </
title >
8 </ head >
9 < body >
10 < h1 >$ { message } </ h1 >
11
12 < form action = " $ { pageContext . request . contextPath }/ workout "
13 method = " GET " >
14
15
16
17 Another workout advice ?
18 < input type = " submit " value = " Yes " / >
19 </ form >
20
21
22
23 < form action = " change " method = " Get " >
24 change age to ? < input type = " number " name = " age " / >
25 < input type = " submit " / >
26 </ form >
27
28 < form action = " $ { pageContext . request . contextPath }/ logOut " >
29
30
31 Logout ? < input type = " submit " value = " Yes " / >
32
33 </ form >
34
35 </ body >
36 </ html >
From the code above, form action = ”change” method = ”Get” ... , this will
call URL pattern /change which will be handled by @RequestMapping(”/change”)public
String changeAge()
Practical activity
Perform a CSRF attack on this application. Complete the start activity
for this. Some code you may need to add in your webapp 08-session
management according to the code given webapp to work CSRF pre-
vention. Some code you may need to change in your webapp 08-session
management to perform CSRF attack.
17
3 Best Practices for Implementing Session Man-
agement
Having many points of attack related to a web session or a large attack surface
can compromise web applications and sessions in many different ways.
Below are some of the best practices for implementing session management.
Implementing these practices will reduce the attack surface and minimize the
risk and damage caused by vulnerabilities and attacks resulting from improper
session management.
3.1 Session Management Best practices according to OWASP
Source: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_
Cheat_Sheet.html
• Use a trusted server for creating session identifiers.
• Efficient algorithms should be used by the session management controls
to ensure the random generation of session identifiers.
• Ensure that the logging out functionality terminates the associated con-
nection/session entirely.
• Ensure that session inactivity timeout is as short as possible, it is recom-
mended that the timeout of the session activity should be less than several
hours.
• Generate a new session identifier when a user re-authenticates or opens a
new browser session.
• Implement periodic termination of sessions, especially for applications that
provide critical services.
• Appropriate access controls should be implemented to protect all server-
side session data from unauthorized access by other users.
18