Restoring Forced Logouts Removed from MacOS Parental Controls

At some point between the release of MacOS "Mojave" and MacOS "Big Sur", one of the key features that I liked about the parental controls — the ability to force logouts from the Mac after the time quota for the day was met — was removed. This is my least favorite removal of a previous feature of the Mac operating system since the removal of the photo mosaic screen saver with the change from Lion to Mountain Lion (see this old video for an example of what it used to look like). While I know the focus now is on screen time specific to various apps across all devices, we really only have the one Mac that our boys use and which we want to limit their time on, and we don't want them to use up their allotted hour on, say, Minecraft, and then spend another hour browsing YouTube videos in a web browser.

Since I could not find any way to force logouts after a time using the current "Screen Time" settings in MacOS Big Sur, I decided I would have to come up with my own programmatic solution. I knew the command line "who" command would show the login time for all users on the machine, so figured I would need a scheduled job to monitor login times and, when it showed either of our boys, Paul or Michael, signed on for over an hour, it was time to force a logout. The tricky part was that, in order to force the logout of other users, I need to do so as a superuser using the "sudo" command — which requires entering my password. How was I to send that password to the "sudo" command without the security risk of exposing the password as plaintext at some point? I finally came across a solution when my searches eventually led me to a marvelous post, "Scripting with sudo on a Mac", by fellow Minnesotan Brett Terpstra. Combine that with what I already knew about crontab scripting, bash scripting, and Java, and learning a bit more about the newer time and date classes added in version 8 of Java, and looking at some examples of using Java ProcessBuilders to make operating system process calls by mkyong and Jonathan Cook on Baeldung.com, and I was able to whip up a working setup within 24 hours.

The first part was to write the script to do the logout. After adding the password to the MacOS keychain per the previously mentioned "Scripting with Sudo on a Mac" article, I started with the example script and modified it as needed to create the following "logout-user.sh", with certain portions replaced by [items in brackets to represent where you want to put your entries].

#!/bin/bash
# See https://brettterpstra.com/2021/04/06/scripting-with-sudo-on-mac/ for technique
# of "Scripting with sudo on Mac".

PASS=$(security find-generic-password -l "[keychain password alias]" -a [sudo username] -w|tr -d '\n')
echo "$PASS" | sudo -S launchctl bootout user/$(id -u $1)

Next, I started work on the Java application, creating it as a simple Maven project, and creating a runnable .jar file using the "maven-shade-plugin". The pom.xml file looks as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>johnwatne</groupId>
    <artifactId>logtimer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>logtimer</name>
    <description>Kid's computer usage monitor and logout tool</description>
    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.14.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.14.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <generateBackupPoms>false</generateBackupPoms>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <!-- Maven Shade Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <!-- add Main-Class to manifest file -->
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>biz.noip.johnwatne.logtimer.LogtimerApp</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I created a "UserLoginTime" model object to represent the information in the output of the "who" command. It implements the "Comparable" interface in such a way that the natural sort order of such objects is by their "loginTime" attribute, allowing picking the most recent login time if multiple entries appear for a user, as is often the case. That code is as follows.

package biz.noip.johnwatne.logtimer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * Class representing time a user has logged in to a specific tty. Takes output
 * parsed from MacOS / BSD &quot;who&quot; command.
 *
 * @author John Watne
 *
 */
public class UserLoginTime implements Comparable<UserLoginTime> {
    private static final DateTimeFormatter DATE_TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy MMM d HH:mm");
    private String user;
    private String tty;
    private LocalDateTime loginTime;

