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;
020
021import java.nio.charset.StandardCharsets;
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024import java.security.SecureRandom;
025import java.util.Iterator;
026import java.util.Map;
027import java.util.concurrent.ConcurrentHashMap;
028import java.util.function.LongSupplier;
029
030/**
031 * In-memory store of single-use, expiring password reset tokens, used by {@code LostPassword.jsp}.
032 * <p>
033 * A password reset is a two-step operation: a cryptographically random token is issued and mailed to the
034 * account owner ({@link #issue(String)}), and the stored credential is only changed when that token is
035 * presented back ({@link #redeem(String)}). Only a SHA-256 hash of the token is kept server-side, tokens
036 * expire after {@link #TOKEN_TTL_MS}, are removed on first use, and at most one token per account may be
037 * outstanding at a time (which also acts as a simple per-account throttle). The store itself is bounded
038 * to {@link #MAX_PENDING} entries as a global backstop.
039 * <p>
040 * Note: the store is per-JVM. On a multi-node deployment a token must be redeemed on the node that
041 * issued it.
042 *
043 * @since 2.12.4
044 */
045public final class PasswordResetTokenStore {
046
047    /** How long an issued token stays valid: 30 minutes. */
048    public static final long TOKEN_TTL_MS = 30L * 60L * 1000L;
049
050    /** Upper bound on simultaneously outstanding tokens. */
051    static final int MAX_PENDING = 1_000;
052
053    private static final SecureRandom RANDOM = new SecureRandom();
054    private static final PasswordResetTokenStore INSTANCE = new PasswordResetTokenStore( System::currentTimeMillis );
055
056    private final Map< String, PendingReset > pending = new ConcurrentHashMap<>();
057    private final LongSupplier clock;
058
059    /** Package-private for tests, which supply their own clock. */
060    PasswordResetTokenStore( final LongSupplier clock ) {
061        this.clock = clock;
062    }
063
064    /**
065     * Returns the shared store instance.
066     *
067     * @return the shared {@link PasswordResetTokenStore}.
068     */
069    public static PasswordResetTokenStore getInstance() {
070        return INSTANCE;
071    }
072
073    /**
074     * Issues a new reset token for the given login name. The raw token is returned exactly once, for
075     * inclusion in the reset e-mail; only its SHA-256 hash is retained. If a non-expired token is already
076     * outstanding for the account, or the store is full, no token is issued.
077     *
078     * @param loginName the login name the token is bound to.
079     * @return the raw token, or {@code null} if issuance was throttled.
080     */
081    public synchronized String issue( final String loginName ) {
082        final long now = clock.getAsLong();
083        purgeExpired( now );
084        if( loginName == null || loginName.isEmpty() || pending.size() >= MAX_PENDING ) {
085            return null;
086        }
087        for( final PendingReset reset : pending.values() ) {
088            if( reset.loginName.equals( loginName ) ) {
089                return null; // one outstanding token per account
090            }
091        }
092        final byte[] raw = new byte[ 32 ];
093        RANDOM.nextBytes( raw );
094        final String token = toHex( raw );
095        pending.put( toHex( sha256( token ) ), new PendingReset( loginName, now + TOKEN_TTL_MS ) );
096        return token;
097    }
098
099    /**
100     * Redeems a token: if it matches a stored, non-expired token hash, the token is removed (single use)
101     * and the login name it was issued for is returned. Comparison of the hashed values is constant-time.
102     *
103     * @param token the raw token as received from the user.
104     * @return the login name the token was bound to, or {@code null} if the token is unknown, already
105     *         used or expired.
106     */
107    public synchronized String redeem( final String token ) {
108        final long now = clock.getAsLong();
109        purgeExpired( now );
110        if( token == null || token.isEmpty() ) {
111            return null;
112        }
113        final byte[] candidate = sha256( token );
114        String matchedKey = null;
115        // Scan every entry and compare via MessageDigest.isEqual, so neither the position of a match nor
116        // a partial prefix match shows up as a timing difference.
117        for( final String key : pending.keySet() ) {
118            if( MessageDigest.isEqual( candidate, fromHex( key ) ) && matchedKey == null ) {
119                matchedKey = key;
120            }
121        }
122        if( matchedKey == null ) {
123            return null;
124        }
125        final PendingReset reset = pending.remove( matchedKey ); // remove-on-use: replay gets null
126        return reset != null && reset.expiry >= now ? reset.loginName : null;
127    }
128
129    private void purgeExpired( final long now ) {
130        for( final Iterator< PendingReset > it = pending.values().iterator(); it.hasNext(); ) {
131            if( it.next().expiry < now ) {
132                it.remove();
133            }
134        }
135    }
136
137    private static byte[] sha256( final String value ) {
138        try {
139            return MessageDigest.getInstance( "SHA-256" ).digest( value.getBytes( StandardCharsets.UTF_8 ) );
140        } catch( final NoSuchAlgorithmException e ) {
141            throw new IllegalStateException( "JVM without SHA-256 support", e );
142        }
143    }
144
145    private static String toHex( final byte[] bytes ) {
146        final StringBuilder sb = new StringBuilder( bytes.length * 2 );
147        for( final byte b : bytes ) {
148            sb.append( Character.forDigit( ( b >> 4 ) & 0x0F, 16 ) ).append( Character.forDigit( b & 0x0F, 16 ) );
149        }
150        return sb.toString();
151    }
152
153    private static byte[] fromHex( final String hex ) {
154        final byte[] bytes = new byte[ hex.length() / 2 ];
155        for( int i = 0; i < bytes.length; i++ ) {
156            bytes[ i ] = ( byte )( ( Character.digit( hex.charAt( 2 * i ), 16 ) << 4 ) + Character.digit( hex.charAt( 2 * i + 1 ), 16 ) );
157        }
158        return bytes;
159    }
160
161    private static final class PendingReset {
162        final String loginName;
163        final long expiry;
164
165        PendingReset( final String loginName, final long expiry ) {
166            this.loginName = loginName;
167            this.expiry = expiry;
168        }
169    }
170
171}