| 1 |
package org.astrogrid.samp.web; |
| 2 |
|
| 3 |
import java.io.IOException; |
| 4 |
import java.io.OutputStream; |
| 5 |
import java.io.UnsupportedEncodingException; |
| 6 |
import java.net.InetAddress; |
| 7 |
import java.net.InetSocketAddress; |
| 8 |
import java.net.ServerSocket; |
| 9 |
import java.net.SocketAddress; |
| 10 |
import java.net.UnknownHostException; |
| 11 |
import java.util.ArrayList; |
| 12 |
import java.util.Arrays; |
| 13 |
import java.util.HashSet; |
| 14 |
import java.util.LinkedHashMap; |
| 15 |
import java.util.List; |
| 16 |
import java.util.Map; |
| 17 |
import java.util.Set; |
| 18 |
import java.util.logging.Level; |
| 19 |
import java.util.logging.Logger; |
| 20 |
import java.util.regex.Pattern; |
| 21 |
import org.astrogrid.samp.httpd.HttpServer; |
| 22 |
|
| 23 |
/** |
| 24 |
* HttpServer which allows or rejects cross-origin access according to |
| 25 |
* the W3C Cross-Origin Resource Sharing standard. |
| 26 |
* This standard is used by XMLHttpResource Level 2 and some other |
| 27 |
* web-based platforms, implemented by a number of modern browsers, |
| 28 |
* and works by the browser inserting and interpreting special headers |
| 29 |
* when cross-origin requests are made by sandboxed clients. |
| 30 |
* The effect is that sandboxed clients will under some circumstances |
| 31 |
* be permitted to access resources served by instances of this server, |
| 32 |
* where they wouldn't for an HTTP server which did not take special |
| 33 |
* measures. |
| 34 |
* |
| 35 |
* @author Mark Taylor |
| 36 |
* @since 2 Feb 2011 |
| 37 |
* @see <a href="http://www.w3.org/TR/cors/" |
| 38 |
* >Cross-Origin Resource Sharing W3C Standard</a> |
| 39 |
*/ |
| 40 |
public class CorsHttpServer extends HttpServer { |
| 41 |
|
| 42 |
private final OriginAuthorizer authorizer_; |
| 43 |
|
| 44 |
private static final String ORIGIN_KEY = "Origin"; |
| 45 |
private static final String ALLOW_ORIGIN_KEY = |
| 46 |
"Access-Control-Allow-Origin"; |
| 47 |
private static final String REQUEST_METHOD_KEY = |
| 48 |
"Access-Control-Request-Method"; |
| 49 |
private static final String ALLOW_METHOD_KEY = |
| 50 |
"Access-Control-Allow-Methods"; |
| 51 |
private static final String ALLOW_HEADERS_KEY = |
| 52 |
"Access-Control-Allow-Headers"; |
| 53 |
private static final String REQUEST_PRIVATE_NETWORK_KEY = |
| 54 |
"Access-Control-Request-Private-Network"; |
| 55 |
private static final String ALLOW_PRIVATE_NETWORK_KEY = |
| 56 |
"Access-Control-Allow-Private-Network"; |
| 57 |
|
| 58 |
// This regex is constructed with reference to RFC6454 and RFC3986. |
| 59 |
// It is less rigorous than those, since the host production in RFC3986 |
| 60 |
// is quite complex, but the required checking is not all that critical. |
| 61 |
private static final Pattern ORIGIN_REGEX = |
| 62 |
Pattern.compile( "[A-Za-z][A-Za-z0-9+.-]*://.+" ); |
| 63 |
|
| 64 |
private static final InetAddress localHostAddress_ = getLocalHostAddress(); |
| 65 |
private static final Logger logger_ = |
| 66 |
Logger.getLogger( CorsHttpServer.class.getName() ); |
| 67 |
|
| 68 |
/** |
| 69 |
* System property ({@value}) which can be used to supply host addresses |
| 70 |
* explicitly permitted to connect via the Web Profile alongside |
| 71 |
* the local host. |
| 72 |
* Normally any non-local host is blocked from access to the CORS |
| 73 |
* web server for security reasons. However, any host specified |
| 74 |
* by hostname or IP number as one element of a comma-separated |
| 75 |
* list in the value of this system property will also be allowed. |
| 76 |
* This might be used to allow access from a "friendly" near-local |
| 77 |
* host like a tablet. |
| 78 |
*/ |
| 79 |
public static final String EXTRAHOSTS_PROP = "jsamp.web.extrahosts"; |
| 80 |
|
| 81 |
/** Set of permitted InetAddrs along side localhost. */ |
| 82 |
private static final Set extraAddrSet_ = |
| 83 |
new HashSet( Arrays.asList( getExtraHostAddresses() ) ); |
| 84 |
|
| 85 |
/** |
| 86 |
* Constructor. |
| 87 |
* |
| 88 |
* @param socket socket hosting the service |
| 89 |
* @param authorizer defines which domains requests will be |
| 90 |
* permitted from |
| 91 |
*/ |
| 92 |
public CorsHttpServer( ServerSocket socket, OriginAuthorizer authorizer ) |
| 93 |
throws IOException { |
| 94 |
super( socket ); |
| 95 |
authorizer_ = authorizer; |
| 96 |
} |
| 97 |
|
| 98 |
public Response serve( Request request ) { |
| 99 |
if ( ! isPermittedHost( request.getRemoteAddress() ) ) { |
| 100 |
return createNonLocalErrorResponse( request ); |
| 101 |
} |
| 102 |
Map hdrMap = request.getHeaderMap(); |
| 103 |
String method = request.getMethod(); |
| 104 |
String originTxt = getHeader( hdrMap, ORIGIN_KEY ); |
| 105 |
if ( originTxt != null ) { |
| 106 |
String reqMethod = getHeader( hdrMap, REQUEST_METHOD_KEY ); |
| 107 |
if ( method.equals( "OPTIONS" ) && reqMethod != null ) { |
| 108 |
return servePreflightOriginRequest( request, originTxt, |
| 109 |
reqMethod ); |
| 110 |
} |
| 111 |
else { |
| 112 |
return serveSimpleOriginRequest( request, originTxt ); |
| 113 |
} |
| 114 |
} |
| 115 |
else { |
| 116 |
return super.serve( request ); |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
/** |
| 121 |
* Does the work for serving <em>simple</em> requests which bear an |
| 122 |
* origin header. Simple requests are effectively ones which do not |
| 123 |
* require pre-flight requests - see the CORS standard for details. |
| 124 |
* |
| 125 |
* @param request HTTP request |
| 126 |
* @param originTxt content of the Origin header |
| 127 |
* @return HTTP response |
| 128 |
*/ |
| 129 |
private Response serveSimpleOriginRequest( Request request, |
| 130 |
String originTxt ) { |
| 131 |
Response response = super.serve( request ); |
| 132 |
if ( isAuthorized( originTxt ) ) { |
| 133 |
Map headerMap = response.getHeaderMap(); |
| 134 |
if ( getHeader( headerMap, ALLOW_ORIGIN_KEY ) == null ) { |
| 135 |
headerMap.put( ALLOW_ORIGIN_KEY, originTxt ); |
| 136 |
} |
| 137 |
} |
| 138 |
return response; |
| 139 |
} |
| 140 |
|
| 141 |
/** |
| 142 |
* Does the work for serving pre-flight requests. |
| 143 |
* See the CORS standard for details. |
| 144 |
* |
| 145 |
* @param request HTTP request |
| 146 |
* @param originTxt content of the Origin header |
| 147 |
* @param reqMethod content of the Access-Control-Request-Method header |
| 148 |
* @return HTTP response |
| 149 |
*/ |
| 150 |
private Response servePreflightOriginRequest( Request request, |
| 151 |
String originTxt, |
| 152 |
String reqMethod ) { |
| 153 |
Map hdrMap = new LinkedHashMap(); |
| 154 |
hdrMap.put( "Content-Length", "0" ); |
| 155 |
if ( isAuthorized( originTxt ) ) { |
| 156 |
hdrMap.put( ALLOW_ORIGIN_KEY, originTxt ); |
| 157 |
hdrMap.put( ALLOW_METHOD_KEY, reqMethod ); |
| 158 |
hdrMap.put( ALLOW_HEADERS_KEY, "Content-Type" ); // allow all here? |
| 159 |
} |
| 160 |
|
| 161 |
/* Manipulate headers according to the "Private Network Access" |
| 162 |
* proposal - see https://wicg.github.io/private-network-access/. |
| 163 |
* Note the Private-Network-Access-Name and Private-Network-Access-ID |
| 164 |
* keys also defined in PNA should not be required here, since |
| 165 |
* the localhost origin is defined as "potentially trustworthy". |
| 166 |
* At time of writing (2024) it's not clear how widespread browser |
| 167 |
* implementation of the PNA specification will be, but it's likely |
| 168 |
* this behaviour will be either beneficial or harmless in the |
| 169 |
* context of future browser development. */ |
| 170 |
if ( "true".equals( getHeader( request.getHeaderMap(), |
| 171 |
REQUEST_PRIVATE_NETWORK_KEY ) ) ) { |
| 172 |
hdrMap.put( ALLOW_PRIVATE_NETWORK_KEY, "true" ); |
| 173 |
} |
| 174 |
|
| 175 |
/* Return results. */ |
| 176 |
return new Response( 200, "OK", hdrMap ) { |
| 177 |
public void writeBody( OutputStream out ) { |
| 178 |
} |
| 179 |
}; |
| 180 |
} |
| 181 |
|
| 182 |
/** |
| 183 |
* Returns an HTTP error response complaining about attempted access |
| 184 |
* from a disallowed host. |
| 185 |
* |
| 186 |
* @param request offending request |
| 187 |
* @return HTTP 403 response |
| 188 |
*/ |
| 189 |
public static Response createNonLocalErrorResponse( Request request ) { |
| 190 |
int status = 403; |
| 191 |
String msg = "Forbidden"; |
| 192 |
String method = request.getMethod(); |
| 193 |
if ( "HEAD".equals( method ) ) { |
| 194 |
return createErrorResponse( status, msg ); |
| 195 |
} |
| 196 |
else { |
| 197 |
Map hdrMap = new LinkedHashMap(); |
| 198 |
hdrMap.put( HDR_CONTENT_TYPE, "text/plain" ); |
| 199 |
byte[] mbuf; |
| 200 |
try { |
| 201 |
mbuf = ( "Access to server from non-local hosts " |
| 202 |
+ "is not permitted.\r\n" ) |
| 203 |
.getBytes( "UTF-8" ); |
| 204 |
} |
| 205 |
catch ( UnsupportedEncodingException e ) { |
| 206 |
logger_.warning( "Unsupported UTF-8??" ); |
| 207 |
mbuf = new byte[ 0 ]; |
| 208 |
} |
| 209 |
final byte[] mbuf1 = mbuf; |
| 210 |
hdrMap.put( "Content-Length", Integer.toString( mbuf1.length ) ); |
| 211 |
return new Response( status, msg, hdrMap ) { |
| 212 |
public void writeBody( OutputStream out ) throws IOException { |
| 213 |
out.write( mbuf1 ); |
| 214 |
out.flush(); |
| 215 |
} |
| 216 |
}; |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
/** |
| 221 |
* Determines whether a given origin is permitted access. |
| 222 |
* This is done by interrogating this server's OriginAuthorizer policy. |
| 223 |
* Results are cached. |
| 224 |
* |
| 225 |
* @param originTxt content of Origin header |
| 226 |
*/ |
| 227 |
private boolean isAuthorized( String originTxt ) { |
| 228 |
|
| 229 |
// CORS sec 5.1 says multiple space-separated origins may be present |
| 230 |
// - but why?? Treat the string as a single origin for now. |
| 231 |
// Not incorrect, though possibly annoying if the same origin |
| 232 |
// crops up multiple times in different sets (unlikely as far |
| 233 |
// as I can see). |
| 234 |
boolean hasLegalOrigin; |
| 235 |
try { |
| 236 |
checkOriginList( originTxt ); |
| 237 |
hasLegalOrigin = true; |
| 238 |
} |
| 239 |
catch ( RuntimeException e ) { |
| 240 |
logger_.warning( "Origin header: " + e.getMessage() ); |
| 241 |
hasLegalOrigin = false; |
| 242 |
} |
| 243 |
return hasLegalOrigin && authorizer_.authorize( originTxt ); |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Indicates whether a network address is known to represent |
| 248 |
* a host permitted to access this server. |
| 249 |
* That generally means the local host, but "extra" hosts may be |
| 250 |
* permitted as well. |
| 251 |
* |
| 252 |
* @param address socket address |
| 253 |
* @return true iff address is known to be permitted |
| 254 |
*/ |
| 255 |
public boolean isPermittedHost( SocketAddress address ) { |
| 256 |
return isLocalHost( address ) || isExtraHost( address ); |
| 257 |
} |
| 258 |
|
| 259 |
/** |
| 260 |
* Indicates whether the given socket address is from the local host. |
| 261 |
* |
| 262 |
* @param address socket to test |
| 263 |
* @return true if the socket is known to be local |
| 264 |
*/ |
| 265 |
public static boolean isLocalHost( SocketAddress address ) { |
| 266 |
if ( address instanceof InetSocketAddress ) { |
| 267 |
InetAddress iAddress = ((InetSocketAddress) address).getAddress(); |
| 268 |
return iAddress != null |
| 269 |
&& ( iAddress.isLoopbackAddress() || |
| 270 |
iAddress.equals( localHostAddress_ ) ); |
| 271 |
} |
| 272 |
else { |
| 273 |
return false; |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
/** |
| 278 |
* Returns the inet address of the local host, or null if not available. |
| 279 |
* |
| 280 |
* @return local host address or null |
| 281 |
*/ |
| 282 |
private static InetAddress getLocalHostAddress() { |
| 283 |
try { |
| 284 |
return InetAddress.getLocalHost(); |
| 285 |
} |
| 286 |
catch ( UnknownHostException e ) { |
| 287 |
logger_.log( Level.WARNING, |
| 288 |
"Can't determine local host address", e ); |
| 289 |
return null; |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
/** |
| 294 |
* Acquires and returns a list of permitted non-local hosts from the |
| 295 |
* environment. |
| 296 |
* |
| 297 |
* @return list of addresses for non-local hosts permitted to access |
| 298 |
* CORS web servers in this JVM |
| 299 |
*/ |
| 300 |
private static InetAddress[] getExtraHostAddresses() { |
| 301 |
String list; |
| 302 |
try { |
| 303 |
list = System.getProperty( EXTRAHOSTS_PROP ); |
| 304 |
} |
| 305 |
catch ( SecurityException e ) { |
| 306 |
list = null; |
| 307 |
} |
| 308 |
String[] names; |
| 309 |
if ( list != null ) { |
| 310 |
list = list.trim(); |
| 311 |
names = list.length() > 0 ? list.split( ", *" ) : new String[ 0 ]; |
| 312 |
} |
| 313 |
else { |
| 314 |
names = new String[ 0 ]; |
| 315 |
} |
| 316 |
int naddr = names.length; |
| 317 |
List addrList = new ArrayList(); |
| 318 |
for ( int i = 0; i < naddr; i++ ) { |
| 319 |
String name = names[ i ]; |
| 320 |
try { |
| 321 |
addrList.add( InetAddress.getByName( name ) ); |
| 322 |
logger_.warning( "Adding web hub exception for host " |
| 323 |
+ "\"" + name + "\"" ); |
| 324 |
} |
| 325 |
catch ( UnknownHostException e ) { |
| 326 |
logger_.warning( "Unknown host \"" + name + "\"" |
| 327 |
+ " - not adding web hub exception" ); |
| 328 |
} |
| 329 |
} |
| 330 |
return (InetAddress[]) addrList.toArray( new InetAddress[ 0 ] ); |
| 331 |
} |
| 332 |
|
| 333 |
/** |
| 334 |
* Indicates whether a given address represents one of the "extra" hosts |
| 335 |
* permitted to access this server alongside the localhost. |
| 336 |
* |
| 337 |
* @param addr address of non-local host to test |
| 338 |
* @return true iff host is permitted to access this server |
| 339 |
*/ |
| 340 |
public static boolean isExtraHost( SocketAddress addr ) { |
| 341 |
return addr instanceof InetSocketAddress |
| 342 |
&& extraAddrSet_.contains( ((InetSocketAddress) addr) |
| 343 |
.getAddress() ); |
| 344 |
} |
| 345 |
|
| 346 |
/** |
| 347 |
* Checks that the content of an Origin header is syntactically legal. |
| 348 |
* |
| 349 |
* @param originTxt content of Origin header |
| 350 |
* @throws IllegalArgumentExeption if originTxt does not represent |
| 351 |
* a legal origin or (non-empty) list of origins |
| 352 |
*/ |
| 353 |
private static void checkOriginList( String originTxt ) { |
| 354 |
String[] origins = originTxt.split( " +" ); |
| 355 |
if ( origins.length > 0 ) { |
| 356 |
for ( int i = 0; i < origins.length; i++ ) { |
| 357 |
if ( ! ORIGIN_REGEX.matcher( origins[ i ] ).matches() ) { |
| 358 |
throw new IllegalArgumentException( |
| 359 |
"Bad origin syntax: \"" + origins[ i ] + "\"" ); |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
else { |
| 364 |
throw new IllegalArgumentException( "No origins supplied" ); |
| 365 |
} |
| 366 |
} |
| 367 |
} |