    /**
     * Constructs a UserLoginTime for the information in the passed line from
     * &quot;who&quot; output.
     *
     * @param line
     *            a line of output from the MacOS / BSD &quot;who&quot; command.
     */
    public UserLoginTime(final String line) {
        final LocalDateTime now = LocalDateTime.now();
        final int year = now.getYear();
        final String[] split = line.split("[\\s]+");
        this.setUser(split[0]);
        this.setTty(split[1]);
        final StringBuilder builder = new StringBuilder();
        builder.append(year);

        for (int i = 2; (i < Math.min(split.length, 5)); i++) {
            builder.append(" ");
            builder.append(split[i]);
        }

        this.setLoginTime(
                LocalDateTime.parse(builder.toString(), DATE_TIME_FORMATTER));
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getTty() {
        return tty;
    }

    public void setTty(String tty) {
        this.tty = tty;
    }

    public LocalDateTime getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(LocalDateTime loginTime) {
        this.loginTime = loginTime;
    }

    @Override
    public String toString() {
        return "UserLoginTime [getUser()=" + getUser() + ", getTty()="
                + getTty() + ", getLoginTime()="
                + getLoginTime().format(DATE_TIME_FORMATTER) + "]";
    }

    @Override
    public int hashCode() {
        return Objects.hash(loginTime, user);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserLoginTime other = (UserLoginTime) obj;
        return Objects.equals(loginTime, other.loginTime)
                && Objects.equals(user, other.user);
    }

    @Override
    public int compareTo(UserLoginTime o) {
        return this.getLoginTime().compareTo(o.getLoginTime());
    }

}

The StringBuilder is initialized with the current year. Then, the month and day are read from the input String and appended to it, and the DATE_TIME_FORMATTER is used to obtain the correct value from the resulting built-up String.

Now, we can see how such UserLoginTimes are used by the logic of the program, contained in the LogtimerApp class, which will be presented in sections below. From the top:

package biz.noip.johnwatne.logtimer;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Application that checks operating system for logged in users and determines
 * how long they've been logged in for the day. If longer than allowed amount,
 * logs them out. This is designed specifically for a Mac, so no provision is
 * made for Windows commands.
 *
 * @author John Watne
 *
 */
public class LogtimerApp {
    private static final Logger LOGGER =
            LogManager.getLogger(LogtimerApp.class);

    /**
     * Main method.
     *
     * @param args
     *            command-line arguments; not used.
     */
    public static void main(final String[] args) {
        final LogtimerApp timer = new LogtimerApp();

        try {
            final Map<String, List<UserLoginTime>> userLogins =
                    timer.getUserLogins();

            if (userLogins != null) {
                timer.checkLoginTimes(userLogins);
            }
        } catch (final Exception e) {
            LOGGER.error("Error checking logout times or logging out user", e);
        }
    }

Original early iterations of the coding had all output going to the console. This was changed to have output logged to a log file, whose log4j2 configuration will be shown later. The main method constructs an instance of the class, then initializes a Map of usernames to their last login time. If the List is not null, then the user login times are checked. The Map is obtained by the getUserLogins() method:

    /**
     * Returns a Map of Lists of login times for each user.
     *
     * @return a Map of Lists of login times for each user.
     * @throws IOException
     *             if an I/O error occurs.
     * @throws InterruptedException
     *             if a thread is interrupted.
     */
    private Map<String, List<UserLoginTime>> getUserLogins()
            throws IOException, InterruptedException {
        final Map<String, List<UserLoginTime>> userLogins = new HashMap<>();
        ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "who");
        Process process = processBuilder.start();

        try (final BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;

            while ((line = reader.readLine()) != null) {
                final UserLoginTime userLoginTime = new UserLoginTime(line);
                LOGGER.debug(userLoginTime);
                final String user = userLoginTime.getUser();
                List<UserLoginTime> list = userLogins.get(user);

                if (list == null) {
                    list = new ArrayList<>();
                    userLogins.put(user, list);
                }

                list.add(userLoginTime);
            }
        }

        LOGGER.debug(process.waitFor());
        return userLogins;
    }

So, for each line in the output of the "who" command, a UserLoginTime object is created and added to the List of login times for the specified user. This map is then returned by the method.

The user login times are checked by the following method:

