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.user;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.commons.text.StringEscapeUtils;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
025import org.apache.wiki.auth.NoSuchPrincipalException;
026import org.apache.wiki.auth.WikiPrincipal;
027import org.apache.wiki.auth.WikiSecurityException;
028import org.apache.wiki.util.Serializer;
029import org.apache.wiki.util.Synchronizer;
030import org.apache.wiki.util.TextUtil;
031import org.w3c.dom.Document;
032import org.w3c.dom.Element;
033import org.w3c.dom.Node;
034import org.w3c.dom.NodeList;
035import org.w3c.dom.Text;
036import org.xml.sax.SAXException;
037
038import javax.xml.parsers.DocumentBuilderFactory;
039import javax.xml.parsers.ParserConfigurationException;
040import java.io.BufferedWriter;
041import java.io.File;
042import java.io.FileInputStream;
043import java.io.FileNotFoundException;
044import java.io.IOException;
045import java.io.OutputStreamWriter;
046import java.io.Serializable;
047import java.nio.charset.StandardCharsets;
048import java.nio.file.Files;
049import java.security.Principal;
050import java.text.DateFormat;
051import java.text.ParseException;
052import java.text.SimpleDateFormat;
053import java.util.Arrays;
054import java.util.Date;
055import java.util.Map;
056import java.util.Properties;
057import java.util.SortedSet;
058import java.util.TreeSet;
059import java.util.concurrent.locks.ReentrantLock;
060import java.util.stream.Collectors;
061import java.util.stream.IntStream;
062import javax.xml.XMLConstants;
063import org.apache.commons.codec.digest.DigestUtils;
064import org.apache.commons.io.FileUtils;
065
066/**
067 * <p>Manages {@link DefaultUserProfile} objects using XML files for persistence. Passwords are hashed using SHA1. User entries are simple
068 * <code>&lt;user&gt;</code> elements under the root. User profile properties are attributes of the element. For example:</p>
069 * <blockquote><code>
070 * &lt;users&gt;<br/>
071 * &nbsp;&nbsp;&lt;user loginName="janne" fullName="Janne Jalkanen"<br/>
072 * &nbsp;&nbsp;&nbsp;&nbsp;wikiName="JanneJalkanen" email="janne@ecyrd.com"<br/>
073 * &nbsp;&nbsp;&nbsp;&nbsp;password="{SHA}457b08e825da547c3b77fbc1ff906a1d00a7daee"/&gt;<br/>
074 * &lt;/users&gt;
075 * </code></blockquote>
076 * <p>In this example, the un-hashed password is <code>myP@5sw0rd</code>. Passwords are hashed without salt.</p>
077 * @since 2.3
078 */
079
080// FIXME: If the DB is shared across multiple systems, it's possible to lose accounts
081//        if two people add new accounts right after each other from different wikis.
082public class XMLUserDatabase extends AbstractUserDatabase {
083
084    /** The jspwiki.properties property specifying the file system location of the user database. */
085    public static final String  PROP_USERDATABASE = "jspwiki.xmlUserDatabaseFile";
086    private static final String DEFAULT_USERDATABASE = "userdatabase.xml";
087    private static final String ATTRIBUTES_TAG    = "attributes";
088    private static final String OLD_HASHES_TAG    = "oldhashes";
089    private static final String CREATED           = "created";
090    private static final String EMAIL             = "email";
091    private static final String FULL_NAME         = "fullName";
092    private static final String LOGIN_NAME        = "loginName";
093    private static final String LAST_MODIFIED     = "lastModified";
094    private static final String LOCK_EXPIRY       = "lockExpiry";
095    private static final String PASSWORD_CHANGED  = "passwordChanged";
096    private static final String PASSWORD          = "password";
097    private static final String UID               = "uid";
098    private static final String USER_TAG          = "user";
099    private static final String WIKI_NAME         = "wikiName";
100    private static final String DATE_FORMAT       = "yyyy.MM.dd 'at' HH:mm:ss:SSS z";
101    private Document            c_dom;
102    private File                c_file;
103    private int m_passwordReusedCount = -1;
104
105    /** Guards the in-memory DOM and its persistence to disk. */
106    private final ReentrantLock lock = new ReentrantLock();
107
108    /** {@inheritDoc} */
109    @Override
110    public void deleteByLoginName( final String loginName ) throws WikiSecurityException {
111        Synchronizer.synchronize( lock, () -> {
112            if( c_dom == null ) {
113                throw new WikiSecurityException( "FATAL: database does not exist" );
114            }
115
116            final NodeList users = c_dom.getDocumentElement().getElementsByTagName( USER_TAG );
117            for( int i = 0; i < users.getLength(); i++ ) {
118                final Element user = ( Element )users.item( i );
119                if( user.getAttribute( LOGIN_NAME ).equals( loginName ) ) {
120                    c_dom.getDocumentElement().removeChild( user );
121
122                    // Commit to disk
123                    saveDOM();
124                    return;
125                }
126            }
127            throw new NoSuchPrincipalException( "Not in database: " + loginName );
128        } );
129    }
130
131    /** {@inheritDoc} */
132    @Override
133    public UserProfile findByEmail( final String index ) throws NoSuchPrincipalException {
134        return findBy( EMAIL, index );
135    }
136
137    /** {@inheritDoc} */
138    @Override
139    public UserProfile findByFullName( final String index ) throws NoSuchPrincipalException {
140        return findBy( FULL_NAME, index );
141    }
142
143    /** {@inheritDoc} */
144    @Override
145    public UserProfile findByLoginName( final String index ) throws NoSuchPrincipalException {
146        return findBy( LOGIN_NAME, index );
147    }
148
149    /** {@inheritDoc} */
150    @Override
151    public UserProfile findByUid( final String uid ) throws NoSuchPrincipalException {
152        return findBy( UID, uid );
153    }
154
155    /** {@inheritDoc} */
156    @Override
157    public UserProfile findByWikiName( final String index ) throws NoSuchPrincipalException {
158        return findBy( WIKI_NAME, index );
159    }
160
161    public UserProfile findBy( final String attr, final String value ) throws NoSuchPrincipalException {
162        final UserProfile profile = findByAttribute( attr, value );
163        if ( profile != null ) {
164            return profile;
165        }
166        throw new NoSuchPrincipalException( "Not in database: " + value );
167    }
168
169    /** {@inheritDoc} */
170    @Override
171    public Principal[] getWikiNames() throws WikiSecurityException {
172        if ( c_dom == null ) {
173            throw new IllegalStateException( "FATAL: database does not exist" );
174        }
175        final SortedSet< WikiPrincipal > principals = new TreeSet<>();
176        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
177        for( int i = 0; i < users.getLength(); i++ ) {
178            final Element user = ( Element )users.item( i );
179            final String wikiName = user.getAttribute( WIKI_NAME );
180            if( StringUtils.isEmpty( wikiName ) ) {
181                LOG.warn( "Detected null or empty wiki name for {} in XMLUserDataBase. Check your user database.", user.getAttribute( LOGIN_NAME ) );
182            } else {
183                final WikiPrincipal principal = new WikiPrincipal( wikiName, WikiPrincipal.WIKI_NAME );
184                principals.add( principal );
185            }
186        }
187        return principals.toArray( new Principal[0] );
188    }
189
190    /** {@inheritDoc} */
191    @Override
192    public void initialize( final Engine engine, final Properties props ) throws NoRequiredPropertyException {
193        m_engine = engine;
194        initializePasswordHashing( props );
195        final File defaultFile;
196        if( engine.getRootPath() == null ) {
197            LOG.warn( "Cannot identify JSPWiki root path" );
198            defaultFile = new File( "WEB-INF/" + DEFAULT_USERDATABASE ).getAbsoluteFile();
199        } else {
200            defaultFile = new File( engine.getRootPath() + "/WEB-INF/" + DEFAULT_USERDATABASE );
201        }
202
203        // Get database file location
204        final String file = TextUtil.getStringProperty( props, PROP_USERDATABASE, defaultFile.getAbsolutePath() );
205        if( file == null ) {
206            LOG.warn( "XML user database property " + PROP_USERDATABASE + " not found; trying " + defaultFile );
207            c_file = defaultFile;
208        } else {
209            c_file = new File( file );
210        }
211
212        LOG.info( "XML user database at " + c_file.getAbsolutePath() );
213        m_passwordReusedCount = TextUtil.getIntegerProperty( props, "jspwiki.credentials.reuseCount", -1);
214        File checkFile = new File(c_file.getParent(), c_file.getName() + ".check");
215        if (checkFile.exists()) {
216            
217            byte[] computedHash = null;
218            byte[] storedHash = null;
219            try (FileInputStream fis = new FileInputStream(c_file)) {
220                computedHash = DigestUtils.sha256(fis);
221                storedHash = FileUtils.readFileToByteArray(checkFile);
222            } catch (Exception ex) {
223                throw new RuntimeException("Failed to compute integrity check. ", ex);
224            } 
225            if (Arrays.equals(computedHash, storedHash)) {
226                LOG.info("XML user database hash check passed. no modifications detected.");
227            } else {
228                throw new RuntimeException("XML user database has been modified outside of JSP Wiki. Refusing start up. An administrator will need to restore the file from backup");
229            }
230
231        } else {
232            LOG.info("XML user database check file does not exist. This is normal if JSPWIki was just installed.");
233        }
234        
235        buildDOM();
236        sanitizeDOM();
237    }
238
239    private void buildDOM() {
240        // Read DOM
241        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
242        factory.setValidating( false );
243        factory.setExpandEntityReferences( false );
244        factory.setIgnoringComments( true );
245        factory.setNamespaceAware( false );
246        factory.setAttribute( XMLConstants.ACCESS_EXTERNAL_DTD, "" );
247        factory.setAttribute( XMLConstants.ACCESS_EXTERNAL_SCHEMA, "" );
248        try {
249            c_dom = factory.newDocumentBuilder().parse( c_file );
250            LOG.debug( "Database successfully initialized" );
251            c_lastModified = c_file.lastModified();
252            c_lastCheck = System.currentTimeMillis();
253        } catch( final ParserConfigurationException e ) {
254            LOG.error( "Configuration error: {}", e.getMessage() );
255        } catch( final SAXException e ) {
256            LOG.error( "SAX error: {}", e.getMessage() );
257        } catch( final FileNotFoundException e ) {
258            LOG.info( "User database not found; creating from scratch..." );
259        } catch( final IOException e ) {
260            LOG.error( "IO error: {}", e.getMessage() );
261        } catch( final Exception e ) {
262            LOG.error( "Error initializing XML database from: {} {}", c_file.getAbsolutePath(), e.getMessage() );
263        }
264        if ( c_dom == null ) {
265            try {
266                //  Create the DOM from scratch
267                c_dom = factory.newDocumentBuilder().newDocument();
268                c_dom.appendChild( c_dom.createElement( "users" ) );
269            } catch( final ParserConfigurationException e ) {
270                LOG.fatal( "Could not create in-memory DOM" );
271            }
272        }
273    }
274
275    private void saveDOM() throws WikiSecurityException {
276        if( c_dom == null ) {
277            throw new IllegalStateException( "FATAL: database does not exist" );
278        }
279
280        final File newFile = new File( c_file.getAbsolutePath() + ".new" );
281        try( final BufferedWriter io = new BufferedWriter( new OutputStreamWriter( Files.newOutputStream( newFile.toPath() ), StandardCharsets.UTF_8 ) ) ) {
282
283            // Write the file header and document root
284            io.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
285            io.write( "<users>\n" );
286
287            // Write each profile as a <user> node
288            final Element root = c_dom.getDocumentElement();
289            final NodeList nodes = root.getElementsByTagName( USER_TAG );
290            for( int i = 0; i < nodes.getLength(); i++ ) {
291                final Element user = ( Element )nodes.item( i );
292                io.write( "    <" + USER_TAG + " " );
293                io.write( UID );
294                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( UID ) ) + "\" " );
295                io.write( LOGIN_NAME );
296                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LOGIN_NAME ) ) + "\" " );
297                io.write( WIKI_NAME );
298                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( WIKI_NAME ) ) + "\" " );
299                io.write( FULL_NAME );
300                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( FULL_NAME ) ) + "\" " );
301                io.write( EMAIL );
302                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( EMAIL ) ) + "\" " );
303                io.write( PASSWORD );
304                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( PASSWORD ) ) + "\" " );
305                io.write( CREATED );
306                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( CREATED ) ) + "\" " );
307                io.write( LAST_MODIFIED );
308                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LAST_MODIFIED ) ) + "\" " );
309                io.write( LOCK_EXPIRY );
310                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LOCK_EXPIRY ) ) + "\" " );
311                io.write( PASSWORD_CHANGED );
312                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( PASSWORD_CHANGED ) ) + "\" " );
313                io.write( OLD_HASHES_TAG );
314                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( OLD_HASHES_TAG ) ) + "\" " );
315                io.write( ">" );
316                final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
317                for( int j = 0; j < attributes.getLength(); j++ ) {
318                    final Element attribute = ( Element )attributes.item( j );
319                    final String value = extractText( attribute );
320                    io.write( "\n        <" + ATTRIBUTES_TAG + ">" );
321                    io.write( value );
322                    io.write( "</" + ATTRIBUTES_TAG + ">" );
323                }
324                io.write( "\n    </" + USER_TAG + ">\n" );
325            }
326            io.write( "</users>" );
327        } catch( final IOException e ) {
328            throw new WikiSecurityException( e.getLocalizedMessage(), e );
329        }
330
331        // Copy new file over old version
332        final File backup = new File( c_file.getAbsolutePath() + ".old" );
333        if( backup.exists() ) {
334            if( !backup.delete() ) {
335                LOG.error( "Could not delete old user database backup: " + backup );
336            }
337        }
338        if( !c_file.renameTo( backup ) ) {
339            LOG.error( "Could not create user database backup: " + backup );
340        }
341        if( !newFile.renameTo( c_file ) ) {
342            LOG.error( "Could not save database: " + backup + " restoring backup." );
343            if( !backup.renameTo( c_file ) ) {
344                LOG.error( "Restore failed. Check the file permissions." );
345            }
346            LOG.error( "Could not save database: " + c_file + ". Check the file permissions" );
347        }
348        
349        try (FileInputStream fis = new FileInputStream(c_file)) {
350            byte[] hash = DigestUtils.sha256(fis);
351            File checkFile = new File(c_file.getParent(), c_file.getName() + ".check");
352            FileUtils.writeByteArrayToFile(checkFile, hash);
353        } catch (Exception ex) {
354            LOG.warn("Failed to recompute and/or save the check file", ex);
355        }
356    }
357
358    private long c_lastCheck;
359    private long c_lastModified;
360
361    private void checkForRefresh() {
362        final long time = System.currentTimeMillis();
363        if( time - c_lastCheck > 60 * 1000L ) {
364            final long lastModified = c_file.lastModified();
365
366            if( lastModified > c_lastModified ) {
367                buildDOM();
368            }
369        }
370    }
371
372    /**
373     * {@inheritDoc}
374     *
375     * @see org.apache.wiki.auth.user.UserDatabase#rename(String, String)
376     */
377    @Override
378    public void rename( final String loginName, final String newName) throws DuplicateUserException, WikiSecurityException {
379        Synchronizer.synchronize( lock, () -> {
380            if( c_dom == null ) {
381                LOG.fatal( "Could not rename profile '" + loginName + "'; database does not exist" );
382                throw new IllegalStateException( "FATAL: database does not exist" );
383            }
384            checkForRefresh();
385
386            // Get the existing user; if not found, throws NoSuchPrincipalException
387            final UserProfile profile = findByLoginName( loginName );
388
389            // Get user with the proposed name; if found, it's a collision
390            try {
391                final UserProfile otherProfile = findByLoginName( newName );
392                if( otherProfile != null ) {
393                    throw new DuplicateUserException( "security.error.cannot.rename", newName );
394                }
395            } catch( final NoSuchPrincipalException e ) {
396                LOG.debug(e.getMessage(), e);
397                // Good! That means it's safe to save using the new name
398            }
399
400            // Find the user with the old login id attribute, and change it
401            final NodeList users = c_dom.getElementsByTagName( USER_TAG );
402            for( int i = 0; i < users.getLength(); i++ ) {
403                final Element user = ( Element )users.item( i );
404                if( user.getAttribute( LOGIN_NAME ).equals( loginName ) ) {
405                    final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
406                    final Date modDate = new Date( System.currentTimeMillis() );
407                    setAttribute( user, LOGIN_NAME, newName );
408                    setAttribute( user, LAST_MODIFIED, c_format.format( modDate ) );
409                    profile.setLoginName( newName );
410                    profile.setLastModified( modDate );
411                    break;
412                }
413            }
414
415            // Commit to disk
416            saveDOM();
417        } );
418    }
419
420    /** {@inheritDoc} */
421    @Override
422    public void save( final UserProfile profile ) throws WikiSecurityException {
423        Synchronizer.synchronize( lock, () -> {
424            if ( c_dom == null ) {
425                LOG.fatal( "Could not save profile " + profile + " database does not exist" );
426                throw new IllegalStateException( "FATAL: database does not exist" );
427            }
428
429            checkForRefresh();
430
431            final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
432            final String index = profile.getLoginName();
433            final NodeList users = c_dom.getElementsByTagName( USER_TAG );
434            Element user = IntStream.range(0, users.getLength()).mapToObj(i -> (Element) users.item(i)).filter(currentUser -> currentUser.getAttribute(LOGIN_NAME).equals(index)).findFirst().orElse(null);
435
436            boolean isNew = false;
437
438            final Date modDate = new Date( System.currentTimeMillis() );
439            if( user == null ) {
440                // Create new user node
441                profile.setCreated( modDate );
442                LOG.info( "Creating new user " + index );
443                user = c_dom.createElement( USER_TAG );
444                c_dom.getDocumentElement().appendChild( user );
445                setAttribute( user, CREATED, c_format.format( profile.getCreated() ) );
446                isNew = true;
447            } else {
448                // To update existing user node, delete old attributes first...
449                final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
450                for( int i = 0; i < attributes.getLength(); i++ ) {
451                    user.removeChild( attributes.item( i ) );
452                }
453            }
454
455            setAttribute( user, UID, profile.getUid() );
456            setAttribute( user, LAST_MODIFIED, c_format.format( modDate ) );
457            setAttribute( user, LOGIN_NAME, profile.getLoginName() );
458            setAttribute( user, FULL_NAME, profile.getFullname() );
459            setAttribute( user, WIKI_NAME, profile.getWikiName() );
460            setAttribute( user, EMAIL, profile.getEmail() );
461            final Date lockExpiry = profile.getLockExpiry();
462            setAttribute( user, LOCK_EXPIRY, lockExpiry == null ? "" : c_format.format( lockExpiry ) );
463
464            // Hash and save the new password if it's different from old one
465            final String newPassword = profile.getPassword();
466            if( newPassword != null && !newPassword.equals( "" ) ) {
467                final String oldPassword = user.getAttribute( PASSWORD );
468                if( !oldPassword.equals( newPassword ) ) {
469                    // Hashing the same password again, e.g. with other settings, is not a change of password
470                    if( !passwordMatches( newPassword, oldPassword ) ) {
471                        profile.setPasswordChanged( modDate );
472                    }
473                    String newhash = getHash( newPassword );
474                    setAttribute( user, PASSWORD, newhash );
475            
476                    profile.getPreviousHashedCredentials().add(newhash);
477                    while (!profile.getPreviousHashedCredentials().isEmpty() &&
478                            profile.getPreviousHashedCredentials().size() > m_passwordReusedCount) {
479                        profile.getPreviousHashedCredentials().remove(0);
480                    }
481
482                }
483            }
484
485            // The date is kept as it is unless the profile has a newer one
486            if( profile.getPasswordChanged() != null ) {
487                setAttribute( user, PASSWORD_CHANGED, c_format.format( profile.getPasswordChanged() ) );
488            }
489
490            // Save the attributes as Base64 string
491            if(!profile.getAttributes().isEmpty()) {
492                try {
493                    final String encodedAttributes = Serializer.serializeToBase64( profile.getAttributes() );
494                    final Element attributes = c_dom.createElement( ATTRIBUTES_TAG );
495                    user.appendChild( attributes );
496                    final Text value = c_dom.createTextNode( encodedAttributes );
497                    attributes.appendChild( value );
498                } catch( final IOException e ) {
499                    throw new WikiSecurityException( "Could not save user profile attribute. Reason: " + e.getMessage(), e );
500                }
501            }
502            if (!profile.getPreviousHashedCredentials().isEmpty()) {
503                setAttribute( user, OLD_HASHES_TAG, StringUtils.join(profile.getPreviousHashedCredentials(), "|"));
504            }
505
506            // Set the profile timestamps
507            if( isNew ) {
508                profile.setCreated( modDate );
509            }
510            profile.setLastModified( modDate );
511
512            // Commit to disk
513            saveDOM();
514        } );
515    }
516
517    /**
518     * Private method that returns the first {@link UserProfile}matching a &lt;user&gt; element's supplied attribute. This method will also
519     * set the UID if it has not yet been set.
520     *
521     * @param matchAttribute matching attribute
522     * @param index value to match
523     * @return the profile, or <code>null</code> if not found
524     */
525    private UserProfile findByAttribute( final String matchAttribute, String index ) {
526        if ( c_dom == null ) {
527            throw new IllegalStateException( "FATAL: database does not exist" );
528        }
529
530        checkForRefresh();
531        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
532        if( users == null ) {
533            return null;
534        }
535
536        // check if we have to do a case-insensitive compare
537        final boolean caseSensitiveCompare = !matchAttribute.equals( EMAIL );
538
539        for( int i = 0; i < users.getLength(); i++ ) {
540            final Element user = (Element) users.item( i );
541            String userAttribute = user.getAttribute( matchAttribute );
542            if( !caseSensitiveCompare ) {
543                userAttribute = StringUtils.lowerCase(userAttribute);
544                index = StringUtils.lowerCase(index);
545            }
546            if( userAttribute.equals( index ) ) {
547                final UserProfile profile = newProfile();
548
549                // Parse basic attributes
550                profile.setUid( user.getAttribute( UID ) );
551                if( profile.getUid() == null || profile.getUid().isEmpty() ) {
552                    profile.setUid( generateUid( this ) );
553                }
554                profile.setLoginName( user.getAttribute( LOGIN_NAME ) );
555                profile.setFullname( user.getAttribute( FULL_NAME ) );
556                profile.setPassword( user.getAttribute( PASSWORD ) );
557                profile.setEmail( user.getAttribute( EMAIL ) );
558
559                // Get created/modified timestamps
560                final String created = user.getAttribute( CREATED );
561                final String modified = user.getAttribute( LAST_MODIFIED );
562                profile.setCreated( parseDate( profile, created ) );
563                profile.setLastModified( parseDate( profile, modified ) );
564
565                // Is the profile locked?
566                profile.setLockExpiry( parseLockExpiry( profile, user.getAttribute( LOCK_EXPIRY ) ) );
567                final String passwordChanged = user.getAttribute( PASSWORD_CHANGED );
568                profile.setPasswordChanged( StringUtils.isBlank( passwordChanged ) ? null : parseDate( profile, passwordChanged ) );
569                final String oldHahes = user.getAttribute(OLD_HASHES_TAG);
570                if (oldHahes != null && oldHahes.length() > 0) {
571                    String[] parts = oldHahes.split("\\|");
572                    for (String s : parts) {
573                        profile.getPreviousHashedCredentials().add(s);
574                    }
575                }
576
577                // Extract all the user's attributes (should only be one attributes tag, but you never know!)
578                final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
579                for( int j = 0; j < attributes.getLength(); j++ ) {
580                    final Element attribute = ( Element )attributes.item( j );
581                    final String serializedMap = extractText( attribute );
582                    try {
583                        final Map< String, ? extends Serializable > map = Serializer.deserializeFromBase64( serializedMap );
584                        profile.getAttributes().putAll( map );
585                    } catch( final IOException e ) {
586                        LOG.error( "Could not parse user profile attributes!", e );
587                    }
588                }
589
590                return profile;
591            }
592        }
593        return null;
594    }
595
596    /**
597     * Extracts all the text nodes that are immediate children of an Element.
598     *
599     * @param element the base element
600     * @return the text nodes that are immediate children of the base element, concatenated together
601     */
602    private String extractText( final Element element ) {
603        String text = "";
604        if( element.getChildNodes().getLength() > 0 ) {
605            final NodeList children = element.getChildNodes();
606            text = IntStream.range(0, children.getLength()).mapToObj(children::item).filter(child -> child.getNodeType() == Node.TEXT_NODE).map(child -> ((Text) child).getData()).collect(Collectors.joining());
607        }
608        return text;
609    }
610
611    /**
612     *  Parses the lock expiry of a profile, which is written in the default date format. Milliseconds since the epoch, which is what
613     *  was expected when reading it, are accepted too. A value that cannot be parsed keeps the profile locked, as it may have been
614     *  tampered with and opening the account would be the unsafe way to fail.
615     *
616     *  @param profile profile associated to the date.
617     *  @param lockExpiry the stored lock expiry, which may be empty.
618     *  @return the date the lock expires, or null if the profile is not locked.
619     */
620    private Date parseLockExpiry( final UserProfile profile, final String lockExpiry ) {
621        if( StringUtils.isBlank( lockExpiry ) ) {
622            return null;
623        }
624        if( StringUtils.isNumeric( lockExpiry ) ) {
625            return new Date( Long.parseLong( lockExpiry ) );
626        }
627        final Date expiry = parseDate( profile, lockExpiry );
628        if( expiry == null ) {
629            LOG.error( "Could not parse the 'lockExpiry' attribute for profile '{}'; keeping the profile locked.", profile.getLoginName() );
630            return new Date( Long.MAX_VALUE );
631        }
632        return expiry;
633    }
634
635    /**
636     *  Tries to parse a date using the default format - then, for backwards compatibility reasons, tries the platform default.
637     *
638     *  @param profile profile associated to the date.
639     *  @param date date to be parsed.
640     *  @return A parsed date, or null, if both parse attempts fail.
641     */
642    private Date parseDate( final UserProfile profile, final String date ) {
643        try {
644            final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
645            return c_format.parse( date );
646        } catch( final ParseException e ) {
647            try {
648                return DateFormat.getDateTimeInstance().parse( date );
649            } catch( final ParseException e2 ) {
650                LOG.warn( "Could not parse a date attribute for profile '" + profile.getLoginName() + "'." +
651                          " It may have been tampered with.", e2 );
652            }
653        }
654        return null;
655    }
656
657    /**
658     * After loading the DOM, this method sanity-checks the dates in the DOM and makes sure they are formatted properly. This is sort-of
659     * hacky, but it should work.
660     */
661    private void sanitizeDOM() {
662        if( c_dom == null ) {
663            throw new IllegalStateException( "FATAL: database does not exist" );
664        }
665
666        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
667        for( int i = 0; i < users.getLength(); i++ ) {
668            final Element user = ( Element )users.item( i );
669
670            // Sanitize UID (and generate a new one if one does not exist)
671            String uid = user.getAttribute( UID ).trim();
672            if( StringUtils.isEmpty( uid ) || "-1".equals( uid ) ) {
673                uid = String.valueOf( generateUid( this ) );
674                user.setAttribute( UID, uid );
675            }
676
677            // Sanitize dates
678            final String loginName = user.getAttribute( LOGIN_NAME );
679            String created = user.getAttribute( CREATED );
680            String modified = user.getAttribute( LAST_MODIFIED );
681            final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
682            try {
683                created = c_format.format( c_format.parse( created ) );
684                modified = c_format.format( c_format.parse( modified ) );
685                user.setAttribute( CREATED, created );
686                user.setAttribute( LAST_MODIFIED, modified );
687            } catch( final ParseException e ) {
688                try {
689                    created = c_format.format( DateFormat.getDateTimeInstance().parse( created ) );
690                    modified = c_format.format( DateFormat.getDateTimeInstance().parse( modified ) );
691                    user.setAttribute( CREATED, created );
692                    user.setAttribute( LAST_MODIFIED, modified );
693                } catch( final ParseException e2 ) {
694                    LOG.warn( "Could not parse 'created' or 'lastModified' attribute for profile '" + loginName + "'."
695                            + " It may have been tampered with." );
696                }
697            }
698        }
699    }
700
701    /**
702     * Private method that sets an attribute value for a supplied DOM element.
703     *
704     * @param element the element whose attribute is to be set
705     * @param attribute the name of the attribute to set
706     * @param value the desired attribute value
707     */
708    private void setAttribute( final Element element, final String attribute, final String value ) {
709        if( value != null ) {
710            element.setAttribute( attribute, value );
711        }
712    }
713
714}