NativeAuthProvider.java 7.89 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 1765 $
 * $Date: 2005-08-10 22:37:59 -0700 (Wed, 10 Aug 2005) $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed 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.
19 20
 */

21
package org.jivesoftware.openfire.auth;
22

23 24 25 26 27 28 29 30 31 32
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;

import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.user.NativeUserProvider;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.openfire.user.UserProvider;
33 34
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.StringUtils;
35 36
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
37

38
import com.cenqua.shaj.Shaj;
39 40 41 42 43 44 45 46 47 48 49

/**
 * Authenticates using the native operating system authentication method. On Windows,
 * this means Win32 authentication; on Unix/Linux, PAM authentication. New user accounts
 * will be created automatically as needed.<p>
 *
 * Authentication is handled using the <a href="http://opensource.cenqua.com/shaj">Shaj</a>
 * library. In order for this provider to work, the appropriate native library must be loaded.
 * The appropriate native library must be manually moved from the resources/nativeAuth
 * directory to the lib directory.<p>
 *
50
 * To enable this provider, set the following in the system properties:
51
 *
52 53 54 55
 * <ul>
 * <li><tt>provider.auth.className = org.jivesoftware.openfire.auth.NativeAuthProvider</tt></li>
 * <li><tt>provider.user.className = org.jivesoftware.openfire.user.NativeUserProvider</tt></li>
 * </ul>
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
 *
 * The properties to configure the provider are as follows:
 *
 * <ul>
 *      <li>nativeAuth.domain -- <i> on Windows, the domain to use for authentication.
 *      If the value is not set, the machine's default domain will be used or standard OS
 *      auth will be used if the machine is not part of a domain. On Unix/Linux, this
 *      value specifies the PAM module to use for authentication. If the value is not set,
 *      the PAM module "other" will be used.
 * </ul>
 *
 * For more information about configuring the domain value and other aspects of Shaj,
 * please see: <a href="http://opensource.cenqua.com/shaj/doc.html">
 * http://opensource.cenqua.com/shaj/doc.html</a>.
 *
 * @author Matt Tucker
 */
public class NativeAuthProvider implements AuthProvider {

75 76
	private static final Logger Log = LoggerFactory.getLogger(NativeAuthProvider.class);

77 78 79
    private String domain;

    public NativeAuthProvider() {
80 81 82 83
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("nativeAuth.domain");

        this.domain = JiveGlobals.getProperty("nativeAuth.domain");
84 85

        // Configure the library path so that we can load the shaj native library
86
        // from the Openfire lib directory.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        // Find the root path of this class.
        try {
            String binaryPath = (new URL(Shaj.class.getProtectionDomain()
                    .getCodeSource().getLocation(), ".")).openConnection()
                    .getPermission().getName();
            binaryPath = (new File(binaryPath)).getCanonicalPath();

            // Add the binary path to "java.library.path".
            String newLibPath = binaryPath + File.pathSeparator +
                    System.getProperty("java.library.path");
            System.setProperty("java.library.path", newLibPath);
            Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
            fieldSysPath.setAccessible(true);
            fieldSysPath.set(System.class.getClassLoader(), null);
        }
        catch (Exception e) {
103
            Log.error(e.getMessage(), e);
104 105
        }

106
        // Configure Shaj to log output to the Openfire logger.
107 108 109 110 111 112 113 114 115 116 117 118 119 120
        com.cenqua.shaj.log.Log.Factory.setInstance(new com.cenqua.shaj.log.Log() {
            public boolean isDebug() {
                return Log.isDebugEnabled();
            }

            public void error(String string) {
                Log.error(string);
            }

            public void error(String string, Throwable throwable) {
                Log.error(string, throwable);
            }

            public void debug(String string) {
121
                Log.debug("NativeAuthProvider: "+string);
122 123 124 125 126
            }
        });
    }

    public void authenticate(String username, String password) throws UnauthorizedException {
127 128 129 130
        if (username.contains("@")) {
            // Check that the specified domain matches the server's domain
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
131
            if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
132 133 134 135 136 137
                username = username.substring(0, index);
            } else {
                // Unknown domain. Return authentication failed.
                throw new UnauthorizedException();
            }
        }
138
        try {
139 140 141 142 143 144
            // Some native authentication mechanisms appear to not handle high load
            // very well. Therefore, synchronize access to Shaj to throttle auth checks.
            synchronized (this) {
                if (!Shaj.checkPassword(domain, username, password)) {
                    throw new UnauthorizedException();
                }
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
            }
        }
        catch (UnauthorizedException ue) {
            throw ue;
        }
        catch (Exception e) {
            throw new UnauthorizedException(e);
        }

        // See if the user exists in the database. If not, automatically create them.
        UserManager userManager = UserManager.getInstance();
        try {
            userManager.getUser(username);
        }
        catch (UserNotFoundException unfe) {
            try {
                Log.debug("Automatically creating new user account for " + username);
                // Create user; use a random password for better safety in the future.
                // Note that we have to go to the user provider directly -- because the
                // provider is read-only, UserManager will usually deny access to createUser.
                UserProvider provider = UserManager.getUserProvider();
                if (!(provider instanceof NativeUserProvider)) {
                    Log.error("Error: not using NativeUserProvider so authentication with " +
                            "NativeAuthProvider will likely fail. Using: " +
                            provider.getClass().getName());
                }
                UserManager.getUserProvider().createUser(username, StringUtils.randomString(8),
                        null, null);
            }
            catch (UserAlreadyExistsException uaee) {
                // Ignore.
            }
        }
    }

    public void authenticate(String username, String token, String digest)
            throws UnauthorizedException
    {
        throw new UnsupportedOperationException();
    }

    public boolean isPlainSupported() {
        return true;
    }

    public boolean isDigestSupported() {
        return false;
    }
193 194 195 196 197 198 199 200 201 202 203 204 205 206

    public String getPassword(String username)
            throws UserNotFoundException, UnsupportedOperationException
    {
        throw new UnsupportedOperationException();    
    }

    public void setPassword(String username, String password) throws UserNotFoundException {
        throw new UnsupportedOperationException();
    }

    public boolean supportsPasswordRetrieval() {
        return false;
    }
207
}