in

Securing Your Web Apps: An In-Depth Guide to Using Secure Cookies in Tomcat

Hey there!

As a fellow technology enthusiast, I know you want to ensure your web applications are secure and protected. There are always new threats emerging, so it‘s crucial we lock down any vulnerabilities in our systems.

One common attack vector is cross-site scripting (XSS). This can allow hackers to steal user sessions, scrape sensitive data, or inject malicious code into your site.

Fortunately, Tomcat provides ways to defend against XSS and other attacks by configuring secure cookie flags. In this comprehensive guide, I‘ll explore how to enable the HttpOnly and Secure cookie settings to boost your security.

I‘ll also share my insights as a data analyst and security geek on best practices for hardening your configurations. By the end, you‘ll be well-equipped to protect your web apps!

Cookies: A Double-Edged Sword

Cookies are those small text files that web sites use to store data in your browser. They are an essential technology that powers a lot of the modern web, enabling session management, personalization, tracking, and more.

But cookies also introduce security risks if not handled properly.

By default, cookies are accessible by any JavaScript running on a page. This allows an XSS attack to potentially read sensitive cookie data. Attackers can even use JavaScript to modify cookie values or inject new malicious cookies.

Some examples of what attackers can do:

  • Steal session ID cookies to impersonate legitimate users
  • Change user account or role values stored in cookies
  • Inject tracking cookies from an ad network they control
  • Poison cookie data to spread malware or manipulate the site‘s functionality

Not great, right?

Fortunately, there are two very important cookie flags that prevent these types of XSS cookie attacks:

HttpOnly – This flag tells the browser to prevent client-side JavaScript from accessing the cookie. So even if an attacker can run JS on your page via XSS, they cannot read the protected cookies.

Secure – The secure flag ensures cookies are only sent over encrypted HTTPS connections. This provides security against man-in-the-middle attacks attempting to intercept traffic.

By enabling these simple flags, you can block entire classes of cookie-based exploits.

Average Number of Security Vulnerabilities per Website

To understand why cookie security is so important, let‘s look at some statistics:

Year Average # of Vulnerabilities per Site
2019 79
2020 117
2021 148

As you can see, the number of security flaws per website has been rising steadily over the past few years. A lot of these are cross-site scripting and injection bugs that put cookies and sessions at risk.

Cybercrime is also major – there were over 1.2 million web application attacks between June 2020 and May 2021 according to stats from CDNetworks.

So threats are very real and exploiting insecure cookies is a prime target for attackers.

Hardening your cookie configurations is a great way to improve your site‘s security posture with minimal effort. Let‘s look at how to do that in Tomcat…

The exact steps to configure the cookie flags depends on which version of Tomcat you are running. Let‘s go through the instructions for each supported release:

Tomcat 6.x Configuration

If you are still on Tomcat 6 (which reached end-of-life in 2016), here‘s what you need to do:

  1. Log into your Tomcat management console or directly onto the server itself.

  2. Navigate to the Tomcat install directory and open the conf/context.xml configuration file in a text editor.

  3. Find the <Context> element and add the useHttpOnly="true" attribute as shown:

<Context useHttpOnly="true">
  1. Now open the conf/server.xml file.

  2. Locate the <Connector> element for your HTTPS connector on port 8443. Add the secure="true" flag:

<Connector 
   protocol="org.apache.coyote.http11.Http11NioProtocol"
   port="8443" maxThreads="200"
   scheme="https" secure="true" SSLEnabled="true"
   keystoreFile="/path/to/keyfile" 
   keystorePass="changeit"
   clientAuth="false" sslProtocol="TLS"/>
  1. Save your changes and restart the Tomcat service.

The HttpOnly flag is now enabled application-wide and Secure will be set on all HTTPS requests.

Tomcat 7.x, 8.x, and 9.x Configuration

For modern Tomcat versions, here are the steps to secure cookies:

  1. Navigate to the conf directory of your Tomcat install.

  2. Use a text editor to open the web.xml file.

  3. Find the <session-config> element and add the following:

<session-config>
 <cookie-config>
   <http-only>true</http-only>
   <secure>true</secure>
 </cookie-config>
</session-config>
  1. Save changes and restart Tomcat.

That‘s all there is to it! Both flags are now enabled.

Verifying the Configuration

To validate the settings are working properly, we can use the browser‘s developer tools to inspect the cookies.

In Chrome:

  1. Open the DevTools via More Tools > Developer Tools.

  2. Click the Application tab.

  3. In the left pane, select Cookies to view the cookie details.

  4. Check that HttpOnly shows "Yes" and the Secure column shows "True".

Chrome Developer Tools showing secure cookies

You can also use online tools like this HTTP header checker to view the raw Set-Cookie headers from your server.

Look for headers like this to verify both flags are set:

Set-Cookie: SESSIONID=abc123; HttpOnly; Secure

With that, you‘ve successfully configured Tomcat to use secure, hardened cookies – great work!

Going Beyond Cookies – Building a Secure Web App

While configuring cookie security is crucial, there are additional best practices for building secure web applications:

Use HTTPS Everywhere

Always use HTTPS across your entire site, not just login pages. HTTP cookies are vulnerable to interception. SSL certificates are free via Let‘s Encrypt.

Input Validation

Validate and sanitize all input from users. This helps block XSS, SQLi, and other injection attacks.

Least Privilege

Follow the principle of least privilege. Restrict access with firewalls, disable unnecessary features and ports, use tight file permissions, etc.

Strong Authentication

Implement secure passwords, multifactor authentication, CAPTCHAs, rate limiting, lockouts, etc. to prevent credential stuffing.

Patch Frequently

Keep Tomcat, Java, web apps, databases and all software updated. Patching fixes known vulnerabilities.

Web Application Firewall

A WAF can monitor and block common attacks like injections, session hijacks, etc. in real-time.

Vulnerability Scanning

Regularly scan your site with tools like Nessus, Burp Suite, etc. to find and fix security holes before hackers do.

HTTP Security Headers

Implement headers like Content Security Policy, X-Frame-Options, etc. to harden browser security.

Incident Response Plan

Have an IR plan and procedures in place in case of a security breach. Know how to respond quickly.

I know that‘s a lot! The key is taking an incremental, defense-in-depth approach over time. Preventative measures like strong input validation will stop many attacks before they reach your cookies.

OWASP – Excellent Web Security Guidance

If you‘re looking for more web security best practices, I highly recommend the OWASP Cheat Sheet Series.

OWASP is an open-source web security project with tons of guides on protections like:

  • Transport Layer Protection (TLS)
  • User Password Management
  • Session Management
  • Input Validation
  • Output Encoding
  • Error Handling
  • Logging
  • Data Protection

And many more topics!

Their Session Management Cheat Sheet in particular covers properly setting cookie flags and other best practices.

Definitely check OWASP out for more security guidance as you harden your web applications.

Closing Thoughts

Hopefully this guide has provided you with a very thorough overview of securely configuring cookies in Tomcat. While no single measure can make you 100% secure, implementing protections like HttpOnly and Secure cookies makes attacking much more difficult.

Please let me know if you have any other questions! I‘m always happy to chat web security and get insights from other technology enthusiasts like yourself.

Stay safe out there and keep hacking!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.