summaryrefslogtreecommitdiff
path: root/qpid/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java
blob: 9dce752021ad9072696f2f3cd74f26a3124a7152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.server.management;

import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase;
import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase;
import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HashedInitialiser;

import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.MBeanServerForwarder;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.sasl.AuthorizeCallback;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;

/**
 * This class starts up an MBeanserver. If out of the box agent is being used then there are no security features
 * implemented. To use the security features like user authentication, turn off the jmx options in the "QPID_OPTS" env
 * variable and use JMXMP connector server. If JMXMP connector is not available, then the standard JMXConnector will be
 * used, which again doesn't have user authentication.
 */
public class JMXManagedObjectRegistry implements ManagedObjectRegistry
{
    private static final Logger _log = Logger.getLogger(JMXManagedObjectRegistry.class);

    private final MBeanServer _mbeanServer;
    private Registry _rmiRegistry;
    private JMXServiceURL _jmxURL;

    public static final String MANAGEMENT_PORT_CONFIG_PATH = "management.jmxport";
    public static final int MANAGEMENT_PORT_DEFAULT = 8999;

    public JMXManagedObjectRegistry() throws AMQException
    {
        _log.info("Initialising managed object registry using platform MBean server");
        IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();

        // Retrieve the config parameters
        boolean platformServer = appRegistry.getConfiguration().getBoolean("management.platform-mbeanserver", true);

        _mbeanServer =
                platformServer ? ManagementFactory.getPlatformMBeanServer()
                : MBeanServerFactory.createMBeanServer(ManagedObject.DOMAIN);
    }


    public void start() throws IOException
    {
        // Check if the "QPID_OPTS" is set to use Out of the Box JMXAgent
        if (areOutOfTheBoxJMXOptionsSet())
        {
            _log.info("JMX: Using the out of the box JMX Agent");
            return;
        }

        IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();

        boolean security = appRegistry.getConfiguration().getBoolean("management.security-enabled", false);
        int port = appRegistry.getConfiguration().getInt(MANAGEMENT_PORT_CONFIG_PATH, MANAGEMENT_PORT_DEFAULT);

        if (security)
        {
            // For SASL using JMXMP
            _jmxURL = new JMXServiceURL("jmxmp", null, port);

            Map env = new HashMap();
            Map<String, PrincipalDatabase> map = appRegistry.getDatabaseManager().getDatabases();
            PrincipalDatabase db = null;

            for (Map.Entry<String, PrincipalDatabase> entry : map.entrySet())
            {
                if (entry.getValue() instanceof Base64MD5PasswordFilePrincipalDatabase)
                {
                    db = entry.getValue();
                    break;
                }
                else if (entry.getValue() instanceof PlainPasswordFilePrincipalDatabase)
                {
                    db = entry.getValue();
                }
            }

            if (db instanceof Base64MD5PasswordFilePrincipalDatabase)
            {
                env.put("jmx.remote.profiles", "SASL/CRAM-MD5");
                CRAMMD5HashedInitialiser initialiser = new CRAMMD5HashedInitialiser();
                initialiser.initialise(db);
                env.put("jmx.remote.sasl.callback.handler", initialiser.getCallbackHandler());
            }
            else if (db instanceof PlainPasswordFilePrincipalDatabase)
            {
                env.put("jmx.remote.profiles", "SASL/PLAIN");
                env.put("jmx.remote.sasl.callback.handler", new UserCallbackHandler(db));
            }

            // Enable the SSL security and server authentication
            /*
           SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
           SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
           env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
           env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            */

            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(_jmxURL, env, _mbeanServer);
            MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance();
            cs.setMBeanServerForwarder(mbsf);
            cs.start();
            _log.warn("JMX: Started JMXConnector server  on port '" + port + "' with SASL");

        }
        else
        {
            startJMXConnectorServer(port);
            _log.warn("JMX: Started JMXConnector server on port '" + port + "' with security disabled");
        }
    }

    /**
     * Starts up an RMIRegistry at configured port and attaches a JMXConnectorServer to it.
     *
     * @param port
     *
     * @throws IOException
     */
    private void startJMXConnectorServer(int port) throws IOException
    {
        startRMIRegistry(port);
        _jmxURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi");
        JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(_jmxURL, null, _mbeanServer);
        cs.start();
    }

    public void registerObject(ManagedObject managedObject) throws JMException
    {
        _mbeanServer.registerMBean(managedObject, managedObject.getObjectName());
    }

    public void unregisterObject(ManagedObject managedObject) throws JMException
    {
        _mbeanServer.unregisterMBean(managedObject.getObjectName());
    }

    /**
     * Checks is the "QPID_OPTS" env variable is set to use the out of the box JMXAgent.
     *
     * @return
     */
    private boolean areOutOfTheBoxJMXOptionsSet()
    {
        if (System.getProperty("com.sun.management.jmxremote") != null)
        {
            return true;
        }

        if (System.getProperty("com.sun.management.jmxremote.port") != null)
        {
            return true;
        }

        return false;
    }

    /**
     * Starts the rmi registry at given port
     *
     * @param port
     *
     * @throws RemoteException
     */
    private void startRMIRegistry(int port) throws RemoteException
    {
        System.setProperty("java.rmi.server.randomIDs", "true");
        _rmiRegistry = LocateRegistry.createRegistry(port);
    }

    // stops the RMIRegistry, if it was running and bound to a port
    public void close() throws RemoteException
    {
        if (_rmiRegistry != null)
        {
            // Stopping the RMI registry
            UnicastRemoteObject.unexportObject(_rmiRegistry, true);
        }
    }

    /** This class is used for SASL enabled JMXConnector for performing user authentication. */
    private class UserCallbackHandler implements CallbackHandler
    {
        private final PrincipalDatabase _principalDatabase;

        protected UserCallbackHandler(PrincipalDatabase database)
        {
            _principalDatabase = database;
        }

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
        {
            // Retrieve callbacks
            NameCallback ncb = null;
            PasswordCallback pcb = null;
            for (int i = 0; i < callbacks.length; i++)
            {
                if (callbacks[i] instanceof NameCallback)
                {
                    ncb = (NameCallback) callbacks[i];
                }
                else if (callbacks[i] instanceof PasswordCallback)
                {
                    pcb = (PasswordCallback) callbacks[i];
                }
                else if (callbacks[i] instanceof AuthorizeCallback)
                {
                    ((AuthorizeCallback) callbacks[i]).setAuthorized(true);
                }
                else
                {
                    throw new UnsupportedCallbackException(callbacks[i]);
                }
            }

            boolean authorized = false;
            // Process retrieval of password; can get password if username is available in NameCallback
            if ((ncb != null) && (pcb != null))
            {
                String username = ncb.getDefaultName();
                try
                {
                    authorized = _principalDatabase.verifyPassword(username, pcb.getPassword());
                }
                catch (AccountNotFoundException e)
                {
                    IOException ioe = new IOException("User not authorized.  " + e);
                    ioe.initCause(e);
                    throw ioe;
                }
            }

            if (!authorized)
            {
                throw new IOException("User not authorized.");
            }
        }
    }
}