Skip to content

Commit

Permalink
Merge pull request #12510 from Tharanidk/master
Browse files Browse the repository at this point in the history
Add RegEx to check if the given IP address is valid in X-Forwarded-For header
  • Loading branch information
Tharanidk authored Aug 10, 2024
2 parents c471485 + 2c5a162 commit 8ab6f30
Showing 1 changed file with 13 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.stream.XMLStreamException;

/**
Expand All @@ -41,7 +42,10 @@
*/
public class DataProcessAndPublishingAgent implements Runnable {
private static final Log log = LogFactory.getLog(DataProcessAndPublishingAgent.class);

private static final Pattern IPV4_PATTERN = Pattern.compile(
"^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$");
private static final Pattern IPV6_PATTERN = Pattern.compile(
"([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4})");
private static String streamID = "org.wso2.throttle.request.stream:1.0.0";
private MessageContext messageContext;
private DataPublisher dataPublisher;
Expand Down Expand Up @@ -209,18 +213,14 @@ public void run() {
log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + ipAddress);
ipAddress = ipAddress.split(":")[0];
}
try {
InetAddress address = APIUtil.getAddress(ipAddress);
if (address instanceof Inet4Address) {
jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
jsonObMap.put(APIThrottleConstants.IPv6, 0);
} else if (address instanceof Inet6Address) {
jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
jsonObMap.put(APIThrottleConstants.IP, 0);
}
} catch (UnknownHostException e) {
//send empty value as ip
log.error("Error while parsing host IP " + ipAddress, e);
if (IPV4_PATTERN.matcher(ipAddress).matches()) {
jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
jsonObMap.put(APIThrottleConstants.IPv6, 0);
} else if (IPV6_PATTERN.matcher(ipAddress).matches()) {
jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
jsonObMap.put(APIThrottleConstants.IP, 0);
} else {
log.error("Error while parsing host IP " + ipAddress);
jsonObMap.put(APIThrottleConstants.IPv6, 0);
jsonObMap.put(APIThrottleConstants.IP, 0);
}
Expand Down

0 comments on commit 8ab6f30

Please sign in to comment.