List of usage examples for org.apache.commons.net.util SubnetUtils SubnetUtils
public SubnetUtils(String cidrNotation)
From source file:com.vmware.photon.controller.model.resources.NetworkService.java
public void validateState(NetworkState state) { Utils.validateState(getStateDescription(), state); // do we have a subnet in CIDR notation // creating new SubnetUtils to validate new SubnetUtils(state.subnetCIDR); }
From source file:com.ethlo.geodata.importer.file.FileIpLookupImporter.java
@Override public long importData() throws IOException { final Map.Entry<Date, File> ipDataFile = super.fetchResource(DataType.IP, url); final AtomicInteger count = new AtomicInteger(0); final File csvFile = ipDataFile.getValue(); final long total = IoUtils.lineCount(csvFile); final ProgressListener prg = new ProgressListener( l -> publish(new DataLoadedEvent(this, DataType.IP, Operation.IMPORT, l, total))); final IpLookupImporter ipLookupImporter = new IpLookupImporter(csvFile); final JsonFactory f = new JsonFactory(); f.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII); f.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); final ObjectMapper mapper = new ObjectMapper(f); final byte newLine = (byte) "\n".charAt(0); logger.info("Writing IP data to file {}", getFile().getAbsolutePath()); try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(getFile()))) { ipLookupImporter.processFile(entry -> { final String strGeoNameId = findMapValue(entry, "geoname_id", "represented_country_geoname_id", "registered_country_geoname_id"); final String strGeoNameCountryId = findMapValue(entry, "represented_country_geoname_id", "registered_country_geoname_id"); final Long geonameId = strGeoNameId != null ? Long.parseLong(strGeoNameId) : null; final Long geonameCountryId = strGeoNameCountryId != null ? Long.parseLong(strGeoNameCountryId) : null;/*ww w . j ava 2 s . co m*/ if (geonameId != null) { final SubnetUtils u = new SubnetUtils(entry.get("network")); final long lower = UnsignedInteger .fromIntBits(InetAddresses .coerceToInteger(InetAddresses.forString(u.getInfo().getLowAddress()))) .longValue(); final long upper = UnsignedInteger .fromIntBits(InetAddresses .coerceToInteger(InetAddresses.forString(u.getInfo().getHighAddress()))) .longValue(); final Map<String, Object> paramMap = new HashMap<>(5); paramMap.put("geoname_id", geonameId); paramMap.put("geoname_country_id", geonameCountryId); paramMap.put("first", lower); paramMap.put("last", upper); try { mapper.writeValue(out, paramMap); out.write(newLine); } catch (IOException exc) { throw new DataAccessResourceFailureException(exc.getMessage(), exc); } } if (count.get() % 100_000 == 0) { logger.info("Processed {}", count.get()); } count.getAndIncrement(); prg.update(); }); } return total; }
From source file:com.binarybirchtree.filters.IpFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Do not block localhost. if (request.getRemoteAddr().equals("127.0.0.1")) { filterChain.doFilter(request, response); return;//from w w w.j av a 2 s.com } boolean allowed = true; // Refuse connections that circumvented Cloudflare. // Checking the latest IP from the X-Forwarded-For header on Heroku, since request.getRemoteAddr() seems to return an IP in Heroku's internal network. if (!ipIsInList(request.getRemoteAddr(), internalIps) || (getForwardedIp(request, 1) != null && !ipIsInList(getForwardedIp(request, 1), bypassCloudflareIps) && !ipIsInList(getForwardedIp(request, 1), cloudflareIps))) allowed = false; if (allowed) { // Check if the IP before Cloudflare is blacklisted. String proxiedIp = getForwardedIp(request, 2); if (proxiedIp != null) { for (String ip : blacklistIps) { SubnetUtils subnet = new SubnetUtils(ip); subnet.setInclusiveHostCount(true); if (!subnet.getInfo().isInRange(proxiedIp)) { allowed = false; break; } } } } // If the request failed one of the tests, send an error response and do not continue processing the request. if (!allowed) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // If the request passed the tests, allow it to be processed normally. filterChain.doFilter(request, response); }
From source file:it.evilsocket.dsploit.net.Network.java
private IP4Address getNetmask() throws UnknownHostException { IP4Address result = new IP4Address(mInfo.netmask); if (System.getSettings().getBoolean("WIDE_SCAN", false)) { SubnetUtils privateNetwork;/*from w ww. ja va2 s . c om*/ for (String cidr_notation : PRIVATE_NETWORKS) { privateNetwork = new SubnetUtils(cidr_notation); if (privateNetwork.getInfo().isInRange(mLocal.toString())) { result = new IP4Address(privateNetwork.getInfo().getNetmask()); break; } } } return result; }
From source file:com.hurence.logisland.processor.MatchIP.java
@Override protected void updateMatchingRules(ProcessContext context) { // loop over dynamic properties to add rules for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) { if (!entry.getKey().isDynamic()) { continue; }/*from w w w.j ava2 s . com*/ final String name = entry.getKey().getName(); final String query = entry.getValue(); String[] params = query.split(":", 2); if (params.length == 2) { String queryField = params[0]; String luceneQuery; String luceneValue; String ipValue = params[1]; Matcher ipMatcher = ipPattern.matcher(ipValue); Matcher cidrMatcher = cidrPattern.matcher(ipValue); if (ipMatcher.lookingAt()) { // This is a static ip address // convert it to a long long addr = ipToLong(ipValue); luceneValue = String.valueOf(addr); luceneQuery = queryField + ":" + luceneValue; matchingRules.put(name, new MatchingRule(name, luceneQuery, query)); luceneAttrsToQuery.add(queryField); } else if (cidrMatcher.lookingAt()) { // This is a cidr // Convert it to a range SubnetUtils su = new SubnetUtils(ipValue); String lowIp = su.getInfo().getLowAddress(); String highIp = su.getInfo().getHighAddress(); long lowIpLong = ipToLong(lowIp); long highIpLong = ipToLong(highIp); luceneValue = "[ " + String.valueOf(lowIpLong) + " TO " + String.valueOf(highIpLong) + " ]"; luceneQuery = queryField + ":" + luceneValue; matchingRules.put(name, new MatchingRule(name, luceneQuery, query)); luceneAttrsToQuery.add(queryField); } else { regexpMatchingRules.put(name, new MatchingRule(name, query)); // Consider the value to be a regexp // To Be Done Pattern ipRegexp = Pattern.compile(ipValue); if (ipRegexps == null) { ipRegexps = new HashMap<>(); } if (ipRegexps.containsKey(queryField)) { HashSet<Pair<String, Pattern>> regexpVals = ipRegexps.get(queryField); regexpVals.add(new ImmutablePair<>(name, ipRegexp)); ipRegexps.put(queryField, regexpVals); } else { HashSet<Pair<String, Pattern>> regexpVals = new HashSet<>(); regexpVals.add(new org.apache.commons.lang3.tuple.ImmutablePair<>(name, ipRegexp)); ipRegexps.put(queryField, regexpVals); } } } } }
From source file:edu.ucsd.crbs.cws.auth.UserIpAddressValidatorImpl.java
/** * Compares <b>requestAddress</b> against ipv4 CIDR in <b>cidrAddress</b> * @param requestAddress requestAddress ipv4 address of the request * @param cidrAddress ipv4 CIDR address//from ww w . j av a 2 s . c o m * @return true if the <b>requestAddress</b> is within the range of the * <b>cidrAddress</b>, false otherwise */ private boolean isIpv4AddressInCidrAddress(InetAddress requestAddress, final String cidrAddress) { try { SubnetUtils snUtils = new SubnetUtils(cidrAddress); return snUtils.getInfo().isInRange(requestAddress.getHostAddress()); } catch (Exception ex) { _log.log(Level.WARNING, "Problems parsing cidr address: {0} and comparing to {1} : {2}", new Object[] { cidrAddress, requestAddress.getHostAddress(), ex.getMessage() }); } return false; }
From source file:com.vmware.photon.controller.model.resources.FirewallService.java
/** * Ensure that the allow rules conform to standard firewall practices. *//*from w ww . jav a 2s . c o m*/ public static void validateRules(List<FirewallState.Allow> rules) { for (FirewallState.Allow rule : rules) { validateRuleName(rule.name); // validate protocol and convert to lower case rule.protocol = validateProtocol(rule.protocol); // IP range must be in CIDR notation // creating new SubnetUtils to validate new SubnetUtils(rule.ipRange); validatePorts(rule.ports); } }
From source file:com.cloudera.hadoop.hdfs.nfs.security.ClientHostsMatcher.java
private static Match getMatch(String line) { String[] parts = line.split("\\s+"); String host;//from www . ja va2 s . com AccessPrivilege privilege = AccessPrivilege.READ_ONLY; switch (parts.length) { case 1: host = parts[0]; break; case 2: host = parts[0]; String option = parts[1].trim(); if ("rw".equalsIgnoreCase(option)) { privilege = AccessPrivilege.READ_WRITE; } break; default: throw new IllegalArgumentException("Incorrectly formatted line '" + line + "'"); } host = host.toLowerCase().trim(); if (host.equals("*")) { LOGGER.debug("Using match all for '" + host + "' and " + privilege); return new AnonymousMatch(privilege); } else if (CIDR_FORMAT_SHORT.matcher(host).matches()) { LOGGER.debug("Using CIDR match for '" + host + "' and " + privilege); return new CIDRMatch(privilege, new SubnetUtils(host).getInfo()); } else if (CIDR_FORMAT_LONG.matcher(host).matches()) { LOGGER.debug("Using CIDR match for '" + host + "' and " + privilege); String[] pair = host.split("/"); return new CIDRMatch(privilege, new SubnetUtils(pair[0], pair[1]).getInfo()); } else if (host.contains("*") || host.contains("?") || host.contains("[") || host.contains("]")) { LOGGER.debug("Using Regex match for '" + host + "' and " + privilege); return new RegexMatch(privilege, host); } LOGGER.debug("Using exact match for '" + host + "' and " + privilege); return new ExactMatch(privilege, host); }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.DhcpSubnetServiceTest.java
private static DhcpSubnetService.State createInitialState() { SubnetUtils subnetUtils = new SubnetUtils("192.168.0.0/16"); SubnetUtils.SubnetInfo subnetInfo = subnetUtils.getInfo(); Long lowIp, highIp;// w w w .jav a2 s . c o m InetAddress lowIpAddress = InetAddresses.forString(subnetInfo.getLowAddress()); lowIp = IpHelper.ipToLong((Inet4Address) lowIpAddress); InetAddress highIpAddress = InetAddresses.forString(subnetInfo.getHighAddress()); highIp = IpHelper.ipToLong((Inet4Address) highIpAddress); DhcpSubnetService.State startState = new DhcpSubnetService.State(); startState.lowIp = lowIp; startState.highIp = highIp; return startState; }
From source file:com.vmware.photon.controller.cloudstore.xenon.entity.SubnetAllocatorService.java
private void seedWithOneAvailableSubnet(String rootCidr) throws InterruptedException, TimeoutException, BadRequestException, DocumentNotFoundException, UnknownHostException { SubnetUtils subnetUtils = new SubnetUtils(rootCidr); SubnetUtils.SubnetInfo subnetInfo = subnetUtils.getInfo(); Long lowIp, highIp;/* w w w. j a v a2 s . c o m*/ InetAddress lowIpAddress = InetAddresses.forString(subnetInfo.getLowAddress()); if (lowIpAddress instanceof Inet4Address) { lowIp = IpHelper.ipToLong((Inet4Address) lowIpAddress); } else { throw new IllegalArgumentException("lowIpAddress not an IPv4 address"); } InetAddress highIpAddress = InetAddresses.forString(subnetInfo.getHighAddress()); if (highIpAddress instanceof Inet4Address) { highIp = IpHelper.ipToLong((Inet4Address) highIpAddress); } else { throw new IllegalArgumentException("highIpAddress not an IPv4 address"); } DhcpSubnetService.State subnet = new DhcpSubnetService.State(); subnet.lowIp = lowIp; subnet.highIp = highIp; Operation postOperation = Operation.createPost(this, DhcpSubnetService.FACTORY_LINK).setBody(subnet); ServiceUtils.doServiceOperation(this, postOperation); }