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.login;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.auth.WikiPrincipal;
025import org.apache.wiki.util.FileUtil;
026import org.apache.wiki.util.HttpUtil;
027import org.apache.wiki.util.Synchronizer;
028import org.apache.wiki.util.TextUtil;
029
030import javax.security.auth.callback.Callback;
031import javax.security.auth.callback.UnsupportedCallbackException;
032import javax.security.auth.login.LoginException;
033import jakarta.servlet.http.Cookie;
034import jakarta.servlet.http.HttpServletRequest;
035import jakarta.servlet.http.HttpServletResponse;
036import java.io.BufferedReader;
037import java.io.BufferedWriter;
038import java.io.File;
039import java.io.IOException;
040import java.io.InputStreamReader;
041import java.io.OutputStreamWriter;
042import java.io.Reader;
043import java.io.StringReader;
044import java.io.Writer;
045import java.nio.charset.StandardCharsets;
046import java.nio.file.Files;
047import java.util.UUID;
048import java.util.concurrent.locks.ReentrantLock;
049
050
051/**
052 * Logs in a user based on a cookie stored in the user's computer.  The cookie
053 * information is stored in the <code>jspwiki.workDir</code>, under the directory
054 * {@value #COOKIE_DIR}.  For security purposes it is a very, very good idea
055 * to prevent access to this directory by everyone except the web server process;
056 * otherwise people having read access to this directory may be able to spoof
057 * other users.
058 * <p>
059 * The cookie directory is scrubbed of old entries at regular intervals.
060 * <p>
061 * This module must be used with a CallbackHandler (such as
062 * {@link WebContainerCallbackHandler}) that supports the following Callback
063 * types:
064 * </p>
065 *  <ol>
066 *  <li>{@link HttpRequestCallback}- supplies the cookie, which should contain
067 *      an unique id for fetching the UID.</li>
068 *  <li>{@link WikiEngineCallback} - allows access to the Engine itself.
069 *  </ol>
070 * <p>
071 * After authentication, a generic WikiPrincipal based on the username will be
072 * created and associated with the Subject.
073 * </p>
074 * @see javax.security.auth.spi.LoginModule#commit()
075 * @see CookieAssertionLoginModule
076 * @since 2.5.62
077 */
078public class CookieAuthenticationLoginModule extends AbstractLoginModule {
079
080    private static final Logger LOG = LogManager.getLogger( CookieAuthenticationLoginModule.class );
081    private static final String LOGIN_COOKIE_NAME = "JSPWikiUID";
082
083    /** The directory name under which the cookies are stored.  The value is {@value}. */
084    protected static final String COOKIE_DIR = "logincookies";
085
086    /**
087     * User property for setting how long the cookie is stored on the user's computer.
088     * The value is {@value}.  The default expiry time is 14 days.
089     */
090    public static final String PROP_LOGIN_EXPIRY_DAYS = "jspwiki.cookieAuthentication.expiry";
091
092    /**
093     * Built-in value for storing the cookie.
094     */
095    private static final int DEFAULT_EXPIRY_DAYS = 14;
096
097    private static long c_lastScrubTime;
098
099    /**
100     * Describes how often we scrub the cookieDir directory.
101     */
102    private static final long SCRUB_PERIOD = 60 * 60 * 1_000L; // In milliseconds
103
104    /**
105     * A lock used to ensure thread safety when accessing shared resources.
106     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
107     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
108     * waiting to acquire a lock.
109     *
110     * @see java.util.concurrent.locks.ReentrantLock
111     */
112    private static final ReentrantLock lock = new ReentrantLock();
113
114    /**
115     * {@inheritDoc}
116     *
117     * @see javax.security.auth.spi.LoginModule#login()
118     */
119    @Override
120    public boolean login() throws LoginException {
121        // Otherwise, let's go and look for the cookie!
122        final HttpRequestCallback hcb = new HttpRequestCallback();
123        final WikiEngineCallback wcb = new WikiEngineCallback();
124        final Callback[] callbacks = new Callback[] { hcb, wcb };
125
126        try {
127            m_handler.handle( callbacks );
128            final HttpServletRequest request = hcb.getRequest();
129            final String uid = getLoginCookie( request );
130
131            if( uid != null ) {
132                final Engine engine = wcb.getEngine();
133                final File cookieFile = getCookieFile( engine, uid );
134                if( cookieFile != null && cookieFile.exists() && cookieFile.canRead() ) {
135                    try( final Reader in = new BufferedReader( new InputStreamReader( Files.newInputStream( cookieFile.toPath() ), StandardCharsets.UTF_8 ) ) ) {
136                        final String username = FileUtil.readContents( in );
137                        LOG.debug( "Logged in cookie authenticated name={}", username );
138
139                        // If login succeeds, commit these principals/roles
140                        m_principals.add( new WikiPrincipal( username, WikiPrincipal.LOGIN_NAME ) );
141
142                        // Tag the file so that we know that it has been accessed recently.
143                        return cookieFile.setLastModified( System.currentTimeMillis() );
144
145                    } catch( final IOException e ) {
146                        LOG.debug(e.getMessage(), e);
147                        return false;
148                    }
149                }
150            }
151        } catch( final IOException e ) {
152            final String message = "IO exception; disallowing login.";
153            LOG.error( message, e );
154            throw new LoginException( message );
155        } catch( final UnsupportedCallbackException e ) {
156            final String message = "Unable to handle callback; disallowing login.";
157            LOG.error( message, e );
158            throw new LoginException( message );
159        }
160        return false;
161    }
162
163    /**
164     * Attempts to locate the cookie file.
165     *
166     * @param engine Engine
167     * @param uid An unique ID fetched from the user cookie
168     * @return A File handle, or null, if there was a problem.
169     */
170    private static File getCookieFile( final Engine engine, final String uid ) {
171        final File cookieDir = new File( engine.getWorkDir(), COOKIE_DIR );
172        if( !cookieDir.exists() ) {
173            cookieDir.mkdirs();
174        }
175        if( !cookieDir.canRead() ) {
176            LOG.error( "Cannot read from cookie directory! {}", cookieDir.getAbsolutePath() );
177            return null;
178        }
179        if( !cookieDir.canWrite() ) {
180            LOG.error( "Cannot write to cookie directory! {}", cookieDir.getAbsolutePath() );
181            return null;
182        }
183
184        //  Scrub away old files
185        final long now = System.currentTimeMillis();
186        if( now > ( c_lastScrubTime + SCRUB_PERIOD ) ) {
187            scrub( TextUtil.getIntegerProperty( engine.getWikiProperties(), PROP_LOGIN_EXPIRY_DAYS, DEFAULT_EXPIRY_DAYS ), cookieDir );
188            c_lastScrubTime = now;
189        }
190
191        //  Find the cookie file
192        final File file = new File( cookieDir, uid );
193        try {
194            if( file.getCanonicalPath().startsWith( cookieDir.getCanonicalPath() ) ) {
195                return file;
196            }
197        } catch( final IOException e ) {
198            LOG.error( "Problem retrieving login cookie, returning null: {}", e.getMessage() );
199            return null;
200        }
201        return null;
202    }
203
204    /**
205     * Extracts the login cookie UID from the servlet request.
206     *
207     * @param request The HttpServletRequest
208     * @return The UID value from the cookie, or null, if no such cookie exists.
209     */
210    private static String getLoginCookie( final HttpServletRequest request ) {
211        return HttpUtil.retrieveCookieValue( request, LOGIN_COOKIE_NAME );
212    }
213
214    /**
215     * Sets a login cookie based on properties set by the user.  This method also
216     * creates the cookie uid-username mapping in the work directory.
217     *
218     * @param engine   The Engine
219     * @param response The HttpServletResponse
220     * @param username The username for whom to create the cookie.
221     */
222    public static void setLoginCookie( final Engine engine, final HttpServletResponse response, final String username ) {
223        final UUID uid = UUID.randomUUID();
224        final int days = TextUtil.getIntegerProperty( engine.getWikiProperties(), PROP_LOGIN_EXPIRY_DAYS, DEFAULT_EXPIRY_DAYS );
225        final Cookie userId = getLoginCookie( uid.toString() );
226        userId.setMaxAge( days * 24 * 60 * 60 );
227        response.addCookie( userId );
228
229        final File cf = getCookieFile( engine, uid.toString() );
230        if( cf != null ) {
231            //  Write the cookie content to the cookie store file.
232            try( final Writer out = new BufferedWriter( new OutputStreamWriter( Files.newOutputStream( cf.toPath() ), StandardCharsets.UTF_8 ) ) ) {
233                FileUtil.copyContents( new StringReader( username ), out );
234                LOG.debug( "Created login cookie for user {} for {} days", username, days );
235            } catch( final IOException ex ) {
236                LOG.error( "Unable to create cookie file to store user id: {}", uid );
237            }
238        }
239    }
240
241    /**
242     * Clears away the login cookie, and removes the uid-username mapping file as well.
243     *
244     * @param engine   Engine
245     * @param request  Servlet request
246     * @param response Servlet response
247     */
248    public static void clearLoginCookie( final Engine engine, final HttpServletRequest request, final HttpServletResponse response ) {
249        final Cookie userId = getLoginCookie( "" );
250        userId.setMaxAge( 0 );
251        response.addCookie( userId );
252        final String uid = getLoginCookie( request );
253        if( uid != null ) {
254            final File cf = getCookieFile( engine, uid );
255            if( cf != null ) {
256                if( !cf.delete() ) {
257                    LOG.debug( "Error deleting cookie login {}", uid );
258                }
259            }
260        }
261    }
262
263    /**
264     * Helper function to get secure LOGIN cookie
265     *
266     * @param value of the cookie
267     */
268    private static Cookie getLoginCookie( final String value ) {
269        final Cookie c = new Cookie( LOGIN_COOKIE_NAME, value );
270        c.setHttpOnly( true ); // no browser access
271        c.setSecure( true ); // only access via encrypted https allowed
272        return c;
273    }
274
275    /**
276     * Goes through the cookie directory and removes any obsolete files.
277     * The scrubbing takes place one day after the cookie was supposed to expire.
278     * However, if the user has logged in during the expiry period, the expiry is
279     * reset, and the cookie file left here.
280     *
281     * @param days number of days that the cookie will survive
282     * @param cookieDir cookie directory
283     */
284    private static void scrub( final int days, final File cookieDir ) {
285        Synchronizer.synchronize(lock, () -> {
286            LOG.debug( "Scrubbing cookieDir..." );
287            final File[] files = cookieDir.listFiles();
288            final long obsoleteDateLimit = System.currentTimeMillis() - ( ( long )days + 1 ) * 24 * 60 * 60 * 1000L;
289            int deleteCount = 0;
290
291            for( int i = 0; i < files.length; i++ ) {
292                final File f = files[ i ];
293                final long lastModified = f.lastModified();
294                if( lastModified < obsoleteDateLimit ) {
295                    if( f.delete() ) {
296                        deleteCount++;
297                    } else {
298                        LOG.debug( "Error deleting cookie login with index {}", i );
299                    }
300                }
301            }
302
303            LOG.debug( "Removed {} obsolete cookie logins", deleteCount );
304        });
305
306    }
307
308}