1/*
2 * Copyright (c) 2003, 2015, 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 6261831
27 * @summary Tests the use of the subject delegation feature in the
28 *          RMI connector
29 * @author Luis-Miguel Alventosa
30 * @modules java.management.rmi
31 *          java.management/com.sun.jmx.remote.security
32 * @run clean SubjectDelegation1Test SimpleStandard SimpleStandardMBean
33 * @run build SubjectDelegation1Test SimpleStandard SimpleStandardMBean
34 * @run main SubjectDelegation1Test policy11 ok
35 * @run main SubjectDelegation1Test policy12 ko
36 * @run main SubjectDelegation1Test policy13 ko
37 * @run main SubjectDelegation1Test policy14 ko
38 * @run main SubjectDelegation1Test policy15 ok
39 * @run main SubjectDelegation1Test policy16 ko
40 */
41
42import com.sun.jmx.remote.security.JMXPluggableAuthenticator;
43import java.io.File;
44import java.lang.management.ManagementFactory;
45import java.rmi.RemoteException;
46import java.rmi.registry.LocateRegistry;
47import java.rmi.registry.Registry;
48import java.util.Collections;
49import java.util.HashMap;
50import java.util.Properties;
51import javax.management.Attribute;
52import javax.management.MBeanServer;
53import javax.management.MBeanServerConnection;
54import javax.management.Notification;
55import javax.management.NotificationListener;
56import javax.management.ObjectName;
57import javax.management.remote.JMXConnector;
58import javax.management.remote.JMXConnectorFactory;
59import javax.management.remote.JMXConnectorServer;
60import javax.management.remote.JMXConnectorServerFactory;
61import javax.management.remote.JMXPrincipal;
62import javax.management.remote.JMXServiceURL;
63import javax.security.auth.Subject;
64
65public class SubjectDelegation1Test {
66
67    public static void main(String[] args) throws Exception {
68        // Check for supported operating systems: Solaris
69        //
70        // This test runs only on Solaris due to CR 6285916
71        //
72        String osName = System.getProperty("os.name");
73        System.out.println("os.name = " + osName);
74        if (!osName.equals("SunOS")) {
75            System.out.println("This test runs on Solaris only.");
76            System.out.println("Bye! Bye!");
77            return;
78        }
79        String policyFile = args[0];
80        String testResult = args[1];
81        System.out.println("Policy file = " + policyFile);
82        System.out.println("Expected test result = " + testResult);
83        JMXConnectorServer jmxcs = null;
84        JMXConnector jmxc = null;
85        try {
86            // Create an RMI registry
87            //
88            System.out.println("Start RMI registry...");
89            Registry reg = null;
90            int port = 5800;
91            while (port++ < 6000) {
92                try {
93                    reg = LocateRegistry.createRegistry(port);
94                    System.out.println("RMI registry running on port " + port);
95                    break;
96                } catch (RemoteException e) {
97                    // Failed to create RMI registry...
98                    System.out.println("Failed to create RMI registry " +
99                                       "on port " + port);
100                }
101            }
102            if (reg == null) {
103                System.exit(1);
104            }
105            // Set the default password file
106            //
107            final String passwordFile = System.getProperty("test.src") +
108                File.separator + "jmxremote.password";
109            System.out.println("Password file = " + passwordFile);
110            // Set policy file
111            //
112            final String policy = System.getProperty("test.src") +
113                File.separator + policyFile;
114            System.out.println("PolicyFile = " + policy);
115            System.setProperty("java.security.policy", policy);
116            // Instantiate the MBean server
117            //
118            System.out.println("Create the MBean server");
119            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
120            // Register the SimpleStandardMBean
121            //
122            System.out.println("Create SimpleStandard MBean");
123            SimpleStandard s = new SimpleStandard("delegate");
124            mbs.registerMBean(s, new ObjectName("MBeans:type=SimpleStandard"));
125            // Create Properties containing the username/password entries
126            //
127            Properties props = new Properties();
128            props.setProperty("jmx.remote.x.password.file", passwordFile);
129            // Initialize environment map to be passed to the connector server
130            //
131            System.out.println("Initialize environment map");
132            HashMap env = new HashMap();
133            env.put("jmx.remote.authenticator",
134                    new JMXPluggableAuthenticator(props));
135            // Create an RMI connector server
136            //
137            System.out.println("Create an RMI connector server");
138            JMXServiceURL url =
139                new JMXServiceURL("rmi", null, 0,
140                                  "/jndi/rmi://:" + port + "/server" + port);
141            jmxcs =
142                JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
143            jmxcs.start();
144            // Create an RMI connector client
145            //
146            System.out.println("Create an RMI connector client");
147            HashMap cli_env = new HashMap();
148            // These credentials must match those in the default password file
149            //
150            String[] credentials = new String[] { "monitorRole" , "QED" };
151            cli_env.put("jmx.remote.credentials", credentials);
152            jmxc = JMXConnectorFactory.connect(url, cli_env);
153            Subject delegationSubject =
154                new Subject(true,
155                            Collections.singleton(new JMXPrincipal("delegate")),
156                            Collections.EMPTY_SET,
157                            Collections.EMPTY_SET);
158            MBeanServerConnection mbsc =
159                jmxc.getMBeanServerConnection(delegationSubject);
160            // Get domains from MBeanServer
161            //
162            System.out.println("Domains:");
163            String domains[] = mbsc.getDomains();
164            for (int i = 0; i < domains.length; i++) {
165                System.out.println("\tDomain[" + i + "] = " + domains[i]);
166            }
167            // Get MBean count
168            //
169            System.out.println("MBean count = " + mbsc.getMBeanCount());
170            // Get State attribute
171            //
172            String oldState =
173                (String) mbsc.getAttribute(
174                              new ObjectName("MBeans:type=SimpleStandard"),
175                              "State");
176            System.out.println("Old State = \"" + oldState + "\"");
177            // Set State attribute
178            //
179            System.out.println("Set State to \"changed state\"");
180            mbsc.setAttribute(new ObjectName("MBeans:type=SimpleStandard"),
181                              new Attribute("State", "changed state"));
182            // Get State attribute
183            //
184            String newState =
185                (String) mbsc.getAttribute(
186                              new ObjectName("MBeans:type=SimpleStandard"),
187                              "State");
188            System.out.println("New State = \"" + newState + "\"");
189            if (!newState.equals("changed state")) {
190                System.out.println("Invalid State = \"" + newState + "\"");
191                System.exit(1);
192            }
193            // Add notification listener on SimpleStandard MBean
194            //
195            System.out.println("Add notification listener...");
196            mbsc.addNotificationListener(
197                 new ObjectName("MBeans:type=SimpleStandard"),
198                 new NotificationListener() {
199                     public void handleNotification(Notification notification,
200                                                    Object handback) {
201                         System.out.println("Received notification: " +
202                                            notification);
203                     }
204                 },
205                 null,
206                 null);
207            // Unregister SimpleStandard MBean
208            //
209            System.out.println("Unregister SimpleStandard MBean...");
210            mbsc.unregisterMBean(new ObjectName("MBeans:type=SimpleStandard"));
211        } catch (SecurityException e) {
212            if (testResult.equals("ko")) {
213                System.out.println("Got expected security exception = " + e);
214            } else {
215                System.out.println("Got unexpected security exception = " + e);
216                e.printStackTrace();
217                throw e;
218            }
219        } catch (Exception e) {
220            System.out.println("Unexpected exception caught = " + e);
221            e.printStackTrace();
222            throw e;
223        } finally {
224            // Close connector client
225            //
226            if (jmxc != null)
227                jmxc.close();
228            // Stop connector server
229            //
230            if (jmxcs != null)
231                jmxcs.stop();
232            // Say goodbye
233            //
234            System.out.println("Bye! Bye!");
235        }
236    }
237}
238