1919import org .apache .http .protocol .HttpContext ;
2020import org .apache .logging .log4j .util .Strings ;
2121
22+ import java .net .Inet4Address ;
2223import java .net .InetAddress ;
2324import java .net .UnknownHostException ;
2425import java .util .Arrays ;
@@ -42,10 +43,7 @@ public int resolve(HttpHost host) throws UnsupportedSchemeException {
4243 }
4344 });
4445
45- builder .setDnsResolver (hostName -> {
46- validateIp (hostName );
47- return InetAddress .getAllByName (hostName );
48- });
46+ builder .setDnsResolver (MLHttpClientFactory ::validateIp );
4947
5048 builder .setRedirectStrategy (new LaxRedirectStrategy () {
5149 @ Override
@@ -79,15 +77,51 @@ protected static void validateSchemaAndPort(HttpHost host) {
7977 }
8078 }
8179
82- protected static void validateIp (String hostName ) throws UnknownHostException {
80+ protected static InetAddress [] validateIp (String hostName ) throws UnknownHostException {
8381 InetAddress [] addresses = InetAddress .getAllByName (hostName );
8482 if (hasPrivateIpAddress (addresses )) {
8583 log .error ("Remote inference host name has private ip address: " + hostName );
8684 throw new IllegalArgumentException (hostName );
8785 }
86+ return addresses ;
8887 }
8988
9089 private static boolean hasPrivateIpAddress (InetAddress [] ipAddress ) {
90+ for (InetAddress ip : ipAddress ) {
91+ if (ip instanceof Inet4Address ) {
92+ byte [] bytes = ip .getAddress ();
93+ if (bytes .length != 4 ) {
94+ return true ;
95+ } else {
96+ int firstOctets = bytes [0 ] & 0xff ;
97+ int firstInOctal = parseWithOctal (String .valueOf (firstOctets ));
98+ int firstInHex = Integer .parseInt (String .valueOf (firstOctets ), 16 );
99+ if (firstInOctal == 127 || firstInHex == 127 ) {
100+ return bytes [1 ] == 0 && bytes [2 ] == 0 && bytes [3 ] == 1 ;
101+ } else if (firstInOctal == 10 || firstInHex == 10 ) {
102+ return true ;
103+ } else if (firstInOctal == 172 || firstInHex == 172 ) {
104+ int secondOctets = bytes [1 ] & 0xff ;
105+ int secondInOctal = parseWithOctal (String .valueOf (secondOctets ));
106+ int secondInHex = Integer .parseInt (String .valueOf (secondOctets ), 16 );
107+ return (secondInOctal >= 16 && secondInOctal <= 32 ) || (secondInHex >= 16 && secondInHex <= 32 );
108+ } else if (firstInOctal == 192 || firstInHex == 192 ) {
109+ int secondOctets = bytes [1 ] & 0xff ;
110+ int secondInOctal = parseWithOctal (String .valueOf (secondOctets ));
111+ int secondInHex = Integer .parseInt (String .valueOf (secondOctets ), 16 );
112+ return secondInOctal == 168 || secondInHex == 168 ;
113+ }
114+ }
115+ }
116+ }
91117 return Arrays .stream (ipAddress ).anyMatch (x -> x .isSiteLocalAddress () || x .isLoopbackAddress () || x .isAnyLocalAddress ());
92118 }
119+
120+ private static int parseWithOctal (String input ) {
121+ try {
122+ return Integer .parseInt (input , 8 );
123+ } catch (NumberFormatException e ) {
124+ return Integer .parseInt (input );
125+ }
126+ }
93127}
0 commit comments