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.WikiContext;
024import org.apache.wiki.api.core.Acl;
025import org.apache.wiki.api.core.AclEntry;
026import org.apache.wiki.api.core.Context;
027import org.apache.wiki.api.core.ContextEnum;
028import org.apache.wiki.api.core.Engine;
029import org.apache.wiki.api.core.Page;
030import org.apache.wiki.api.core.Session;
031import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
032import org.apache.wiki.api.exceptions.WikiException;
033import org.apache.wiki.auth.acl.AclManager;
034import org.apache.wiki.auth.acl.UnresolvedPrincipal;
035import org.apache.wiki.auth.authorize.GroupManager;
036import org.apache.wiki.auth.authorize.Role;
037import org.apache.wiki.auth.permissions.AllPermission;
038import org.apache.wiki.auth.permissions.GroupPermission;
039import org.apache.wiki.auth.permissions.PagePermission;
040import org.apache.wiki.auth.user.UserDatabase;
041import org.apache.wiki.event.WikiEventListener;
042import org.apache.wiki.event.WikiEventManager;
043import org.apache.wiki.event.WikiSecurityEvent;
044import org.apache.wiki.i18n.InternationalizationManager;
045import org.apache.wiki.pages.PageManager;
046import org.apache.wiki.preferences.Preferences;
047import org.apache.wiki.util.ClassUtil;
048import org.apache.wiki.util.Synchronizer;
049import org.freshcookies.security.policy.LocalPolicy;
050
051import jakarta.servlet.http.HttpServletResponse;
052import java.io.File;
053import java.io.IOException;
054import java.net.URL;
055import java.security.CodeSource;
056import java.security.Permission;
057import java.security.Principal;
058import java.security.ProtectionDomain;
059import java.security.cert.Certificate;
060import java.text.MessageFormat;
061import java.util.Arrays;
062import java.util.Map;
063import java.util.Properties;
064import java.util.ResourceBundle;
065import java.util.WeakHashMap;
066import java.util.concurrent.locks.ReentrantLock;
067
068
069/**
070 * <p>Default implementation for {@link AuthorizationManager}</p>
071 * {@inheritDoc}
072 *
073 * <p>See the {@link #checkPermission(Session, Permission)} and {@link #hasRoleOrPrincipal(Session, Principal)} methods for more
074 * information on the authorization logic.</p>
075 * @since 2.3
076 * @see AuthenticationManager
077 */
078public class DefaultAuthorizationManager implements AuthorizationManager {
079
080    private static final Logger LOG = LogManager.getLogger( DefaultAuthorizationManager.class );
081
082    private Authorizer m_authorizer;
083
084    /** Cache for storing ProtectionDomains used to evaluate the local policy. */
085    private final Map< Principal, ProtectionDomain > m_cachedPds = new WeakHashMap<>();
086
087    private Engine m_engine;
088
089    private LocalPolicy m_localPolicy;
090
091    /**
092     * A lock used to ensure thread safety when accessing shared resources.
093     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
094     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
095     * waiting to acquire a lock.
096     *
097     * @see java.util.concurrent.locks.ReentrantLock
098     */
099    private final ReentrantLock lock = new ReentrantLock();
100
101    /** {@inheritDoc} */
102    @Override
103    public boolean checkPermission( final Session session, final Permission permission ) {
104        // A slight sanity check.
105        if( session == null || permission == null ) {
106            fireEvent( WikiSecurityEvent.ACCESS_DENIED, null, permission );
107            return false;
108        }
109
110        final Principal user = session.getLoginPrincipal();
111
112        // A context that needs no permission asks for the dummy one, which no policy grants
113        if( WikiContext.DUMMY_PERMISSION.equals( permission ) ) {
114            fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission );
115            return true;
116        }
117
118        // Always allow the action if user has AllPermission
119        final Permission allPermission = new AllPermission( m_engine.getApplicationName() );
120        final boolean hasAllPermission = checkStaticPermission( session, allPermission );
121        if( hasAllPermission ) {
122            fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission );
123            return true;
124        }
125
126        // If the user doesn't have *at least* the permission granted by policy, return false.
127        final boolean hasPolicyPermission = checkStaticPermission( session, permission );
128        if( !hasPolicyPermission ) {
129            fireEvent( WikiSecurityEvent.ACCESS_DENIED, user, permission );
130            return false;
131        }
132
133        // If this isn't a PagePermission, it's allowed
134        if( !( permission instanceof PagePermission ) ) {
135            fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission );
136            return true;
137        }
138
139        // If the page or ACL is null, it's allowed.
140        final String pageName = ((PagePermission)permission).getPage();
141        final Page page = m_engine.getManager( PageManager.class ).getPage( pageName );
142        final Acl acl = ( page == null) ? null : m_engine.getManager( AclManager.class ).getPermissions( page );
143        if( page == null ||  acl == null || acl.isEmpty() ) {
144            fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission );
145            return true;
146        }
147
148        // Next, iterate through the Principal objects assigned this permission. If the context's subject possesses
149        // any of these, the action is allowed.
150        final Principal[] aclPrincipals = acl.findPrincipals( permission );
151
152        LOG.debug( "Checking ACL entries..." );
153        LOG.debug( "Acl for this page is: {}", acl );
154        LOG.debug( "Checking for principal: {}", Arrays.toString( aclPrincipals ) );
155        LOG.debug( "Permission: {}", permission );
156
157        for( Principal aclPrincipal : aclPrincipals ) {
158            // If the ACL principal we're looking at is unresolved, try to resolve it here & correct the Acl
159            if ( aclPrincipal instanceof UnresolvedPrincipal ) {
160                final AclEntry aclEntry = acl.getAclEntry( aclPrincipal );
161                aclPrincipal = resolvePrincipal( aclPrincipal.getName() );
162                if ( aclEntry != null && !( aclPrincipal instanceof UnresolvedPrincipal ) ) {
163                    aclEntry.setPrincipal( aclPrincipal );
164                }
165            }
166
167            if ( hasRoleOrPrincipal( session, aclPrincipal ) ) {
168                fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission );
169                return true;
170            }
171        }
172        fireEvent( WikiSecurityEvent.ACCESS_DENIED, user, permission );
173        return false;
174    }
175
176    /** {@inheritDoc} */
177    @Override
178    public Authorizer getAuthorizer() throws WikiSecurityException {
179        if ( m_authorizer != null ) {
180            return m_authorizer;
181        }
182        throw new WikiSecurityException( "Authorizer did not initialize properly. Check the logs." );
183    }
184
185    /** {@inheritDoc} */
186    @Override
187    public boolean hasRoleOrPrincipal( final Session session, final Principal principal ) {
188        // If either parameter is null, always deny
189        if( session == null || principal == null ) {
190            return false;
191        }
192
193        // If principal is role, delegate to isUserInRole
194        if( AuthenticationManager.isRolePrincipal( principal ) ) {
195            return isUserInRole( session, principal );
196        }
197
198        // We must be looking for a user principal, assuming that the user has been properly logged in. So just look for a name match.
199        if( session.isAuthenticated() && AuthenticationManager.isUserPrincipal( principal ) ) {
200            final String principalName = principal.getName();
201            final Principal[] userPrincipals = session.getPrincipals();
202            return Arrays.stream(userPrincipals).anyMatch(userPrincipal -> userPrincipal.getName().equals(principalName));
203        }
204        return false;
205    }
206
207    /** {@inheritDoc} */
208    @Override
209    public boolean hasAccess( final Context context, final HttpServletResponse response, final boolean redirect ) throws IOException {
210        final boolean allowed = checkPermission( context.getWikiSession(), context.requiredPermission() );
211
212        // Stash the wiki context
213        if ( context.getHttpRequest() != null && context.getHttpRequest().getAttribute( Context.ATTR_CONTEXT ) == null ) {
214            context.getHttpRequest().setAttribute( Context.ATTR_CONTEXT, context );
215        }
216
217        // If access not allowed, redirect
218        if( !allowed && redirect ) {
219            final ResourceBundle rb = Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE );
220            final Principal currentUser  = context.getWikiSession().getUserPrincipal();
221            final String pageurl = context.getPage().getName();
222            if( context.getWikiSession().isAuthenticated() ) {
223                LOG.info( "User {} has no access - forbidden (permission={})", currentUser.getName(), context.requiredPermission() );
224                context.getWikiSession().addMessage( MessageFormat.format( rb.getString( "security.error.noaccess.logged" ), context.getName()) );
225            } else {
226                LOG.info( "User {} has no access - redirecting (permission={})", currentUser.getName(), context.requiredPermission() );
227                context.getWikiSession().addMessage( MessageFormat.format( rb.getString( "security.error.noaccess" ), context.getName() ) );
228            }
229            response.sendRedirect( m_engine.getURL( ContextEnum.WIKI_LOGIN.getRequestContext(), pageurl, null ) );
230        }
231        return allowed;
232    }
233
234    /**
235     * {@inheritDoc}
236     *
237     * Expects to find property 'jspwiki.authorizer' with a valid Authorizer implementation name to take care of role lookup operations.
238     */
239    @Override
240    public void initialize( final Engine engine, final Properties properties ) throws WikiException {
241        m_engine = engine;
242
243        //  JAAS authorization continues
244        m_authorizer = getAuthorizerImplementation( properties );
245        m_authorizer.initialize( engine, properties );
246
247        // Initialize local security policy
248        try {
249            final String policyFileName = properties.getProperty( POLICY, DEFAULT_POLICY );
250            final URL policyURL = engine.findConfigFile( policyFileName );
251
252            if (policyURL != null) {
253                final File policyFile = new File( policyURL.toURI().getPath() );
254                LOG.info("We found security policy URL: {} and transformed it to file {}",policyURL, policyFile.getAbsolutePath());
255                m_localPolicy = new LocalPolicy( policyFile, engine.getContentEncoding().displayName() );
256                m_localPolicy.refresh();
257                LOG.info( "Initialized default security policy: {}", policyFile.getAbsolutePath() );
258            } else {
259                final String sb = "JSPWiki was unable to initialize the default security policy (WEB-INF/jspwiki.policy) file. " +
260                                  "Please ensure that the jspwiki.policy file exists in the default location. " +
261                                  "This file should exist regardless of the existance of a global policy file. " +
262                                  "The global policy file is identified by the java.security.policy variable. ";
263                final WikiSecurityException wse = new WikiSecurityException( sb );
264                LOG.fatal( sb, wse );
265                throw wse;
266            }
267        } catch ( final Exception e) {
268            LOG.error("Could not initialize local security policy: {}", e.getMessage() );
269            throw new WikiException( "Could not initialize local security policy: " + e.getMessage(), e );
270        }
271    }
272
273    /**
274     * Attempts to locate and initialize an Authorizer to use with this manager. Throws a WikiException if no entry is found, or if one
275     * fails to initialize.
276     *
277     * @param props jspwiki.properties, containing a 'jspwiki.authorization.provider' class name.
278     * @return an Authorizer used to get page authorization information.
279     * @throws WikiException if there are problems finding the authorizer implementation.
280     */
281    private Authorizer getAuthorizerImplementation( final Properties props ) throws WikiException {
282        final String authClassName = props.getProperty( PROP_AUTHORIZER, DEFAULT_AUTHORIZER );
283        return locateImplementation( authClassName );
284    }
285
286    private Authorizer locateImplementation( final String clazz ) throws WikiException {
287        if ( clazz != null ) {
288            try {
289                return ClassUtil.buildInstance( "org.apache.wiki.auth.authorize", clazz );
290            } catch( final ReflectiveOperationException e ) {
291                LOG.fatal( "Authorizer {} cannot be instantiated", clazz, e );
292                throw new WikiException( "Authorizer " + clazz + " cannot be instantiated", e );
293            }
294        }
295
296        throw new NoRequiredPropertyException( "Unable to find a " + PROP_AUTHORIZER + " entry in the properties.", PROP_AUTHORIZER );
297    }
298
299    /** {@inheritDoc} */
300    @Override
301    public boolean allowedByLocalPolicy( final Principal[] principals, final Permission permission ) {
302        for ( final Principal principal : principals ) {
303            // Get ProtectionDomain for this Principal from cache, or create new one
304            ProtectionDomain pd = m_cachedPds.get( principal );
305            if ( pd == null ) {
306                final ClassLoader cl = this.getClass().getClassLoader();
307                final CodeSource cs = new CodeSource( null, (Certificate[])null );
308                pd = new ProtectionDomain( cs, null, cl, new Principal[]{ principal } );
309                m_cachedPds.put( principal, pd );
310            }
311
312            // Consult the local policy and get the answer
313            if ( m_localPolicy.implies( pd, permission ) ) {
314                return true;
315            }
316        }
317        return false;
318    }
319
320    /** {@inheritDoc} */
321    @Override
322    public boolean checkStaticPermission( final Session session, final Permission permission ) {
323        // Check each Role/Group and User Principal
324        final Principal[] roles = session.getRoles();
325        final Principal[] principals = session.getPrincipals();
326        if( allowedByLocalPolicy( roles, permission ) || allowedByLocalPolicy( principals, permission ) ) {
327            return true;
328        }
329
330        // What the policy grants to <groupmember> applies to the groups the user is a member of
331        if( permission instanceof GroupPermission ) {
332            final GroupPermission groupPermission = ( GroupPermission )permission;
333            if( isMemberOf( session, groupPermission.getGroup() ) ) {
334                final GroupPermission memberPermission = groupPermission.toMemberPermission();
335                return allowedByLocalPolicy( roles, memberPermission ) || allowedByLocalPolicy( principals, memberPermission );
336            }
337        }
338        return false;
339    }
340
341    private boolean isMemberOf( final Session session, final String group ) {
342        return session.getSubject().getPrincipals( GroupPrincipal.class ).stream().anyMatch( principal -> principal.getName().equals( group ) );
343    }
344
345    /** {@inheritDoc} */
346    @Override
347    public Principal resolvePrincipal( final String name ) {
348        // Check built-in Roles first
349        final Role role = new Role(name);
350        if ( Role.isBuiltInRole( role ) ) {
351           return role;
352        }
353
354        // Check Authorizer Roles
355        Principal principal = m_authorizer.findRole( name );
356        if ( principal != null ) {
357           return principal;
358        }
359
360        // Check Groups
361        principal = m_engine.getManager( GroupManager.class ).findRole( name );
362        if ( principal != null ) {
363           return principal;
364        }
365
366        // Ok, no luck---this must be a user principal
367        final Principal[] principals;
368        final UserDatabase db = m_engine.getManager( UserManager.class ).getUserDatabase();
369        try {
370           principals = db.getPrincipals( name );
371           for( final Principal value : principals ) {
372               principal = value;
373               if( principal.getName().equals( name ) ) {
374                   return principal;
375               }
376           }
377        } catch( final NoSuchPrincipalException e ) {
378           // We couldn't find the user...
379           LOG.debug(e.getMessage(), e);
380        }
381        // Ok, no luck---mark this as unresolved and move on
382        return new UnresolvedPrincipal( name );
383    }
384
385
386    // events processing .......................................................
387
388    /** {@inheritDoc} */
389    @Override
390    public void addWikiEventListener( final WikiEventListener listener ) {
391        Synchronizer.synchronize(lock, () -> {
392            WikiEventManager.addWikiEventListener( this, listener );
393        });
394    }
395
396    /** {@inheritDoc} */
397    @Override
398    public void removeWikiEventListener( final WikiEventListener listener ) {
399        Synchronizer.synchronize(lock, () -> {
400            WikiEventManager.removeWikiEventListener( this, listener );
401        });
402    }
403
404}