#!/bin/sh
# Copyright 2013 Paul Wise <pabs@debian.org>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND I DISCLAIM ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL I BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


# corekeeper dump adds some extra privacy on Linux multi-user systems
# by putting core files into per-user directories. This is needed
# because Linux does not create directories when dumping core files
# and it is apparently painful to do that from within Linux.
#
# Thanks for the security audits go to:
# Jakub Wilk <jwilk@jwilk.net>
# Kees Cook <kees@debian.org>

set -e

if [ "$(id -u)" != "0" ]; then
	echo "This script must be run as root" 1>&2
	exit 1
fi

# Check how many arguments the kernel sent us.
uid="$1" ; shift
if [ "$1" = -- ] || [ "$1" -ne 1 ] ; then
	# Either old kernel that does not support %d
	# (see v3.6-6800-g12a2b4b in linux.git for more info)
	# or a process that was not set as dumpable
	# cannot set the core file owner safely, use root
	owner="0"
fi
shift
if [ "$1" = -- ] ; then
	shift
fi
core="$*"

# These are shell metacharacters
core="$(printf '%s' "$core" | tr '! ' '-')"
umask 0077
mkdir -p "/var/crash/$owner"
chown "$owner" "/var/crash/$owner"
owner="$owner" core="$core" \
	su -s /bin/sh -c '/bin/cat > /var/crash/"$owner"/"$core"' \
	"$(getent passwd "$owner" | cut -d: -f1)"
