#!/usr/bin/env bash

# monkeysphere-authentication: Monkeysphere authentication admin tool
#
# The monkeysphere scripts are written by:
# Jameson Rollins <jrollins@fifthhorseman.net>
# Jamie McClelland <jm@mayfirst.org>
# Daniel Kahn Gillmor <dkg@fifthhorseman.net>
# Micah Anderson <micah@riseup.net>
#
# They are Copyright 2008-2009, and are all released under the GPL,
# version 3 or later.

########################################################################
PGRM=$(basename $0)

SYSSHAREDIR=${MONKEYSPHERE_SYSSHAREDIR:-"/usr/share/monkeysphere"}
export SYSSHAREDIR
. "${SYSSHAREDIR}/common" || exit 1

SYSDATADIR=${MONKEYSPHERE_SYSDATADIR:-"/var/lib/monkeysphere/authentication"}
export SYSDATADIR

# monkeysphere temp directory, in sysdatadir to enable atomic moves of
# authorized_keys files
MSTMPDIR="${SYSDATADIR}/tmp"
export MSTMPDIR

# UTC date in ISO 8601 format if needed
DATE=$(date -u '+%FT%T')

# unset some environment variables that could screw things up
unset GREP_OPTIONS

# default return code
RETURN=0

########################################################################
# FUNCTIONS
########################################################################

usage() {
    cat <<EOF >&2
usage: $PGRM <subcommand> [options] [args]
Monkeysphere authentication admin tool.

subcommands:
 update-users (u) [USER]...          update user authorized_keys files
 add-id-certifier (c+) KEYID         import and tsign a certification key
   --domain (-n) DOMAIN                limit ID certifications to DOMAIN
   --trust (-t) TRUST                  trust level of certifier (full)
   --depth (-d) DEPTH                  trust depth for certifier (1)
 remove-id-certifier (c-) KEYID      remove a certification key
 list-id-certifiers (c)              list certification keys

 expert
  diagnostics (d)                    monkeysphere authentication status
  gpg-cmd CMD                        execute gpg command

 version (v)                         show version number
 help (h,?)                          this help

EOF
}

# function to run command as monkeysphere user
su_monkeysphere_user() {
    # if the current user is the monkeysphere user, then just eval
    # command
    if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
	eval "$@"

    # otherwise su command as monkeysphere user
    else
	su "$MONKEYSPHERE_USER" -c "$@"
    fi
}

# function to interact with the host gnupg keyring
gpg_host() {
    local returnCode

    GNUPGHOME="$GNUPGHOME_HOST"
    export GNUPGHOME

    # NOTE: we supress this warning because we need the monkeysphere
    # user to be able to read the host pubring.  we realize this might
    # be problematic, but it's the simplest solution, without too much
    # loss of security.
    gpg --no-permission-warning "$@"
    returnCode="$?"

    # always reset the permissions on the host pubring so that the
    # monkeysphere user can read the trust signatures
    chgrp "$MONKEYSPHERE_USER" "${GNUPGHOME_HOST}/pubring.gpg"
    chmod g+r "${GNUPGHOME_HOST}/pubring.gpg"
    
    return "$returnCode"
}

# function to interact with the authentication gnupg keyring
# FIXME: this function requires basically accepts only a single
# argument because of problems with quote expansion.  this needs to be
# fixed/improved.
gpg_authentication() {
    GNUPGHOME="$GNUPGHOME_AUTHENTICATION"
    export GNUPGHOME

    su_monkeysphere_user "gpg $@"
}

# check if user is root
is_root() {
    [ $(id -u 2>/dev/null) = '0' ]
}

# check that user is root, for functions that require root access
check_user() {
    is_root || failure "You must be root to run this command."
}

# output just key fingerprint
fingerprint_server_key() {
    # set the pipefail option so functions fails if can't read sec key
    set -o pipefail

    gpg_host --list-secret-keys --fingerprint \
	--with-colons --fixed-list-mode 2> /dev/null | \
	grep '^fpr:' | head -1 | cut -d: -f10 2>/dev/null
}

