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.util;
020
021import javax.crypto.SecretKeyFactory;
022import javax.crypto.spec.PBEKeySpec;
023import java.nio.charset.StandardCharsets;
024import java.security.MessageDigest;
025import java.security.NoSuchAlgorithmException;
026import java.security.SecureRandom;
027import java.security.spec.InvalidKeySpecException;
028import java.util.Base64;
029import java.util.Random;
030
031
032/**
033 * Hashes and verifies salted SHA-1 passwords, which are compliant with RFC
034 * 2307.
035 */
036public final class CryptoUtil {
037
038    private static final String SSHA = "{SSHA}";
039
040    private static final String SHA1 = "{SHA-1}";
041
042    private static final String SHA256 = "{SHA-256}";
043
044    private static final Random RANDOM = new SecureRandom();
045
046    private static final int DEFAULT_SALT_SIZE = 8;
047
048    /** Name of the PBKDF2-HMAC-SHA256 algorithm, as used in {@code jspwiki.credentials.hash.algorithm}. */
049    public static final String PBKDF2_SHA256 = "PBKDF2-SHA256";
050
051    /** Name of the PBKDF2-HMAC-SHA512 algorithm, as used in {@code jspwiki.credentials.hash.algorithm}. */
052    public static final String PBKDF2_SHA512 = "PBKDF2-SHA512";
053
054    /** Prefix of PBKDF2-HMAC-SHA256 password entries, the format used by default. */
055    public static final String PBKDF2_PREFIX = "{" + PBKDF2_SHA256 + "}";
056
057    /** Prefix of PBKDF2-HMAC-SHA512 password entries. */
058    public static final String PBKDF2_SHA512_PREFIX = "{" + PBKDF2_SHA512 + "}";
059
060    /** Algorithm used for new password entries unless configured otherwise. */
061    public static final String DEFAULT_PBKDF2_ALGORITHM = PBKDF2_SHA256;
062
063    private static final int PBKDF2_SALT_SIZE = 16;
064
065    /**
066     * The PBKDF2 flavours that can be used to store passwords. The default iteration counts follow the current OWASP password-storage
067     * guidance for each of them.
068     */
069    private enum Pbkdf2 {
070
071        SHA256( PBKDF2_SHA256, "PBKDF2WithHmacSHA256", 32, 600_000 ),
072        SHA512( PBKDF2_SHA512, "PBKDF2WithHmacSHA512", 64, 210_000 );
073
074        private final String algorithm;
075        private final String jcaName;
076        private final int keyLengthBytes;
077        private final int defaultIterations;
078
079        Pbkdf2( final String algorithm, final String jcaName, final int keyLengthBytes, final int defaultIterations ) {
080            this.algorithm = algorithm;
081            this.jcaName = jcaName;
082            this.keyLengthBytes = keyLengthBytes;
083            this.defaultIterations = defaultIterations;
084        }
085
086        String prefix() {
087            return "{" + algorithm + "}";
088        }
089
090        static Pbkdf2 forAlgorithm( final String algorithm ) {
091            for( final Pbkdf2 pbkdf2 : values() ) {
092                if( pbkdf2.algorithm.equals( algorithm ) ) {
093                    return pbkdf2;
094                }
095            }
096            throw new IllegalArgumentException( "Unsupported password hash algorithm: " + algorithm );
097        }
098
099        static Pbkdf2 forEntry( final String entry ) {
100            if( entry != null ) {
101                for( final Pbkdf2 pbkdf2 : values() ) {
102                    if( entry.startsWith( pbkdf2.prefix() ) ) {
103                        return pbkdf2;
104                    }
105                }
106            }
107            return null;
108        }
109    }
110
111    private static final Object HELP = "--help";
112
113    private static final Object HASH = "--hash";
114
115    private static final Object VERIFY = "--verify";
116
117    /**
118     * Private constructor to prevent direct instantiation.
119     */
120    private CryptoUtil() {}
121
122    /**
123     * <p>
124     * Convenience method for hashing and verifying salted SHA-1 or SHA-256 passwords from
125     * the command line. This method requires <code>commons-codec-1.3.jar</code>
126     * (or a newer version) to be on the classpath. Command line arguments are
127     * as follows:
128     * </p>
129     * <ul>
130     * <li><code>--hash <var>password</var> SSHA</code> - hashes <var>password</var></code>
131     * and prints a password digest that looks like this: <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code></blockquote></li>
132     * <li><code>--verify <var>password</var> <var>digest</var></code> -
133     * verifies <var>password</var> by extracting the salt from <var>digest</var>
134     * (which is identical to what is printed by <code>--hash</code>) and
135     * re-computing the digest again using the password and salt. If the
136     * password supplied is the same as the one used to create the original
137     * digest, <code>true</code> will be printed; otherwise <code>false</code></li>
138     * </ul>
139     * <p>For example, one way to use this utility is to change to JSPWiki's <code>build</code> directory
140     * and type the following command:</p>
141     * <blockquote><code>java -cp JSPWiki.jar:../lib/commons-codec-1.3.jar org.apache.wiki.util.CryptoUtil --hash mynewpassword</code></blockquote>
142     * 
143     * @param args arguments for this method as described above
144     * @throws Exception Catches nothing; throws everything up.
145     */
146    public static void main( final String[] args ) throws Exception {
147        // Print help if the user requested it, or if no arguments
148        if( args.length == 0 || ( args.length == 1 && HELP.equals( args[0] ) ) ) {
149            System.out.println( "Usage: CryptoUtil [options] " );
150            System.out.println( "   --hash   password algorithm             create hash for password" );
151            System.out.println( "   --verify password digest algorithm      verify password for digest" );
152            System.out.println( "Valid algorithm options are {SSHA} and {SHA-256}. If no algorithm is specified or an unsupported algorithm is specified, SHA-256 is used." );
153        }
154
155        if( HASH.equals( args[0] ) ) {
156        // User wants to hash the password
157            if( args.length < 2 ) {
158                throw new IllegalArgumentException( "Error: --hash requires a 'password' argument." );
159            }
160            final String password = args[1].trim();
161            final String algorithm = args.length > 2 ? args[2].trim() : SHA256;
162
163            System.out.println( CryptoUtil.getSaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), algorithm ) );
164        } else if( VERIFY.equals( args[0] ) ) {
165        // User wants to verify an existing password
166            if( args.length < 3 ) {
167                throw new IllegalArgumentException( "Error: --hash requires 'password' and 'digest' arguments." );
168            }
169            final String password = args[1].trim();
170            final String digest = args[2].trim();
171
172            System.out.println( CryptoUtil.verifySaltedPassword( password.getBytes( StandardCharsets.UTF_8 ), digest ) );
173        } else {
174            System.out.println( "Wrong usage. Try --help." );
175        }
176    }
177
178    /**
179     * <p>
180     * Creates an RFC 2307-compliant salted, hashed password with the SHA1 or SHA-256
181     * MessageDigest algorithm. After the password is digested, the first 20 or 32
182     * bytes of the digest will be the actual password hash; the remaining bytes
183     * will be a randomly generated salt of length {@link #DEFAULT_SALT_SIZE},
184     * for example: <blockquote><code>{SSHA}3cGWem65NCEkF5Ew5AEk45ak8LHUWAwPVXAyyw==</code></blockquote>
185     * </p>
186     * <p>
187     * In layman's terms, the formula is
188     * <code>digest( secret + salt ) + salt</code>. The resulting digest is Base64-encoded.
189     * </p>
190     * <p>
191     * Note that successive invocations of this method with the same password
192     * will result in different hashes! (This, of course, is exactly the point.)
193     * </p>
194     * 
195     * @param password the password to be digested
196     * @return the Base64-encoded password hash, prepended by
197     *         <code>{SSHA}</code> or <code>{SHA256}</code>.
198     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
199     */
200    public static String getSaltedPassword( final byte[] password, final String algorithm ) throws NoSuchAlgorithmException {
201        final byte[] salt = new byte[ DEFAULT_SALT_SIZE ];
202        RANDOM.nextBytes( salt );
203
204        return getSaltedPassword( password, salt, algorithm );
205    }
206
207    /**
208     * <p>
209     * Helper method that creates an RFC 2307-compliant salted, hashed password with the SHA1 or SHA256
210     * MessageDigest algorithm. After the password is digested, the first 20 or 32
211     * bytes of the digest will be the actual password hash; the remaining bytes
212     * will be the salt. Thus, supplying a password <code>testing123</code>
213     * and a random salt <code>foo</code> produces the hash when using SHA1:
214     * </p>
215     * <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code></blockquote>
216     * <p>
217     * In layman's terms, the formula is
218     * <code>digest( secret + salt ) + salt</code>. The resulting digest is Base64-encoded.</p>
219     * 
220     * @param password the password to be digested
221     * @param salt the random salt
222     * @return the Base64-encoded password hash, prepended by <code>{SSHA}</code> or <code>{SHA256}</code>.
223     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
224     */
225    static String getSaltedPassword( final byte[] password, final byte[] salt, final String algorithm ) throws NoSuchAlgorithmException {
226        //The term SSHA is used as a password prefix for backwards compatibility, but we use SHA-1 when fetching an instance
227        //of MessageDigest, as it is the guaranteed option. We also need to remove curly braces surrounding the string for
228        //backwards compatibility.
229        final String algorithmToUse = algorithm.equals(SSHA) ? SHA1 : algorithm;
230        final MessageDigest digest = MessageDigest.getInstance( algorithmToUse.substring( 1, algorithmToUse.length() -1 ) );
231        digest.update( password );
232        final byte[] hash = digest.digest( salt );
233
234        // Create an array with the hash plus the salt
235        final byte[] all = new byte[hash.length + salt.length];
236        System.arraycopy(hash, 0, all, 0, hash.length);
237        System.arraycopy(salt, 0, all, hash.length, salt.length);
238        final byte[] base64 = Base64.getEncoder().encode( all );
239        
240        return algorithm + new String( base64, StandardCharsets.UTF_8 );
241    }
242
243    /**
244     * <p>Creates an iterated, salted PBKDF2-HMAC-SHA256 hash of the given password, suitable for storage. Unlike the
245     * single-iteration digests above, the work factor makes offline cracking of a disclosed user database
246     * expensive. The format is <code>{PBKDF2-SHA256}<var>iterations</var>$base64(salt)$base64(hash)</code>, so the
247     * iteration count of stored entries can be raised in the future without breaking old entries.</p>
248     *
249     * @param password the password to be hashed
250     * @return the password entry, prepended by <code>{PBKDF2-SHA256}</code>
251     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
252     */
253    public static String getPbkdf2SaltedPassword( final byte[] password ) throws NoSuchAlgorithmException {
254        return getPbkdf2SaltedPassword( password, DEFAULT_PBKDF2_ALGORITHM, defaultPbkdf2Iterations( DEFAULT_PBKDF2_ALGORITHM ) );
255    }
256
257    /**
258     * Creates an iterated, salted PBKDF2 hash of the given password with the given algorithm and iteration count, in the format
259     * <code>{<var>algorithm</var>}<var>iterations</var>$base64(salt)$base64(hash)</code>.
260     *
261     * @param password the password to be hashed
262     * @param algorithm one of {@link #PBKDF2_SHA256} and {@link #PBKDF2_SHA512}
263     * @param iterations the iteration count, which must be positive
264     * @return the password entry, prepended by the algorithm
265     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
266     * @throws IllegalArgumentException if the algorithm is not supported or the iteration count is not positive
267     * @since 3.0.1
268     */
269    public static String getPbkdf2SaltedPassword( final byte[] password, final String algorithm, final int iterations ) throws NoSuchAlgorithmException {
270        final byte[] salt = new byte[ PBKDF2_SALT_SIZE ];
271        RANDOM.nextBytes( salt );
272        return getPbkdf2SaltedPassword( password, salt, algorithm, iterations );
273    }
274
275    static String getPbkdf2SaltedPassword( final byte[] password, final byte[] salt, final String algorithm, final int iterations ) throws NoSuchAlgorithmException {
276        final Pbkdf2 pbkdf2 = Pbkdf2.forAlgorithm( algorithm );
277        if( iterations < 1 ) {
278            throw new IllegalArgumentException( "The iteration count must be positive: " + iterations );
279        }
280        final byte[] hash = pbkdf2( password, salt, pbkdf2, iterations );
281        final Base64.Encoder encoder = Base64.getEncoder();
282        return pbkdf2.prefix() + iterations + "$" + encoder.encodeToString( salt ) + "$" + encoder.encodeToString( hash );
283    }
284
285    /**
286     * Verifies a password against a PBKDF2 entry created by {@link #getPbkdf2SaltedPassword(byte[])} or
287     * {@link #getPbkdf2SaltedPassword(byte[], String, int)}, with whatever algorithm and iteration count it was created with.
288     * The comparison is constant-time.
289     *
290     * @param password the password to verify
291     * @param entry the stored password entry
292     * @return true if the password matches the entry
293     * @throws NoSuchAlgorithmException If your JVM does not supply the necessary algorithm. Should not happen.
294     */
295    public static boolean verifyPbkdf2SaltedPassword( final byte[] password, final String entry ) throws NoSuchAlgorithmException {
296        final Pbkdf2 pbkdf2 = Pbkdf2.forEntry( entry );
297        if( pbkdf2 == null ) {
298            throw new IllegalArgumentException( "Hash not prefixed by expected algorithm; is it really a PBKDF2 hash?" );
299        }
300        final String[] fields = entry.substring( pbkdf2.prefix().length() ).split( "\\$" );
301        if( fields.length != 3 ) {
302            throw new IllegalArgumentException( "Malformed PBKDF2 password entry" );
303        }
304        final int iterations = Integer.parseInt( fields[ 0 ] );
305        final byte[] salt = Base64.getDecoder().decode( fields[ 1 ] );
306        final byte[] expected = Base64.getDecoder().decode( fields[ 2 ] );
307        final byte[] hash = pbkdf2( password, salt, pbkdf2, iterations );
308        return MessageDigest.isEqual( expected, hash );
309    }
310
311    /**
312     * Tells if the entry is a PBKDF2 password entry of any of the supported algorithms.
313     *
314     * @param entry a stored password entry, which may be {@code null}
315     * @return {@code true} if the entry starts with the prefix of a supported PBKDF2 algorithm
316     * @since 3.0.1
317     */
318    public static boolean isPbkdf2Entry( final String entry ) {
319        return Pbkdf2.forEntry( entry ) != null;
320    }
321
322    /**
323     * Tells if a stored entry was created with exactly the given algorithm and iteration count, which is how to find out that an
324     * entry has to be hashed again after the settings changed.
325     *
326     * @param entry a stored password entry
327     * @param algorithm one of {@link #PBKDF2_SHA256} and {@link #PBKDF2_SHA512}
328     * @param iterations the iteration count
329     * @return {@code true} if the entry is a well formed PBKDF2 entry of that algorithm and iteration count
330     * @since 3.0.1
331     */
332    public static boolean hasPbkdf2Parameters( final String entry, final String algorithm, final int iterations ) {
333        final Pbkdf2 pbkdf2 = Pbkdf2.forEntry( entry );
334        if( pbkdf2 == null || !pbkdf2.algorithm.equals( algorithm ) ) {
335            return false;
336        }
337        final String[] fields = entry.substring( pbkdf2.prefix().length() ).split( "\\$" );
338        if( fields.length != 3 ) {
339            return false;
340        }
341        try {
342            return Integer.parseInt( fields[ 0 ] ) == iterations;
343        } catch( final NumberFormatException e ) {
344            return false;
345        }
346    }
347
348    /**
349     * Tells if the algorithm is one of those that can be used to hash new passwords.
350     *
351     * @param algorithm the name of an algorithm, which may be {@code null}
352     * @return {@code true} for {@link #PBKDF2_SHA256} and {@link #PBKDF2_SHA512}
353     * @since 3.0.1
354     */
355    public static boolean isSupportedPbkdf2Algorithm( final String algorithm ) {
356        return PBKDF2_SHA256.equals( algorithm ) || PBKDF2_SHA512.equals( algorithm );
357    }
358
359    /**
360     * Returns the iteration count used for an algorithm unless configured otherwise.
361     *
362     * @param algorithm one of {@link #PBKDF2_SHA256} and {@link #PBKDF2_SHA512}
363     * @return the default iteration count
364     * @throws IllegalArgumentException if the algorithm is not supported
365     * @since 3.0.1
366     */
367    public static int defaultPbkdf2Iterations( final String algorithm ) {
368        return Pbkdf2.forAlgorithm( algorithm ).defaultIterations;
369    }
370
371    private static byte[] pbkdf2( final byte[] password, final byte[] salt, final Pbkdf2 pbkdf2, final int iterations ) throws NoSuchAlgorithmException {
372        final char[] chars = new String( password, StandardCharsets.UTF_8 ).toCharArray();
373        final PBEKeySpec spec = new PBEKeySpec( chars, salt, iterations, pbkdf2.keyLengthBytes * 8 );
374        try {
375            return SecretKeyFactory.getInstance( pbkdf2.jcaName ).generateSecret( spec ).getEncoded();
376        } catch( final InvalidKeySpecException e ) {
377            throw new NoSuchAlgorithmException( "Unable to compute PBKDF2 hash", e );
378        } finally {
379            spec.clearPassword();
380        }
381    }
382
383    /**
384     *  Compares a password to a given entry and returns true, if it matches.
385     *
386     *  @param password The password in bytes.
387     *  @param entry The password entry, typically starting with {SSHA}.
388     *  @return True, if the password matches.
389     *  @throws NoSuchAlgorithmException If there is no SHA available.
390     */
391    public static boolean verifySaltedPassword( final byte[] password, final String entry ) throws NoSuchAlgorithmException {
392        if( !entry.startsWith( SSHA ) && !entry.startsWith( SHA256 ) && !isPbkdf2Entry( entry ) ) {
393            throw new IllegalArgumentException( "Hash not prefixed by expected algorithm; is it really a salted hash?" );
394        }
395        final String algorithm;
396        if( isPbkdf2Entry( entry ) ) {
397            return verifyPbkdf2SaltedPassword( password, entry );
398        } else if (entry.startsWith(SSHA)) {
399            algorithm = SSHA;
400        } else if (entry.startsWith(SHA256)) {
401            algorithm = SHA256;
402        } else {
403            throw new NoSuchAlgorithmException("unknown hash algorithm prefix");
404        }
405
406        String hash2 = entry.substring( algorithm.length() );
407        byte[] bits = hash2.getBytes( StandardCharsets.UTF_8 );
408        final byte[] challenge = Base64.getDecoder().decode(bits);
409
410        // Extract the password hash and salt
411        final byte[] passwordHash = extractPasswordHash( challenge, algorithm.equals( SSHA ) ? 20 : 32 );
412        final byte[] salt = extractSalt( challenge, algorithm.equals( SSHA ) ? 20 : 32  );
413
414        // Re-create the hash using the password and the extracted salt
415        // The term SSHA is used as a password prefix for backwards compatibility, but we use SHA-1 when fetching an instance
416        // of MessageDigest, as it is the guaranteed option. We also need to remove curly braces surrounding the string for
417        // backwards compatibility.
418        final String algorithmToUse = algorithm.equals( SSHA ) ? SHA1 : algorithm;
419        final MessageDigest digest = MessageDigest.getInstance( algorithmToUse.substring( 1, algorithmToUse.length() -1 ) );
420        digest.update( password );
421        final byte[] hash = digest.digest( salt );
422
423        // See if our extracted hash matches what we just re-created
424        return MessageDigest.isEqual( passwordHash, hash );
425    }
426
427    /**
428     * Helper method that extracts the hashed password fragment from a supplied salted SHA-1 or SHA-256 digest
429     * by taking all the characters before position 20 or 32 depending on algorithm.
430     * 
431     * @param digest the salted digest, which is assumed to have been previously decoded from Base64.
432     * @return the password hash
433     * @throws IllegalArgumentException if the length of the supplied digest is less than or equal to 20 bytes
434     */
435    static byte[] extractPasswordHash( final byte[] digest, final int hashLength ) throws IllegalArgumentException {
436        if( digest.length < hashLength ) {
437            throw new IllegalArgumentException( "Hash was shorter than expected; could not extract password hash!" );
438        }
439
440        // Extract the password hash
441        final byte[] hash = new byte[ hashLength ];
442        System.arraycopy( digest, 0, hash, 0, hashLength );
443
444        return hash;
445    }
446
447    /**
448     * Helper method that extracts the salt from supplied salted digest by taking all the characters after a given index.
449     * 
450     * @param digest the salted digest, which is assumed to have been previously decoded from Base64.
451     * @return the salt
452     * @throws IllegalArgumentException if the length of the supplied digest is less than given length.
453     */
454    static byte[] extractSalt( final byte[] digest, final int hashLength ) throws IllegalArgumentException {
455        if( digest.length <= hashLength ) {
456            throw new IllegalArgumentException( "Hash was shorter than expected; we found no salt!" );
457        }
458
459        // Extract the salt
460        final byte[] salt = new byte[digest.length - hashLength];
461        System.arraycopy(digest, hashLength, salt, 0, digest.length - hashLength);
462
463        return salt;
464    }
465
466}