Sometimes you need a user to run a daemon/service, and you want them to have as little power as possible (in case the service is hacked in some way). This script is what I have used - almost entirely copied from "Securing Debian Manual: Chapter 9 - Developer's Best Practices for OS Security" https://www.debian.org/doc/manuals/securing-debian-howto/ch9.en.html
Script
#! /bin/sh
# KMW 2015-06-07
# based on https://www.debian.org/doc/manuals/securing-debian-howto/ch9.en.html
SERVER_HOME=/home/daemonuser
SERVER_USER=daemonuser
SERVER_NAME="Daemon user"
SERVER_GROUP=daemonuser
# Groups that the user will be added to, if undefined, then none.
#ADDGROUP=""
case "$1" in
install|upgrade)
# If the package has default file it could be sourced, so that
# the local admin can overwrite the defaults
[ -f "/etc/default/packagename" ] && . /etc/default/packagename
# Sane defaults:
[ -z "$SERVER_HOME" ] && SERVER_HOME=server_dir
[ -z "$SERVER_USER" ] && SERVER_USER=server_user
[ -z "$SERVER_NAME" ] && SERVER_NAME="Server description"
[ -z "$SERVER_GROUP" ] && SERVER_GROUP=server_group
# create user to avoid running server as root
# 1. create group if not existing
if ! getent group | grep -q "^$SERVER_GROUP:" ; then
echo -n "Adding group $SERVER_GROUP.."
addgroup --quiet --system $SERVER_GROUP 2>/dev/null || true
echo "..done"
fi
# 2. create homedir if not existing
test -d $SERVER_HOME || mkdir $SERVER_HOME
# 3. create user if not existing
if ! getent passwd | grep -q "^$SERVER_USER:"; then
echo -n "Adding system user $SERVER_USER.."
adduser --quiet \
--system \
--ingroup $SERVER_GROUP \
--no-create-home \
--disabled-password \
$SERVER_USER 2>/dev/null || true
echo "..done"
fi
# 4. adjust passwd entry
echo -n "Running usermod.."
usermod -c "$SERVER_NAME" \
-d $SERVER_HOME \
-g $SERVER_GROUP \
$SERVER_USER
echo "..done"
# 5. adjust file and directory permissions
echo -n "Adjusting file/dir perms.."
if ! dpkg-statoverride --list $SERVER_HOME >/dev/null; then
chown -R $SERVER_USER:adm $SERVER_HOME
chmod u=rwx,g=rxs,o= $SERVER_HOME
fi
echo "..done"
# 6. Add the user to the ADDGROUP group
if [ ! "$ADDGROUP" = "" ]; then
echo -n "Adding extra groups.."
if ! groups $SERVER_USER | cut -d: -f2 \
| grep -qw $ADDGROUP; then
adduser $SERVER_USER $ADDGROUP
fi
echo "..done"
fi
;;
*)
echo "usage: $0 install" ;;
esac
exit 0