001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.auth.user;
020
021import org.apache.commons.lang3.math.NumberUtils;
022import org.apache.logging.log4j.LogManager;
023import org.apache.logging.log4j.Logger;
024import org.apache.wiki.api.core.Engine;
025import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
026import org.apache.wiki.auth.NoSuchPrincipalException;
027import org.apache.wiki.auth.WikiPrincipal;
028import org.apache.wiki.auth.WikiSecurityException;
029import org.apache.wiki.util.ByteUtils;
030import org.apache.wiki.util.CryptoUtil;
031import org.apache.wiki.util.TextUtil;
032
033import java.nio.charset.StandardCharsets;
034import java.security.MessageDigest;
035import java.security.NoSuchAlgorithmException;
036import java.security.Principal;
037import java.util.ArrayList;
038import java.util.Properties;
039import java.util.UUID;
040
041/**
042 * Abstract UserDatabase class that provides convenience methods for finding profiles, building Principal collections and hashing passwords.
043 *
044 * @since 2.3
045 */
046public abstract class AbstractUserDatabase implements UserDatabase {
047
048    protected static final Logger LOG = LogManager.getLogger( AbstractUserDatabase.class );
049    /** Property that sets the algorithm used to hash new passwords: {@code PBKDF2-SHA256} (the default) or {@code PBKDF2-SHA512}. */
050    public static final String PROP_HASH_ALGORITHM = "jspwiki.credentials.hash.algorithm";
051
052    /** Property that sets the iteration count used to hash new passwords. The default depends on the algorithm. */
053    public static final String PROP_HASH_ITERATIONS = "jspwiki.credentials.hash.iterations";
054
055    private String m_hashAlgorithm = CryptoUtil.DEFAULT_PBKDF2_ALGORITHM;
056    private int m_hashIterations = CryptoUtil.defaultPbkdf2Iterations( CryptoUtil.DEFAULT_PBKDF2_ALGORITHM );
057
058    protected static final String SHA_PREFIX = "{SHA}";
059    protected static final String SSHA_PREFIX = "{SSHA}";
060    protected static final String SHA256_PREFIX = "{SHA-256}";
061    protected Engine m_engine;
062    /**
063     * Looks up and returns the first {@link UserProfile} in the user database that whose login name, full name, or wiki name matches the
064     * supplied string. This method provides a "forgiving" search algorithm for resolving principal names when the exact profile attribute
065     * that supplied the name is unknown.
066     *
067     * @param index the login name, full name, or wiki name
068     * @return non null
069     * @throws org.apache.wiki.auth.NoSuchPrincipalException
070     * @see org.apache.wiki.auth.user.UserDatabase#find(java.lang.String)
071     */
072    @Override
073    public UserProfile find( final String index ) throws NoSuchPrincipalException {
074        UserProfile profile = null;
075
076        // Try finding by full name
077        try {
078            profile = findByFullName( index );
079        } catch( final NoSuchPrincipalException e ) {
080            LOG.debug(e.getMessage(), e);
081        }
082        if( profile != null ) {
083            return profile;
084        }
085
086        // Try finding by wiki name
087        try {
088            profile = findByWikiName( index );
089        } catch( final NoSuchPrincipalException e ) {
090            LOG.debug(e.getMessage(), e);
091        }
092        if( profile != null ) {
093            return profile;
094        }
095
096        // Try finding by login name
097        try {
098            profile = findByLoginName( index );
099        } catch( final NoSuchPrincipalException e ) {
100            LOG.debug(e.getMessage(), e);
101        }
102        if( profile != null ) {
103            return profile;
104        }
105
106        throw new NoSuchPrincipalException( "Not in database: " + index );
107    }
108
109    /**
110     * {@inheritDoc}
111     * @see org.apache.wiki.auth.user.UserDatabase#findByEmail(java.lang.String)
112     */
113    @Override
114    public abstract UserProfile findByEmail( String index ) throws NoSuchPrincipalException;
115
116    /**
117     * {@inheritDoc}
118     * @see org.apache.wiki.auth.user.UserDatabase#findByFullName(java.lang.String)
119     */
120    @Override
121    public abstract UserProfile findByFullName( String index ) throws NoSuchPrincipalException;
122
123    /**
124     * {@inheritDoc}
125     * @see org.apache.wiki.auth.user.UserDatabase#findByLoginName(java.lang.String)
126     */
127    @Override
128    public abstract UserProfile findByLoginName( String index ) throws NoSuchPrincipalException;
129
130    /**
131     * {@inheritDoc}
132     * @see org.apache.wiki.auth.user.UserDatabase#findByWikiName(java.lang.String)
133     */
134    @Override
135    public abstract UserProfile findByWikiName( String index ) throws NoSuchPrincipalException;
136
137    /**
138     * <p>Looks up the Principals representing a user from the user database. These
139     * are defined as a set of WikiPrincipals manufactured from the login name,
140     * full name, and wiki name. If the user database does not contain a user
141     * with the supplied identifier, throws a {@link NoSuchPrincipalException}.</p>
142     * <p>When this method creates WikiPrincipals, the Principal containing
143     * the user's full name is marked as containing the common name (see
144     * {@link org.apache.wiki.auth.WikiPrincipal#WikiPrincipal(String, String)}).
145     * @param identifier the name of the principal to retrieve; this corresponds to
146     *            value returned by the user profile's
147     *            {@link UserProfile#getLoginName()}method.
148     * @return the array of Principals representing the user
149     * @see org.apache.wiki.auth.user.UserDatabase#getPrincipals(java.lang.String)
150     * @throws NoSuchPrincipalException If the user database does not contain user with the supplied identifier
151     */
152    @Override
153    public Principal[] getPrincipals( final String identifier ) throws NoSuchPrincipalException {
154        final UserProfile profile = findByLoginName( identifier );
155        final ArrayList< Principal > principals = new ArrayList<>();
156        if( profile.getLoginName() != null && !profile.getLoginName().isEmpty() ) {
157            principals.add( new WikiPrincipal( profile.getLoginName(), WikiPrincipal.LOGIN_NAME ) );
158        }
159        if ("true".equalsIgnoreCase(m_engine.getWikiProperties().getProperty(Engine.PROP_USE_2_X_ACL_LOGIC, "false"))) {
160            if( profile.getFullname() != null && !profile.getFullname().isEmpty() ) {
161                principals.add( new WikiPrincipal( profile.getFullname(), WikiPrincipal.FULL_NAME ) );
162            }
163        }
164        
165        
166        if( profile.getWikiName() != null && !profile.getWikiName().isEmpty() ) {
167            principals.add( new WikiPrincipal( profile.getWikiName(), WikiPrincipal.WIKI_NAME ) );
168        }
169        return principals.toArray( new Principal[0] );
170    }
171
172    /**
173     * {@inheritDoc}
174     *
175     * @see org.apache.wiki.auth.user.UserDatabase#initialize(org.apache.wiki.api.core.Engine, java.util.Properties)
176     */
177    @Override
178    public void initialize( Engine engine, Properties props ) throws NoRequiredPropertyException, WikiSecurityException {
179        this.m_engine = engine;
180        initializePasswordHashing( props );
181    }
182
183    /**
184     * Reads {@link #PROP_HASH_ALGORITHM} and {@link #PROP_HASH_ITERATIONS}, which say how new passwords are hashed. An algorithm that is
185     * not supported, or an iteration count that is not a positive number, is logged and replaced by the default, which is never weaker
186     * than what an administrator could have meant. If the algorithm is replaced, so is the iteration count, as the count is meant for the
187     * other algorithm. Subclasses that do not call {@link #initialize(Engine, Properties)} have to call this method.
188     *
189     * @param props the wiki properties
190     * @since 3.0.1
191     */
192    protected void initializePasswordHashing( final Properties props ) {
193        String algorithm = TextUtil.getStringProperty( props, PROP_HASH_ALGORITHM, CryptoUtil.DEFAULT_PBKDF2_ALGORITHM ).trim();
194        String iterations = TextUtil.getStringProperty( props, PROP_HASH_ITERATIONS, "" ).trim();
195        if( !CryptoUtil.isSupportedPbkdf2Algorithm( algorithm ) ) {
196            LOG.error( "{}={} is not supported; using {} with its default iteration count", PROP_HASH_ALGORITHM, algorithm, CryptoUtil.DEFAULT_PBKDF2_ALGORITHM );
197            algorithm = CryptoUtil.DEFAULT_PBKDF2_ALGORITHM;
198            iterations = "";
199        }
200
201        final int defaultIterations = CryptoUtil.defaultPbkdf2Iterations( algorithm );
202        int count = defaultIterations;
203        if( !iterations.isEmpty() ) {
204            try {
205                count = Integer.parseInt( iterations );
206            } catch( final NumberFormatException e ) {
207                count = 0;
208            }
209            if( count < 1 ) {
210                LOG.error( "{}={} is not a positive number; using {}", PROP_HASH_ITERATIONS, iterations, defaultIterations );
211                count = defaultIterations;
212            } else if( count < defaultIterations ) {
213                LOG.warn( "{}={} is below the {} recommended for {}", PROP_HASH_ITERATIONS, count, defaultIterations, algorithm );
214            }
215        }
216        m_hashAlgorithm = algorithm;
217        m_hashIterations = count;
218    }
219
220    /**
221     * Factory method that instantiates a new DefaultUserProfile with a new, distinct unique identifier.
222     * 
223     * @return A new, empty profile.
224     */
225    @Override
226    public UserProfile newProfile() {
227        final UserProfile profile = new DefaultUserProfile();
228        profile.setUid( AbstractUserDatabase.generateUid( this ) );
229        return profile;
230    }
231
232    /**
233     * {@inheritDoc}
234     * @see org.apache.wiki.auth.user.UserDatabase#save(org.apache.wiki.auth.user.UserProfile)
235     */
236    @Override
237    public abstract void save( UserProfile profile ) throws WikiSecurityException;
238
239    /**
240     * Validates the password for a given user. If the user does not exist in the user database, this method always returns
241     * <code>false</code>. If the user exists, the supplied password is compared to the stored password. Note that if the stored password's
242     * value starts with <code>{SHA}</code>, the supplied password is hashed prior to the comparison.
243     *
244     * @param loginName the user's login name
245     * @param password the user's password (obtained from user input, e.g., a web form)
246     * @return <code>true</code> if the supplied user password matches the stored password
247     * @see org.apache.wiki.auth.user.UserDatabase#validatePassword(java.lang.String, java.lang.String)
248     */
249    @Override
250    public boolean validatePassword( final String loginName, final String password ) {
251        try {
252            final UserProfile profile = findByLoginName( loginName );
253            final String storedPassword = profile.getPassword();
254            final boolean verified = passwordMatches( password, storedPassword );
255
256            // If verified against anything but the configured algorithm and iterations, hash the password again on this successful login
257            if( verified && !CryptoUtil.hasPbkdf2Parameters( storedPassword, m_hashAlgorithm, m_hashIterations ) ) {
258                profile.setPassword( password );
259                save( profile );
260            }
261
262            return verified;
263        } catch( final NoSuchPrincipalException e ) {
264            LOG.debug(e.getMessage(), e);
265        } catch( final WikiSecurityException e ) {
266            LOG.error( "Could not upgrade SHA password to SSHA because profile could not be saved. Reason: " + e.getMessage(), e );
267        }
268        return false;
269    }
270
271    /**
272     * Tells if a password is the one that a stored password entry was made from, whatever the format of the entry: the current PBKDF2
273     * one or any of the older SHA ones. An entry in none of those formats never matches.
274     *
275     * @param password the password in clear
276     * @param storedPassword the stored password entry
277     * @return {@code true} if the entry was made from the password
278     * @since 3.0.1
279     */
280    protected boolean passwordMatches( final String password, final String storedPassword ) {
281        if( password == null || storedPassword == null ) {
282            return false;
283        }
284        try {
285            if( CryptoUtil.isPbkdf2Entry( storedPassword ) ) {
286                // current format: iterated, salted PBKDF2-HMAC
287                return CryptoUtil.verifyPbkdf2SaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), storedPassword );
288            } else if( storedPassword.startsWith( SHA256_PREFIX ) || storedPassword.startsWith( SSHA_PREFIX ) ) {
289                // legacy salted, single-iteration digests
290                return CryptoUtil.verifySaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), storedPassword );
291            } else if( storedPassword.startsWith( SHA_PREFIX ) ) {
292                // legacy unsalted SHA-1; compare in constant time while this format survives
293                final String hashedPassword = getShaHash( password );
294                return MessageDigest.isEqual( hashedPassword.getBytes( StandardCharsets.UTF_8 ),
295                                              storedPassword.substring( SHA_PREFIX.length() ).getBytes( StandardCharsets.UTF_8 ) );
296            }
297        } catch( final NoSuchAlgorithmException e ) {
298            LOG.error( "Unsupported algorithm: " + e.getMessage() );
299        } catch( final IllegalArgumentException e ) {
300            LOG.warn( "Malformed password entry: {}", e.getMessage() );
301        }
302        return false;
303    }
304    
305    @Override
306    public boolean validatePasswordReuse( final String loginName, final String password ) {
307        try {
308            final UserProfile profile = findByLoginName( loginName );
309
310            // If the password is stored as SHA-256 or SSHA, verify the hash
311            
312             for (String storedPassword : profile.getPreviousHashedCredentials()) {
313                if (CryptoUtil.isPbkdf2Entry(storedPassword)) {
314                    boolean match = CryptoUtil.verifyPbkdf2SaltedPassword(password.getBytes(StandardCharsets.UTF_8), storedPassword);
315                    if (match) {
316                        return false;
317                    }
318                }
319                if (storedPassword.startsWith(SHA256_PREFIX) || storedPassword.startsWith(SSHA_PREFIX)) {
320                    boolean match = CryptoUtil.verifySaltedPassword(password.getBytes(StandardCharsets.UTF_8), storedPassword);
321                    if (match) {
322                        return false;
323                    }
324                }
325                if (storedPassword.startsWith(SHA_PREFIX)) {
326                    String fragment  = storedPassword.substring(SHA_PREFIX.length());
327                    String hashedPassword = getShaHash(password);
328                    boolean match  = hashedPassword.equals(fragment);
329                     if (match) {
330                        return false;
331                    }
332                }
333            }
334
335            return true;
336        } catch( final NoSuchPrincipalException e ) {
337            LOG.debug(e.getMessage(), e);
338        } catch( final NoSuchAlgorithmException e ) {
339            LOG.error( "Unsupported algorithm: " + e.getMessage() );
340        } catch( final WikiSecurityException e ) {
341            LOG.error( "Could not upgrade SHA password to SSHA because profile could not be saved. Reason: " + e.getMessage(), e );
342        }
343        return true;
344    }
345
346    /**
347     * Generates a new random user identifier (uid) that is guaranteed to be unique.
348     * 
349     * @param db The database for which the UID should be generated.
350     * @return A random, unique UID.
351     */
352    protected static String generateUid( final UserDatabase db ) {
353        // Keep generating UUIDs until we find one that doesn't collide
354        String uid;
355        boolean collision;
356        
357        do {
358            uid = UUID.randomUUID().toString();
359            collision = true;
360            try {
361                db.findByUid( uid );
362            } catch ( final NoSuchPrincipalException e ) {
363                LOG.debug(e.getMessage(), e);
364                collision = false;
365            }
366        } 
367        while ( collision || uid == null );
368        return uid;
369    }
370    
371    /**
372     * Calculates the salted, iterated PBKDF2 hash of a given <code>String</code>, with the algorithm and iteration count that are
373     * configured through {@link #PROP_HASH_ALGORITHM} and {@link #PROP_HASH_ITERATIONS}.
374     *
375     * @param text the text to hash
376     * @return the result hash
377     */
378    protected String getHash( final String text ) {
379        try {
380            return CryptoUtil.getPbkdf2SaltedPassword( text.getBytes( StandardCharsets.UTF_8 ), m_hashAlgorithm, m_hashIterations );
381        } catch( final NoSuchAlgorithmException e ) {
382            LOG.error( "Error creating salted password hash: {}", e.getMessage() );
383            return text;
384        }
385    }
386
387    /**
388     * Private method that calculates the SHA-1 hash of a given <code>String</code>
389     *
390     * @param text the text to hash
391     * @return the result hash
392     * @deprecated this method is retained for backwards compatibility purposes; use {@link #getHash(String)} instead
393     */
394    @Deprecated
395    String getShaHash(final String text ) {
396        try {
397            final MessageDigest md = MessageDigest.getInstance( "SHA" );
398            md.update( text.getBytes( StandardCharsets.UTF_8 ) );
399            final byte[] digestedBytes = md.digest();
400            return ByteUtils.bytes2hex( digestedBytes );
401        } catch( final NoSuchAlgorithmException e ) {
402            LOG.error( "Error creating SHA password hash:" + e.getMessage() );
403            return text;
404        }
405    }
406
407    /**
408     * Parses a long integer from a supplied string, or returns 0 if not parsable.
409     *
410     * @param value the string to parse
411     * @return the value parsed
412     */
413    protected long parseLong( final String value ) {
414        if( NumberUtils.isParsable( value ) ) {
415            return Long.parseLong( value );
416        } else {
417            return 0L;
418        }
419    }
420
421}