DefaultAuthProvider.java 12.9 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 1116 $
 * $Date: 2005-03-10 20:18:08 -0300 (Thu, 10 Mar 2005) $
 *
6
 * Copyright (C) 2004-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
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
26 27 28 29 30 31
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

32 33 34
import javax.security.sasl.SaslException;
import javax.xml.bind.DatatypeConverter;

35
import org.jivesoftware.database.DbConnectionManager;
36
import org.jivesoftware.openfire.XMPPServer;
37 38 39 40
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
41 42

/**
43
 * Default AuthProvider implementation. It authenticates against the <tt>ofUser</tt>
44 45 46 47 48 49 50 51 52
 * database table and supports plain text and digest authentication.
 *
 * Because each call to authenticate() makes a database connection, the
 * results of authentication should be cached whenever possible.
 *
 * @author Matt Tucker
 */
public class DefaultAuthProvider implements AuthProvider {

53 54
	private static final Logger Log = LoggerFactory.getLogger(DefaultAuthProvider.class);

55 56 57 58
	    private static final String LOAD_PASSWORD =
	            "SELECT plainPassword,encryptedPassword FROM ofUser WHERE username=?";
	    private static final String TEST_PASSWORD =
	            "SELECT plainPassword,encryptedPassword,iterations,salt,storedKey FROM ofUser WHERE username=?";
59
    private static final String UPDATE_PASSWORD =
60 61 62
            "UPDATE ofUser SET plainPassword=?, encryptedPassword=?, storedKey=?, serverKey=?, salt=?, iterations=? WHERE username=?";
    
    private static final SecureRandom random = new SecureRandom();
63 64 65 66 67

    /**
     * Constructs a new DefaultAuthProvider.
     */
    public DefaultAuthProvider() {
68

69
    }
70

71
    @Override
72 73 74 75 76
    public void authenticate(String username, String password) throws UnauthorizedException {
        if (username == null || password == null) {
            throw new UnauthorizedException();
        }
        username = username.trim().toLowerCase();
77 78 79 80
        if (username.contains("@")) {
            // Check that the specified domain matches the server's domain
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
81
            if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
82 83 84 85 86 87
                username = username.substring(0, index);
            } else {
                // Unknown domain. Return authentication failed.
                throw new UnauthorizedException();
            }
        }
88
        try {
89
            if (!checkPassword(username, password)) {
90 91 92
                throw new UnauthorizedException();
            }
        }
93
        catch (UserNotFoundException unfe) {
94 95 96 97 98
            throw new UnauthorizedException();
        }
        // Got this far, so the user must be authorized.
    }

99
    @Override
100 101 102 103 104 105 106
    public String getPassword(String username) throws UserNotFoundException {
        if (!supportsPasswordRetrieval()) {
            // Reject the operation since the provider is read-only
            throw new UnsupportedOperationException();
        }
        Connection con = null;
        PreparedStatement pstmt = null;
107
        ResultSet rs = null;
108 109 110 111
        if (username.contains("@")) {
            // Check that the specified domain matches the server's domain
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
112
            if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
113 114 115 116 117 118
                username = username.substring(0, index);
            } else {
                // Unknown domain.
                throw new UserNotFoundException();
            }
        }
119 120 121 122
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PASSWORD);
            pstmt.setString(1, username);
123
            rs = pstmt.executeQuery();
124 125 126 127 128 129 130 131 132 133 134 135 136
            if (!rs.next()) {
                throw new UserNotFoundException(username);
            }
            String plainText = rs.getString(1);
            String encrypted = rs.getString(2);
            if (encrypted != null) {
                try {
                    return AuthFactory.decryptPassword(encrypted);
                }
                catch (UnsupportedOperationException uoe) {
                    // Ignore and return plain password instead.
                }
            }
137 138 139
            if (plainText == null) {
                throw new UnsupportedOperationException();
            }