    /**
     * Checks the time logged in for the most recent login for each user.
     *
     * @param userLogins
     *            Lists of login times for each user.
     * @throws IOException
     *             if an I/O error occurs.
     * @throws InterruptedException
     *             if a thread is interrupted.
     */
    private void
            checkLoginTimes(final Map<String, List<UserLoginTime>> userLogins)
                    throws IOException, InterruptedException {
        LOGGER.debug("*** User login lists ****");
        final LocalDateTime now = LocalDateTime.now();

        for (final Entry<String, List<UserLoginTime>> entry : userLogins
                .entrySet()) {
            final String user = entry.getKey();
            final List<UserLoginTime> loginsForUser = entry.getValue();
            final UserLoginTime lastLoginForUser =
                    Collections.max(loginsForUser);
            LOGGER.info("*** Maximum login: " + lastLoginForUser);
            final LocalDateTime fromTemp =
                    LocalDateTime.from(lastLoginForUser.getLoginTime());
            final long minutes = fromTemp.until(now, ChronoUnit.MINUTES);
            LOGGER.debug("Elapsed time: " + minutes + " minutes");
            logoutIfKidLoggedInTooLong(user, minutes);
        }
    }

Having obtained the latest login time for each user, that user's time is checked against the maximum allowed if it is one of the kids and, if it exceeds it, a call is made to the "logout-user.sh" script, passing it the username to logout, by the following method.

    /**
     * Logs out the specified user if
     * <ol>
     * <li>they are a named child within the family, and</li>
     * <li>the number of minutes they have been logged in exceeds the maximum
     * limit.</li>
     * </ol>
     *
     * @param user
     *            the user whose login time is being checked.
     * @param minutes
     *            the number of minutes the user has been logged in.
     * @throws IOException
     *             if an I/O error occurs.
     * @throws InterruptedException
     *             if an thread is interrupted.
     */
    private void logoutIfKidLoggedInTooLong(final String user,
            final long minutes) throws IOException, InterruptedException {
        switch (user) {
        case "[kid accountname 1]":
        case "[kid accountname 2]":
            if (minutes > 59) { /* 1 hour limit; adjust as needed */
                LOGGER.info("Logging out user " + user);
                ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh",
                        "-c", "./logout-user.sh " + user);
                processBuilder.directory(new File("[complete path of folder containing logout-user.sh]"));
                Process process = processBuilder.start();

                try (final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()))) {
                    String line;

                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    LOGGER.debug(process.waitFor());
                }
            }

            break;
        default:
            LOGGER.debug("Time limits not enforced for user " + user);
        }
    }

For the last part of the Java coding, the log4j2.xml file is added to src/main/resources, using a fairly minimal configuration for a rolling file appender as follows.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>

        <Console name="Console" target="SYSTEM_OUT">
            <PattternLayout pattern="%d %p %C{1.} [%t] %m%n" />
        </Console>

        <RollingFile name="RollingFile"
            fileName="[Full path to log folder]/logtimer.log"
            filePattern="[Full path to log folder]/archived/logtimer-%d{yyyy-MM-dd}.%i.log">
            <PatternLayout>
                <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy
                    size="10 MB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- LOG everything at INFO level -->
        <Root level="info">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Root>

        <!-- LOG "biz.noip.johnwatne*" at DEBUG level -->
        <Logger name="biz.noip.johnwatne" level="debug"
            additivity="false">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Logger>

    </Loggers>

</Configuration>

Finally, I edited my root crontab file to add the following line, running the new job every 5 minutes.

*/5 * * * * /usr/bin/java -jar [full path to folder containing jar file]/logtimer-0.0.1-SNAPSHOT.jar > null 

The superuser scheduled jobs can then be updated (if you already have such jobs) or created by running the following command in the Terminal:

sudo crontab [name of crontab file]

Note that the crontab file should be plain text - make sure you do not put in any formatting characters with a text editor.

With everything up and running, a look at the log file looks something like the following, which you can find by opening your log file in the "Console" application in the Applications > Utilities folder.

