View Javadoc
1   /*
2    * Copyright 2002-2020 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.security;
18  
19  import java.net.InetAddress;
20  import java.net.UnknownHostException;
21  import org.springframework.util.Assert;
22  import org.springframework.util.StringUtils;
23  
24  /**
25   * Matches a request based on IP Address or subnet mask matching against the remote address.
26   *
27   * <p>Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an IPv4
28   * address will never match a request which returns an IPv6 address, and vice-versa.
29   *
30   * <p>The original Spring {@code org.springframework.security.web.util.matcher.IpAddressMatcher}
31   * imports {@code javax.servlet.http.HttpServletRequest}, that is not available in a reactive environment. Here is the
32   * method {@code boolean matches(HttpServletRequest request)} skipped and ths class does not implements {@code
33   * org.springframework.security.web.util.matcher.RequestMatcher},
34   *
35   * @author Luke Taylor
36   */
37  public class IpAddressMatcher {
38  
39    private final int numMaskBits;
40  
41    private final InetAddress requiredAddress;
42  
43    /**
44     * Takes a specific IP address or a range specified using the IP/Netmask (e.g. 192.168.1.0/24 or 202.24.0.0/14).
45     *
46     * @param ipAddress the address or range of addresses from which the request must come.
47     */
48    public IpAddressMatcher(String ipAddress) {
49  
50      if (ipAddress.indexOf('/') > 0) {
51        String[] addressAndMask = StringUtils.split(ipAddress, "/");
52        //noinspection ConstantConditions
53        ipAddress = addressAndMask[0];
54        numMaskBits = Integer.parseInt(addressAndMask[1]);
55      } else {
56        numMaskBits = -1;
57      }
58      requiredAddress = parseAddress(ipAddress);
59      Assert.isTrue(requiredAddress.getAddress().length * 8 >= numMaskBits,
60          String.format("IP address %s is too short for bitmask of length %d",
61              ipAddress, numMaskBits));
62    }
63  
64    /**
65     * Matches an IPv6 and IPv4 address.
66     *
67     * @param address the address
68     * @return the {@code true} id the given address matches an IPv6 and IPv4 address, otherwise {@code false}
69     */
70    public boolean matches(String address) {
71      InetAddress remoteAddress = parseAddress(address);
72  
73      if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
74        return false;
75      }
76  
77      if (numMaskBits < 0) {
78        return remoteAddress.equals(requiredAddress);
79      }
80  
81      byte[] remAddr = remoteAddress.getAddress();
82      byte[] reqAddr = requiredAddress.getAddress();
83  
84      int numMaskFullBytes = numMaskBits / 8;
85      byte finalByte = (byte) (0xFF00 >> (numMaskBits & 0x07));
86  
87      // System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));
88  
89      for (int i = 0; i < numMaskFullBytes; i++) {
90        if (remAddr[i] != reqAddr[i]) {
91          return false;
92        }
93      }
94  
95      if (finalByte != 0) {
96        return (remAddr[numMaskFullBytes] & finalByte) == (reqAddr[numMaskFullBytes] & finalByte);
97      }
98  
99      return true;
100   }
101 
102   private InetAddress parseAddress(String address) {
103     try {
104       return InetAddress.getByName(address);
105     } catch (UnknownHostException e) {
106       throw new IllegalArgumentException("Failed to parse address" + address, e);
107     }
108   }
109 }