Skip to content

Instantly share code, notes, and snippets.

@robmathers
Last active August 28, 2018 15:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmathers/d22f1e501644051eea64068ff2427581 to your computer and use it in GitHub Desktop.
Save robmathers/d22f1e501644051eea64068ff2427581 to your computer and use it in GitHub Desktop.
Improved version of the Private Internet Access port forwarding script with better cross-platform support
#!/usr/bin/env bash
#
# Enable port forwarding when using Private Internet Access
#
# Usage:
# ./port_forwarding.sh
error( )
{
echo "$@" 1>&2
exit 1
}
error_and_usage( )
{
echo "$@" 1>&2
usage_and_exit 1
}
usage( )
{
echo "Usage: `dirname $0`/$PROGRAM"
}
usage_and_exit( )
{
usage
exit $1
}
version( )
{
echo "$PROGRAM version $VERSION"
}
port_forward_assignment( )
{
client_id_file="/usr/local/etc/openvpn/pia_client_id"
if [ ! -f "$client_id_file" ]; then
if hash shasum 2>/dev/null; then
head -n 100 /dev/urandom | shasum -a 256 | tr -d " -" > "$client_id_file"
elif hash sha256sum 2>/dev/null; then
head -n 100 /dev/urandom | sha256sum | tr -d " -" > "$client_id_file"
else
echo "Please install shasum or sha256sum, and make sure it is visible in your \$PATH"
exit 1
fi
fi
client_id=`cat "$client_id_file"`
json=`curl "http://209.222.18.222:2000/?client_id=$client_id" 2>/dev/null`
if [ "$json" == "" ]; then
json='Port forwarding is already activated on this connection, has expired, or you are not connected to a PIA region that supports port forwarding'
fi
echo $json
}
EXITCODE=0
PROGRAM=`basename $0`
VERSION=2.1
while test $# -gt 0
do
case $1 in
--usage | --help | -h )
usage_and_exit 0
;;
--version | -v )
version
exit 0
;;
*)
error_and_usage "Unrecognized option: $1"
;;
esac
shift
done
port_forward_assignment
exit 0
@robmathers
Copy link
Author

robmathers commented Sep 5, 2017

This script improves on the original by checking for the presence of shasum or sha256sum, rather than testing against platform names, in order to be more widely compatible (with FreeBSD, for example). It also displays a relevant error message if neither utility is found.
Also adapted a user-submitted change to store and re-use the ClientID, which will return an already opened port, if one exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment