mbsync-get-cert 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/bin/sh
  2. #
  3. # SPDX-FileCopyrightText: 2003 Theodore Ts'o <tytso@alum.mit.edu>
  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. usage() {
  12. echo "Usage: $0 [-s] <host>" >&2
  13. echo " -s Use IMAP+STARTTLS (port 143) instead of IMAPS (port 993)" >&2
  14. exit 1
  15. }
  16. STARTTLS=false
  17. while getopts "s" opt; do
  18. case $opt in
  19. s) STARTTLS=true ;;
  20. *) usage ;;
  21. esac
  22. done
  23. shift `expr $OPTIND - 1`
  24. if [ $# -ne 1 ]; then
  25. usage
  26. fi
  27. HOST=$1
  28. seed=`date '+%s'`
  29. try=0
  30. while :; do
  31. TMPDIR=/tmp/get-cert.$$.$seed
  32. mkdir $TMPDIR 2> /dev/null && break
  33. if [ $try = 1000 ]; then
  34. echo "Cannot create temporary directory." >&2
  35. exit 1
  36. fi
  37. try=`expr $try + 1`
  38. seed=`expr \( \( $seed \* 1103515245 \) + 12345 \) % 2147483648`
  39. done
  40. TMPFILE=$TMPDIR/get-cert
  41. ERRFILE=$TMPDIR/get-cert-err
  42. CERTFILE=$TMPDIR/cert
  43. if $STARTTLS; then
  44. FLAGS="-starttls imap"
  45. PORT=143
  46. else
  47. FLAGS=
  48. PORT=993
  49. fi
  50. echo QUIT | openssl s_client $FLAGS -connect $HOST:$PORT -showcerts \
  51. > $TMPFILE 2> $ERRFILE
  52. sed -e '1,/^-----BEGIN CERTIFICATE-----/d' \
  53. -e '/^-----END CERTIFICATE-----/,$d' < $TMPFILE > $CERTFILE
  54. if test -s $CERTFILE ; then
  55. echo -----BEGIN CERTIFICATE-----
  56. cat $CERTFILE
  57. echo -----END CERTIFICATE-----
  58. else
  59. echo "Couldn't retrieve certificate. openssl reported the following errors:"
  60. cat $ERRFILE
  61. fi
  62. rm -r $TMPDIR