#!/bin/bash
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

# https://medium.com/@appmattus/android-security-ssl-pinning-1db8acb6621e

prog=$( basename $0 .bash )
PREFIX=/usr/local
ROLE=proxy

. /usr/local/bin/proxy_ping_lib.bash || \
    { ERROR loading /usr/local/bin/proxy_ping_lib.bash ; exit 2; }
. /usr/local/bin/usr_local_base.bash || exit 2

proxy_ping_mode
#? . /usr/local/bin/proxy_export.bash $MODE

. /usr/local/bin/usr_local_base.bash || exit 2
CERT=$( proxy_ping_update_cacert )
[ "$?" -ne 0 -o -n "$CERT" ] && CAFILE=$CERT || \
	CAFILE=/usr/local/etc/ssl/cacert-testforge.pem

openssl=openssl
OPENSSL_ARGS="-4 --CAfile $CAFILE -bugs -showcerts"
if [ -n "$https_proxy" ] ; then
    HTTPS_HOST=$( echo $https_proxy|sed -e 's@/@@g' -e 's/:/ /g' -e 's/https* //' -e 's/ .*//' )
    HTTPS_PORT=$( echo $https_proxy|sed -e 's@/@@g' -e 's/:/ /g' -e 's/.* //' )

    OPENSSL_ARGS="$OPENSSL_ARGS -proxy ${HTTPS_HOST}:$HTTPS_PORT"
elif [ -n "$socks_proxy" ] ; then
    SOCKS_HOST=$( echo $socks_proxy|sed  -e 's/.*@//' -e 's@/@@g' -e 's/:/ /g' -e 's/socks5* //'  -e 's/ .*//' )
    SOCKS_PORT=$( echo $socks_proxy|sed -e 's@/@@g' -e 's/:/ /g' -e 's/.* //' )
    # check /etc/tor/torsocks.conf
    openssl='torsocks openssl'
fi

OUTR=/tmp/$prog$$
for item in "$@" ; do
    i=0
    OUTRF=$OUTR.$item

    INFO openssl s_client -connect ${item}:443 -servername $item  $OPENSSL_ARGS
    $openssl s_client -connect ${item}:443 -servername $item  $OPENSSL_ARGS \
	     </dev/null 2>$OUTRF.err >$OUTRF.out
    [ $? -eq 0 ] || {
	retval=$?
	ERROR $prog $retval see $OUTRF.err
	cat $OUTRF.err
	exit 1$retval
    }
    [ -s $OUTRF.out ] || { ERROR $prog empty $OUTRF.out ; exit 2 ; }

    sed -n '/Certificate chain/,/Server certificate/p' $OUTRF.out >$OUTRF.chain
    DBUG $prog Certificate chain:
    grep '^ [0-9][0-9]* ' $OUTRF.chain
    INFO $prog Base64 Certificate sha256 digests:
    rest=$( cat $OUTRF.chain )
    while [[ "$rest" =~ '-----BEGIN CERTIFICATE-----' ]] ; do
	cert="${rest%%-----END CERTIFICATE-----*}-----END CERTIFICATE-----"
	rest=${rest#*-----END CERTIFICATE-----}
	echo $( echo "$cert" | grep 's:' | sed 's/.*s:\(.*\)/\1/' ) echo "$cert" |
	    openssl x509 -pubkey -noout |
	    openssl rsa -pubin -outform der 2>/dev/null |
	    openssl dgst -sha256 -binary | openssl enc -base64
    done

    # rm -f $OUTRF.chain $OUTRF.out $OUTRF.err
done

exit 0
