001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.activemq.jaas;
019
020import java.io.IOException;
021import java.security.Principal;
022import java.security.cert.X509Certificate;
023import java.util.HashSet;
024import java.util.Iterator;
025import java.util.Map;
026import java.util.Set;
027
028import javax.security.auth.Subject;
029import javax.security.auth.callback.Callback;
030import javax.security.auth.callback.CallbackHandler;
031import javax.security.auth.callback.UnsupportedCallbackException;
032import javax.security.auth.login.FailedLoginException;
033import javax.security.auth.login.LoginException;
034import javax.security.auth.spi.LoginModule;
035
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039/**
040 * A LoginModule that allows for authentication based on SSL certificates.
041 * Allows for subclasses to define methods used to verify user certificates and
042 * find user groups. Uses CertificateCallbacks to retrieve certificates.
043 * 
044 * @author sepandm@gmail.com (Sepand)
045 */
046public abstract class CertificateLoginModule extends PropertiesLoader implements LoginModule {
047
048    private static final Logger LOG = LoggerFactory.getLogger(CertificateLoginModule.class);
049
050    private CallbackHandler callbackHandler;
051    private Subject subject;
052
053    private X509Certificate certificates[];
054    private String username;
055    private Set<String> groups;
056    private Set<Principal> principals = new HashSet<Principal>();
057
058    /**
059     * Overriding to allow for proper initialization. Standard JAAS.
060     */
061    @Override
062    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
063        this.subject = subject;
064        this.callbackHandler = callbackHandler;
065        init(options);
066    }
067
068    /**
069     * Overriding to allow for certificate-based login. Standard JAAS.
070     */
071    @Override
072    public boolean login() throws LoginException {
073        Callback[] callbacks = new Callback[1];
074
075        callbacks[0] = new CertificateCallback();
076        try {
077            callbackHandler.handle(callbacks);
078        } catch (IOException ioe) {
079            throw new LoginException(ioe.getMessage());
080        } catch (UnsupportedCallbackException uce) {
081            throw new LoginException(uce.getMessage() + " Unable to obtain client certificates.");
082        }
083        certificates = ((CertificateCallback)callbacks[0]).getCertificates();
084
085        username = getUserNameForCertificates(certificates);
086        if (username == null) {
087            throw new FailedLoginException("No user for client certificate: " + getDistinguishedName(certificates));
088        }
089
090        groups = getUserGroups(username);
091
092        if (debug) {
093            LOG.debug("Certificate for user: " + username);
094        }
095        return true;
096    }
097
098    /**
099     * Overriding to complete login process. Standard JAAS.
100     */
101    @Override
102    public boolean commit() throws LoginException {
103        principals.add(new UserPrincipal(username));
104
105        for (String group : groups) {
106             principals.add(new GroupPrincipal(group));
107        }
108
109        subject.getPrincipals().addAll(principals);
110
111        clear();
112
113        if (debug) {
114            LOG.debug("commit");
115        }
116        return true;
117    }
118
119    /**
120     * Standard JAAS override.
121     */
122    @Override
123    public boolean abort() throws LoginException {
124        clear();
125
126        if (debug) {
127            LOG.debug("abort");
128        }
129        return true;
130    }
131
132    /**
133     * Standard JAAS override.
134     */
135    @Override
136    public boolean logout() {
137        subject.getPrincipals().removeAll(principals);
138        principals.clear();
139
140        if (debug) {
141            LOG.debug("logout");
142        }
143        return true;
144    }
145
146    /**
147     * Helper method.
148     */
149    private void clear() {
150        groups.clear();
151        certificates = null;
152    }
153
154    /**
155     * Should return a unique name corresponding to the certificates given. The
156     * name returned will be used to look up access levels as well as group
157     * associations.
158     * 
159     * @param certs The distinguished name.
160     * @return The unique name if the certificate is recognized, null otherwise.
161     */
162    protected abstract String getUserNameForCertificates(final X509Certificate[] certs) throws LoginException;
163
164    /**
165     * Should return a set of the groups this user belongs to. The groups
166     * returned will be added to the user's credentials.
167     * 
168     * @param username The username of the client. This is the same name that
169     *                getUserNameForDn returned for the user's DN.
170     * @return A Set of the names of the groups this user belongs to.
171     */
172    protected abstract Set<String> getUserGroups(final String username) throws LoginException;
173
174    protected String getDistinguishedName(final X509Certificate[] certs) {
175        if (certs != null && certs.length > 0 && certs[0] != null) {
176            return certs[0].getSubjectDN().getName();
177        } else {
178            return null;
179        }
180    }
181
182}