公司线上的tomcat版本是7,在使用过程中遇到一些问题,记录一下
源码中看到对于cookie中的字符有特殊限制,参考ascii表,如 https://baike.baidu.com/item/ASCII/309296?fr=aladdin 得知不允许特殊字符,接下来就是如何替换源码使我们能够支持这种字符。 查看官方文档 我们看到tomcat7在2021年3月31日就不再支持更新维护了,因此升级tomcat8势在必行。
继续翻看tomcat8官方文档 https://tomcat.apache.org/tomcat-8.0-doc/config/cookie-processor.html,发现如下文字
Note: CookieProcessor is a new configuration element, introduced in Tomcat 8.0.15. The CookieProcessor element allows different cookie parsing configuration in each web application, or globally in the default conf/context.xml file. The legacy cookie parsing algorithm supported only limited global configuration via several system properties. Those system properties are still supported, but are going to be deprecated in favor of this new configuration element. The new RFC6265-compliant implementation is a drop-in replacement for the original legacy one. The legacy implementation remains the default. You can select the implementation by setting className attribute on CookieProcessor element.
通俗的讲就是tomcat8.0.15版本之后可以在conf/context.xml文件中指定cookie处理器。之前的版本不支持。
很明显的方案是:我们将tomcat版本升级到8之后,再自定义这个cookie处理器将报错的代码注释掉不就OK了?
private boolean isHttpSeparator(final char c) { // 中文字符过滤,暂时下掉 /** if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw new IllegalArgumentException( "Control character in cookie value or attribute."); } } */ return httpSeparatorFlags.get(c); }将源码中LegacyCookieProcessor类拷贝出来,注释掉代码中的如图部分,然后在context.xml配置文件中配置 配置上线,运行一段时间。又出现了新的异常。
cookie长度超过200,我们没有设置过这玩意啊。
在tomcat7的变更历史中,https://tomcat.apache.org/tomcat-7.0-doc/changelog.html#Tomcat_7.0.106_(violetagg),在7.0.71版本中添加了cookie长度200的限制,原因是tomcat团队认为如果不限制的话超长的cookie可引发堆栈异常,是个bug给修复了,而我们之前的版本是7.0.42.0,因此低版本没有限制。
问题转换成如何修改cookie长度的问题,我们知道tomcat启动需要配置 Connector,因此在Connector可配置的属性中查找
The HTTP Connector element represents a Connector component that supports the HTTP/1.1 protocol. It enables Catalina to function as a stand-alone web server, in addition to its ability to execute servlets and JSP pages. A particular instance of this component listens for connections on a specific TCP port number on the server. One or more such Connectors can be configured as part of a single Service, each forwarding to the associated Engine to perform request processing and create the response.
进一步翻看tomcat文档 https://tomcat.apache.org/tomcat-8.0-doc/config/http.html 我们找到了这两个属性,设置下看看 启动之后,完美~
一个站点的cookie长度一般都够用,这个200应该能满足大多数的需要,那么这么长到底是啥,打印出来看看 在源码处理cookie之前,判断cookie的长度是否大于某个值(我这里设置的200),超过之后打印,完美~
上线后发现这种超长的cookie都是非法请求,直接干掉~