Path: blob/master/test/jdk/java/net/URLPermission/nstest/LookupTest.java
41152 views
/*1* Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @summary A simple smoke test of the HttpURLPermission mechanism, which checks26* for either IOException (due to unknown host) or SecurityException27* due to lack of permission to connect28* @run main/othervm -Djava.security.manager=allow -Djdk.net.hosts.file=LookupTestHosts LookupTest29*/3031import java.io.BufferedWriter;32import java.io.FilePermission;33import java.io.FileWriter;34import java.io.IOException;35import java.io.InputStream;36import java.io.OutputStream;37import java.io.PrintWriter;38import java.net.InetAddress;39import java.net.InetSocketAddress;40import java.net.NetPermission;41import java.net.ProxySelector;42import java.net.ServerSocket;43import java.net.Socket;44import java.net.SocketPermission;45import java.net.URL;46import java.net.URLConnection;47import java.net.URLPermission;48import java.security.CodeSource;49import java.security.Permission;50import java.security.PermissionCollection;51import java.security.Permissions;52import java.security.Policy;53import java.security.ProtectionDomain;54import static java.nio.charset.StandardCharsets.US_ASCII;5556public class LookupTest {5758static final Policy DEFAULT_POLICY = Policy.getPolicy();59static int port;60static volatile ServerSocket serverSocket;6162static void test(String url,63boolean throwsSecException,64boolean throwsIOException) {65ProxySelector.setDefault(null);66URL u;67InputStream is = null;68try {69u = new URL(url);70System.err.println("Connecting to " + u);71URLConnection urlc = u.openConnection();72is = urlc.getInputStream();73} catch (SecurityException e) {74if (!throwsSecException) {75throw new RuntimeException("Unexpected SecurityException:", e);76}77return;78} catch (IOException e) {79if (!throwsIOException) {80System.err.println("Unexpected IOException:" + e.getMessage());81throw new RuntimeException(e);82}83return;84} finally {85if (is != null) {86try {87is.close();88} catch (IOException e) {89System.err.println("Unexpected IOException:" + e.getMessage());90throw new RuntimeException(e);91}92}93}9495if (throwsSecException || throwsIOException) {96System.err.printf("was expecting a %s\n", throwsSecException97? "security exception" : "IOException");98throw new RuntimeException("was expecting an exception");99}100}101102static final String HOSTS_FILE_NAME = System.getProperty("jdk.net.hosts.file");103104public static void main(String args[]) throws Exception {105addMappingToHostsFile("allowedAndFound.com",106InetAddress.getLoopbackAddress().getHostAddress(),107HOSTS_FILE_NAME,108false);109addMappingToHostsFile("notAllowedButFound.com",110"99.99.99.99",111HOSTS_FILE_NAME,112true);113// name "notAllowedAndNotFound.com" is not in map114// name "allowedButNotfound.com" is not in map115Server server = new Server();116try {117Policy.setPolicy(new LookupTestPolicy());118System.setSecurityManager(new SecurityManager());119server.start();120test("http://allowedAndFound.com:" + port + "/foo", false, false);121test("http://notAllowedButFound.com:" + port + "/foo", true, false);122test("http://allowedButNotfound.com:" + port + "/foo", false, true);123test("http://notAllowedAndNotFound.com:" + port + "/foo", true, false);124} finally {125server.terminate();126}127}128129static class Server extends Thread {130private volatile boolean done;131132public Server() throws IOException {133InetAddress loopback = InetAddress.getLoopbackAddress();134serverSocket = new ServerSocket();135serverSocket.bind(new InetSocketAddress(loopback, 0));136port = serverSocket.getLocalPort();137}138139public void run() {140try {141while (!done) {142try (Socket s = serverSocket.accept()) {143readOneRequest(s.getInputStream());144OutputStream o = s.getOutputStream();145String rsp = "HTTP/1.1 200 Ok\r\n" +146"Connection: close\r\n" +147"Content-length: 0\r\n\r\n";148o.write(rsp.getBytes(US_ASCII));149}150}151} catch (IOException e) {152if (!done)153e.printStackTrace();154}155}156157void terminate() {158done = true;159try { serverSocket.close(); }160catch (IOException unexpected) { unexpected.printStackTrace(); }161}162163static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' };164165// Read until the end of a HTTP request166void readOneRequest(InputStream is) throws IOException {167int requestEndCount = 0, r;168while ((r = is.read()) != -1) {169if (r == requestEnd[requestEndCount]) {170requestEndCount++;171if (requestEndCount == 4) {172break;173}174} else {175requestEndCount = 0;176}177}178}179}180181private static void addMappingToHostsFile(String host,182String addr,183String hostsFileName,184boolean append)185throws IOException186{187String mapping = addr + " " + host;188try (FileWriter fr = new FileWriter(hostsFileName, append);189PrintWriter hfPWriter = new PrintWriter(new BufferedWriter(fr))) {190hfPWriter.println(mapping);191}192}193194static class LookupTestPolicy extends Policy {195final PermissionCollection perms = new Permissions();196197LookupTestPolicy() throws Exception {198perms.add(new NetPermission("setProxySelector"));199perms.add(new SocketPermission("localhost:1024-", "resolve,accept"));200perms.add(new URLPermission("http://allowedAndFound.com:" + port + "/-", "*:*"));201perms.add(new URLPermission("http://allowedButNotfound.com:" + port + "/-", "*:*"));202perms.add(new FilePermission("<<ALL FILES>>", "read,write,delete"));203//perms.add(new PropertyPermission("java.io.tmpdir", "read"));204}205206public PermissionCollection getPermissions(ProtectionDomain domain) {207return perms;208}209210public PermissionCollection getPermissions(CodeSource codesource) {211return perms;212}213214public boolean implies(ProtectionDomain domain, Permission perm) {215return perms.implies(perm) || DEFAULT_POLICY.implies(domain, perm);216}217}218}219220221