2021-06-29 00:00:03,093 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[kid1], getTty()=console, getLoginTime()=2021 Jun 28 16:47]
2021-06-29 00:00:03,128 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[kid2], getTty()=console, getLoginTime()=2021 Jun 28 09:10]
2021-06-29 00:00:03,129 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[kid2], getTty()=console, getLoginTime()=2021 Jun 28 08:10]
2021-06-29 00:00:03,131 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[kid1], getTty()=console, getLoginTime()=2021 Jun 27 15:25]
2021-06-29 00:00:03,132 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[kid1], getTty()=console, getLoginTime()=2021 Jun 27 14:25]
2021-06-29 00:00:03,133 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[adult], getTty()=console, getLoginTime()=2021 Jun 26 11:46]
2021-06-29 00:00:03,134 DEBUG b.n.j.l.LogtimerApp [main] UserLoginTime [getUser()=[adult], getTty()=ttys000, getLoginTime()=2021 Jun 26 11:46]
2021-06-29 00:00:03,134 DEBUG b.n.j.l.LogtimerApp [main] 0
2021-06-29 00:00:03,135 DEBUG b.n.j.l.LogtimerApp [main] *** User login lists ****
2021-06-29 00:00:03,136 INFO b.n.j.l.LogtimerApp [main] *** Maximum login: UserLoginTime [getUser()=[kid2], getTty()=console, getLoginTime()=2021 Jun 28 09:10]
2021-06-29 00:00:03,142 DEBUG b.n.j.l.LogtimerApp [main] Elapsed time: 890 minutes
2021-06-29 00:00:03,143 INFO b.n.j.l.LogtimerApp [main] Logging out user [kid2]
2021-06-29 00:00:03,251 DEBUG b.n.j.l.LogtimerApp [main] 0
2021-06-29 00:00:03,252 INFO b.n.j.l.LogtimerApp [main] *** Maximum login: UserLoginTime [getUser()=[adult], getTty()=console, getLoginTime()=2021 Jun 26 11:46]
2021-06-29 00:00:03,252 DEBUG b.n.j.l.LogtimerApp [main] Elapsed time: 3614 minutes
2021-06-29 00:00:03,253 DEBUG b.n.j.l.LogtimerApp [main] Time limits not enforced for user [adult]
2021-06-29 00:00:03,254 INFO b.n.j.l.LogtimerApp [main] *** Maximum login: UserLoginTime [getUser()=[kid1], getTty()=console, getLoginTime()=2021 Jun 28 16:47]
2021-06-29 00:00:03,254 DEBUG b.n.j.l.LogtimerApp [main] Elapsed time: 433 minutes
2021-06-29 00:00:03,254 INFO b.n.j.l.LogtimerApp [main] Logging out user [kid1]
2021-06-29 00:00:03,347 DEBUG b.n.j.l.LogtimerApp [main] 0

So, it DOES log the kids out after they have been signed on for an hour. Why the 433 or 890 minutes entries, then? It turns out that, even though they have been logged out, they still appear in the output of the "who" command, with their most recent login time still shown. A future refinement of this job should include looking at the output of the "ps -u" command to see if they have any running processes and, if not, not bother to do the login check on them.

Crafty minds can probably already spot one loophole with how this works. The kids will only get logged out from their current session if the current session has been an hour or more. There is nothing checking their usage for the day. So, if they want to get the most time, they could log in for, say, 50 minutes, and then log in a few minutes later for another 50 minutes or so, and so forth. The fix will involve a more complex refinement. I think I will need to create a small database of total minutes logged in per day and user (for the monitored kids, not the adults), and add 5 minutes for every time they show up as being logged in by the every-5-minute-run of LogTimerApp. Then, if the total time for the day hits the hour limit, then do the logout.

I hope other parents trying to limit the screen time of their kids on their Mac may find this helpful and not too hard to adapt and implement on their own.

Comments

Popular posts from this blog

Using KeePass with Dropbox for Cross-Platform Password Management

Visiting CareLink Site on OS X Mavericks

Website FINALLY Adapted to Apple Silicon