140 141 142 143 144 145
            return plainText;
        }
        catch (SQLException sqle) {
            throw new UserNotFoundException(sqle);
        }
        finally {
146
            DbConnectionManager.closeConnection(rs, pstmt, con);
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
    public boolean checkPassword(String username, String testPassword) throws UserNotFoundException {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        if (username.contains("@")) {
            // Check that the specified domain matches the server's domain
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
            if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
                username = username.substring(0, index);
            } else {
                // Unknown domain.
                throw new UserNotFoundException();
            }
        }
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(TEST_PASSWORD);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                throw new UserNotFoundException(username);
            }
            String plainText = rs.getString(1);
            String encrypted = rs.getString(2);
            int iterations = rs.getInt(3);
            String salt = rs.getString(4);
            String storedKey = rs.getString(5);
            if (encrypted != null) {
                try {
                    plainText = AuthFactory.decryptPassword(encrypted);
                }
                catch (UnsupportedOperationException uoe) {
                    // Ignore and return plain password instead.
                }
            }
            if (plainText != null) {
                boolean scramOnly = JiveGlobals.getBooleanProperty("user.scramHashedPasswordOnly");
                if (scramOnly) {
                    // If we have a password here, but we're meant to be scramOnly, we should reset it.
                    setPassword(username, plainText);
                }
                return testPassword.equals(plainText);
            }
            // Don't have either plain or encrypted, so test SCRAM hash.
            if (salt == null || iterations == 0 || storedKey == null) {
                Log.warn("No available credentials for checkPassword.");
                return false;
            }
            byte[] saltShaker = DatatypeConverter.parseBase64Binary(salt);
            byte[] saltedPassword = null, clientKey = null, testStoredKey = null;
            try {
                   saltedPassword = ScramUtils.createSaltedPassword(saltShaker, testPassword, iterations);
                   clientKey = ScramUtils.computeHmac(saltedPassword, "Client Key");
                   testStoredKey = MessageDigest.getInstance("SHA-1").digest(clientKey);
205
            } catch(SaslException | NoSuchAlgorithmException e) {
206 207 208 209 210 211 212 213 214 215 216 217 218 219
                Log.warn("Unable to check SCRAM values for PLAIN authentication.");
                return false;
            }
            return DatatypeConverter.printBase64Binary(testStoredKey).equals(storedKey);
        }
        catch (SQLException sqle) {
            Log.error("User SQL failure:", sqle);
            throw new UserNotFoundException(sqle);
        }
        finally {
            DbConnectionManager.closeConnection(rs, pstmt, con);
        }
    }

220
    @Override
221 222 223
    public void setPassword(String username, String password) throws UserNotFoundException {
        // Determine if the password should be stored as plain text or encrypted.
        boolean usePlainPassword = JiveGlobals.getBooleanProperty("user.usePlainPassword");
224
        boolean scramOnly = JiveGlobals.getBooleanProperty("user.scramHashedPasswordOnly");
225
        String encryptedPassword = null;
226 227 228 229
        if (username.contains("@")) {
            // Check that the specified domain matches the server's domain
            int index = username.indexOf("@");
            String domain = username.substring(index + 1);
230
            if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
231 232 233 234 235 236
                username = username.substring(0, index);
            } else {
                // Unknown domain.
                throw new UserNotFoundException();
            }
        }
237 238
        
        // Store the salt and salted password so SCRAM-SHA-1 SASL auth can be used later.
239
        byte[] saltShaker = new byte[24];
240 241 242 243 244 245 246 247 248 249 250 251
        random.nextBytes(saltShaker);
        String salt = DatatypeConverter.printBase64Binary(saltShaker);

        
        int iterations = JiveGlobals.getIntProperty("sasl.scram-sha-1.iteration-count",
                        ScramUtils.DEFAULT_ITERATION_COUNT);
        byte[] saltedPassword = null, clientKey = null, storedKey = null, serverKey = null;
	try {
	       saltedPassword = ScramUtils.createSaltedPassword(saltShaker, password, iterations);
               clientKey = ScramUtils.computeHmac(saltedPassword, "Client Key");
               storedKey = MessageDigest.getInstance("SHA-1").digest(clientKey);
               serverKey = ScramUtils.computeHmac(saltedPassword, "Server Key");
252
       } catch (SaslException | NoSuchAlgorithmException e) {
253 254 255 256
           Log.warn("Unable to persist values for SCRAM authentication.");
       }
   
        if (!scramOnly && !usePlainPassword) {
257 258 259 260 261 262 263 264 265 266
            try {
                encryptedPassword = AuthFactory.encryptPassword(password);
                // Set password to null so that it's inserted that way.
                password = null;
            }
            catch (UnsupportedOperationException uoe) {
                // Encryption may fail. In that case, ignore the error and
                // the plain password will be stored.
            }
        }
267 268 269 270
        if (scramOnly) {
            encryptedPassword = null;
            password = null;
        }
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_PASSWORD);
            if (password == null) {
                pstmt.setNull(1, Types.VARCHAR);
            }
            else {
                pstmt.setString(1, password);
            }
            if (encryptedPassword == null) {
                pstmt.setNull(2, Types.VARCHAR);
            }
            else {
                pstmt.setString(2, encryptedPassword);
            }
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
            if (storedKey == null) {
            	pstmt.setNull(3, Types.VARCHAR);
            }
            else {
            	pstmt.setString(3, DatatypeConverter.printBase64Binary(storedKey));
            }
            if (serverKey == null) {
            	pstmt.setNull(4, Types.VARCHAR);
            }
            else {
            	pstmt.setString(4, DatatypeConverter.printBase64Binary(serverKey));
            }
            pstmt.setString(5, salt);
            pstmt.setInt(6, iterations);
            pstmt.setString(7, username);
304 305 306 307 308 309
            pstmt.executeUpdate();
        }
        catch (SQLException sqle) {
            throw new UserNotFoundException(sqle);
        }
        finally {
310
            DbConnectionManager.closeConnection(pstmt, con);
311 312 313
        }
    }

314
    @Override
315
    public boolean supportsPasswordRetrieval() {
316 317 318 319 320 321
        boolean scramOnly = JiveGlobals.getBooleanProperty("user.scramHashedPasswordOnly");
        return !scramOnly;
    }

    @Override
    public boolean isScramSupported() {
322 323
        return true;
    }
324
}