1 /*
   2  * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug     7150256
  27  * @summary Permissions Tests for the DiagnosticCommandMBean
  28  * @author  Frederic Parain
  29  *
  30  * @run main/othervm DcmdMBeanPermissionsTest
  31  */
  32 
  33 import java.lang.management.ManagementFactory;
  34 import java.lang.reflect.Constructor;
  35 import java.lang.reflect.InvocationTargetException;
  36 import java.lang.reflect.ReflectPermission;
  37 import java.security.Permission;
  38 import java.util.HashSet;
  39 import java.util.Iterator;
  40 import javax.management.Descriptor;
  41 import javax.management.InstanceNotFoundException;
  42 import javax.management.IntrospectionException;
  43 import javax.management.MBeanException;
  44 import javax.management.MBeanInfo;
  45 import javax.management.MBeanOperationInfo;
  46 import javax.management.MBeanPermission;
  47 import javax.management.MBeanServer;
  48 import javax.management.MalformedObjectNameException;
  49 import javax.management.ObjectName;
  50 import javax.management.ReflectionException;
  51 import javax.management.RuntimeMBeanException;
  52 
  53 /**
  54  *
  55  * @author fparain
  56  */
  57 public class DcmdMBeanPermissionsTest {
  58 
  59     
  60     private static String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME =
  61         "com.sun.management:type=DiagnosticCommand";
  62     
  63     static public class CustomSecurityManager extends SecurityManager {
  64 
  65         private HashSet<Permission> grantedPermissions;
  66 
  67         public CustomSecurityManager() {
  68             grantedPermissions = new HashSet<Permission>();
  69         }
  70 
  71         public final void grantPermission(final Permission perm) {
  72             grantedPermissions.add(perm);
  73         }
  74 
  75         public final void denyPermission(final Permission perm) {
  76             Iterator<Permission> it = grantedPermissions.iterator();
  77             while (it.hasNext()) {
  78                 Permission p = it.next();
  79                 if (p.equals(perm)) {
  80                     it.remove();
  81                 }
  82             }
  83         }
  84 
  85         public final void checkPermission(final Permission perm) {
  86             for (Permission p : grantedPermissions) {
  87                 if (p.implies(perm)) {
  88                     return;
  89                 }
  90             }
  91             throw new SecurityException(perm.toString());
  92         }
  93     };
  94 
  95     static Permission createPermission(String classname, String name,
  96             String action) {
  97         Permission permission = null;
  98         try {
  99             Class c = Class.forName(classname);
 100             if (action == null) {
 101                 try {
 102                     Constructor constructor = c.getConstructor(String.class);
 103                     permission = (Permission) constructor.newInstance(name);
 104 
 105                 } catch (InstantiationException | IllegalAccessException
 106                         | IllegalArgumentException | InvocationTargetException
 107                         | NoSuchMethodException | SecurityException ex) {
 108                     ex.printStackTrace();
 109                     throw new RuntimeException("TEST FAILED");
 110                 }
 111             }
 112             if (permission == null) {
 113                 try {
 114                     Constructor constructor = c.getConstructor(String.class,
 115                             String.class);
 116                     permission = (Permission) constructor.newInstance(
 117                             name,
 118                             action);
 119                 } catch (InstantiationException | IllegalAccessException
 120                         | IllegalArgumentException | InvocationTargetException
 121                         | NoSuchMethodException | SecurityException ex) {
 122                     ex.printStackTrace();
 123                     throw new RuntimeException("TEST FAILED");
 124                 }
 125             }
 126         } catch (ClassNotFoundException ex) {
 127             ex.printStackTrace();
 128                     throw new RuntimeException("TEST FAILED");
 129         }
 130         if (permission == null) {
 131             throw new RuntimeException("TEST FAILED");
 132             
 133         }
 134         return permission;
 135     }
 136     
 137     // return true if invokation triggered a SecurityException
 138     static boolean invokeOperation(MBeanServer mbs, ObjectName on,
 139             MBeanOperationInfo opInfo) {
 140         try {
 141             if (opInfo.getSignature().length == 0) {
 142                 mbs.invoke(on, opInfo.getName(),
 143                         new Object[0], new String[0]);
 144             } else {
 145                 mbs.invoke(on, opInfo.getName(),
 146                         new Object[1], new String[]{ String[].class.getName()});
 147             }
 148         } catch (SecurityException ex) {
 149             ex.printStackTrace();
 150             return true;
 151         } catch (RuntimeMBeanException ex) {
 152             if (ex.getCause() instanceof SecurityException) {
 153                 //ex.printStackTrace();
 154                 return true;
 155             }
 156         } catch (MBeanException | InstanceNotFoundException
 157                 | ReflectionException ex) {
 158             throw new RuntimeException("TEST FAILED");
 159         }
 160         return false;
 161     }
 162     
 163     static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
 164             ObjectName on, MBeanOperationInfo opInfo) {
 165         System.out.println("Testing " + opInfo.getName());
 166         Descriptor desc = opInfo.getDescriptor();
 167         if (desc.getFieldValue("dcmd.permissionClass") == null) {
 168         // No special permission required, execution should not trigger
 169         // any security exception
 170             if (invokeOperation(mbs, on, opInfo)) {
 171                 throw new RuntimeException("TEST FAILED");
 172             }
 173         } else {
 174             // Building the required permission
 175             Permission reqPerm = createPermission(
 176                     (String)desc.getFieldValue("dcmd.permissionClass"),
 177                     (String)desc.getFieldValue("dcmd.permissionName"),
 178                     (String)desc.getFieldValue("dcmd.permissionAction"));
 179             // Paranoid mode: check that the SecurityManager has not already
 180             // been granted the permission
 181             sm.denyPermission(reqPerm);
 182             // A special permission is required for this operation,
 183             // invoking it without the permission granted must trigger
 184             // a security exception
 185             if(!invokeOperation(mbs, on, opInfo)) {
 186                 throw new RuntimeException("TEST FAILED");
 187             }
 188             // grant the permission and re-try invoking the operation
 189             sm.grantPermission(reqPerm);
 190             if(invokeOperation(mbs, on, opInfo)) {
 191                 throw new RuntimeException("TEST FAILED");
 192             }
 193             // Clean up
 194             sm.denyPermission(reqPerm);
 195         }
 196     }
 197     
 198     public static void main(final String[] args) {
 199         final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
 200         ObjectName on = null;
 201         try {
 202             on = new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME);
 203         } catch (MalformedObjectNameException ex) {
 204             ex.printStackTrace();
 205             throw new RuntimeException("TEST FAILED");
 206         }
 207         MBeanInfo info = null;
 208         try {
 209             info = mbs.getMBeanInfo(on);
 210         } catch (InstanceNotFoundException | IntrospectionException
 211                 | ReflectionException ex) {
 212             ex.printStackTrace();
 213             throw new RuntimeException("TEST FAILED");
 214         }
 215         CustomSecurityManager sm = new CustomSecurityManager();
 216         System.setSecurityManager(sm);
 217         // Set of permission required to run the test cleanly
 218         // Some permissions are required by the MBeanServer and other
 219         // platform services (RuntimePermission("createClassLoader"),
 220         // ReflectPermission("suppressAccessChecks"),
 221         // java.util.logging.LoggingPermission("control"),
 222         // RuntimePermission("exitVM.97")).
 223         // Other permissions are required by commands being invoked
 224         // in the test (for instance, RuntimePermission("modifyThreadGroup")
 225         // and RuntimePermission("modifyThread") are checked when 
 226         // runFinalization() is invoked by the gcRunFinalization command.
 227         sm.grantPermission(new RuntimePermission("createClassLoader"));
 228         sm.grantPermission(new ReflectPermission("suppressAccessChecks"));
 229         sm.grantPermission(new java.util.logging.LoggingPermission("control", ""));
 230         sm.grantPermission(new java.lang.RuntimePermission("exitVM.97"));
 231         sm.grantPermission(new java.lang.RuntimePermission("modifyThreadGroup"));
 232         sm.grantPermission(new java.lang.RuntimePermission("modifyThread"));
 233         for(MBeanOperationInfo opInfo : info.getOperations()) {
 234             Permission opPermission = new MBeanPermission(info.getClassName(),
 235                     opInfo.getName(),
 236                     on,
 237                     "invoke");
 238             sm.grantPermission(opPermission);
 239             testOperation(mbs, sm, on, opInfo);
 240             sm.denyPermission(opPermission);
 241         }
 242         System.out.println("TEST PASSED");
 243     }
 244 }