¿Cómo se configuran las cookies HttpOnly en las aplicaciones web tomcat / java?


Después de leer la entrada del blog de Jeff en Protegiendo sus cookies: HttpOnly. Me gustaría implementar cookies HttpOnly en mi aplicación web.

¿Cómo le dice a tomcat que use cookies solo http para las sesiones?

Author: Cheekysoft, 2008-08-29

8 answers

HttpOnly es soportado a partir de Tomcat 6.0.19 y Tomcat 5.5.28.

Vea la entrada changelog para el error 44382.

El último comentario para bug 44382 afirma: "esto se ha aplicado a 5.5.x y se incluirán en 5.5.28 en adelante."Sin embargo, no parece que la versión 5.5.28 haya sido liberada.

La funcionalidad HttpOnly se puede habilitar para todas las aplicaciones web en conf/context.xml :

<Context useHttpOnly="true">
...
</Context>

Mi interpretación es que también funciona para un individuo contexto configurándolo en el deseado Contexto entrada en conf/server.xml (del mismo modo que el anterior).

 61
Author: jt.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-06 16:46:12

Actualización: Las cosas JSESSIONID aquí es solo para contenedores más antiguos. Por favor use respuesta actualmente aceptada de jt a menos que usted está utilizando

Al configurar cookies en su aplicación, use

response.setHeader( "Set-Cookie", "name=value; HttpOnly");

Sin embargo, en muchas aplicaciones web, la cookie más importante es el identificador de sesión, que se establece automáticamente por el contenedor como el Cookie JSESSIONID.

Si solo usa esta cookie, puede escribir un ServletFilter para volver a configurar las cookies al salir, forzando a JSESSIONID a HttpOnly. La página en http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx http://alexsmolen.com/blog/?p=16 sugiere agregar lo siguiente en un filtro.

if (response.containsHeader( "SET-COOKIE" )) {
  String sessionid = request.getSession().getId();
  response.setHeader( "SET-COOKIE", "JSESSIONID=" + sessionid 
                      + ";Path=/<whatever>; Secure; HttpOnly" );
} 

Pero tenga en cuenta que esto sobrescribirá todas las cookies y solo establecerá lo que indica aquí en este filtro.

Si utiliza cookies a la cookie JSESSIONID, entonces necesitará extender este código para configurar todas las cookies en el filtro. Esta no es una gran solución en el caso de las cookies múltiples, pero es quizás una solución rápida aceptable para la configuración solo de JSESSIONID.

Tenga en cuenta que a medida que su código evoluciona con el tiempo, hay un error oculto desagradable esperándole cuando se olvide de este filtro e intente establecer otra cookie en otro lugar de su código. Por supuesto, no se establecen.

Esto realmente es un hack sin embargo. Si usas Tomcat y puedes compilarlo, entonces echa un vistazo a la excelente sugerencia de Shabaz de parchear el soporte de HttpOnly en Tomcat.

 19
Author: Cheekysoft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 08:57:47

Tenga cuidado de no sobrescribir la bandera de cookies ";secure" en las sesiones https. Esta bandera evita que el navegador envíe la cookie a través de una conexión http sin cifrar, básicamente haciendo que el uso de https para solicitudes legítimas no tenga sentido.

private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
    if (response.containsHeader("SET-COOKIE")) {
        String sessionid = request.getSession().getId();
        String contextPath = request.getContextPath();
        String secure = "";
        if (request.isSecure()) {
            secure = "; Secure"; 
        }
        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
                         + "; Path=" + contextPath + "; HttpOnly" + secure);
    }
}
 14
Author: Hendrik Brummermann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-22 23:02:46

Para las cookies de sesión no parece ser compatible con Tomcat todavía. Vea el informe de error Necesita agregar soporte para el parámetro de cookie de sesión HttpOnly. Una solución un tanto complicada por ahora se puede encontrar aquí, que básicamente se reduce a parchear manualmente Tomcat. Realmente no puedo encontrar una manera fácil de hacerlo en este momento en este punto me temo.

Para resumir la solución, implica descargar la fuente 5.5 , y luego cambiar la fuente en el siguientes lugares:

org.apache.catalina.conector.Solicitud.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.Respuesta del conector.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}
 9
Author: Shabaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-28 21:36:07

Si su servidor web es compatible con la especificación Serlvet 3.0, como tomcat 7.0+, puede usar a continuación en web.xml como:

<session-config>
  <cookie-config>
     <http-only>true</http-only>        
     <secure>true</secure>        
  </cookie-config>
</session-config>

Como se menciona en los documentos:

HttpOnly : Especifica si alguna cookie de seguimiento de sesión creada por esta aplicación web se marcará como HttpOnly

Secure: Especifica si hay cookies de seguimiento de sesión creadas por esta aplicación web se marcará como seguro incluso si la solicitud que inició el la sesión correspondiente es usando HTTP simple en lugar de HTTPS

Consulte cómo configurar httponly y cookie de sesión para la aplicación web java

 7
Author: Alireza Fattahi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 04:02:23

También debe tenerse en cuenta que activar HttpOnly romperá los applets que requieren acceso con estado de vuelta a la jvm.

Las solicitudes http del Applet no usarán la cookie jsessionid y pueden ser asignadas a un tomcat diferente.

 2
Author: Pete Brumm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-18 20:33:57

Para las cookies que estoy configurando explícitamente, cambié a usar SimpleCookie proporcionada por Apache Shiro. No hereda de javax.servlet.http.Cookie por lo que se necesita un poco más de malabarismo para que todo funcione correctamente, sin embargo, proporciona una propiedad set HttpOnly y funciona con Servlet 2.5.

Para configurar una cookie en una respuesta, en lugar de hacer response.addCookie(cookie) debe hacer cookie.saveTo(request, response).

 2
Author: Jesse Vogt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-30 17:49:40

En Tomcat6, puede habilitar condicionalmente desde su clase de escucha HTTP:

public void contextInitialized(ServletContextEvent event) {                 
   if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
}

Usando esta clase

import java.lang.reflect.Field;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.catalina.core.StandardContext;
public class HttpOnlyConfig
{
    public static void enable(ServletContextEvent event)
    {
        ServletContext servletContext = event.getServletContext();
        Field f;
        try
        { // WARNING TOMCAT6 SPECIFIC!!
            f = servletContext.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
            f = ac.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
            sc.setUseHttpOnly(true);
        }
        catch (Exception e)
        {
            System.err.print("HttpOnlyConfig cant enable");
            e.printStackTrace();
        }
    }
}
 0
Author: Systemsplanet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-08 03:21:21