src/jdk/internal/dynalink/beans/CheckRestrictedPackageInternal.java

changeset 90
5a820fb11814
child 101
f8221ce53c2e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/jdk/internal/dynalink/beans/CheckRestrictedPackageInternal.java	Thu Feb 14 13:22:26 2013 +0100
     1.3 @@ -0,0 +1,252 @@
     1.4 +/*
     1.5 + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +/*
    1.30 + * This file is available under and governed by the GNU General Public
    1.31 + * License version 2 only, as published by the Free Software Foundation.
    1.32 + * However, the following notice accompanied the original version of this
    1.33 + * file, and Oracle licenses the original version of this file under the BSD
    1.34 + * license:
    1.35 + */
    1.36 +/*
    1.37 +   Copyright 2009-2013 Attila Szegedi
    1.38 +
    1.39 +   Licensed under both the Apache License, Version 2.0 (the "Apache License")
    1.40 +   and the BSD License (the "BSD License"), with licensee being free to
    1.41 +   choose either of the two at their discretion.
    1.42 +
    1.43 +   You may not use this file except in compliance with either the Apache
    1.44 +   License or the BSD License.
    1.45 +
    1.46 +   If you choose to use this file in compliance with the Apache License, the
    1.47 +   following notice applies to you:
    1.48 +
    1.49 +       You may obtain a copy of the Apache License at
    1.50 +
    1.51 +           http://www.apache.org/licenses/LICENSE-2.0
    1.52 +
    1.53 +       Unless required by applicable law or agreed to in writing, software
    1.54 +       distributed under the License is distributed on an "AS IS" BASIS,
    1.55 +       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    1.56 +       implied. See the License for the specific language governing
    1.57 +       permissions and limitations under the License.
    1.58 +
    1.59 +   If you choose to use this file in compliance with the BSD License, the
    1.60 +   following notice applies to you:
    1.61 +
    1.62 +       Redistribution and use in source and binary forms, with or without
    1.63 +       modification, are permitted provided that the following conditions are
    1.64 +       met:
    1.65 +       * Redistributions of source code must retain the above copyright
    1.66 +         notice, this list of conditions and the following disclaimer.
    1.67 +       * Redistributions in binary form must reproduce the above copyright
    1.68 +         notice, this list of conditions and the following disclaimer in the
    1.69 +         documentation and/or other materials provided with the distribution.
    1.70 +       * Neither the name of the copyright holder nor the names of
    1.71 +         contributors may be used to endorse or promote products derived from
    1.72 +         this software without specific prior written permission.
    1.73 +
    1.74 +       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    1.75 +       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    1.76 +       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    1.77 +       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
    1.78 +       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    1.79 +       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    1.80 +       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
    1.81 +       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    1.82 +       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
    1.83 +       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
    1.84 +       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.85 +*/
    1.86 +
    1.87 +package jdk.internal.dynalink.beans;
    1.88 +
    1.89 +import java.io.ByteArrayOutputStream;
    1.90 +import java.io.IOException;
    1.91 +import java.io.InputStream;
    1.92 +import java.lang.invoke.MethodHandle;
    1.93 +import java.lang.invoke.MethodHandles;
    1.94 +import java.lang.reflect.Method;
    1.95 +import java.security.AccessController;
    1.96 +import java.security.Permissions;
    1.97 +import java.security.PrivilegedAction;
    1.98 +import java.security.ProtectionDomain;
    1.99 +import java.security.SecureClassLoader;
   1.100 +
   1.101 +/**
   1.102 + * A utility class to check whether a given class is in a package with restricted access e.g. "sun.*". These packages
   1.103 + * are normally listed in the security property "package.access" for most JRE implementations, although we fortunately
   1.104 + * don't rely on it but solely on {@link SecurityManager#checkPackageAccess(String)}).
   1.105 + *
   1.106 + * This class accomplishes the check in a fashion that works reliably even if Dynalink itself (and all the code on the
   1.107 + * stack that led to the invocation) has the permission to access the restricted package.
   1.108 + *
   1.109 + * If Dynalink has a broad set of privileges (notably, it is loaded from boot or extension class path), then it loads
   1.110 + * the {@link RestrictedPackageTester} class into a isolated secure class loader that gives it no permissions
   1.111 + * whatsoever, and uses this completely unprivileged class to subsequently invoke
   1.112 + * {@link SecurityManager#checkPackageAccess(String)}. This will reliably throw a {@link SecurityException} for every
   1.113 + * restricted package even if Dynalink and other code on the stack have the requisite {@code "accessClassInPackage.*"}
   1.114 + * {@link RuntimePermission} privilege.
   1.115 + *
   1.116 + * On the other hand, if Dynalink does not have a broad set of privileges normally granted by the boot or extension
   1.117 + * class path, it will probably lack the privilege to create a new secure class loader into which to load the tester
   1.118 + * class. In this case, it will invoke {@link SecurityManager#checkPackageAccess(String)} itself with the reasoning that
   1.119 + * it will also be sufficient to discover whether a package is restricted or not.
   1.120 + *
   1.121 + * The rationale for this design is that if Dynalink is running as part of a privileged classpath - boot or extension
   1.122 + * class path, it will have all privileges, so a security manager's package access check might succeed if all other code
   1.123 + * on the stack when requesting linking with a particular restricted class is also privileged. A subsequent linking
   1.124 + * request from less privileged code would then also succeed in requesting methods in privileged package. On the other
   1.125 + * hand, if Dynalink is privileged, it will be able to delegate the package access check to the unprivileged class and
   1.126 + * narrow the access based on its result. Finally, if Dynalink itself is unprivileged, it will not be able to load the
   1.127 + * unprivileged class, but then it will also fail the security manager's package access.
   1.128 + *
   1.129 + * With this design, Dynalink effectively restrains itself from giving unauthorized access to restricted packages from
   1.130 + * classes doing the linking in case it itself has access to those packages. The only way to defeat it would be to
   1.131 + * selectively give Dynalink some {@code "accessClassInPackage.*"} permissions while denying it the privilege to
   1.132 + * manipulate class loaders.
   1.133 + */
   1.134 +class CheckRestrictedPackageInternal {
   1.135 +    private static final MethodHandle PACKAGE_ACCESS_CHECK = getPackageAccessCheckMethod();
   1.136 +    private static final String TESTER_CLASS_NAME = "jdk.internal.dynalink.beans.RestrictedPackageTester";
   1.137 +
   1.138 +    /**
   1.139 +     * Returns true if the specified package has restricted access.
   1.140 +     * @param pkgName the name of the package to check.
   1.141 +     * @return true if the specified package has restricted access, false otherwise.
   1.142 +     * @throws NullPointerException if pkgName is null, or if there is {@link System#getSecurityManager()} returns null
   1.143 +     * as this method is only expected to be invoked in the presence of a security manager.
   1.144 +     */
   1.145 +    static boolean isRestrictedPackageName(String pkgName) {
   1.146 +        try {
   1.147 +            if(PACKAGE_ACCESS_CHECK != null) {
   1.148 +                // If we were able to load our unprivileged tester class, use it to check package access
   1.149 +                try {
   1.150 +                    PACKAGE_ACCESS_CHECK.invokeExact(pkgName);
   1.151 +                } catch(Error|RuntimeException e) {
   1.152 +                    throw e;
   1.153 +                } catch(Throwable t) {
   1.154 +                    throw new RuntimeException(t);
   1.155 +                }
   1.156 +            } else {
   1.157 +                // If we didn't have sufficient permissions to load our unprivileged tester class, we're definitely not
   1.158 +                // running in a privileged class path, so invoking SecurityManager.checkPackageAccess() directly should
   1.159 +                // have the same effect as going through an unprivileged tester.
   1.160 +                System.getSecurityManager().checkPackageAccess(pkgName);
   1.161 +            }
   1.162 +            return false;
   1.163 +        } catch(SecurityException e) {
   1.164 +            return true;
   1.165 +        }
   1.166 +    }
   1.167 +
   1.168 +    private static MethodHandle getPackageAccessCheckMethod() {
   1.169 +        try {
   1.170 +            return AccessController.doPrivileged(new PrivilegedAction<MethodHandle>() {
   1.171 +                @Override
   1.172 +                public MethodHandle run() {
   1.173 +                    return getPackageAccessCheckMethodInternal();
   1.174 +                }
   1.175 +            });
   1.176 +        } catch(SecurityException e) {
   1.177 +            // We don't have sufficient privileges to load our tester class into a separate protection domain, so just
   1.178 +            // return null so isRestrictedPackageName() will default to itself invoking
   1.179 +            // SecurityManager.checkPackageAccess().
   1.180 +            return null;
   1.181 +        }
   1.182 +    }
   1.183 +
   1.184 +    static MethodHandle getPackageAccessCheckMethodInternal() {
   1.185 +        try {
   1.186 +            // Can't use MethodHandles.lookup().findStatic() -- even though both this class and the loaded class are in
   1.187 +            // the same package, findStatic() will throw an IllegalAccessException since they have different class
   1.188 +            // loaders. That's why we have to use unreflect with a setAccessible(true)...
   1.189 +            final Method m = getTesterClass().getDeclaredMethod("checkPackageAccess", String.class);
   1.190 +            m.setAccessible(true);
   1.191 +            return MethodHandles.lookup().unreflect(m);
   1.192 +        } catch(IllegalAccessException|NoSuchMethodException e) {
   1.193 +            throw new AssertionError(e);
   1.194 +        }
   1.195 +    }
   1.196 +
   1.197 +    private static Class<?> getTesterClass() {
   1.198 +        final ClassLoader loader = getTesterClassLoader();
   1.199 +        try {
   1.200 +            final Class<?> checkerClass = Class.forName(TESTER_CLASS_NAME, true, loader);
   1.201 +            // Sanity check to ensure we didn't accidentally pick up the class from elsewhere
   1.202 +            if(checkerClass.getClassLoader() != loader) {
   1.203 +                throw new AssertionError(TESTER_CLASS_NAME + " was loaded from a different class loader");
   1.204 +            }
   1.205 +            return checkerClass;
   1.206 +        } catch(ClassNotFoundException e) {
   1.207 +            throw new AssertionError(e);
   1.208 +        }
   1.209 +    }
   1.210 +
   1.211 +    private static ClassLoader getTesterClassLoader() {
   1.212 +        // We deliberately override loadClass instead of findClass so that we don't give a chance to finding this
   1.213 +        // class already loaded anywhere else. Not that there's a big possibility for this, especially since the parent
   1.214 +        // class loader is the bootstrap class loader, but still...
   1.215 +        return new SecureClassLoader(null) {
   1.216 +
   1.217 +            @Override
   1.218 +            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
   1.219 +                if(name.equals(TESTER_CLASS_NAME)) {
   1.220 +                    final byte[] bytes = getTesterClassBytes();
   1.221 +                    // Define the class with a protection domain that grants no permissions.
   1.222 +                    Class<?> clazz = defineClass(name, bytes, 0, bytes.length, new ProtectionDomain(null,
   1.223 +                            new Permissions()));
   1.224 +                    if(resolve) {
   1.225 +                        resolveClass(clazz);
   1.226 +                    }
   1.227 +                    return clazz;
   1.228 +                } else {
   1.229 +                    return super.loadClass(name, resolve);
   1.230 +                }
   1.231 +            }
   1.232 +        };
   1.233 +    }
   1.234 +
   1.235 +    private static byte[] getTesterClassBytes() {
   1.236 +        try {
   1.237 +            final InputStream in = CheckRestrictedPackage.class.getResourceAsStream("RestrictedPackageTester.class");
   1.238 +            try {
   1.239 +                final ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
   1.240 +                for(;;) {
   1.241 +                    final int b = in.read();
   1.242 +                    if(b == -1) {
   1.243 +                        break;
   1.244 +                    }
   1.245 +                    out.write(b);
   1.246 +                }
   1.247 +                return out.toByteArray();
   1.248 +            } finally {
   1.249 +                in.close();
   1.250 +            }
   1.251 +        } catch(IOException e) {
   1.252 +            throw new RuntimeException(e);
   1.253 +        }
   1.254 +    }
   1.255 +}

mercurial