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 org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.api.core.Session;
025import org.apache.wiki.api.exceptions.WikiException;
026import org.apache.wiki.api.spi.Wiki;
027import org.apache.wiki.auth.authorize.WebAuthorizer;
028import org.apache.wiki.auth.authorize.WebContainerAuthorizer;
029import org.apache.wiki.auth.login.AnonymousLoginModule;
030import org.apache.wiki.auth.login.CookieAssertionLoginModule;
031import org.apache.wiki.auth.login.CookieAuthenticationLoginModule;
032import org.apache.wiki.auth.login.UserDatabaseLoginModule;
033import org.apache.wiki.auth.login.WebContainerCallbackHandler;
034import org.apache.wiki.auth.login.WebContainerLoginModule;
035import org.apache.wiki.auth.login.WikiCallbackHandler;
036import org.apache.wiki.event.WikiEventListener;
037import org.apache.wiki.event.WikiEventManager;
038import org.apache.wiki.event.WikiSecurityEvent;
039import org.apache.wiki.util.ClassUtil;
040import org.apache.wiki.util.TextUtil;
041import org.apache.wiki.util.TimedCounterList;
042
043import javax.security.auth.Subject;
044import javax.security.auth.callback.CallbackHandler;
045import javax.security.auth.login.LoginException;
046import javax.security.auth.spi.LoginModule;
047import javax.servlet.http.HttpServletRequest;
048import javax.servlet.http.HttpSession;
049import java.security.Principal;
050import java.util.Collections;
051import java.util.HashMap;
052import java.util.HashSet;
053import java.util.Map;
054import java.util.Properties;
055import java.util.Set;
056import org.apache.wiki.WikiSession;
057
058
059/**
060 * Default implementation for {@link AuthenticationManager}
061 *
062 * {@inheritDoc}
063 * 
064 * @since 2.3
065 */
066public class DefaultAuthenticationManager implements AuthenticationManager {
067
068    /** How many milliseconds the logins are stored before they're cleaned away. */
069    private static final long LASTLOGINS_CLEANUP_TIME = 10 * 60 * 1_000L; // Ten minutes
070
071    private static final long MAX_LOGIN_DELAY = 20 * 1_000L; // 20 seconds
072
073    private static final Logger LOG = LogManager.getLogger( DefaultAuthenticationManager.class );
074
075    /** Empty Map passed to JAAS {@link #doJAASLogin(Class, CallbackHandler, Map)} method. */
076    protected static final Map< String, String > EMPTY_MAP = Collections.unmodifiableMap( new HashMap<>() );
077
078    /** Class (of type LoginModule) to use for custom authentication. */
079    protected Class< ? extends LoginModule > m_loginModuleClass = UserDatabaseLoginModule.class;
080
081    /** Options passed to {@link LoginModule#initialize(Subject, CallbackHandler, Map, Map)};
082     * initialized by {@link #initialize(Engine, Properties)}. */
083    protected final Map< String, String > m_loginModuleOptions = new HashMap<>();
084
085    /** The default {@link LoginModule} class name to use for custom authentication. */
086    private static final String DEFAULT_LOGIN_MODULE = "org.apache.wiki.auth.login.UserDatabaseLoginModule";
087
088    /** Empty principal set. */
089    private static final Set<Principal> NO_PRINCIPALS = new HashSet<>();
090
091    /** Static Boolean for lazily-initializing the "allows assertions" flag */
092    private boolean m_allowsCookieAssertions = true;
093
094    private boolean m_throttleLogins = true;
095
096    /** Static Boolean for lazily-initializing the "allows cookie authentication" flag */
097    private boolean m_allowsCookieAuthentication;
098
099    private Engine m_engine;
100
101    /** If true, logs the IP address of the editor */
102    private boolean m_storeIPAddress = true;
103
104    /** Keeps a list of the usernames who have attempted a login recently. */
105    private final TimedCounterList< String > m_lastLoginAttempts = new TimedCounterList<>();
106
107    /**
108     * {@inheritDoc}
109     */
110    @Override
111    public void initialize( final Engine engine, final Properties props ) throws WikiException {
112        m_engine = engine;
113        m_storeIPAddress = TextUtil.getBooleanProperty( props, PROP_STOREIPADDRESS, m_storeIPAddress );
114
115        // Should we allow cookies for assertions? (default: yes)
116        m_allowsCookieAssertions = TextUtil.getBooleanProperty( props, PROP_ALLOW_COOKIE_ASSERTIONS,true );
117
118        // Should we allow cookies for authentication? (default: no)
119        m_allowsCookieAuthentication = TextUtil.getBooleanProperty( props, PROP_ALLOW_COOKIE_AUTH, false );
120
121        // Should we throttle logins? (default: yes)
122        m_throttleLogins = TextUtil.getBooleanProperty( props, PROP_LOGIN_THROTTLING, true );
123
124        // Look up the LoginModule class
125        final String loginModuleClassName = TextUtil.getStringProperty( props, PROP_LOGIN_MODULE, DEFAULT_LOGIN_MODULE );
126        try {
127            m_loginModuleClass = ClassUtil.findClass( "", loginModuleClassName );
128        } catch( final ClassNotFoundException e ) {
129            LOG.error( e.getMessage(), e );
130            throw new WikiException( "Could not instantiate LoginModule class.", e );
131        }
132
133        // Initialize the LoginModule options
134        initLoginModuleOptions( props );
135    }
136
137    /**
138     * {@inheritDoc}
139     */
140    @Override
141    public boolean isContainerAuthenticated() {
142        try {
143            final Authorizer authorizer = m_engine.getManager( AuthorizationManager.class ).getAuthorizer();
144            if ( authorizer instanceof WebContainerAuthorizer ) {
145                 return ( ( WebContainerAuthorizer )authorizer ).isContainerAuthorized();
146            }
147        } catch ( final WikiException e ) {
148            // It's probably ok to fail silently...
149        }
150        return false;
151    }
152
153    /**
154     * {@inheritDoc}
155     */
156    @Override
157    public boolean login( final HttpServletRequest request ) throws WikiSecurityException {
158        final HttpSession httpSession = request.getSession();
159        final Session session = SessionMonitor.getInstance( m_engine ).find( httpSession );
160        final AuthenticationManager authenticationMgr = m_engine.getManager( AuthenticationManager.class );
161        final AuthorizationManager authorizationMgr = m_engine.getManager( AuthorizationManager.class );
162        CallbackHandler handler = null;
163        final Map< String, String > options = EMPTY_MAP;
164
165        // If user not authenticated, check if container logged them in, or if there's an authentication cookie
166        if ( !session.isAuthenticated() ) {
167            // Create a callback handler
168            handler = new WebContainerCallbackHandler( m_engine, request );
169
170            // Execute the container login module, then (if that fails) the cookie auth module
171            Set< Principal > principals = authenticationMgr.doJAASLogin( WebContainerLoginModule.class, handler, options );
172            if (principals.isEmpty() && authenticationMgr.allowsCookieAuthentication() ) {
173                principals = authenticationMgr.doJAASLogin( CookieAuthenticationLoginModule.class, handler, options );
174            }
175
176            // If the container logged the user in successfully, tell the Session (and add all the Principals)
177            if (!principals.isEmpty()) {
178                rotateSessionAfterAuthentication( request, session );
179                fireEvent( WikiSecurityEvent.LOGIN_AUTHENTICATED, getLoginPrincipal( principals ), session );
180                for( final Principal principal : principals ) {
181                    fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, principal, session );
182                }
183
184                // Add all appropriate Authorizer roles
185                injectAuthorizerRoles( session, authorizationMgr.getAuthorizer(), request );
186            }
187        }
188
189        // If user still not authenticated, check if assertion cookie was supplied
190        if ( !session.isAuthenticated() && authenticationMgr.allowsCookieAssertions() ) {
191            // Execute the cookie assertion login module
192            final Set< Principal > principals = authenticationMgr.doJAASLogin( CookieAssertionLoginModule.class, handler, options );
193            if (!principals.isEmpty()) {
194                fireEvent( WikiSecurityEvent.LOGIN_ASSERTED, getLoginPrincipal( principals ), session);
195            }
196        }
197
198        // If user still anonymous, use the remote address
199        if( session.isAnonymous() ) {
200            final Set< Principal > principals = authenticationMgr.doJAASLogin( AnonymousLoginModule.class, handler, options );
201            if(!principals.isEmpty()) {
202                fireEvent( WikiSecurityEvent.LOGIN_ANONYMOUS, getLoginPrincipal( principals ), session );
203                return true;
204            }
205        }
206
207        // If by some unusual turn of events the Anonymous login module doesn't work, login failed!
208        return false;
209    }
210
211    /**
212     * {@inheritDoc}
213     */
214    @Override
215    public boolean login( final Session session, final HttpServletRequest request, final String username, final String password ) throws WikiSecurityException {
216        if ( session == null ) {
217            LOG.error( "No wiki session provided, cannot log in." );
218            return false;
219        }
220
221        // Protect against brute-force password guessing if configured to do so
222        if ( m_throttleLogins ) {
223            delayLogin( username );
224        }
225
226        final CallbackHandler handler = new WikiCallbackHandler( m_engine, null, username, password );
227
228        // Execute the user's specified login module
229        final Set< Principal > principals = doJAASLogin( m_loginModuleClass, handler, m_loginModuleOptions );
230        if(!principals.isEmpty()) {
231            rotateSessionAfterAuthentication( request, session );
232            fireEvent(WikiSecurityEvent.LOGIN_AUTHENTICATED, getLoginPrincipal( principals ), session );
233            for ( final Principal principal : principals ) {
234                fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, principal, session );
235            }
236
237            // Add all appropriate Authorizer roles
238            injectAuthorizerRoles( session, m_engine.getManager( AuthorizationManager.class ).getAuthorizer(), null );
239
240            return true;
241        }
242        return false;
243    }
244
245    /**
246     * Session-fixation defense: the pre-authentication HTTP session id and anti-CSRF token must not survive the
247     * upgrade to an authenticated session. Rotates the servlet session id, re-keys the {@link SessionMonitor} entry
248     * so the wiki session attaches to the new id, and regenerates the wiki session's anti-CSRF token so a token
249     * observed before login cannot be replayed against the authenticated session.
250     *
251     * @param request the servlet request, may be <code>null</code> (e.g. embedded use); nothing to rotate then
252     * @param session the wiki session being upgraded
253     */
254    private void rotateSessionAfterAuthentication( final HttpServletRequest request, final Session session ) {
255        if( request != null ) {
256            final HttpSession httpSession = request.getSession( false );
257            if( httpSession != null ) {
258                final SessionMonitor monitor = SessionMonitor.getInstance( m_engine );
259                monitor.remove( httpSession );
260                try {
261                    request.changeSessionId();
262                } catch( final IllegalStateException e ) {
263                    LOG.debug( "Unable to rotate the http session id: {}", e.getMessage() );
264                }
265                monitor.register( httpSession, session );
266            }
267        }
268        session.regenerateAntiCsrfToken();
269        
270    }
271
272    /**
273     *  This method builds a database of login names that are being attempted, and will try to delay if there are too many requests coming
274     *  in for the same username.
275     *  <p>
276     *  The current algorithm uses 2^loginattempts as the delay in milliseconds, i.e. at 10 login attempts it'll add 1.024 seconds to the login.
277     *
278     *  @param username The username that is being logged in
279     */
280    private void delayLogin( final String username ) {
281        try {
282            m_lastLoginAttempts.cleanup( LASTLOGINS_CLEANUP_TIME );
283            final int count = m_lastLoginAttempts.count( username );
284
285            final long delay = Math.min( 1L << count, MAX_LOGIN_DELAY );
286            LOG.debug( "Sleeping for " + delay + " ms to allow login." );
287            Thread.sleep( delay );
288
289            m_lastLoginAttempts.add( username );
290        } catch( final InterruptedException e ) {
291            // FALLTHROUGH is fine
292        }
293    }
294
295    /**
296     * {@inheritDoc}
297     */
298    @Override
299    public void logout( final HttpServletRequest request ) {
300        if( request == null ) {
301            LOG.error( "No HTTP reqest provided; cannot log out." );
302            return;
303        }
304
305        final HttpSession session = request.getSession();
306        final String sid = ( session == null ) ? "(null)" : session.getId();
307        LOG.debug( "Invalidating Session for session ID= {}", sid );
308        // Retrieve the associated Session and clear the Principal set
309        final Session wikiSession = Wiki.session().find( m_engine, request );
310        final Principal originalPrincipal = wikiSession.getLoginPrincipal();
311        wikiSession.invalidate();
312
313        // Remove the wikiSession from the WikiSession cache
314        Wiki.session().remove( m_engine, request );
315
316        // We need to flush the HTTP session too
317        if( session != null ) {
318            session.invalidate();
319        }
320
321        // Log the event
322        fireEvent( WikiSecurityEvent.LOGOUT, originalPrincipal, null );
323    }
324
325    /**
326     * {@inheritDoc}
327     */
328    @Override
329    public boolean allowsCookieAssertions() {
330        return m_allowsCookieAssertions;
331    }
332
333    /**
334     * {@inheritDoc}
335     */
336    @Override
337    public boolean allowsCookieAuthentication() {
338        return m_allowsCookieAuthentication;
339    }
340
341    /**
342     * {@inheritDoc}
343     */
344    @Override
345    public Set< Principal > doJAASLogin( final Class< ? extends LoginModule > clazz,
346                                         final CallbackHandler handler,
347                                         final Map< String, String > options ) throws WikiSecurityException {
348        // Instantiate the login module
349        final LoginModule loginModule;
350        try {
351            loginModule = ClassUtil.buildInstance( clazz );
352        } catch( final ReflectiveOperationException e ) {
353            throw new WikiSecurityException( e.getMessage(), e );
354        }
355
356        // Initialize the LoginModule
357        final Subject subject = new Subject();
358        loginModule.initialize( subject, handler, EMPTY_MAP, options );
359
360        // Try to log in:
361        boolean loginSucceeded = false;
362        boolean commitSucceeded = false;
363        try {
364            loginSucceeded = loginModule.login();
365            if( loginSucceeded ) {
366                commitSucceeded = loginModule.commit();
367            }
368        } catch( final LoginException e ) {
369            // Login or commit failed! No principal for you!
370        }
371
372        // If we successfully logged in & committed, return all the principals
373        if( loginSucceeded && commitSucceeded ) {
374            return subject.getPrincipals();
375        }
376        return NO_PRINCIPALS;
377    }
378
379    // events processing .......................................................
380
381    /**
382     * {@inheritDoc}
383     */
384    @Override
385    public synchronized void addWikiEventListener( final WikiEventListener listener ) {
386        WikiEventManager.addWikiEventListener( this, listener );
387    }
388
389    /**
390     * {@inheritDoc}
391     */
392    @Override
393    public synchronized void removeWikiEventListener( final WikiEventListener listener ) {
394        WikiEventManager.removeWikiEventListener( this, listener );
395    }
396
397    /**
398     * Initializes the options Map supplied to the configured LoginModule every time it is invoked. The properties and values extracted from
399     * <code>jspwiki.properties</code> are of the form <code>jspwiki.loginModule.options.<var>param</var> = <var>value</var>, where
400     * <var>param</var> is the key name, and <var>value</var> is the value.
401     *
402     * @param props the properties used to initialize JSPWiki
403     * @throws IllegalArgumentException if any of the keys are duplicated
404     */
405    private void initLoginModuleOptions( final Properties props ) {
406        for( final Object key : props.keySet() ) {
407            final String propName = key.toString();
408            if( propName.startsWith( PREFIX_LOGIN_MODULE_OPTIONS ) ) {
409                // Extract the option name and value
410                final String optionKey = propName.substring( PREFIX_LOGIN_MODULE_OPTIONS.length() ).trim();
411                if( !optionKey.isEmpty() ) {
412                    final String optionValue = props.getProperty( propName );
413
414                    // Make sure the key is unique before stashing the key/value pair
415                    if ( m_loginModuleOptions.containsKey( optionKey ) ) {
416                        throw new IllegalArgumentException( "JAAS LoginModule key " + propName + " cannot be specified twice!" );
417                    }
418                    m_loginModuleOptions.put( optionKey, optionValue );
419                }
420            }
421        }
422    }
423
424    /**
425     * After successful login, this method is called to inject authorized role Principals into the Session. To determine which roles
426     * should be injected, the configured Authorizer is queried for the roles it knows about by calling  {@link Authorizer#getRoles()}.
427     * Then, each role returned by the authorizer is tested by calling {@link Authorizer#isUserInRole(Session, Principal)}. If this
428     * check fails, and the Authorizer is of type WebAuthorizer, the role is checked again by calling
429     * {@link WebAuthorizer#isUserInRole(HttpServletRequest, Principal)}). Any roles that pass the test are injected into the Subject by
430     * firing appropriate authentication events.
431     *
432     * @param session the user's current Session
433     * @param authorizer the Engine's configured Authorizer
434     * @param request the user's HTTP session, which may be <code>null</code>
435     */
436    private void injectAuthorizerRoles( final Session session, final Authorizer authorizer, final HttpServletRequest request ) {
437        // Test each role the authorizer knows about
438        for( final Principal role : authorizer.getRoles() ) {
439            // Test the Authorizer
440            if( authorizer.isUserInRole( session, role ) ) {
441                fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, role, session );
442                LOG.debug( "Added authorizer role {}.", role.getName() );
443            // If web authorizer, test the request.isInRole() method also
444            } else if ( request != null && authorizer instanceof WebAuthorizer ) {
445                final WebAuthorizer wa = ( WebAuthorizer )authorizer;
446                if ( wa.isUserInRole( request, role ) ) {
447                    fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, role, session );
448                    LOG.debug( "Added container role {}.",role.getName() );
449                }
450            }
451        }
452    }
453
454}