# function to check for host secret key
check_host_keyring() {
    fingerprint_server_key >/dev/null \
	|| failure "You don't appear to have a Monkeysphere host key on this server.  Please run 'monkeysphere-server gen-key' first."
}

########################################################################
# MAIN
########################################################################

# unset variables that should be defined only in config file
unset KEYSERVER
unset AUTHORIZED_USER_IDS
unset RAW_AUTHORIZED_KEYS
unset MONKEYSPHERE_USER

# load configuration file
[ -e ${MONKEYSPHERE_SERVER_CONFIG:="${SYSCONFIGDIR}/monkeysphere-server.conf"} ] && . "$MONKEYSPHERE_SERVER_CONFIG"

# set empty config variable with ones from the environment, or with
# defaults
LOG_LEVEL=${MONKEYSPHERE_LOG_LEVEL:=${LOG_LEVEL:="INFO"}}
KEYSERVER=${MONKEYSPHERE_KEYSERVER:=${KEYSERVER:="pool.sks-keyservers.net"}}
AUTHORIZED_USER_IDS=${MONKEYSPHERE_AUTHORIZED_USER_IDS:=${AUTHORIZED_USER_IDS:="%h/.monkeysphere/authorized_user_ids"}}
RAW_AUTHORIZED_KEYS=${MONKEYSPHERE_RAW_AUTHORIZED_KEYS:=${RAW_AUTHORIZED_KEYS:="%h/.ssh/authorized_keys"}}
MONKEYSPHERE_USER=${MONKEYSPHERE_MONKEYSPHERE_USER:=${MONKEYSPHERE_USER:="monkeysphere"}}

# other variables
CHECK_KEYSERVER=${MONKEYSPHERE_CHECK_KEYSERVER:="true"}
REQUIRED_USER_KEY_CAPABILITY=${MONKEYSPHERE_REQUIRED_USER_KEY_CAPABILITY:="a"}
GNUPGHOME_HOST=${MONKEYSPHERE_GNUPGHOME_HOST:="${SYSDATADIR}/gnupg-host"}
GNUPGHOME_AUTHENTICATION=${MONKEYSPHERE_GNUPGHOME_AUTHENTICATION:="${SYSDATADIR}/gnupg-authentication"}

# export variables needed in su invocation
export DATE
export MODE
export MONKEYSPHERE_USER
export LOG_LEVEL
export KEYSERVER
export CHECK_KEYSERVER
export REQUIRED_USER_KEY_CAPABILITY
export GNUPGHOME_HOST
export GNUPGHOME_AUTHENTICATION
export GNUPGHOME

# get subcommand
COMMAND="$1"
[ "$COMMAND" ] || failure "Type '$PGRM help' for usage."
shift

case $COMMAND in
    'update-users'|'update-user'|'u')
	check_user
	check_host_keyring
	update_users "$@"
	;;

    'add-identity-certifier'|'add-id-certifier'|'add-certifier'|'c+')
	check_user
	check_host_keyring
	add_certifier "$@"
	;;

    'remove-identity-certifier'|'remove-id-certifier'|'remove-certifier'|'c-')
	check_user
	check_host_keyring
	remove_certifier "$@"
	;;

    'list-identity-certifiers'|'list-id-certifiers'|'list-certifiers'|'list-certifier'|'c')
	check_user
	check_host_keyring
	list_certifiers "$@"
	;;

    'expert'|'e')
	check_user
	SUBCOMMAND="$1"
	shift
	case "$SUBCOMMAND" in
	    'diagnostics'|'d')
		diagnostics
		;;

	    'gpg-cmd')
		gpg_authentication "$@"
		;;

	    *)
		failure "Unknown expert subcommand: '$COMMAND'
Type '$PGRM help' for usage."
		;;
	esac
	;;

    'version'|'v')
	echo "$VERSION"
	;;

    '--help'|'help'|'-h'|'h'|'?')
        usage
        ;;

    *)
        failure "Unknown command: '$COMMAND'
Type '$PGRM help' for usage."
        ;;
esac

exit "$RETURN"