summaryrefslogtreecommitdiff
path: root/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java
blob: b43229292f42d7cdd9a8fe9b877143228f52a20a (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
/*
 *
 * 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.client.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.qpid.util.FileUtils;

import javax.security.sasl.SaslClientFactory;
import java.io.IOException;
import java.io.InputStream;
import java.security.Provider;
import java.security.Security;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

/**
 * DynamicSaslRegistrar provides a collection of helper methods for reading a configuration file that contains a mapping
 * from SASL mechanism names to implementing client factory class names and registering a security provider with the
 * Java runtime system, that uses the configured client factory implementations.
 *
 * <p/>The sasl configuration should be specified in a properties file, refered to by the System property
 * "amp.dynamicsaslregistrar.properties". The format of the properties file is:
 *
 * <p/><pre>
 * mechanism=fully.qualified.class.name
 * </pre>
 *
 * <p/>Where mechanism is an IANA-registered mechanism name and the fully qualified class name refers to a class that
 * implements javax.security.sasl.SaslClientFactory and provides the specified mechanism.
 *
 * <p><table id="crc"><caption>CRC Card</caption> <tr><th> Responsibilities <th> Collaborations <tr><td> Parse SASL
 * mechanism properties. <tr><td> Create and register security provider for SASL mechanisms. </table>
 */
public class DynamicSaslRegistrar
{
    private static final Logger _logger = LoggerFactory.getLogger(DynamicSaslRegistrar.class);

    /** The name of the system property that holds the name of the SASL configuration properties. */
    private static final String FILE_PROPERTY = "amq.dynamicsaslregistrar.properties";

    /** The default name of the SASL properties file resource. */
    public static final String DEFAULT_RESOURCE_NAME = "org/apache/qpid/client/security/DynamicSaslRegistrar.properties";

    private DynamicSaslRegistrar()
    {
    }

    /** Reads the properties file, and creates a dynamic security provider to register the SASL implementations with. */
    public static ProviderRegistrationResult registerSaslProviders()
    {
        _logger.debug("public static void registerSaslProviders(): called");
        ProviderRegistrationResult result = ProviderRegistrationResult.FAILED;
        // Open the SASL properties file, using the default name is one is not specified.
        String filename = System.getProperty(FILE_PROPERTY);
        InputStream is =
            FileUtils.openFileOrDefaultResource(filename, DEFAULT_RESOURCE_NAME,
                DynamicSaslRegistrar.class.getClassLoader());

        try
        {
            Properties props = new Properties();
            props.load(is);

            _logger.debug("props = " + props);

            Map<String, Class<? extends SaslClientFactory>> factories = parseProperties(props);

            if (factories.size() > 0)
            {
                // Ensure we are used before the defaults
                JCAProvider qpidProvider = new JCAProvider(factories);
                if (Security.insertProviderAt(qpidProvider, 1) == -1)
                {
                    Provider registeredProvider = findProvider(JCAProvider.QPID_CLIENT_SASL_PROVIDER_NAME);
                    if (registeredProvider == null)
                    {
                        result = ProviderRegistrationResult.FAILED;
                        _logger.error("Unable to load custom SASL providers.");
                    }
                    else if (registeredProvider.equals(qpidProvider))
                    {
                        result = ProviderRegistrationResult.EQUAL_ALREADY_REGISTERED;
                        _logger.debug("Custom SASL provider is already registered with equal properties.");
                    }
                    else
                    {
                        result = ProviderRegistrationResult.DIFFERENT_ALREADY_REGISTERED;
                        _logger.warn("Custom SASL provider was already registered with different properties.");
                        if (_logger.isDebugEnabled())
                        {
                            _logger.debug("Custom SASL provider " + registeredProvider + " properties: " + new HashMap<Object, Object>(registeredProvider));
                        }
                    }
                }
                else
                {
                    result = ProviderRegistrationResult.SUCCEEDED;
                    _logger.info("Additional SASL providers successfully registered.");
                }
            }
            else
            {
                result = ProviderRegistrationResult.NO_SASL_FACTORIES;
                _logger.warn("No additional SASL factories found to register.");
            }
        }
        catch (IOException e)
        {
            result = ProviderRegistrationResult.FAILED;
            _logger.error("Error reading properties: " + e, e);
        }
        finally
        {
            if (is != null)
            {
                try
                {
                    is.close();

                }
                catch (IOException e)
                {
                    _logger.error("Unable to close properties stream: " + e, e);
                }
            }
        }
        return result;
    }

    static Provider findProvider(String name)
    {
        Provider[] providers = Security.getProviders();
        Provider registeredProvider = null;
        for (Provider provider : providers)
        {
            if (name.equals(provider.getName()))
            {
                registeredProvider = provider;
                break;
            }
        }
        return registeredProvider;
    }

    /**
     * Parses the specified properties as a mapping from IANA registered SASL mechanism names to implementing client
     * factories. If the client factories cannot be instantiated or do not implement SaslClientFactory then the
     * properties refering to them are ignored.
     *
     * @param props The properties to scan for Sasl client factory implementations.
     *
     * @return A map from SASL mechanism names to implementing client factory classes.
     *
     * @todo Why tree map here? Do really want mechanisms in alphabetical order? Seems more likely that the declared
     * order of the mechanisms is intended to be preserved, so that they are registered in the declared order of
     * preference. Consider LinkedHashMap instead.
     */
    private static Map<String, Class<? extends SaslClientFactory>> parseProperties(Properties props)
    {
        Enumeration e = props.propertyNames();

        TreeMap<String, Class<? extends SaslClientFactory>> factoriesToRegister =
            new TreeMap<String, Class<? extends SaslClientFactory>>();

        while (e.hasMoreElements())
        {
            String mechanism = (String) e.nextElement();
            String className = props.getProperty(mechanism);
            try
            {
                Class<?> clazz = Class.forName(className);
                if (!(SaslClientFactory.class.isAssignableFrom(clazz)))
                {
                    _logger.error("Class " + clazz + " does not implement " + SaslClientFactory.class + " - skipping");

                    continue;
                }

                _logger.debug("Found class "+ clazz.getName() +" for mechanism "+mechanism);
                factoriesToRegister.put(mechanism, (Class<? extends SaslClientFactory>) clazz);
            }
            catch (Exception ex)
            {
                _logger.error("Error instantiating SaslClientFactory class " + className + " - skipping");
            }
        }

        return factoriesToRegister;
    }

    public static enum ProviderRegistrationResult
    {
        SUCCEEDED,
        EQUAL_ALREADY_REGISTERED,
        DIFFERENT_ALREADY_REGISTERED,
        NO_SASL_FACTORIES,
        FAILED;
    }
}