| 1 |
#!/bin/sh |
| 2 |
# |
| 3 |
# SPDX-FileCopyrightText: 2003 Theodore Ts'o <[email protected]> |
| 4 |
# SPDX-License-Identifier: GPL-2.0-or-later |
| 5 |
# |
| 6 |
# This script will extract the necessary certificate from the IMAP server |
| 7 |
# It assumes that an attacker isn't trying to spoof you when you connect |
| 8 |
# to the IMAP server! You're better off downloading the certificate |
| 9 |
# from a trusted source. |
| 10 |
# |
| 11 |
|
| 12 |
usage() { |
| 13 |
echo "Usage: $0 [-s] <host>" >&2 |
| 14 |
echo " -s Use IMAP+STARTTLS (port 143) instead of IMAPS (port 993)" >&2 |
| 15 |
exit 1 |
| 16 |
} |
| 17 |
|
| 18 |
STARTTLS=false |
| 19 |
|
| 20 |
while getopts "s" opt; do |
| 21 |
case $opt in |
| 22 |
s) STARTTLS=true ;; |
| 23 |
*) usage ;; |
| 24 |
esac |
| 25 |
done |
| 26 |
|
| 27 |
shift `expr $OPTIND - 1` |
| 28 |
|
| 29 |
if [ $# -ne 1 ]; then |
| 30 |
usage |
| 31 |
fi |
| 32 |
|
| 33 |
HOST=$1 |
| 34 |
|
| 35 |
seed=`date '+%s'` |
| 36 |
try=0 |
| 37 |
while :; do |
| 38 |
TMPDIR=/tmp/get-cert.$$.$seed |
| 39 |
mkdir $TMPDIR 2> /dev/null && break |
| 40 |
if [ $try = 1000 ]; then |
| 41 |
echo "Cannot create temporary directory." >&2 |
| 42 |
exit 1 |
| 43 |
fi |
| 44 |
try=`expr $try + 1` |
| 45 |
seed=`expr \( \( $seed \* 1103515245 \) + 12345 \) % 2147483648` |
| 46 |
done |
| 47 |
|
| 48 |
TMPFILE=$TMPDIR/get-cert |
| 49 |
ERRFILE=$TMPDIR/get-cert-err |
| 50 |
CERTFILE=$TMPDIR/cert |
| 51 |
|
| 52 |
if $STARTTLS; then |
| 53 |
FLAGS="-starttls imap" |
| 54 |
PORT=143 |
| 55 |
else |
| 56 |
FLAGS= |
| 57 |
PORT=993 |
| 58 |
fi |
| 59 |
|
| 60 |
echo QUIT | openssl s_client $FLAGS -connect $HOST:$PORT -showcerts \ |
| 61 |
> $TMPFILE 2> $ERRFILE |
| 62 |
sed -e '1,/^-----BEGIN CERTIFICATE-----/d' \ |
| 63 |
-e '/^-----END CERTIFICATE-----/,$d' < $TMPFILE > $CERTFILE |
| 64 |
|
| 65 |
if test -s $CERTFILE ; then |
| 66 |
echo -----BEGIN CERTIFICATE----- |
| 67 |
cat $CERTFILE |
| 68 |
echo -----END CERTIFICATE----- |
| 69 |
else |
| 70 |
echo "Couldn't retrieve certificate. openssl reported the following errors:" |
| 71 |
cat $ERRFILE |
| 72 |
fi |
| 73 |
|
| 74 |
rm -r $TMPDIR |