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; 020 021import org.apache.commons.lang3.StringUtils; 022import org.apache.logging.log4j.LogManager; 023import org.apache.logging.log4j.Logger; 024import org.apache.wiki.api.core.Engine; 025import org.apache.wiki.api.core.Session; 026import org.apache.wiki.auth.AuthenticationManager; 027import org.apache.wiki.auth.GroupPrincipal; 028import org.apache.wiki.auth.NoSuchPrincipalException; 029import org.apache.wiki.auth.SessionMonitor; 030import org.apache.wiki.auth.UserManager; 031import org.apache.wiki.auth.WikiPrincipal; 032import org.apache.wiki.auth.authorize.Group; 033import org.apache.wiki.auth.authorize.GroupManager; 034import org.apache.wiki.auth.authorize.Role; 035import org.apache.wiki.auth.user.UserDatabase; 036import org.apache.wiki.auth.user.UserProfile; 037import org.apache.wiki.event.WikiEvent; 038import org.apache.wiki.event.WikiSecurityEvent; 039import org.apache.wiki.util.HttpUtil; 040 041import javax.security.auth.Subject; 042import jakarta.servlet.http.HttpServletRequest; 043import jakarta.servlet.http.HttpSession; 044import java.net.http.HttpRequest; 045import java.security.Principal; 046import java.util.Arrays; 047import java.util.HashSet; 048import java.util.LinkedHashSet; 049import java.util.Locale; 050import java.util.Map; 051import java.util.Set; 052import java.util.UUID; 053import java.util.concurrent.ConcurrentHashMap; 054 055 056/** 057 * <p>Default implementation for {@link Session}.</p> 058 * <p>In addition to methods for examining individual <code>WikiSession</code> objects, this class also contains a number of static 059 * methods for managing WikiSessions for an entire wiki. These methods allow callers to find, query and remove WikiSession objects, and 060 * to obtain a list of the current wiki session users.</p> 061 */ 062public class WikiSession implements Session { 063 064 private static final Logger LOG = LogManager.getLogger( WikiSession.class ); 065 066 private static final String ALL = "*"; 067 068 private static final ThreadLocal< Session > c_guestSession = new ThreadLocal<>(); 069 070 private final Subject m_subject = new Subject(); 071 072 private final Map< String, Set< String > > m_messages = new ConcurrentHashMap<>(); 073 074 /** The Engine that created this session. */ 075 private Engine m_engine; 076 private String remoteAddress; 077 private String antiCsrfToken; 078 private String m_status = ANONYMOUS; 079 080 private Principal m_userPrincipal = WikiPrincipal.GUEST; 081 082 private Principal m_loginPrincipal = WikiPrincipal.GUEST; 083 084 private Locale m_cachedLocale = Locale.getDefault(); 085 086 /** 087 * Returns <code>true</code> if one of this WikiSession's user Principals can be shown to belong to a particular wiki group. If 088 * the user is not authenticated, this method will always return <code>false</code>. 089 * 090 * @param group the group to test 091 * @return the result 092 */ 093 protected boolean isInGroup( final Group group ) { 094 return Arrays.stream(getPrincipals()).anyMatch(principal -> isAuthenticated() && group.isMember(principal)); 095 } 096 097 /** 098 * Private constructor to prevent WikiSession from being instantiated directly. 099 */ 100 private WikiSession() { 101 } 102 103 /** {@inheritDoc} */ 104 @Override 105 public boolean isAsserted() { 106 return m_subject.getPrincipals().contains( Role.ASSERTED ); 107 } 108 109 /** {@inheritDoc} */ 110 @Override 111 public boolean isAuthenticated() { 112 // If Role.AUTHENTICATED is in principals set, always return true. 113 if ( m_subject.getPrincipals().contains( Role.AUTHENTICATED ) ) { 114 return true; 115 } 116 117 // With non-JSPWiki LoginModules, the role may not be there, so we need to add it if the user really is authenticated. 118 if ( !isAnonymous() && !isAsserted() ) { 119 m_subject.getPrincipals().add( Role.AUTHENTICATED ); 120 return true; 121 } 122 123 return false; 124 } 125 126 /** {@inheritDoc} */ 127 @Override 128 public boolean isAnonymous() { 129 final Set< Principal > principals = m_subject.getPrincipals(); 130 return principals.contains( Role.ANONYMOUS ) || 131 principals.contains( WikiPrincipal.GUEST ) || 132 HttpUtil.isIPV4Address( getUserPrincipal().getName() ); 133 } 134 135 /** {@inheritDoc} */ 136 @Override 137 public Principal getLoginPrincipal() { 138 return m_loginPrincipal; 139 } 140 141 /** {@inheritDoc} */ 142 @Override 143 public Principal getUserPrincipal() { 144 return m_userPrincipal; 145 } 146 147 /** {@inheritDoc} */ 148 @Override 149 public String antiCsrfToken() { 150 return antiCsrfToken; 151 } 152 153 /** 154 * Regenerates the anti-CSRF token. Called when the session's privilege level changes (i.e. at login), so that 155 * a token observed before authentication cannot be replayed against the authenticated session. 156 */ 157 @Override 158 public void regenerateAntiCsrfToken() { 159 antiCsrfToken = UUID.randomUUID().toString(); 160 } 161 162 /** {@inheritDoc} */ 163 @Override 164 public Locale getLocale() { 165 return m_cachedLocale; 166 } 167 168 /** {@inheritDoc} */ 169 @Override 170 public void addMessage( final String message ) { 171 addMessage( ALL, message ); 172 } 173 174 /** {@inheritDoc} */ 175 @Override 176 public void addMessage( final String topic, final String message ) { 177 if ( topic == null ) { 178 throw new IllegalArgumentException( "addMessage: topic cannot be null." ); 179 } 180 final Set< String > messages = m_messages.computeIfAbsent( topic, k -> new LinkedHashSet<>() ); 181 messages.add( StringUtils.defaultString( message ) ); 182 } 183 184 /** {@inheritDoc} */ 185 @Override 186 public void clearMessages() { 187 m_messages.clear(); 188 } 189 190 /** {@inheritDoc} */ 191 @Override 192 public void clearMessages( final String topic ) { 193 final Set< String > messages = m_messages.get( topic ); 194 if ( messages != null ) { 195 m_messages.clear(); 196 } 197 } 198 199 /** {@inheritDoc} */ 200 @Override 201 public String[] getMessages() { 202 return getMessages( ALL ); 203 } 204 205 /** {@inheritDoc} */ 206 @Override 207 public String[] getMessages( final String topic ) { 208 final Set< String > messages = m_messages.get( topic ); 209 if( messages == null || messages.isEmpty()) { 210 return new String[ 0 ]; 211 } 212 return messages.toArray( new String[0] ); 213 } 214 215 /** {@inheritDoc} */ 216 @Override 217 public Principal[] getPrincipals() { 218 219 // Take the first non Role as the main Principal 220 221 return m_subject.getPrincipals().stream().filter(AuthenticationManager::isUserPrincipal).toArray(Principal[]::new); 222 } 223 224 /** {@inheritDoc} */ 225 @Override 226 public Principal[] getRoles() { 227 final Set< Principal > roles = new HashSet<>(); 228 229 // Add all the Roles possessed by the Subject directly 230 roles.addAll( m_subject.getPrincipals( Role.class ) ); 231 232 // Add all the GroupPrincipals possessed by the Subject directly 233 roles.addAll(m_subject.getPrincipals(GroupPrincipal.class)); 234 235 236 // Return a defensive copy 237 final Principal[] roleArray = roles.toArray( new Principal[0] ); 238 Arrays.sort( roleArray, WikiPrincipal.COMPARATOR ); 239 return roleArray; 240 } 241 242 /** {@inheritDoc} */ 243 @Override 244 public boolean hasPrincipal( final Principal principal ) { 245 return m_subject.getPrincipals().contains( principal ); 246 } 247 248 /** 249 * Listens for WikiEvents generated by source objects such as the GroupManager, UserManager or AuthenticationManager. This method adds 250 * Principals to the private Subject managed by the WikiSession. 251 * 252 * @see org.apache.wiki.event.WikiEventListener#actionPerformed(WikiEvent) 253 */ 254 @Override 255 public void actionPerformed( final WikiEvent event ) { 256 if ( event instanceof WikiSecurityEvent ) { 257 final WikiSecurityEvent e = (WikiSecurityEvent)event; 258 if ( e.getTarget() != null ) { 259 switch( e.getType() ) { 260 case WikiSecurityEvent.GROUP_ADD: 261 final Group groupAdd = ( Group )e.getTarget(); 262 if( isInGroup( groupAdd ) ) { 263 m_subject.getPrincipals().add( groupAdd.getPrincipal() ); 264 } 265 break; 266 case WikiSecurityEvent.GROUP_REMOVE: 267 final Group group = ( Group )e.getTarget(); 268 m_subject.getPrincipals().remove( group.getPrincipal() ); 269 break; 270 case WikiSecurityEvent.GROUP_CLEAR_GROUPS: 271 m_subject.getPrincipals().removeAll( m_subject.getPrincipals( GroupPrincipal.class ) ); 272 break; 273 case WikiSecurityEvent.LOGIN_INITIATED: 274 // Do nothing 275 break; 276 case WikiSecurityEvent.PRINCIPAL_ADD: 277 final WikiSession targetPA = ( WikiSession )e.getTarget(); 278 if( this.equals( targetPA ) && m_status.equals( AUTHENTICATED ) ) { 279 final Set< Principal > principals = m_subject.getPrincipals(); 280 principals.add( ( Principal )e.getPrincipal() ); 281 } 282 break; 283 case WikiSecurityEvent.LOGIN_ANONYMOUS: 284 final WikiSession targetLAN = ( WikiSession )e.getTarget(); 285 if( this.equals( targetLAN ) ) { 286 m_status = ANONYMOUS; 287 288 // Set the login/user principals and login status 289 final Set< Principal > principals = m_subject.getPrincipals(); 290 m_loginPrincipal = ( Principal )e.getPrincipal(); 291 m_userPrincipal = m_loginPrincipal; 292 293 // Add the login principal to the Subject, and set the built-in roles 294 principals.clear(); 295 principals.add( m_loginPrincipal ); 296 principals.add( Role.ALL ); 297 principals.add( Role.ANONYMOUS ); 298 } 299 break; 300 case WikiSecurityEvent.LOGIN_ASSERTED: 301 final WikiSession targetLAS = ( WikiSession )e.getTarget(); 302 if( this.equals( targetLAS ) ) { 303 m_status = ASSERTED; 304 305 // Set the login/user principals and login status 306 final Set< Principal > principals = m_subject.getPrincipals(); 307 m_loginPrincipal = ( Principal )e.getPrincipal(); 308 m_userPrincipal = m_loginPrincipal; 309 310 // Add the login principal to the Subject, and set the built-in roles 311 principals.clear(); 312 principals.add( m_loginPrincipal ); 313 principals.add( Role.ALL ); 314 principals.add( Role.ASSERTED ); 315 } 316 break; 317 case WikiSecurityEvent.LOGIN_AUTHENTICATED: 318 final WikiSession targetLAU = ( WikiSession )e.getTarget(); 319 if( this.equals( targetLAU ) ) { 320 m_status = AUTHENTICATED; 321 322 // Set the login/user principals and login status 323 final Set< Principal > principals = m_subject.getPrincipals(); 324 m_loginPrincipal = ( Principal )e.getPrincipal(); 325 m_userPrincipal = m_loginPrincipal; 326 327 // Add the login principal to the Subject, and set the built-in roles 328 principals.clear(); 329 principals.add( m_loginPrincipal ); 330 principals.add( Role.ALL ); 331 principals.add( Role.AUTHENTICATED ); 332 333 // Add the user and group principals 334 injectUserProfilePrincipals(); // Add principals for the user profile 335 injectGroupPrincipals(); // Inject group principals 336 } 337 break; 338 case WikiSecurityEvent.PROFILE_SAVE: 339 final WikiSession sourcePS = e.getSrc(); 340 if( this.equals( sourcePS ) ) { 341 injectUserProfilePrincipals(); // Add principals for the user profile 342 injectGroupPrincipals(); // Inject group principals 343 } 344 break; 345 case WikiSecurityEvent.PROFILE_NAME_CHANGED: 346 // Refresh user principals based on new user profile 347 final WikiSession sourcePNC = e.getSrc(); 348 if( this.equals( sourcePNC ) && m_status.equals( AUTHENTICATED ) ) { 349 // To prepare for refresh, set the new full name as the primary principal 350 final UserProfile[] profiles = ( UserProfile[] )e.getTarget(); 351 final UserProfile newProfile = profiles[ 1 ]; 352 if( newProfile.getFullname() == null ) { 353 throw new IllegalStateException( "User profile FullName cannot be null." ); 354 } 355 356 final Set< Principal > principals = m_subject.getPrincipals(); 357 m_loginPrincipal = new WikiPrincipal( newProfile.getLoginName() ); 358 359 // Add the login principal to the Subject, and set the built-in roles 360 principals.clear(); 361 principals.add( m_loginPrincipal ); 362 principals.add( Role.ALL ); 363 principals.add( Role.AUTHENTICATED ); 364 365 // Add the user and group principals 366 injectUserProfilePrincipals(); // Add principals for the user profile 367 injectGroupPrincipals(); // Inject group principals 368 } 369 break; 370 371 // No action, if the event is not recognized. 372 default: 373 break; 374 } 375 } 376 } 377 } 378 379 /** {@inheritDoc} */ 380 @Override 381 public void invalidate() { 382 m_subject.getPrincipals().clear(); 383 m_subject.getPrincipals().add( WikiPrincipal.GUEST ); 384 m_subject.getPrincipals().add( Role.ANONYMOUS ); 385 m_subject.getPrincipals().add( Role.ALL ); 386 m_userPrincipal = WikiPrincipal.GUEST; 387 m_loginPrincipal = WikiPrincipal.GUEST; 388 } 389 390 /** 391 * Injects GroupPrincipal objects into the user's Principal set based on the groups the user belongs to. For Groups, the algorithm 392 * first calls the {@link GroupManager#getRoles()} to obtain the array of GroupPrincipals the authorizer knows about. Then, the 393 * method {@link GroupManager#isUserInRole(Session, Principal)} is called for each Principal. If the user is a member of the 394 * group, an equivalent GroupPrincipal is injected into the user's principal set. Existing GroupPrincipals are flushed and replaced. 395 * This method should generally be called after a user's {@link org.apache.wiki.auth.user.UserProfile} is saved. If the wiki session 396 * is null, or there is no matching user profile, the method returns silently. 397 */ 398 protected void injectGroupPrincipals() { 399 // Flush the existing GroupPrincipals 400 m_subject.getPrincipals().removeAll( m_subject.getPrincipals(GroupPrincipal.class) ); 401 402 // Get the GroupManager and test for each Group 403 final GroupManager manager = m_engine.getManager( GroupManager.class ); 404 for( final Principal group : manager.getRoles() ) { 405 if ( manager.isUserInRole( this, group ) ) { 406 m_subject.getPrincipals().add( group ); 407 } 408 } 409 } 410 411 /** 412 * Adds Principal objects to the Subject that correspond to the logged-in user's profile attributes for the wiki name, full name 413 * and login name. These Principals will be WikiPrincipals, and they will replace all other WikiPrincipals in the Subject. <em>Note: 414 * this method is never called during anonymous or asserted sessions.</em> 415 */ 416 protected void injectUserProfilePrincipals() { 417 // Search for the user profile 418 final String searchId = m_loginPrincipal.getName(); 419 if ( searchId == null ) { 420 // Oh dear, this wasn't an authenticated user after all 421 LOG.info("Refresh principals failed because WikiSession had no user Principal; maybe not logged in?"); 422 return; 423 } 424 425 // Look up the user and go get the new Principals 426 final UserDatabase database = m_engine.getManager( UserManager.class ).getUserDatabase(); 427 if( database == null ) { 428 throw new IllegalStateException( "User database cannot be null." ); 429 } 430 try { 431 final UserProfile profile = database.findByLoginName( searchId ); 432 final Principal[] principals = database.getPrincipals( profile.getLoginName() ); 433 for( final Principal principal : principals ) { 434 // Add the Principal to the Subject 435 m_subject.getPrincipals().add( principal ); 436 437 // Set the user principal if needed; we prefer FullName, but the WikiName will also work 438 final boolean isFullNamePrincipal = ( principal instanceof WikiPrincipal && 439 ( ( WikiPrincipal )principal ).getType().equals( WikiPrincipal.FULL_NAME ) ); 440 if (( principal instanceof WikiPrincipal && 441 ( ( WikiPrincipal )principal ).getType().equals( WikiPrincipal.LOGIN_NAME )) ){ 442 m_loginPrincipal = principal; 443 } 444 445 446 if ( isFullNamePrincipal ) { 447 m_userPrincipal = principal; 448 } else if ( !( m_userPrincipal instanceof WikiPrincipal ) ) { 449 m_userPrincipal = principal; 450 } 451 } 452 } catch ( final NoSuchPrincipalException e ) { 453 // We will get here if the user has a principal but not a profile 454 // For example, it's a container-managed user who hasn't set up a profile yet 455 LOG.warn("User profile '" + searchId + "' not found. This is normal for container-auth users who haven't set up a profile yet."); 456 } 457 } 458 459 /** {@inheritDoc} */ 460 @Override 461 public String getStatus() { 462 return m_status; 463 } 464 465 /** {@inheritDoc} */ 466 @Override 467 public Subject getSubject() { 468 return m_subject; 469 } 470 471 /** 472 * Removes the wiki session associated with the user's HTTP request from the cache of wiki sessions, typically as part of a 473 * logout process. 474 * 475 * @param engine the wiki engine 476 * @param request the user's HTTP request 477 */ 478 public static void removeWikiSession( final Engine engine, final HttpServletRequest request ) { 479 if ( engine == null || request == null ) { 480 throw new IllegalArgumentException( "Request or engine cannot be null." ); 481 } 482 final SessionMonitor monitor = SessionMonitor.getInstance( engine ); 483 monitor.remove( request.getSession() ); 484 c_guestSession.remove(); 485 } 486 487 /** 488 * <p>Static factory method that returns the Session object associated with the current HTTP request. This method looks up 489 * the associated HttpSession in an internal WeakHashMap and attempts to retrieve the WikiSession. If not found, one is created. 490 * This method is guaranteed to always return a Session, although the authentication status is unpredictable until the user 491 * attempts to log in. If the servlet request parameter is <code>null</code>, a synthetic {@link #guestSession(Engine)} is 492 * returned.</p> 493 * <p>When a session is created, this method attaches a WikiEventListener to the GroupManager, UserManager and AuthenticationManager, 494 * so that changes to users, groups, logins, etc. are detected automatically.</p> 495 * 496 * @param engine the engine 497 * @param request the servlet request object 498 * @return the existing (or newly created) session 499 */ 500 public static Session getWikiSession( final Engine engine, final HttpServletRequest request ) { 501 if ( request == null ) { 502 LOG.debug( "Looking up WikiSession for NULL HttpRequest: returning guestSession()" ); 503 return staticGuestSession( engine ); 504 } 505 506 // Look for a WikiSession associated with the user's Http Session and create one if it isn't there yet. 507 final HttpSession session = request.getSession(); 508 final SessionMonitor monitor = SessionMonitor.getInstance( engine ); 509 final WikiSession wikiSession = ( WikiSession )monitor.find( session ); 510 wikiSession.remoteAddress = request.getRemoteAddr(); 511 // Attach reference to wiki engine 512 wikiSession.m_engine = engine; 513 wikiSession.m_cachedLocale = request.getLocale(); 514 515 String v = engine.getWikiProperties().getProperty("jspwiki.role.extraRoles", null); 516 if (v != null) { 517 String[] extraRoles = v.split("\\,"); 518 for (String s : extraRoles) { 519 if (request.isUserInRole(s)) { 520 wikiSession.m_subject.getPrincipals().add(new GroupPrincipal(s)); 521 } 522 } 523 } 524 525 return wikiSession; 526 } 527 528 /** 529 * Static factory method that creates a new "guest" session containing a single user Principal 530 * {@link org.apache.wiki.auth.WikiPrincipal#GUEST}, plus the role principals {@link Role#ALL} and {@link Role#ANONYMOUS}. This 531 * method also adds the session as a listener for GroupManager, AuthenticationManager and UserManager events. 532 * 533 * @param engine the wiki engine 534 * @return the guest wiki session 535 */ 536 public static Session guestSession( final Engine engine ) { 537 final WikiSession session = new WikiSession(); 538 session.m_engine = engine; 539 session.invalidate(); 540 session.antiCsrfToken = UUID.randomUUID().toString(); 541 542 // Add the session as listener for GroupManager, AuthManager, UserManager events 543 final GroupManager groupMgr = engine.getManager( GroupManager.class ); 544 final AuthenticationManager authMgr = engine.getManager( AuthenticationManager.class ); 545 final UserManager userMgr = engine.getManager( UserManager.class ); 546 groupMgr.addWikiEventListener( session ); 547 authMgr.addWikiEventListener( session ); 548 userMgr.addWikiEventListener( session ); 549 550 return session; 551 } 552 553 /** 554 * Returns a static guest session, which is available for this thread only. This guest session is used internally whenever 555 * there is no HttpServletRequest involved, but the request is done e.g. when embedding JSPWiki code. 556 * 557 * @param engine Engine for this session 558 * @return A static WikiSession which is shared by all in this same Thread. 559 */ 560 // FIXME: Should really use WeakReferences to clean away unused sessions. 561 private static Session staticGuestSession( final Engine engine ) { 562 Session session = c_guestSession.get(); 563 if( session == null ) { 564 session = guestSession( engine ); 565 c_guestSession.set( session ); 566 } 567 568 return session; 569 } 570 571 /** 572 * Returns the total number of active wiki sessions for a particular wiki. This method delegates to the wiki's 573 * {@link SessionMonitor#sessions()} method. 574 * 575 * @param engine the wiki session 576 * @return the number of sessions 577 * @deprecated use {@link SessionMonitor#sessions()} instead 578 * @see SessionMonitor#sessions() 579 */ 580 @Deprecated 581 public static int sessions( final Engine engine ) { 582 final SessionMonitor monitor = SessionMonitor.getInstance( engine ); 583 return monitor.sessions(); 584 } 585 586 /** 587 * Returns Principals representing the current users known to a particular wiki. Each Principal will correspond to the 588 * value returned by each WikiSession's {@link #getUserPrincipal()} method. This method delegates to 589 * {@link SessionMonitor#userPrincipals()}. 590 * 591 * @param engine the wiki engine 592 * @return an array of Principal objects, sorted by name 593 * @deprecated use {@link SessionMonitor#userPrincipals()} instead 594 * @see SessionMonitor#userPrincipals() 595 */ 596 @Deprecated 597 public static Principal[] userPrincipals( final Engine engine ) { 598 final SessionMonitor monitor = SessionMonitor.getInstance( engine ); 599 return monitor.userPrincipals(); 600 } 601 602 @Override 603 public String getRemoteAddress() { 604 return remoteAddress; 605 } 606 607}