1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
|
From dc194fc977ab6cfbf3c1ecb085e2bac5db14af6d Mon Sep 17 00:00:00 2001
From: Brian Demers <bdemers@apache.org>
Date: Tue, 7 Jul 2020 21:06:35 -0400
Subject: [PATCH] Add a feature to allow for global filters
Adds new filter to block invalid requests
---
.../shiro/guice/web/ShiroWebModule.java | 25 ++-
.../shiro/guice/web/ShiroWebModuleTest.java | 153 ++++++++++++++++++
.../ShiroWebFilterConfiguration.java | 8 +
.../web/ConfiguredGlobalFiltersTest.groovy | 104 ++++++++++++
.../web/DisabledGlobalFiltersTest.groovy | 64 ++++++++
...ShiroWebSpringAutoConfigurationTest.groovy | 30 +++-
...roWebAutoConfigurationTestApplication.java | 4 +-
.../spring/web/ShiroFilterFactoryBean.java | 23 +++
.../config/AbstractShiroWebConfiguration.java | 3 -
.../AbstractShiroWebFilterConfiguration.java | 9 +-
.../config/ShiroWebFilterConfiguration.java | 6 +
.../ShiroWebFilterConfigurationTest.groovy | 3 +-
.../web/ShiroFilterFactoryBeanTest.java | 8 +-
.../config/IniFilterChainResolverFactory.java | 18 +++
.../web/filter/InvalidRequestFilter.java | 124 ++++++++++++++
.../shiro/web/filter/mgt/DefaultFilter.java | 4 +-
.../filter/mgt/DefaultFilterChainManager.java | 37 ++++-
.../web/filter/mgt/FilterChainManager.java | 22 +++
.../web/servlet/AbstractShiroFilter.java | 1 +
.../IniFilterChainResolverFactoryTest.groovy | 26 +++
.../web/env/IniWebEnvironmentTest.groovy | 69 ++++++++
.../filter/InvalidRequestFilterTest.groovy | 106 ++++++++++++
.../mgt/DefaultFilterChainManagerTest.groovy | 52 ++++++
.../org/apache/shiro/web/env/FilterStub.java | 45 ++++++
24 files changed, 925 insertions(+), 19 deletions(-)
create mode 100644 support/spring-boot/spring-boot-web-starter/src/test/groovy/org/apache/shiro/spring/boot/autoconfigure/web/ConfiguredGlobalFiltersTest.groovy
create mode 100644 support/spring-boot/spring-boot-web-starter/src/test/groovy/org/apache/shiro/spring/boot/autoconfigure/web/DisabledGlobalFiltersTest.groovy
create mode 100644 web/src/main/java/org/apache/shiro/web/filter/InvalidRequestFilter.java
create mode 100644 web/src/test/groovy/org/apache/shiro/web/filter/InvalidRequestFilterTest.groovy
create mode 100644 web/src/test/java/org/apache/shiro/web/env/FilterStub.java
--- a/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java
+++ b/support/guice/src/main/java/org/apache/shiro/guice/web/ShiroWebModule.java
@@ -30,6 +30,7 @@
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.env.WebEnvironment;
+import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
@@ -84,7 +85,8 @@
public static final Key<SslFilter> SSL = Key.get(SslFilter.class);
@SuppressWarnings({"UnusedDeclaration"})
public static final Key<UserFilter> USER = Key.get(UserFilter.class);
-
+ @SuppressWarnings({"UnusedDeclaration"})
+ public static final Key<InvalidRequestFilter> INVALID_REQUEST = Key.get(InvalidRequestFilter.class);
static final String NAME = "SHIRO";
@@ -121,6 +123,12 @@
};
}
+ public List<FilterConfig<? extends Filter>> globalFilters() {
+ ArrayList<FilterConfig<? extends Filter>> filters = new ArrayList<FilterConfig<? extends Filter>>();
+ filters.add(filterConfig(INVALID_REQUEST));
+ return Collections.unmodifiableList(filters);
+ }
+
@Override
protected final void configureShiro() {
bindBeanType(TypeLiteral.get(ServletContext.class), Key.get(ServletContext.class, Names.named(NAME)));
@@ -132,6 +140,12 @@
this.configureShiroWeb();
+ // add default matching route if not already set
+ if (!filterChains.containsKey("/**")) {
+ // no config, this will add only the global filters
+ this.addFilterChain("/**", new FilterConfig[0]);
+ }
+
bind(FilterChainResolver.class).toProvider(new FilterChainResolverProvider(setupFilterChainConfigs()));
}
@@ -150,8 +164,15 @@
// collect the keys used for this path
List<Key<? extends Filter>> keysForPath = new ArrayList<Key<? extends Filter>>();
- for (int i = 0; i < filterChain.getValue().length; i++) {
- FilterConfig<? extends Filter> filterConfig = filterChain.getValue()[i];
+ List<FilterConfig<? extends Filter>> globalFilters = this.globalFilters();
+ FilterConfig<? extends Filter>[] pathFilters = filterChain.getValue();
+
+ // merge the global filters and the path specific filters
+ List<FilterConfig<? extends Filter>> filterConfigs = new ArrayList<FilterConfig<? extends Filter>>(globalFilters.size() + pathFilters.length);
+ filterConfigs.addAll(globalFilters);
+ filterConfigs.addAll(Arrays.asList(pathFilters));
+
+ for (FilterConfig<? extends Filter> filterConfig : filterConfigs) {
Key<? extends Filter> key = filterConfig.getKey();
String config = filterConfig.getConfigValue();
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java
@@ -24,6 +24,7 @@
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.binder.AnnotatedBindingBuilder;
+import com.google.inject.name.Names;
import org.apache.shiro.guice.ShiroModuleTest;
import org.apache.shiro.env.Environment;
import org.apache.shiro.mgt.SecurityManager;
@@ -31,6 +32,7 @@
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.web.env.EnvironmentLoader;
import org.apache.shiro.web.env.WebEnvironment;
+import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
@@ -55,7 +57,9 @@
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collection;
+import java.util.Collections;
import java.util.Iterator;
+import java.util.List;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
@@ -212,35 +216,184 @@
FilterChain filterChain = simpleFilterChainResolver.getChain(request, null, null);
assertThat(filterChain, instanceOf(SimpleFilterChain.class));
Filter nextFilter = getNextFilter((SimpleFilterChain) filterChain);
+ assertThat(nextFilter, instanceOf(InvalidRequestFilter.class));
+ nextFilter = getNextFilter((SimpleFilterChain) filterChain);
assertThat(nextFilter, instanceOf(FormAuthenticationFilter.class));
// test the /test_custom_filter resource
filterChain = simpleFilterChainResolver.getChain(request, null, null);
assertThat(filterChain, instanceOf(SimpleFilterChain.class));
nextFilter = getNextFilter((SimpleFilterChain) filterChain);
+ assertThat(nextFilter, instanceOf(InvalidRequestFilter.class));
+ nextFilter = getNextFilter((SimpleFilterChain) filterChain);
assertThat(nextFilter, instanceOf(CustomFilter.class));
// test the /test_authc_basic resource
filterChain = simpleFilterChainResolver.getChain(request, null, null);
assertThat(filterChain, instanceOf(SimpleFilterChain.class));
nextFilter = getNextFilter((SimpleFilterChain) filterChain);
+ assertThat(nextFilter, instanceOf(InvalidRequestFilter.class));
+ nextFilter = getNextFilter((SimpleFilterChain) filterChain);
assertThat(nextFilter, instanceOf(BasicHttpAuthenticationFilter.class));
// test the /test_perms resource
filterChain = simpleFilterChainResolver.getChain(request, null, null);
assertThat(filterChain, instanceOf(SimpleFilterChain.class));
nextFilter = getNextFilter((SimpleFilterChain) filterChain);
+ assertThat(nextFilter, instanceOf(InvalidRequestFilter.class));
+ nextFilter = getNextFilter((SimpleFilterChain) filterChain);
assertThat(nextFilter, instanceOf(PermissionsAuthorizationFilter.class));
// test the /multiple_configs resource
filterChain = simpleFilterChainResolver.getChain(request, null, null);
assertThat(filterChain, instanceOf(SimpleFilterChain.class));
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(InvalidRequestFilter.class));
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(FormAuthenticationFilter.class));
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(RolesAuthorizationFilter.class));
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(PermissionsAuthorizationFilter.class));
verify(servletContext, request);
}
+
+ @Test
+ public void testDefaultPath() {
+
+ final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
+ ServletContext servletContext = createMock(ServletContext.class);
+ HttpServletRequest request = createMock(HttpServletRequest.class);
+
+ servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject());
+ expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes();
+ expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
+ expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes();
+ expect(request.getPathInfo()).andReturn(null).anyTimes();
+ expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar");
+ replay(servletContext, request);
+
+ Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) {
+ @Override
+ protected void configureShiroWeb() {
+ bindRealm().to(ShiroModuleTest.MockRealm.class);
+ expose(FilterChainResolver.class);
+ // no paths configured
+ }
+
+ @Provides
+ public ShiroModuleTest.MockRealm createRealm() {
+ return mockRealm;
+ }
+ });
+
+ FilterChainResolver resolver = injector.getInstance(FilterChainResolver.class);
+ assertThat(resolver, instanceOf(SimpleFilterChainResolver.class));
+ SimpleFilterChainResolver simpleFilterChainResolver = (SimpleFilterChainResolver) resolver;
+
+ // test the /test_authc resource
+ FilterChain filterChain = simpleFilterChainResolver.getChain(request, null, null);
+ assertThat(filterChain, instanceOf(SimpleFilterChain.class));
+
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(InvalidRequestFilter.class));
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
+
+ verify(servletContext, request);
+ }
+
+ @Test
+ public void testDisableGlobalFilters() {
+
+ final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
+ ServletContext servletContext = createMock(ServletContext.class);
+ HttpServletRequest request = createMock(HttpServletRequest.class);
+
+ servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject());
+ expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes();
+ expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
+ expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes();
+ expect(request.getPathInfo()).andReturn(null).anyTimes();
+ expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar");
+ replay(servletContext, request);
+
+ Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) {
+ @Override
+ protected void configureShiroWeb() {
+ bindRealm().to(ShiroModuleTest.MockRealm.class);
+ expose(FilterChainResolver.class);
+ this.addFilterChain("/**", filterConfig(AUTHC));
+ }
+
+ @Override
+ public List<FilterConfig<? extends Filter>> globalFilters() {
+ return Collections.emptyList();
+ }
+
+ @Provides
+ public ShiroModuleTest.MockRealm createRealm() {
+ return mockRealm;
+ }
+ });
+
+ FilterChainResolver resolver = injector.getInstance(FilterChainResolver.class);
+ assertThat(resolver, instanceOf(SimpleFilterChainResolver.class));
+ SimpleFilterChainResolver simpleFilterChainResolver = (SimpleFilterChainResolver) resolver;
+
+ // test the /test_authc resource
+ FilterChain filterChain = simpleFilterChainResolver.getChain(request, null, null);
+ assertThat(filterChain, instanceOf(SimpleFilterChain.class));
+
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(FormAuthenticationFilter.class));
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
+
+ verify(servletContext, request);
+ }
+
+ @Test
+ public void testChangeInvalidFilterConfig() {
+
+ final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
+ ServletContext servletContext = createMock(ServletContext.class);
+ HttpServletRequest request = createMock(HttpServletRequest.class);
+
+ servletContext.setAttribute(eq(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY), EasyMock.anyObject());
+ expect(request.getAttribute("javax.servlet.include.context_path")).andReturn("").anyTimes();
+ expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
+ expect(request.getAttribute("javax.servlet.include.path_info")).andReturn(null).anyTimes();
+ expect(request.getPathInfo()).andReturn(null).anyTimes();
+ expect(request.getAttribute("javax.servlet.include.servlet_path")).andReturn("/test/foobar");
+ replay(servletContext, request);
+
+ Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) {
+ @Override
+ protected void configureShiroWeb() {
+
+ bindConstant().annotatedWith(Names.named("shiro.blockBackslash")).to(false);
+
+ bindRealm().to(ShiroModuleTest.MockRealm.class);
+ expose(FilterChainResolver.class);
+ this.addFilterChain("/**", filterConfig(AUTHC));
+ }
+
+ @Provides
+ public ShiroModuleTest.MockRealm createRealm() {
+ return mockRealm;
+ }
+ });
+
+ FilterChainResolver resolver = injector.getInstance(FilterChainResolver.class);
+ assertThat(resolver, instanceOf(SimpleFilterChainResolver.class));
+ SimpleFilterChainResolver simpleFilterChainResolver = (SimpleFilterChainResolver) resolver;
+
+ // test the /test_authc resource
+ FilterChain filterChain = simpleFilterChainResolver.getChain(request, null, null);
+ assertThat(filterChain, instanceOf(SimpleFilterChain.class));
+
+ Filter invalidRequestFilter = getNextFilter((SimpleFilterChain) filterChain);
+ assertThat(invalidRequestFilter, instanceOf(InvalidRequestFilter.class));
+ assertFalse("Expected 'blockBackslash' to be false", ((InvalidRequestFilter) invalidRequestFilter).isBlockBackslash());
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(FormAuthenticationFilter.class));
+ assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
+
+ verify(servletContext, request);
+ }
private Filter getNextFilter(SimpleFilterChain filterChain) {
--- /dev/null
+++ b/support/spring-boot/spring-boot-web-starter/src/test/groovy/org/apache/shiro/spring/boot/autoconfigure/web/ConfiguredGlobalFiltersTest.groovy
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.shiro.spring.boot.autoconfigure.web
+
+import org.apache.shiro.spring.boot.autoconfigure.web.application.ShiroWebAutoConfigurationTestApplication
+import org.apache.shiro.spring.web.ShiroFilterFactoryBean
+import org.apache.shiro.spring.web.config.AbstractShiroWebFilterConfiguration
+import org.apache.shiro.web.filter.InvalidRequestFilter
+import org.apache.shiro.web.filter.authz.PortFilter
+import org.apache.shiro.web.filter.mgt.DefaultFilter
+import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager
+import org.apache.shiro.web.filter.mgt.NamedFilterList
+import org.apache.shiro.web.servlet.AbstractShiroFilter
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.boot.test.context.SpringBootTest
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.test.context.junit4.SpringRunner
+
+import static org.hamcrest.MatcherAssert.assertThat
+import static org.hamcrest.Matchers.*
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = [ShiroWebAutoConfigurationTestApplication, Config])
+
+class ConfiguredGlobalFiltersTest {
+
+ @Configuration
+ static class Config extends AbstractShiroWebFilterConfiguration {
+
+ @Bean
+ List<String> globalFilters() {
+ return [DefaultFilter.invalidRequest.name(), DefaultFilter.port.name()]
+ }
+
+ @Bean
+ @Override
+ ShiroFilterFactoryBean shiroFilterFactoryBean() {
+ ShiroFilterFactoryBean bean = super.shiroFilterFactoryBean()
+ InvalidRequestFilter invalidRequestFilter = new InvalidRequestFilter()
+ invalidRequestFilter.setBlockBackslash(false)
+ PortFilter portFilter = new PortFilter()
+ portFilter.setPort(9999)
+ bean.getFilters().put("invalidRequest", invalidRequestFilter)
+ bean.getFilters().put("port", portFilter)
+ return bean
+ }
+ }
+
+ @Autowired
+ private AbstractShiroFilter shiroFilter
+
+ @Test
+ void testGlobalFiltersConfigured() {
+ // make sure global chains are configured
+ assertThat shiroFilter.filterChainResolver.filterChainManager, instanceOf(DefaultFilterChainManager)
+ DefaultFilterChainManager filterChainManager = shiroFilter.filterChainResolver.filterChainManager
+
+ // default config set
+ assertThat filterChainManager.globalFilterNames, contains(DefaultFilter.invalidRequest.name(),
+ DefaultFilter.port.name())
+ // default route configured
+ NamedFilterList allChain = filterChainManager.getChain("/**")
+ assertThat allChain, contains(
+ instanceOf(DefaultFilter.invalidRequest.filterClass),
+ instanceOf(DefaultFilter.port.filterClass))
+
+ InvalidRequestFilter invalidRequest = allChain.get(0)
+ assertThat "Expected invalidRequest.blockBackslash to be false", !invalidRequest.isBlockBackslash()
+ PortFilter portFilter = allChain.get(1) // an ugly line, but we want to make sure that we can override the filters
+ // defined in Shiro's DefaultFilter
+ assertThat portFilter.port, equalTo(9999)
+
+ // configured routes also contain global filters
+ NamedFilterList loginChain = filterChainManager.getChain("/login.html")
+ assertThat loginChain, contains(
+ instanceOf(DefaultFilter.invalidRequest.filterClass),
+ instanceOf(DefaultFilter.port.filterClass),
+ instanceOf(DefaultFilter.authc.filterClass)) // configured in ShiroWebAutoConfigurationTestApplication
+
+ assertThat loginChain.get(0), sameInstance(invalidRequest)
+ assertThat loginChain.get(1), sameInstance(portFilter)
+
+
+ }
+}
--- /dev/null
+++ b/support/spring-boot/spring-boot-web-starter/src/test/groovy/org/apache/shiro/spring/boot/autoconfigure/web/DisabledGlobalFiltersTest.groovy
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.shiro.spring.boot.autoconfigure.web;
+
+import org.apache.shiro.spring.boot.autoconfigure.web.application.ShiroWebAutoConfigurationTestApplication
+import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager
+import org.apache.shiro.web.servlet.AbstractShiroFilter
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.boot.test.context.SpringBootTest
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.test.context.junit4.SpringRunner
+
+import static org.hamcrest.MatcherAssert.assertThat
+import static org.hamcrest.Matchers.equalTo
+import static org.hamcrest.Matchers.instanceOf
+import static org.hamcrest.Matchers.nullValue
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = [ShiroWebAutoConfigurationTestApplication, Config])
+class DisabledGlobalFiltersTest {
+
+ @Configuration
+ static class Config {
+
+ @Bean
+ List<String> globalFilters() {
+ return []
+ }
+ }
+
+ @Autowired
+ private AbstractShiroFilter shiroFilter
+
+ @Test
+ void testGlobalFiltersDisabled() {
+ // make sure global chains are configured
+ assertThat shiroFilter.filterChainResolver.filterChainManager, instanceOf(DefaultFilterChainManager)
+ DefaultFilterChainManager filterChainManager = shiroFilter.filterChainResolver.filterChainManager
+
+ // default config set
+ assertThat filterChainManager.globalFilterNames, equalTo([])
+ // default route configured
+ assertThat filterChainManager.getChain("/**"), nullValue()
+ }
+}
--- a/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java
+++ b/support/spring/src/main/java/org/apache/shiro/spring/web/ShiroFilterFactoryBean.java
@@ -25,8 +25,10 @@
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.apache.shiro.web.filter.AccessControlFilter;
+import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
+import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
@@ -41,7 +43,9 @@
import org.springframework.beans.factory.config.BeanPostProcessor;
import javax.servlet.Filter;
+import java.util.ArrayList;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
/**
@@ -121,6 +125,8 @@
private Map<String, Filter> filters;
+ private List<String> globalFilters;
+
private Map<String, String> filterChainDefinitionMap; //urlPathExpression_to_comma-delimited-filter-chain-definition
private String loginUrl;
@@ -131,6 +137,8 @@
public ShiroFilterFactoryBean() {
this.filters = new LinkedHashMap<String, Filter>();
+ this.globalFilters = new ArrayList<String>();
+ this.globalFilters.add(DefaultFilter.invalidRequest.name());
this.filterChainDefinitionMap = new LinkedHashMap<String, String>(); //order matters!
}
@@ -332,6 +340,14 @@
}
/**
+ * Sets the list of filters that will be executed against every request. Defaults to the {@link InvalidRequestFilter} which will block known invalid request attacks.
+ * @param globalFilters the list of filters to execute before specific path filters.
+ */
+ public void setGlobalFilters(List<String> globalFilters) {
+ this.globalFilters = globalFilters;
+ }
+
+ /**
* Lazily creates and returns a {@link AbstractShiroFilter} concrete instance via the
* {@link #createInstance} method.
*
@@ -388,6 +404,9 @@
}
}
+ // set the global filters
+ manager.setGlobalFilters(this.globalFilters);
+
//build up the chains:
Map<String, String> chains = getFilterChainDefinitionMap();
if (!CollectionUtils.isEmpty(chains)) {
@@ -398,6 +417,9 @@
}
}
+ // create the default chain, to match anything the path matching would have missed
+ manager.createDefaultChain("/**"); // TODO this assumes ANT path matching, which might be OK here
+
return manager;
}
@@ -533,6 +555,7 @@
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
}
setSecurityManager(webSecurityManager);
+
if (resolver != null) {
setFilterChainResolver(resolver);
}
--- a/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java
@@ -18,6 +18,7 @@
*/
package org.apache.shiro.spring.web;
+import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
@@ -55,11 +56,12 @@
DefaultFilterChainManager fcManager = (DefaultFilterChainManager) resolver.getFilterChainManager();
NamedFilterList chain = fcManager.getChain("/test");
assertNotNull(chain);
- assertEquals(chain.size(), 2);
+ assertEquals(chain.size(), 3);
Filter[] filters = new Filter[chain.size()];
filters = chain.toArray(filters);
- assertTrue(filters[0] instanceof DummyFilter);
- assertTrue(filters[1] instanceof FormAuthenticationFilter);
+ assertTrue(filters[0] instanceof InvalidRequestFilter); // global filter
+ assertTrue(filters[1] instanceof DummyFilter);
+ assertTrue(filters[2] instanceof FormAuthenticationFilter);
}
/**
--- a/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java
+++ b/web/src/main/java/org/apache/shiro/web/config/IniFilterChainResolverFactory.java
@@ -24,6 +24,7 @@
import org.apache.shiro.config.ReflectionBuilder;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.Factory;
+import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
@@ -32,7 +33,9 @@
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
+import java.util.Collections;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
/**
@@ -51,6 +54,8 @@
private Map<String, ?> defaultBeans;
+ private List<String> globalFilters = Collections.singletonList(DefaultFilter.invalidRequest.name());
+
public IniFilterChainResolverFactory() {
super();
}
@@ -72,6 +77,14 @@
this.filterConfig = filterConfig;
}
+ public List<String> getGlobalFilters() {
+ return globalFilters;
+ }
+
+ public void setGlobalFilters(List<String> globalFilters) {
+ this.globalFilters = globalFilters;
+ }
+
protected FilterChainResolver createInstance(Ini ini) {
FilterChainResolver filterChainResolver = createDefaultInstance();
if (filterChainResolver instanceof PathMatchingFilterChainResolver) {
@@ -122,9 +135,14 @@
//add the filters to the manager:
registerFilters(filters, manager);
+ manager.setGlobalFilters(getGlobalFilters());
+
//urls section:
section = ini.getSection(URLS);
createChains(section, manager);
+
+ // create the default chain, to match anything the path matching would have missed
+ manager.createDefaultChain("/**"); // TODO this assumes ANT path matching
}
protected void registerFilters(Map<String, Filter> filters, FilterChainManager manager) {
--- /dev/null
+++ b/web/src/main/java/org/apache/shiro/web/filter/InvalidRequestFilter.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.shiro.web.filter;
+
+import org.apache.shiro.web.util.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * A request filter that blocks malicious requests. Invalid request will respond with a 400 response code.
+ * <p>
+ * This filter checks and blocks the request if the following characters are found in the request URI:
+ * <ul>
+ * <li>Semicolon - can be disabled by setting {@code blockSemicolon = false}</li>
+ * <li>Backslash - can be disabled by setting {@code blockBackslash = false}</li>
+ * <li>Non-ASCII characters - can be disabled by setting {@code blockNonAscii = false}, the ability to disable this check will be removed in future version.</li>
+ * </ul>
+ *
+ * @see <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/firewall/StrictHttpFirewall.html">This class was inspired by Spring Security StrictHttpFirewall</a>
+ * @since 1.6
+ */
+public class InvalidRequestFilter extends AccessControlFilter {
+
+ private static final List<String> SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));
+
+ private static final List<String> BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));
+
+ private boolean blockSemicolon = true;
+
+ private boolean blockBackslash = true;
+
+ private boolean blockNonAscii = true;
+
+ @Override
+ protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
+ String uri = WebUtils.toHttp(request).getRequestURI();
+ return !containsSemicolon(uri)
+ && !containsBackslash(uri)
+ && !containsNonAsciiCharacters(uri);
+ }
+
+ @Override
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+ WebUtils.toHttp(response).sendError(400, "Invalid request");
+ return false;
+ }
+
+ private boolean containsSemicolon(String uri) {
+ if (isBlockSemicolon()) {
+ int length = uri.length();
+ for (int i = 0; i < length; i++) {
+ char c = uri.charAt(i);
+ if (c == ';') {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean containsBackslash(String uri) {
+ if (isBlockBackslash()) {
+ int length = uri.length();
+ for (int i = 0; i < length; i++) {
+ char c = uri.charAt(i);
+ if (c == '\\') {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean containsNonAsciiCharacters(String uri) {
+ if (isBlockNonAscii()) {
+ return !containsOnlyPrintableAsciiCharacters(uri);
+ }
+ return false;
+ }
+
+ private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
+ int length = uri.length();
+ for (int i = 0; i < length; i++) {
+ char c = uri.charAt(i);
+ if (c < '\u0020' || c > '\u007e') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean isBlockSemicolon() {
+ return blockSemicolon;
+ }
+
+ public void setBlockSemicolon(boolean blockSemicolon) {
+ this.blockSemicolon = blockSemicolon;
+ }
+
+ public boolean isBlockBackslash() {
+ return blockBackslash;
+ }
+
+ public void setBlockBackslash(boolean blockBackslash) {
+ this.blockBackslash = blockBackslash;
+ }
+
+ public boolean isBlockNonAscii() {
+ return blockNonAscii;
+ }
+
+ public void setBlockNonAscii(boolean blockNonAscii) {
+ this.blockNonAscii = blockNonAscii;
+ }
+}
--- a/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilter.java
+++ b/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilter.java
@@ -19,6 +19,7 @@
package org.apache.shiro.web.filter.mgt;
import org.apache.shiro.util.ClassUtils;
+import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.authc.*;
import org.apache.shiro.web.filter.authz.*;
import org.apache.shiro.web.filter.session.NoSessionCreationFilter;
@@ -47,7 +48,8 @@
rest(HttpMethodPermissionFilter.class),
roles(RolesAuthorizationFilter.class),
ssl(SslFilter.class),
- user(UserFilter.class);
+ user(UserFilter.class),
+ invalidRequest(InvalidRequestFilter.class);
private final Class<? extends Filter> filterClass;
--- a/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java
+++ b/web/src/main/java/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.java
@@ -30,8 +30,10 @@
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -52,17 +54,21 @@
private Map<String, Filter> filters; //pool of filters available for creating chains
+ private List<String> globalFilterNames; // list of filters to prepend to every chain
+
private Map<String, NamedFilterList> filterChains; //key: chain name, value: chain
public DefaultFilterChainManager() {
this.filters = new LinkedHashMap<String, Filter>();
this.filterChains = new LinkedHashMap<String, NamedFilterList>();
+ this.globalFilterNames = new ArrayList<String>();
addDefaultFilters(false);
}
public DefaultFilterChainManager(FilterConfig filterConfig) {
this.filters = new LinkedHashMap<String, Filter>();
this.filterChains = new LinkedHashMap<String, NamedFilterList>();
+ this.globalFilterNames = new ArrayList<String>();
setFilterConfig(filterConfig);
addDefaultFilters(true);
}
@@ -115,6 +121,17 @@
addFilter(name, filter, init, true);
}
+ public void createDefaultChain(String chainName) {
+ // only create the defaultChain if we don't have a chain with this name already
+ // (the global filters will already be in that chain)
+ if (!getChainNames().contains(chainName) && !CollectionUtils.isEmpty(globalFilterNames)) {
+ // add each of global filters
+ for (String filterName : globalFilterNames) {
+ addToChain(chainName, filterName);
+ }
+ }
+ }
+
public void createChain(String chainName, String chainDefinition) {
if (!StringUtils.hasText(chainName)) {
throw new NullPointerException("chainName cannot be null or empty.");
@@ -124,7 +141,14 @@
}
if (log.isDebugEnabled()) {
- log.debug("Creating chain [" + chainName + "] from String definition [" + chainDefinition + "]");
+ log.debug("Creating chain [" + chainName + "] with global filters " + globalFilterNames + " and from String definition [" + chainDefinition + "]");
+ }
+
+ // first add each of global filters
+ if (!CollectionUtils.isEmpty(globalFilterNames)) {
+ for (String filterName : globalFilterNames) {
+ addToChain(chainName, filterName);
+ }
}
//parse the value by tokenizing it to get the resulting filter-specific config entries
@@ -273,6 +297,21 @@
chain.add(filter);
}
+ public void setGlobalFilters(List<String> globalFilterNames) throws ConfigurationException {
+ // validate each filter name
+ if (!CollectionUtils.isEmpty(globalFilterNames)) {
+ for (String filterName : globalFilterNames) {
+ Filter filter = filters.get(filterName);
+ if (filter == null) {
+ throw new ConfigurationException("There is no filter with name '" + filterName +
+ "' to apply to the global filters in the pool of available Filters. Ensure a " +
+ "filter with that name/path has first been registered with the addFilter method(s).");
+ }
+ this.globalFilterNames.add(filterName);
+ }
+ }
+ }
+
protected void applyChainConfig(String chainName, Filter filter, String chainSpecificFilterConfig) {
if (log.isDebugEnabled()) {
log.debug("Attempting to apply path [" + chainName + "] to filter [" + filter + "] " +
--- a/web/src/main/java/org/apache/shiro/web/filter/mgt/FilterChainManager.java
+++ b/web/src/main/java/org/apache/shiro/web/filter/mgt/FilterChainManager.java
@@ -22,6 +22,7 @@
import javax.servlet.Filter;
import javax.servlet.FilterChain;
+import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -165,6 +166,14 @@
void createChain(String chainName, String chainDefinition);
/**
+ * Creates a chain that should match any non-matched request paths, typically {@code /**} assuming an {@link AntPathMatcher} I used.
+ * @param chainName The name of the chain to create, likely {@code /**}.
+ * @since 1.6
+ * @see org.apache.shiro.lang.util.AntPathMatcher AntPathMatcher
+ */
+ void createDefaultChain(String chainName);
+
+ /**
* Adds (appends) a filter to the filter chain identified by the given {@code chainName}. If there is no chain
* with the given name, a new one is created and the filter will be the first in the chain.
*
@@ -195,4 +204,17 @@
* interface).
*/
void addToChain(String chainName, String filterName, String chainSpecificFilterConfig) throws ConfigurationException;
+
+ /**
+ * Configures the set of named filters that will match all paths. These filters will match BEFORE explicitly
+ * configured filter chains i.e. by calling {@link #createChain(String, String)}, {@link #addToChain(String, String)}, etc.
+ * <br>
+ * <strong>Filters configured in this list wll apply to ALL requests.</strong>
+ *
+ * @param globalFilterNames the list of filter names to match ALL paths.
+ * @throws ConfigurationException if one of the filter names is invalid and cannot be loaded from the set of
+ * configured filters {@link #getFilters()}}.
+ * @since 1.6
+ */
+ void setGlobalFilters(List<String> globalFilterNames) throws ConfigurationException;
}
--- a/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java
+++ b/web/src/main/java/org/apache/shiro/web/servlet/AbstractShiroFilter.java
@@ -404,6 +404,7 @@
* @since 1.0
*/
protected FilterChain getExecutionChain(ServletRequest request, ServletResponse response, FilterChain origChain) {
+
FilterChain chain = origChain;
FilterChainResolver resolver = getFilterChainResolver();
--- /dev/null
+++ b/web/src/test/java/org/apache/shiro/web/env/FilterStub.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.shiro.web.env;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+public class FilterStub implements Filter {
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+
+ }
+
+ @Override
+ public void destroy() {
+
+ }
+}
|