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.commons.lang3.ArrayUtils;
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.api.exceptions.WikiException;
027import org.apache.wiki.auth.authorize.Group;
028import org.apache.wiki.auth.authorize.GroupDatabase;
029import org.apache.wiki.auth.authorize.GroupManager;
030import org.apache.wiki.auth.authorize.Role;
031import org.apache.wiki.auth.authorize.WebContainerAuthorizer;
032import org.apache.wiki.auth.permissions.AllPermission;
033import org.apache.wiki.auth.permissions.GroupPermission;
034import org.apache.wiki.auth.permissions.PermissionFactory;
035import org.apache.wiki.auth.permissions.WikiPermission;
036import org.apache.wiki.auth.user.DummyUserDatabase;
037import org.apache.wiki.auth.user.UserDatabase;
038import org.apache.wiki.auth.user.UserProfile;
039import org.freshcookies.security.policy.PolicyReader;
040
041import javax.security.auth.spi.LoginModule;
042import java.io.File;
043import java.io.IOException;
044import java.net.MalformedURLException;
045import java.net.URL;
046import java.security.KeyStore;
047import java.security.Permission;
048import java.security.Principal;
049import java.security.ProtectionDomain;
050import java.util.Arrays;
051import java.util.LinkedHashSet;
052import java.util.List;
053import java.util.Set;
054
055/**
056 * Helper class for verifying JSPWiki's security configuration. Invoked by <code>admin/SecurityConfig.jsp</code>.
057 *
058 * @since 2.4
059 */
060public final class SecurityVerifier {
061
062    private final Engine                m_engine;
063
064    private boolean               m_isSecurityPolicyConfigured;
065
066    private Principal[]           m_policyPrincipals           = new Principal[0];
067
068    private final Session               m_session;
069
070    /** Message prefix for errors. */
071    public static final String    ERROR                        = "Error.";
072
073    /** Message prefix for warnings. */
074    public static final String    WARNING                      = "Warning.";
075
076    /** Message prefix for information messages. */
077    public static final String    INFO                         = "Info.";
078
079    /** Message topic for policy errors. */
080    public static final String    ERROR_POLICY                 = "Error.Policy";
081
082    /** Message topic for policy warnings. */
083    public static final String    WARNING_POLICY               = "Warning.Policy";
084
085    /** Message topic for policy information messages. */
086    public static final String    INFO_POLICY                  = "Info.Policy";
087
088    /** Message topic for JAAS errors. */
089    public static final String    ERROR_JAAS                   = "Error.Jaas";
090
091    /** Message topic for JAAS warnings. */
092    public static final String    WARNING_JAAS                 = "Warning.Jaas";
093
094    /** Message topic for role-checking errors. */
095    public static final String    ERROR_ROLES                  = "Error.Roles";
096
097    /** Message topic for role-checking information messages. */
098    public static final String    INFO_ROLES                   = "Info.Roles";
099
100    /** Message topic for user database errors. */
101    public static final String    ERROR_DB                     = "Error.UserDatabase";
102
103    /** Message topic for user database warnings. */
104    public static final String    WARNING_DB                   = "Warning.UserDatabase";
105
106    /** Message topic for user database information messages. */
107    public static final String    INFO_DB                      = "Info.UserDatabase";
108
109    /** Message topic for group database errors. */
110    public static final String    ERROR_GROUPS                 = "Error.GroupDatabase";
111
112    /** Message topic for group database warnings. */
113    public static final String    WARNING_GROUPS               = "Warning.GroupDatabase";
114
115    /** Message topic for group database information messages. */
116    public static final String    INFO_GROUPS                  = "Info.GroupDatabase";
117
118    /** Message topic for JAAS information messages. */
119    public static final String    INFO_JAAS                    = "Info.Jaas";
120
121    private static final String[] CONTAINER_ACTIONS            = new String[] { "View pages",
122                                                                                "Comment on existing pages",
123                                                                                "Edit pages",
124                                                                                "Upload attachments",
125                                                                                "Create a new group",
126                                                                                "Rename an existing page",
127                                                                                "Delete pages"
128                                                                              };
129
130    private static final String[] CONTAINER_JSPS               = new String[] { "/Wiki.jsp",
131                                                                                "/Comment.jsp",
132                                                                                "/Edit.jsp",
133                                                                                "/Upload.jsp",
134                                                                                "/NewGroup.jsp",
135                                                                                "/Rename.jsp",
136                                                                                "/Delete.jsp"
137                                                                              };
138
139    private static final String   BG_GREEN                     = "bgcolor=\"#c0ffc0\"";
140
141    private static final String   BG_RED                       = "bgcolor=\"#ffc0c0\"";
142
143    private static final Logger LOG = LogManager.getLogger( SecurityVerifier.class.getName() );
144
145    /**
146     * Constructs a new SecurityVerifier for a supplied Engine and WikiSession.
147     *
148     * @param engine the wiki engine
149     * @param session the wiki session (typically, that of an administrator)
150     */
151    public SecurityVerifier( final Engine engine, final Session session ) {
152        m_engine = engine;
153        m_session = session;
154        m_session.clearMessages();
155        verifyJaas();
156        verifyPolicy();
157        try {
158            verifyPolicyAndContainerRoles();
159        } catch( final WikiException e ) {
160            m_session.addMessage( ERROR_ROLES, e.getMessage() );
161        }
162        verifyGroupDatabase();
163        verifyUserDatabase();
164    }
165
166    /**
167     * Returns an array of unique Principals from the JSPWIki security policy
168     * file. This array will be zero-length if the policy file was not
169     * successfully located, or if the file did not specify any Principals in
170     * the policy.
171     * @return the array of principals
172     */
173    public Principal[] policyPrincipals()
174    {
175        return m_policyPrincipals;
176    }
177
178    /**
179     * Formats and returns an HTML table containing sample permissions and what
180     * roles are allowed to have them. This method will throw an
181     * {@link IllegalStateException} if the authorizer is not of type
182     * {@link org.apache.wiki.auth.authorize.WebContainerAuthorizer}
183     * @return the formatted HTML table containing the result of the tests
184     */
185    public String policyRoleTable()
186    {
187        final Principal[] roles = m_policyPrincipals;
188        final String wiki = m_engine.getApplicationName();
189
190        final String[] pages = new String[]
191        { "Main", "Index", "GroupTest", "GroupAdmin" };
192        final String[] pageActions = new String[]
193        { "view", "edit", "modify", "rename", "delete" };
194
195        final String[] groups = new String[]
196        { "Admin", "TestGroup", "Foo" };
197        final String[] groupActions = new String[]
198        { "view", "edit", null, null, "delete" };
199
200
201        final int rolesLength = roles.length;
202        final int pageActionsLength = pageActions.length;
203        // Calculate column widths
204        final String colWidth;
205        if( rolesLength > 0 ) {
206            colWidth = ( 67f / ( pageActionsLength * rolesLength ) ) + "%";
207        } else {
208            colWidth = "67%";
209        }
210
211        final StringBuilder s = new StringBuilder();
212
213        // Write the table header
214        s.append( "<table class=\"wikitable\" border=\"1\">\n" );
215        s.append( "  <colgroup span=\"1\" width=\"33%\"/>\n" );
216        s.append( "  <colgroup span=\"" ).append( pageActionsLength * rolesLength ).append( "\" width=\"" ).append( colWidth ).append( "\" align=\"center\"/>\n" );
217        s.append( "  <tr>\n" );
218        s.append( "    <th rowspan=\"2\" valign=\"bottom\">Permission</th>\n" );
219        for (final Principal principal : roles) {
220            s.append("    <th colspan=\"").append(pageActionsLength).append("\" title=\"").append(principal.getClass().getName()).append("\">").append(principal.getName()).append("</th>\n");
221        }
222        s.append( "  </tr>\n" );
223
224        // Print a column for each role
225        s.append( "  <tr>\n" );
226        for( int i = 0; i < rolesLength; i++ )
227        {
228            for( final String pageAction : pageActions )
229            {
230                final String action = pageAction.substring( 0, 1 );
231                s.append( "    <th title=\"" ).append( pageAction ).append( "\">" ).append( action ).append( "</th>\n" );
232            }
233        }
234        s.append( "  </tr>\n" );
235
236        // Write page permission tests first
237        for( final String page : pages ) {
238            s.append( "  <tr>\n" );
239            s.append( "    <td>PagePermission \"" ).append( wiki ).append( ":" ).append( page ).append( "\"</td>\n" );
240            for( final Principal role : roles ) {
241                for( final String pageAction : pageActions ) {
242                    final Permission permission = PermissionFactory.getPagePermission( wiki + ":" + page, pageAction );
243                    s.append( printPermissionTest( permission, role, 1 ) );
244                }
245            }
246            s.append( "  </tr>\n" );
247        }
248
249        // Now do the group tests
250        for( final String group : groups ) {
251            s.append( "  <tr>\n" );
252            s.append( "    <td>GroupPermission \"" ).append( wiki ).append( ":" ).append( group ).append( "\"</td>\n" );
253            for( final Principal role : roles ) {
254                for( final String groupAction : groupActions ) {
255                    Permission permission = null;
256                    if( groupAction != null ) {
257                        permission = new GroupPermission( wiki + ":" + group, groupAction );
258                    }
259                    s.append( printPermissionTest( permission, role, 1 ) );
260                }
261            }
262            s.append( "  </tr>\n" );
263        }
264
265
266        // Now check the wiki-wide permissions
267        final String[] wikiPerms = new String[] { "createGroups", "createPages", "login", "editPreferences", "editProfile" };
268        for( final String wikiPerm : wikiPerms ) {
269            s.append( "  <tr>\n" );
270            s.append( "    <td>WikiPermission \"" ).append( wiki ).append( "\",\"" ).append( wikiPerm ).append( "\"</td>\n" );
271            for( final Principal role : roles ) {
272                final Permission permission = new WikiPermission( wiki, wikiPerm );
273                s.append( printPermissionTest( permission, role, pageActionsLength ) );
274            }
275            s.append( "  </tr>\n" );
276        }
277
278        // Lastly, check for AllPermission
279        s.append( "  <tr>\n" );
280        s.append( "    <td>AllPermission \"" ).append( wiki ).append( "\"</td>\n" );
281        for( final Principal role : roles )
282        {
283            final Permission permission = new AllPermission( wiki );
284            s.append( printPermissionTest( permission, role, pageActionsLength ) );
285        }
286        s.append( "  </tr>\n" );
287
288        // We're done!
289        s.append( "</table>" );
290        return s.toString();
291    }
292
293    /**
294     * Prints a &lt;td&gt; HTML element with the results of a permission test.
295     * @param permission the permission to format
296     * @param principal
297     * @param cols
298     */
299    private String printPermissionTest( final Permission permission, final Principal principal, final int cols ) {
300        final StringBuilder s = new StringBuilder();
301        if( permission == null ) {
302            s.append( "    <td colspan=\"" ).append( cols ).append( "\" align=\"center\" title=\"N/A\">" );
303            s.append( "&nbsp;</td>\n" );
304        } else {
305            final boolean allowed = verifyStaticPermission( principal, permission );
306            s.append( "    <td colspan=\"" ).append( cols ).append( "\" align=\"center\" title=\"" );
307            s.append( allowed ? "ALLOW: " : "DENY: " );
308            s.append( permission.getClass().getName() );
309            s.append( " &quot;" );
310            s.append( permission.getName() );
311            s.append( "&quot;" );
312            if ( permission.getName() != null )
313            {
314                s.append( ",&quot;" );
315                s.append( permission.getActions() );
316                s.append( "&quot;" );
317            }
318            s.append( " " );
319            s.append( principal.getClass().getName() );
320            s.append( " &quot;" );
321            s.append( principal.getName() );
322            s.append( "&quot;" );
323            s.append( "\"" );
324            s.append( allowed ? BG_GREEN + ">" : BG_RED + ">" );
325            s.append( "&nbsp;</td>\n" );
326        }
327        return s.toString();
328    }
329
330    /**
331     * Formats and returns an HTML table containing the roles the web container
332     * is aware of, and whether each role maps to particular JSPs. This method
333     * throws an {@link IllegalStateException} if the authorizer is not of type
334     * {@link org.apache.wiki.auth.authorize.WebContainerAuthorizer}
335     * @return the formatted HTML table containing the result of the tests
336     * @throws WikiException if tests fail for unexpected reasons
337     */
338    public String containerRoleTable() throws WikiException {
339        final AuthorizationManager authorizationManager = m_engine.getManager( AuthorizationManager.class );
340        final Authorizer authorizer = authorizationManager.getAuthorizer();
341
342        // If authorizer not WebContainerAuthorizer, print error message
343        if ( !( authorizer instanceof final WebContainerAuthorizer wca ) ) {
344            throw new IllegalStateException( "Authorizer should be WebContainerAuthorizer" );
345        }
346
347        // Now, print a table with JSP pages listed on the left, and
348        // an evaluation of each pages' constraints for each role
349        // we discovered
350        final StringBuilder s = new StringBuilder();
351        final Principal[] roles = authorizer.getRoles();
352        s.append( "<table class=\"wikitable\" border=\"1\">\n" );
353        s.append( "<thead>\n" );
354        s.append( "  <tr>\n" );
355        s.append( "    <th rowspan=\"2\">Action</th>\n" );
356        s.append( "    <th rowspan=\"2\">Page</th>\n" );
357        s.append( "    <th colspan=\"" ).append( roles.length ).append( 1 ).append( "\">Roles</th>\n" );
358        s.append( "  </tr>\n" );
359        s.append( "  <tr>\n" );
360        s.append( "    <th>Anonymous</th>\n" );
361        for( final Principal role : roles ) {
362            s.append( "    <th>" ).append( role.getName() ).append( "</th>\n" );
363        }
364        s.append( "</tr>\n" );
365        s.append( "</thead>\n" );
366        s.append( "<tbody>\n" );
367
368        for( int i = 0; i < CONTAINER_ACTIONS.length; i++ ) {
369            final String action = CONTAINER_ACTIONS[i];
370            final String jsp = CONTAINER_JSPS[i];
371
372            // Print whether the page is constrained for each role
373            final boolean allowsAnonymous = !wca.isConstrained( jsp, Role.ALL );
374            s.append( "  <tr>\n" );
375            s.append( "    <td>" ).append( action ).append( "</td>\n" );
376            s.append( "    <td>" ).append( jsp ).append( "</td>\n" );
377            s.append( "    <td title=\"" );
378            s.append( allowsAnonymous ? "ALLOW: " : "DENY: " );
379            s.append( jsp );
380            s.append( " Anonymous" );
381            s.append( "\"" );
382            s.append( allowsAnonymous ? BG_GREEN + ">" : BG_RED + ">" );
383            s.append( "&nbsp;</td>\n" );
384            for( final Principal role : roles )
385            {
386                final boolean allowed = allowsAnonymous || wca.isConstrained( jsp, (Role)role );
387                s.append( "    <td title=\"" );
388                s.append( allowed ? "ALLOW: " : "DENY: " );
389                s.append( jsp );
390                s.append( " " );
391                s.append( role.getClass().getName() );
392                s.append( " &quot;" );
393                s.append( role.getName() );
394                s.append( "&quot;" );
395                s.append( "\"" );
396                s.append( allowed ? BG_GREEN + ">" : BG_RED + ">" );
397                s.append( "&nbsp;</td>\n" );
398            }
399            s.append( "  </tr>\n" );
400        }
401
402        s.append( "</tbody>\n" );
403        s.append( "</table>\n" );
404        return s.toString();
405    }
406
407    /**
408     * Returns <code>true</code> if the Java security policy is configured
409     * correctly, and it verifies as valid.
410     * @return the result of the configuration check
411     */
412    public boolean isSecurityPolicyConfigured()
413    {
414        return m_isSecurityPolicyConfigured;
415    }
416
417    /**
418     * If the active Authorizer is the WebContainerAuthorizer, returns the roles it knows about; otherwise, a zero-length array.
419     *
420     * @return the roles parsed from <code>web.xml</code>, or a zero-length array
421     * @throws WikiException if the web authorizer cannot obtain the list of roles
422     */
423    public Principal[] webContainerRoles() throws WikiException {
424        final Authorizer authorizer = m_engine.getManager( AuthorizationManager.class ).getAuthorizer();
425        if ( authorizer instanceof WebContainerAuthorizer ) {
426            return authorizer.getRoles();
427        }
428        return new Principal[0];
429    }
430
431    /**
432     * Verifies that the roles given in the security policy are reflected by the
433     * container <code>web.xml</code> file.
434     * @throws WikiException if the web authorizer cannot verify the roles
435     */
436    void verifyPolicyAndContainerRoles() throws WikiException {
437        final Authorizer authorizer = m_engine.getManager( AuthorizationManager.class ).getAuthorizer();
438        final Principal[] containerRoles = authorizer.getRoles();
439        boolean missing = false;
440        for( final Principal principal : m_policyPrincipals ) {
441            if( principal instanceof final Role role ) {
442                final boolean isContainerRole = ArrayUtils.contains( containerRoles, role );
443                if ( !Role.isBuiltInRole( role ) && !isContainerRole ) {
444                    m_session.addMessage( ERROR_ROLES, "Role '" + role.getName() + "' is defined in security policy but not in web.xml." );
445                    missing = true;
446                }
447            }
448        }
449        if ( !missing ) {
450            m_session.addMessage( INFO_ROLES, "Every non-standard role defined in the security policy was also found in web.xml." );
451        }
452    }
453
454    /**
455     * Verifies that the group datbase was initialized properly, and that
456     * user add and delete operations work as they should.
457     */
458    void verifyGroupDatabase() {
459        final GroupManager mgr = m_engine.getManager( GroupManager.class );
460        GroupDatabase db = null;
461        try {
462            db = m_engine.getManager( GroupManager.class ).getGroupDatabase();
463        } catch ( final WikiSecurityException e ) {
464            m_session.addMessage( ERROR_GROUPS, "Could not retrieve GroupManager: " + e.getMessage() );
465        }
466
467        // Check for obvious error conditions
468        if ( mgr == null || db == null ) {
469            if ( mgr == null ) {
470                m_session.addMessage( ERROR_GROUPS, "GroupManager is null; JSPWiki could not initialize it. Check the error logs." );
471            }
472            if ( db == null ) {
473                m_session.addMessage( ERROR_GROUPS, "GroupDatabase is null; JSPWiki could not initialize it. Check the error logs." );
474            }
475            return;
476        }
477
478        // Everything initialized OK...
479
480        // Tell user what class of database this is.
481        m_session.addMessage( INFO_GROUPS, "GroupDatabase is of type '" + db.getClass().getName() + "'. It appears to be initialized properly." );
482
483        // Now, see how many groups we have.
484        final int oldGroupCount;
485        try {
486            final Group[] groups = db.groups();
487            oldGroupCount = groups.length;
488            m_session.addMessage( INFO_GROUPS, "The group database contains " + oldGroupCount + " groups." );
489        } catch( final WikiSecurityException e ) {
490            m_session.addMessage( ERROR_GROUPS, "Could not obtain a list of current groups: " + e.getMessage() );
491            return;
492        }
493
494        // Try adding a bogus group with random name
495        final String name = "TestGroup" + System.currentTimeMillis();
496        final Group group;
497        try {
498            // Create dummy test group
499            group = mgr.parseGroup( name, "", true );
500            final Principal user = new WikiPrincipal( "TestUser" );
501            group.add( user );
502            db.save( group, new WikiPrincipal( "SecurityVerifier" ) );
503
504            // Make sure the group saved successfully
505            if( db.groups().length == oldGroupCount ) {
506                m_session.addMessage( ERROR_GROUPS, "Could not add a test group to the database." );
507                return;
508            }
509            m_session.addMessage( INFO_GROUPS, "The group database allows new groups to be created, as it should." );
510        } catch( final WikiSecurityException e ) {
511            m_session.addMessage( ERROR_GROUPS, "Could not add a group to the database: " + e.getMessage() );
512            return;
513        }
514
515        // Now delete the group; should be back to old count
516        try {
517            db.delete( group );
518            if( db.groups().length != oldGroupCount ) {
519                m_session.addMessage( ERROR_GROUPS, "Could not delete a test group from the database." );
520                return;
521            }
522            m_session.addMessage( INFO_GROUPS, "The group database allows groups to be deleted, as it should." );
523        } catch( final WikiSecurityException e ) {
524            m_session.addMessage( ERROR_GROUPS, "Could not delete a test group from the database: " + e.getMessage() );
525            return;
526        }
527
528        m_session.addMessage( INFO_GROUPS, "The group database configuration looks fine." );
529    }
530
531    /**
532     * Verfies the JAAS configuration. The configuration is valid if value of the
533     * <code>jspwiki.properties<code> property
534     * {@value org.apache.wiki.auth.AuthenticationManager#PROP_LOGIN_MODULE}
535     * resolves to a valid class on the classpath.
536     */
537    void verifyJaas() {
538        // Verify that the specified JAAS moduie corresponds to a class we can load successfully.
539        final String jaasClass = m_engine.getWikiProperties().getProperty( AuthenticationManager.PROP_LOGIN_MODULE );
540        if( jaasClass == null || jaasClass.isEmpty() ) {
541            m_session.addMessage( ERROR_JAAS, "The value of the '" + AuthenticationManager.PROP_LOGIN_MODULE
542                    + "' property was null or blank. This is a fatal error. This value should be set to a valid LoginModule implementation "
543                    + "on the classpath." );
544            return;
545        }
546
547        // See if we can find the LoginModule on the classpath
548        Class< ? > c = null;
549        try {
550            m_session.addMessage( INFO_JAAS,
551                    "The property '" + AuthenticationManager.PROP_LOGIN_MODULE + "' specified the class '" + jaasClass + ".'" );
552            c = Class.forName( jaasClass );
553        } catch( final ClassNotFoundException e ) {
554            m_session.addMessage( ERROR_JAAS, "We could not find the the class '" + jaasClass + "' on the " + "classpath. This is fatal error." );
555        }
556
557        // Is the specified class actually a LoginModule?
558        if( LoginModule.class.isAssignableFrom( c ) ) {
559            m_session.addMessage( INFO_JAAS, "We found the the class '" + jaasClass + "' on the classpath, and it is a LoginModule implementation. Good!" );
560        } else {
561            m_session.addMessage( ERROR_JAAS, "We found the the class '" + jaasClass + "' on the classpath, but it does not seem to be LoginModule implementation! This is fatal error." );
562        }
563    }
564
565    /**
566     * Looks up a file name based on a JRE system property and returns the associated
567     * File object if it exists. This method adds messages with the topic prefix 
568     * {@link #ERROR} and {@link #INFO} as appropriate, with the suffix matching the 
569     * supplied property.
570     * @param property the system property to look up
571     * @return the file object, or <code>null</code> if not found
572     */
573    File getFileFromProperty( final String property )
574    {
575        String propertyValue;
576        try
577        {
578            propertyValue = System.getProperty( property );
579            if ( propertyValue == null )
580            {
581                m_session.addMessage( "Error." + property, "The system property '" + property + "' is null." );
582                return null;
583            }
584
585            //
586            //  It's also possible to use "==" to mark a property.  We remove that
587            //  here so that we can actually find the property file, then.
588            //
589            if( propertyValue.startsWith("=") )
590            {
591                propertyValue = propertyValue.substring(1);
592            }
593
594            try
595            {
596                m_session.addMessage( "Info." + property, "The system property '" + property + "' is set to: "
597                        + propertyValue + "." );
598
599                // Prepend a file: prefix if not there already
600                if ( !propertyValue.startsWith( "file:" ) )
601                {
602                  propertyValue = "file:" + propertyValue;
603                }
604                final URL url = new URL( propertyValue );
605                final File file = new File( url.getPath() );
606                if ( file.exists() )
607                {
608                    m_session.addMessage( "Info." + property, "File '" + propertyValue + "' exists in the filesystem." );
609                    return file;
610                }
611            }
612            catch( final MalformedURLException e )
613            {
614                LOG.debug(e.getMessage(), e);
615                // Swallow exception because we can't find it anyway
616            }
617            m_session.addMessage( "Error." + property, "File '" + propertyValue
618                    + "' doesn't seem to exist. This might be a problem." );
619            return null;
620        }
621        catch( final SecurityException e )
622        {
623            LOG.debug(e.getMessage(), e);
624            m_session.addMessage( "Error." + property, "We could not read system property '" + property
625                    + "'. This is probably because you are running with a security manager." );
626            return null;
627        }
628    }
629
630    /**
631     * Verfies the Java security policy configuration. The configuration is
632     * valid if value of the local policy (at <code>WEB-INF/jspwiki.policy</code>
633     * resolves to an existing file, and the policy file contained therein
634     * represents a valid policy.
635     */
636    @SuppressWarnings("unchecked")
637    void verifyPolicy() {
638        // Look up the policy file and set the status text.
639        final URL policyURL = m_engine.findConfigFile( AuthorizationManager.DEFAULT_POLICY );
640        String path = policyURL.getPath();
641        if ( path.startsWith("file:") ) {
642            path = path.substring( 5 );
643        }
644        final File policyFile = new File( path );
645
646        // Next, verify the policy
647        try {
648            // Get the file
649            final PolicyReader policy = new PolicyReader( policyFile );
650            m_session.addMessage( INFO_POLICY, "The security policy '" + policy.getFile() + "' exists." );
651
652            // See if there is a keystore that's valid
653            final KeyStore ks = policy.getKeyStore();
654            if ( ks == null ) {
655                m_session.addMessage( WARNING_POLICY,
656                    "Policy file does not have a keystore... at least not one that we can locate. If your policy file " +
657                    "does not contain any 'signedBy' blocks, this is probably ok." );
658            } else {
659                m_session.addMessage( INFO_POLICY,
660                    "The security policy specifies a keystore, and we were able to locate it in the filesystem." );
661            }
662
663            // Verify the file
664            policy.read();
665            final List<Exception> errors = policy.getMessages();
666            if (!errors.isEmpty()) {
667                for( final Exception e : errors ) {
668                    m_session.addMessage( ERROR_POLICY, e.getMessage() );
669                }
670            } else {
671                m_session.addMessage( INFO_POLICY, "The security policy looks fine." );
672                m_isSecurityPolicyConfigured = true;
673            }
674
675            // Stash the unique principals mentioned in the file,
676            // plus our standard roles.
677            final Set<Principal> principals = new LinkedHashSet<>();
678            principals.add( Role.ALL );
679            principals.add( Role.ANONYMOUS );
680            principals.add( Role.ASSERTED );
681            principals.add( Role.AUTHENTICATED );
682            final ProtectionDomain[] domains = policy.getProtectionDomains();
683            for ( final ProtectionDomain domain : domains ) {
684                principals.addAll(Arrays.asList(domain.getPrincipals()));
685            }
686            m_policyPrincipals = principals.toArray( new Principal[0] );
687        } catch( final IOException e ) {
688            m_session.addMessage( ERROR_POLICY, e.getMessage() );
689        }
690    }
691
692    /**
693     * Verifies that a particular Principal possesses a Permission, as defined
694     * in the security policy file.
695     * @param principal the principal
696     * @param permission the permission
697     * @return the result, based on consultation with the active Java security
698     *         policy
699     */
700    boolean verifyStaticPermission( final Principal principal, final Permission permission )
701    {
702        final Principal[] principals = new Principal[]{ principal };
703        return m_engine.getManager( AuthorizationManager.class ).allowedByLocalPolicy( principals, permission );
704    }
705
706    /**
707     * Verifies that the user datbase was initialized properly, and that
708     * user add and delete operations work as they should.
709     */
710    void verifyUserDatabase() {
711        final UserDatabase db = m_engine.getManager( UserManager.class ).getUserDatabase();
712
713        // Check for obvious error conditions
714        if ( db == null ) {
715            m_session.addMessage( ERROR_DB, "UserDatabase is null; JSPWiki could not initialize it. Check the error logs." );
716            return;
717        }
718
719        if ( db instanceof DummyUserDatabase ) {
720            m_session.addMessage( ERROR_DB, "UserDatabase is DummyUserDatabase; JSPWiki " +
721                    "may not have been able to initialize the database you supplied in " +
722                    "jspwiki.properties, or you left the 'jspwiki.userdatabase' property " +
723                    "blank. Check the error logs." );
724        }
725
726        // Tell user what class of database this is.
727        m_session.addMessage( INFO_DB, "UserDatabase is of type '" + db.getClass().getName() +
728                                       "'. It appears to be initialized properly." );
729
730        // Now, see how many users we have.
731        final int oldUserCount;
732        try {
733            final Principal[] users = db.getWikiNames();
734            oldUserCount = users.length;
735            m_session.addMessage( INFO_DB, "The user database contains " + oldUserCount + " users." );
736        } catch( final WikiSecurityException e ) {
737            m_session.addMessage( ERROR_DB, "Could not obtain a list of current users: " + e.getMessage() );
738            return;
739        }
740
741        // Try adding a bogus user with random name
742        final String loginName = "TestUser" + System.currentTimeMillis();
743        try {
744            final UserProfile profile = db.newProfile();
745            profile.setEmail( "jspwiki.tests@mailinator.com" );
746            profile.setLoginName( loginName );
747            profile.setFullname( "FullName" + loginName );
748            profile.setPassword( "password" );
749            db.save( profile );
750
751            // Make sure the profile saved successfully
752            if( db.getWikiNames().length == oldUserCount ) {
753                m_session.addMessage( ERROR_DB, "Could not add a test user to the database." );
754                return;
755            }
756            m_session.addMessage( INFO_DB, "The user database allows new users to be created, as it should." );
757        } catch( final WikiSecurityException e ) {
758            m_session.addMessage( ERROR_DB, "Could not add a test user to the database: " + e.getMessage() );
759            return;
760        }
761
762        // Now delete the profile; should be back to old count
763        try {
764            db.deleteByLoginName( loginName );
765            if( db.getWikiNames().length != oldUserCount ) {
766                m_session.addMessage( ERROR_DB, "Could not delete a test user from the database." );
767                return;
768            }
769            m_session.addMessage( INFO_DB, "The user database allows users to be deleted, as it should." );
770        } catch( final WikiSecurityException e ) {
771            m_session.addMessage( ERROR_DB, "Could not delete a test user to the database: " + e.getMessage() );
772            return;
773        }
774
775        m_session.addMessage( INFO_DB, "The user database configuration looks fine." );
776    }
777}