springboot 内置tomcat禁止不安全http方法

1、在tomcat的web.xml中可以配置如下内容

让tomcat禁止不安全的http方法

<security-constraint>  
   <web-resource-collection>  
      <url-pattern>/*</url-pattern>  
      <http-method>put</http-method>  
   <http-method>delete</http-method>  
   <http-method>head</http-method>  
   <http-method>options</http-method>  
   <http-method>trace</http-method>  
   </web-resource-collection>  
   <auth-constraint>  
   </auth-constraint>  
</security-constraint>  
<login-config>  
  <auth-method>basic</auth-method>  
</login-config>

2、spring boot使用内置tomcat

没有web.xml配置文件,可以通过以下配置进行,简单来说就是要注入到spring容器中

@configuration
public class tomcatconfig { 
    @bean
    public embeddedservletcontainerfactory servletcontainer() {
        tomcatembeddedservletcontainerfactory tomcatservletcontainerfactory = new tomcatembeddedservletcontainerfactory();
        tomcatservletcontainerfactory.addcontextcustomizers(new tomcatcontextcustomizer(){
 
   @override
   public void customize(context context) {
    securityconstraint constraint = new securityconstraint();
    securitycollection collection = new securitycollection();
    //http方法
    collection.addmethod("put");
    collection.addmethod("delete");
    collection.addmethod("head");
    collection.addmethod("options");
    collection.addmethod("trace");
    //url匹配表达式
    collection.addpattern("/*");
    constraint.addcollection(collection);
    constraint.setauthconstraint(true);
    context.addconstraint(constraint );
    
    //设置使用httponly
    context.setusehttponly(true);    
   }
        });
        return tomcatservletcontainerfactory;
    } 
}

启用不安全的http方法

问题描述:

可能会在web服务器上上载、修改或删除web页面、脚本和文件。

‘启用了不安全的http方法:options /system http/1.1allow: head, put, delete, trace, options, patch

上述方法的用途:

  • options、head、trace:主要由应用程序来发现和跟踪服务器支持和网络行为;
  • get:检索文档;
  • put和post:将文档提交到服务器;
  • delete:销毁资源或集合;
  • mkcol:创建集合
  • propfind和proppatch:针对资源和集合检索和设置属性;
  • copy和move:管理命名空间上下文中的集合和资源;
  • lock和unlock:改写保护

很显然上述操作明细可以对web服务器进行上传、修改、删除等操作,对服务造成威胁。虽然webdav有权限控制但是网上一搜还是一大堆的攻击方法,所以如果不需要这些方法还是建议直接屏蔽就好了。

解决方案:

在web应用中的web.xml加上如下内容

<security-constraint>
        <web-resource-collection>
            <web-resource-name>disp</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>put</http-method>
            <http-method>delete</http-method>
            <http-method>head</http-method>
            <http-method>options</http-method>
            <http-method>trace</http-method>
            <http-method>patch</http-method>
        </web-resource-collection>
        <auth-constraint></auth-constraint>
    </security-constraint>

标签介绍:

  • <security-constraint>用于限制对资源的访问;
  • <auth-constraint>用于限制那些角色可以访问资源,这里设置为空就是禁止所有角色用户访问;
  • <url-pattern>指定需要验证的资源
  • <http-method>指定那些方法需要验证

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。