1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.web.filter.authz;
20
21 import org.apache.shiro.util.StringUtils;
22
23 import javax.servlet.ServletRequest;
24 import javax.servlet.ServletResponse;
25 import java.util.regex.Pattern;
26 import java.util.Map;
27
28
29
30
31
32
33
34
35 public class HostFilter extends AuthorizationFilter {
36
37 public static final String IPV4_QUAD_REGEX = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2(?:[0-4][0-9]|5[0-5]))";
38
39 public static final String IPV4_REGEX = "(?:" + IPV4_QUAD_REGEX + "\\.){3}" + IPV4_QUAD_REGEX + "$";
40 public static final Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
41
42 public static final String PRIVATE_CLASS_B_SUBSET = "(?:1[6-9]|2[0-9]|3[0-1])";
43
44 public static final String PRIVATE_CLASS_A_REGEX = "10\\.(?:" + IPV4_QUAD_REGEX + "\\.){2}" + IPV4_QUAD_REGEX + "$";
45
46 public static final String PRIVATE_CLASS_B_REGEX =
47 "172\\." + PRIVATE_CLASS_B_SUBSET + "\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
48
49 public static final String PRIVATE_CLASS_C_REGEX = "192\\.168\\." + IPV4_QUAD_REGEX + "\\." + IPV4_QUAD_REGEX + "$";
50
51 Map<String, String> authorizedIps;
52 Map<String, String> deniedIps;
53 Map<String, String> authorizedHostnames;
54 Map<String, String> deniedHostnames;
55
56
57 public void setAuthorizedHosts(String authorizedHosts) {
58 if (!StringUtils.hasText(authorizedHosts)) {
59 throw new IllegalArgumentException("authorizedHosts argument cannot be null or empty.");
60 }
61 String[] hosts = StringUtils.tokenizeToStringArray(authorizedHosts, ", \t");
62
63 for (String host : hosts) {
64
65 String periodsReplaced = host.replace(".", "\\.");
66
67 String wildcardsReplaced = periodsReplaced.replace("*", IPV4_QUAD_REGEX);
68
69 if (IPV4_PATTERN.matcher(wildcardsReplaced).matches()) {
70 authorizedIps.put(host, wildcardsReplaced);
71 } else {
72
73 }
74
75
76 }
77
78 }
79
80 public void setDeniedHosts(String deniedHosts) {
81 if (!StringUtils.hasText(deniedHosts)) {
82 throw new IllegalArgumentException("deniedHosts argument cannot be null or empty.");
83 }
84 }
85
86 protected boolean isIpv4Candidate(String host) {
87 String[] quads = StringUtils.tokenizeToStringArray(host, ".");
88 if (quads == null || quads.length != 4) {
89 return false;
90 }
91 for (String quad : quads) {
92 if (!quad.equals("*")) {
93 try {
94 Integer.parseInt(quad);
95 } catch (NumberFormatException nfe) {
96 return false;
97 }
98 }
99 }
100 return true;
101 }
102
103 protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
104 throw new UnsupportedOperationException("Not yet fully implemented!!!" );
105 }
106 }