[
  {
    "path": ".gitignore",
    "content": "*~\n"
  },
  {
    "path": ".travis.yml",
    "content": "# Disallowing packages: openvpn\n# If you require these packages, please review the package approval process at: https://github.com/travis-ci/apt-package-whitelist#package-approval-process\n#addons:\n#    apt:\n#        sources:\n#            - ubuntu-toolchain-r-test\n#        packages:\n#            - openvpn\n\nservices:\n    - docker\n\nbefore_install:\n    - docker --version\n\ninstall:\n    - git clone https://github.com/docker-library/official-images.git official-images\n\n# Assist with ci test debugging:\n#   - DEBUG=1\nbefore_script:\n    - image=\"kylemanna/openvpn\"\n    - docker build -t \"$image\" .\n    - docker inspect \"$image\"\n    - docker run --rm \"$image\" openvpn --version || true # why does it return 1?\n    - docker run --rm \"$image\" openssl version\n\nscript:\n    - official-images/test/run.sh \"$image\"\n    - test/run.sh \"$image\"\n\nafter_script:\n    - docker images\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to docker-openvpn\n\nCommunity contributions are welcome and help move the project along.  Please review this document before sending any pull requests.\n\nThanks!\n\n## Bug Fixes\n\nAll bug fixes are welcome.  Please try to add a test if the bug is something that should have been fixed already.  Oops.\n\n## Feature Additions\n\nNew features are welcome provided that the feature has a general audience and is reasonably simple.  The goal of the repository is to support a wide audience and be simple enough.\n\nPlease add new documentation in the `docs` folder for any new features.  Pull requests for missing documentation is welcome as well.  Keep the `README.md` focused on the most popular use case, details belong in the docs directory.\n\nIf you have a special feature, you're likely to try but it will likely be rejected if not too many people seem interested.\n\n## Tests\n\nIn an effort to not repeat bugs (and break less popular features), unit tests are run on [Travis CI](https://travis-ci.org/kylemanna/docker-openvpn).  The goal of the tests are to be simple and to be placed in the `test/tests` directory where it will be automatically run.  Review existing tests for an example.\n\n## Style\n\nThe style of the repo follows that of the Linux kernel, in particular:\n\n* Pull requests should be rebased to small atomic commits so that the merged history is more coherent\n* The subject of the commit should be in the form \"`<subsystem>: <subject>`\"\n* More details in the body\n* Match surrounding coding style (line wrapping, spaces, etc)\n\nMore details in the [SubmittingPatches](https://www.kernel.org/doc/html/latest/process/submitting-patches.html) document included with the Linux kernel.  In particular the following sections:\n\n* `2) Describe your changes`\n* `3) Separate your changes`\n"
  },
  {
    "path": "Dockerfile",
    "content": "# Original credit: https://github.com/jpetazzo/dockvpn\n\n# Smallest base image\nFROM alpine:latest\n\nLABEL maintainer=\"Kyle Manna <kyle@kylemanna.com>\"\n\n# Testing: pamtester\nRUN echo \"http://dl-cdn.alpinelinux.org/alpine/edge/testing/\" >> /etc/apk/repositories && \\\n    apk add --update openvpn iptables bash easy-rsa openvpn-auth-pam google-authenticator pamtester libqrencode && \\\n    ln -s /usr/share/easy-rsa/easyrsa /usr/local/bin && \\\n    rm -rf /tmp/* /var/tmp/* /var/cache/apk/* /var/cache/distfiles/*\n\n# Needed by scripts\nENV OPENVPN=/etc/openvpn\nENV EASYRSA=/usr/share/easy-rsa \\\n    EASYRSA_CRL_DAYS=3650 \\\n    EASYRSA_PKI=$OPENVPN/pki\n\nVOLUME [\"/etc/openvpn\"]\n\n# Internally uses port 1194/udp, remap using `docker run -p 443:1194/tcp`\nEXPOSE 1194/udp\n\nCMD [\"ovpn_run\"]\n\nADD ./bin /usr/local/bin\nRUN chmod a+x /usr/local/bin/*\n\n# Add support for OTP authentication using a PAM module\nADD ./otp/openvpn /etc/pam.d/\n"
  },
  {
    "path": "Dockerfile.aarch64",
    "content": "# Original credit: https://github.com/jpetazzo/dockvpn\n\n# Smallest base image\nFROM aarch64/alpine:3.5\n\nLABEL maintainer=\"Kyle Manna <kyle@kylemanna.com>\"\n\nRUN echo \"http://dl-4.alpinelinux.org/alpine/edge/community/\" >> /etc/apk/repositories && \\\n    echo \"http://dl-4.alpinelinux.org/alpine/edge/testing/\" >> /etc/apk/repositories && \\\n    apk add --update openvpn iptables bash easy-rsa openvpn-auth-pam google-authenticator pamtester && \\\n    ln -s /usr/share/easy-rsa/easyrsa /usr/local/bin && \\\n    rm -rf /tmp/* /var/tmp/* /var/cache/apk/* /var/cache/distfiles/*\n\n# Needed by scripts\nENV OPENVPN /etc/openvpn\nENV EASYRSA /usr/share/easy-rsa\nENV EASYRSA_PKI $OPENVPN/pki\n\n# Prevents refused client connection because of an expired CRL\nENV EASYRSA_CRL_DAYS 3650\n\nVOLUME [\"/etc/openvpn\"]\n\n# Internally uses port 1194/udp, remap using `docker run -p 443:1194/tcp`\nEXPOSE 1194/udp\n\nCMD [\"ovpn_run\"]\n\nADD ./bin /usr/local/bin\nRUN chmod a+x /usr/local/bin/*\n\n# Add support for OTP authentication using a PAM module\nADD ./otp/openvpn /etc/pam.d/\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014 Kyle Manna\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# OpenVPN for Docker\n\n[![Build Status](https://travis-ci.org/kylemanna/docker-openvpn.svg)](https://travis-ci.org/kylemanna/docker-openvpn)\n[![Docker Stars](https://img.shields.io/docker/stars/kylemanna/openvpn.svg)](https://hub.docker.com/r/kylemanna/openvpn/)\n[![Docker Pulls](https://img.shields.io/docker/pulls/kylemanna/openvpn.svg)](https://hub.docker.com/r/kylemanna/openvpn/)\n[![ImageLayers](https://images.microbadger.com/badges/image/kylemanna/openvpn.svg)](https://microbadger.com/#/images/kylemanna/openvpn)\n[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkylemanna%2Fdocker-openvpn.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkylemanna%2Fdocker-openvpn?ref=badge_shield)\n\n\nOpenVPN server in a Docker container complete with an EasyRSA PKI CA.\n\nExtensively tested on [Digital Ocean $5/mo node](http://bit.ly/1C7cKr3) and has\na corresponding [Digital Ocean Community Tutorial](http://bit.ly/1AGUZkq).\n\n#### Upstream Links\n\n* Docker Registry @ [kylemanna/openvpn](https://hub.docker.com/r/kylemanna/openvpn/)\n* GitHub @ [kylemanna/docker-openvpn](https://github.com/kylemanna/docker-openvpn)\n\n## Quick Start\n\n* Pick a name for the `$OVPN_DATA` data volume container. It's recommended to\n  use the `ovpn-data-` prefix to operate seamlessly with the reference systemd\n  service.  Users are encourage to replace `example` with a descriptive name of\n  their choosing.\n\n      OVPN_DATA=\"ovpn-data-example\"\n\n* Initialize the `$OVPN_DATA` container that will hold the configuration files\n  and certificates.  The container will prompt for a passphrase to protect the\n  private key used by the newly generated certificate authority.\n\n      docker volume create --name $OVPN_DATA\n      docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u udp://VPN.SERVERNAME.COM\n      docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn ovpn_initpki\n\n* Start OpenVPN server process\n\n      docker run -v $OVPN_DATA:/etc/openvpn -d -p 1194:1194/udp --cap-add=NET_ADMIN kylemanna/openvpn\n\n* Generate a client certificate without a passphrase\n\n      docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn easyrsa build-client-full CLIENTNAME nopass\n\n* Retrieve the client configuration with embedded certificates\n\n      docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_getclient CLIENTNAME > CLIENTNAME.ovpn\n\n## Next Steps\n\n### More Reading\n\nMiscellaneous write-ups for advanced configurations are available in the\n[docs](docs) folder.\n\n### Systemd Init Scripts\n\nA `systemd` init script is available to manage the OpenVPN container.  It will\nstart the container on system boot, restart the container if it exits\nunexpectedly, and pull updates from Docker Hub to keep itself up to date.\n\nPlease refer to the [systemd documentation](docs/systemd.md) to learn more.\n\n### Docker Compose\n\nIf you prefer to use `docker-compose` please refer to the [documentation](docs/docker-compose.md).\n\n## Debugging Tips\n\n* Create an environment variable with the name DEBUG and value of 1 to enable debug output (using \"docker -e\").\n\n        docker run -v $OVPN_DATA:/etc/openvpn -p 1194:1194/udp --cap-add=NET_ADMIN -e DEBUG=1 kylemanna/openvpn\n\n* Test using a client that has openvpn installed correctly\n\n        $ openvpn --config CLIENTNAME.ovpn\n\n* Run through a barrage of debugging checks on the client if things don't just work\n\n        $ ping 8.8.8.8    # checks connectivity without touching name resolution\n        $ dig google.com  # won't use the search directives in resolv.conf\n        $ nslookup google.com # will use search\n\n* Consider setting up a [systemd service](/docs/systemd.md) for automatic\n  start-up at boot time and restart in the event the OpenVPN daemon or Docker\n  crashes.\n\n## How Does It Work?\n\nInitialize the volume container using the `kylemanna/openvpn` image with the\nincluded scripts to automatically generate:\n\n- Diffie-Hellman parameters\n- a private key\n- a self-certificate matching the private key for the OpenVPN server\n- an EasyRSA CA key and certificate\n- a TLS auth key from HMAC security\n\nThe OpenVPN server is started with the default run cmd of `ovpn_run`\n\nThe configuration is located in `/etc/openvpn`, and the Dockerfile\ndeclares that directory as a volume. It means that you can start another\ncontainer with the `-v` argument, and access the configuration.\nThe volume also holds the PKI keys and certs so that it could be backed up.\n\nTo generate a client certificate, `kylemanna/openvpn` uses EasyRSA via the\n`easyrsa` command in the container's path.  The `EASYRSA_*` environmental\nvariables place the PKI CA under `/etc/openvpn/pki`.\n\nConveniently, `kylemanna/openvpn` comes with a script called `ovpn_getclient`,\nwhich dumps an inline OpenVPN client configuration file.  This single file can\nthen be given to a client for access to the VPN.\n\nTo enable Two Factor Authentication for clients (a.k.a. OTP) see [this document](/docs/otp.md).\n\n## OpenVPN Details\n\nWe use `tun` mode, because it works on the widest range of devices.\n`tap` mode, for instance, does not work on Android, except if the device\nis rooted.\n\nThe topology used is `net30`, because it works on the widest range of OS.\n`p2p`, for instance, does not work on Windows.\n\nThe UDP server uses`192.168.255.0/24` for dynamic clients by default.\n\nThe client profile specifies `redirect-gateway def1`, meaning that after\nestablishing the VPN connection, all traffic will go through the VPN.\nThis might cause problems if you use local DNS recursors which are not\ndirectly reachable, since you will try to reach them through the VPN\nand they might not answer to you. If that happens, use public DNS\nresolvers like those of Google (8.8.4.4 and 8.8.8.8) or OpenDNS\n(208.67.222.222 and 208.67.220.220).\n\n\n## Security Discussion\n\nThe Docker container runs its own EasyRSA PKI Certificate Authority.  This was\nchosen as a good way to compromise on security and convenience.  The container\nruns under the assumption that the OpenVPN container is running on a secure\nhost, that is to say that an adversary does not have access to the PKI files\nunder `/etc/openvpn/pki`.  This is a fairly reasonable compromise because if an\nadversary had access to these files, the adversary could manipulate the\nfunction of the OpenVPN server itself (sniff packets, create a new PKI CA, MITM\npackets, etc).\n\n* The certificate authority key is kept in the container by default for\n  simplicity.  It's highly recommended to secure the CA key with some\n  passphrase to protect against a filesystem compromise.  A more secure system\n  would put the EasyRSA PKI CA on an offline system (can use the same Docker\n  image and the script [`ovpn_copy_server_files`](/docs/paranoid.md) to accomplish this).\n* It would be impossible for an adversary to sign bad or forged certificates\n  without first cracking the key's passphase should the adversary have root\n  access to the filesystem.\n* The EasyRSA `build-client-full` command will generate and leave keys on the\n  server, again possible to compromise and steal the keys.  The keys generated\n  need to be signed by the CA which the user hopefully configured with a passphrase\n  as described above.\n* Assuming the rest of the Docker container's filesystem is secure, TLS + PKI\n  security should prevent any malicious host from using the VPN.\n\n\n## Benefits of Running Inside a Docker Container\n\n### The Entire Daemon and Dependencies are in the Docker Image\n\nThis means that it will function correctly (after Docker itself is setup) on\nall distributions Linux distributions such as: Ubuntu, Arch, Debian, Fedora,\netc.  Furthermore, an old stable server can run a bleeding edge OpenVPN server\nwithout having to install/muck with library dependencies (i.e. run latest\nOpenVPN with latest OpenSSL on Ubuntu 12.04 LTS).\n\n### It Doesn't Stomp All Over the Server's Filesystem\n\nEverything for the Docker container is contained in two images: the ephemeral\nrun time image (kylemanna/openvpn) and the `$OVPN_DATA` data volume. To remove\nit, remove the corresponding containers, `$OVPN_DATA` data volume and Docker\nimage and it's completely removed.  This also makes it easier to run multiple\nservers since each lives in the bubble of the container (of course multiple IPs\nor separate ports are needed to communicate with the world).\n\n### Some (arguable) Security Benefits\n\nAt the simplest level compromising the container may prevent additional\ncompromise of the server.  There are many arguments surrounding this, but the\ntake away is that it certainly makes it more difficult to break out of the\ncontainer.  People are actively working on Linux containers to make this more\nof a guarantee in the future.\n\n## Differences from jpetazzo/dockvpn\n\n* No longer uses serveconfig to distribute the configuration via https\n* Proper PKI support integrated into image\n* OpenVPN config files, PKI keys and certs are stored on a storage\n  volume for re-use across containers\n* Addition of tls-auth for HMAC security\n\n## Originally Tested On\n\n* Docker hosts:\n  * server a [Digital Ocean](https://www.digitalocean.com/?refcode=d19f7fe88c94) Droplet with 512 MB RAM running Ubuntu 14.04\n* Clients\n  * Android App OpenVPN Connect 1.1.14 (built 56)\n     * OpenVPN core 3.0 android armv7a thumb2 32-bit\n  * OS X Mavericks with Tunnelblick 3.4beta26 (build 3828) using openvpn-2.3.4\n  * ArchLinux OpenVPN pkg 2.3.4-1\n\n\n## License\n[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fkylemanna%2Fdocker-openvpn.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fkylemanna%2Fdocker-openvpn?ref=badge_large)\n"
  },
  {
    "path": "alpine/google-authenticator/APKBUILD",
    "content": "# Contributor: Fabio Napoleoni <f.napoleoni@gmail.com>\n# Maintainer:\npkgname=google-authenticator\npkgver=20160207\npkgrel=1\npkgdesc=\"Google Authenticator PAM module\"\nurl=\"https://github.com/google/google-authenticator\"\narch=\"all\"\nlicense=\"ASL 2.0\"\ndepends=\ndepends_dev=\nmakedepends=\"$depends_dev autoconf automake libtool linux-pam-dev m4 openssl-dev\"\ninstall=\nsubpackages=\"$pkgname-doc\"\nsource=\"https://github.com/google/google-authenticator/archive/c0404dcdbda9ab9e4f0b8451ecdd44eee8db2425.zip\"\n\n_builddir=\"$srcdir\"/$pkgname-c0404dcdbda9ab9e4f0b8451ecdd44eee8db2425/libpam\n\nprepare() {\n\tlocal i\n\tcd \"$_builddir\"\n\tfor i in $source; do\n\t\tcase $i in\n\t\t\t*.patch) msg $i; patch -p1 -i \"$srcdir\"/$i || return 1;;\n\t\tesac\n\tdone\n}\n\nbuild() {\n\tcd \"$_builddir\"\n\t\t./bootstrap.sh || return 1\n\t\t./configure \\\n\t\t\t--build=$CBUILD \\\n\t\t\t--host=$CHOST \\\n\t\t\t--prefix=/usr \\\n\t\t\t--libdir=/lib \\\n\t\t\t--sysconfdir=/etc \\\n\t\t\t--mandir=/usr/share/man \\\n\t\t\t--infodir=/usr/share/info \\\n\t\t\t|| return 1\n\n\t\tmake || return 1\n}\n\npackage() {\n\tcd \"$_builddir\"\n\tmake DESTDIR=\"$pkgdir\" install || return 1\n}\n\nmd5sums=\"33d3cbd0488bcb4f50b34b5670deffae  c0404dcdbda9ab9e4f0b8451ecdd44eee8db2425.zip\"\nsha256sums=\"e32abe693e54195bdb6aca52783e6e1c239e67296876ac59211a59e4608338b8  c0404dcdbda9ab9e4f0b8451ecdd44eee8db2425.zip\"\nsha512sums=\"b44a626e6cc5d8e27685f5d39b5d33f49fc7070331db7b458d3ee40723972821bb8ed5458f27a287dc664d162acf1f8f9a36ca3b1bf767f2bbf27d4f538e9872  c0404dcdbda9ab9e4f0b8451ecdd44eee8db2425.zip\"\n"
  },
  {
    "path": "bin/ovpn_copy_server_files",
    "content": "#!/bin/bash\n## @licence MIT <http://opensource.org/licenses/MIT>\n## @author Copyright (C) 2015 Robin Schneider <ypid@riseup.net>\n\nset -e\n\nif [ -z \"$OPENVPN\" ]; then\n    export OPENVPN=\"$PWD\"\nfi\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\n\nTARGET=\"$OPENVPN/server\"\nif [ -n \"$1\" ]; then\n    TARGET=\"$1\"\nfi\nmkdir -p \"${TARGET}\"\n\n## Ensure that no other keys then the one for the server is present.\nrm -rf \"$TARGET/pki/private\" \"$TARGET/pki/issued\"\n\nFILES=(\n    \"openvpn.conf\"\n    \"ovpn_env.sh\"\n    \"pki/private/${OVPN_CN}.key\"\n    \"pki/issued/${OVPN_CN}.crt\"\n    \"pki/dh.pem\"\n    \"pki/ta.key\"\n    \"pki/ca.crt\"\n    \"ccd\"\n)\n\nif [ -f \"${OPENVPN}/pki/crl.pem\" ]; then\n    FILES+=(\"pki/crl.pem\")\nfi\n\n# Ensure the ccd directory exists, even if empty\nmkdir -p \"ccd\"\n\n# rsync isn't available to keep size down\n# cp --parents isn't in busybox version\n# hack the directory structure with tar\ntar cf - -C \"${OPENVPN}\" \"${FILES[@]}\" | tar xvf - -C \"${TARGET}\"\n\necho \"Created the openvpn configuration for the server: $TARGET\"\n"
  },
  {
    "path": "bin/ovpn_genconfig",
    "content": "#!/bin/bash\n\n#\n# Generate OpenVPN configs\n#\n\nTMP_PUSH_CONFIGFILE=$(mktemp -t vpn_push.XXXXXXX)\nTMP_ROUTE_CONFIGFILE=$(mktemp -t vpn_route.XXXXXXX)\nTMP_EXTRA_CONFIGFILE=$(mktemp -t vpn_extra.XXXXXXX)\n\n#Traceback on Error and Exit come from https://docwhat.org/tracebacks-in-bash/\nset -eu\n\n_showed_traceback=f\n\ntraceback() {\n\t# Hide the traceback() call.\n\tlocal -i start=$(( ${1:-0} + 1 ))\n\tlocal -i end=${#BASH_SOURCE[@]}\n\tlocal -i i=0\n\tlocal -i j=0\n\n\techo \"Traceback (last called is first):\" 1>&2\n\tfor ((i=${start}; i < ${end}; i++)); do\n\t\tj=$(( $i - 1 ))\n\t\tlocal function=\"${FUNCNAME[$i]}\"\n\t\tlocal file=\"${BASH_SOURCE[$i]}\"\n\t\tlocal line=\"${BASH_LINENO[$j]}\"\n\t\techo \"     ${function}() in ${file}:${line}\" 1>&2\n\tdone\n}\n\non_error() {\n  local _ec=\"$?\"\n  local _cmd=\"${BASH_COMMAND:-unknown}\"\n  traceback 1\n  _showed_traceback=t\n  echo \"The command ${_cmd} exited with exit code ${_ec}.\" 1>&2\n}\ntrap on_error ERR\n\n\non_exit() {\n  echo \"Cleaning up before Exit ...\"\n  rm -f $TMP_PUSH_CONFIGFILE\n  rm -f $TMP_ROUTE_CONFIGFILE\n  rm -f $TMP_EXTRA_CONFIGFILE\n  local _ec=\"$?\"\n  if [[ $_ec != 0 && \"${_showed_traceback}\" != t ]]; then\n    traceback 1\n  fi\n}\ntrap on_exit EXIT\n\n# Convert 1.2.3.4/24 -> 255.255.255.0\ncidr2mask()\n{\n    local i\n    local subnetmask=\"\"\n    local cidr=${1#*/}\n    local full_octets=$(($cidr/8))\n    local partial_octet=$(($cidr%8))\n\n    for ((i=0;i<4;i+=1)); do\n        if [ $i -lt $full_octets ]; then\n            subnetmask+=255\n        elif [ $i -eq $full_octets ]; then\n            subnetmask+=$((256 - 2**(8-$partial_octet)))\n        else\n            subnetmask+=0\n        fi\n        [ $i -lt 3 ] && subnetmask+=.\n    done\n    echo $subnetmask\n}\n\n# Used often enough to justify a function\ngetroute() {\n    echo ${1%/*} $(cidr2mask $1)\n}\n\nusage() {\n    echo \"usage: $0 [-d]\"\n    echo \"                  -u SERVER_PUBLIC_URL\"\n    echo \"                 [-e EXTRA_SERVER_CONFIG ]\"\n    echo \"                 [-E EXTRA_CLIENT_CONFIG ]\"\n    echo \"                 [-f FRAGMENT ]\"\n    echo \"                 [-n DNS_SERVER ...]\"\n    echo \"                 [-p PUSH ...]\"\n    echo \"                 [-r ROUTE ...]\"\n    echo \"                 [-s SERVER_SUBNET]\"\n    echo\n    echo \"optional arguments:\"\n    echo \" -2    Enable two factor authentication using Google Authenticator.\"\n    echo \" -a    Authenticate  packets with HMAC using the given message digest algorithm (auth).\"\n    echo \" -b    Disable 'push block-outside-dns'\"\n    echo \" -c    Enable client-to-client option\"\n    echo \" -C    A list of allowable TLS ciphers delimited by a colon (cipher).\"\n    echo \" -d    Disable default route\"\n    echo \" -D    Do not push dns servers\"\n    echo \" -k    Set keepalive. Default: '10 60'\"\n    echo \" -m    Set client MTU\"\n    echo \" -N    Configure NAT to access external server network\"\n    echo \" -t    Use TAP device (instead of TUN device)\"\n    echo \" -T    Encrypt packets with the given cipher algorithm instead of the default one (tls-cipher).\"\n    echo \" -z    Enable comp-lzo compression.\"\n}\n\nprocess_route_config() {\n  local ovpn_route_config=''\n  ovpn_route_config=\"$1\"\n  # If user passed \"0\" skip this, assume no extra routes\n  [[ \"$ovpn_route_config\" == \"0\" ]] && break;\n  echo \"Processing Route Config: '${ovpn_route_config}'\"\n  [[ -n \"$ovpn_route_config\" ]] && echo \"route $(getroute $ovpn_route_config)\" >> \"$TMP_ROUTE_CONFIGFILE\"\n}\n\nprocess_push_config() {\n  local ovpn_push_config=''\n  ovpn_push_config=\"$1\"\n  echo \"Processing PUSH Config: '${ovpn_push_config}'\"\n  [[ -n \"$ovpn_push_config\" ]] && echo \"push \\\"$ovpn_push_config\\\"\" >> \"$TMP_PUSH_CONFIGFILE\"\n}\n\nprocess_extra_config() {\n  local ovpn_extra_config=''\n  ovpn_extra_config=\"$1\"\n  echo \"Processing Extra Config: '${ovpn_extra_config}'\"\n  [[ -n \"$ovpn_extra_config\" ]] && echo \"$ovpn_extra_config\" >> \"$TMP_EXTRA_CONFIGFILE\"\n}\n\nif [ \"${DEBUG:-}\" == \"1\" ]; then\n  set -x\nfi\n\nset -e\n\nif [ -z \"${OPENVPN:-}\" ]; then\n  export OPENVPN=\"$PWD\"\nfi\nif [ -z \"${EASYRSA_PKI:-}\" ]; then\n    export EASYRSA_PKI=\"$OPENVPN/pki\"\nfi\n\nOVPN_AUTH=''\nOVPN_CIPHER=''\nOVPN_CLIENT_TO_CLIENT=''\nOVPN_CN=''\nOVPN_COMP_LZO=0\nOVPN_DEFROUTE=1\nOVPN_DEVICE=\"tun\"\nOVPN_DEVICEN=0\nOVPN_DISABLE_PUSH_BLOCK_DNS=0\nOVPN_DNS=1\nOVPN_DNS_SERVERS=()\nOVPN_ENV=${OPENVPN}/ovpn_env.sh\nOVPN_EXTRA_CLIENT_CONFIG=()\nOVPN_EXTRA_SERVER_CONFIG=()\nOVPN_FRAGMENT=''\nOVPN_KEEPALIVE=\"10 60\"\nOVPN_MTU=''\nOVPN_NAT=0\nOVPN_PORT=''\nOVPN_PROTO=''\nOVPN_PUSH=()\nOVPN_ROUTES=()\nOVPN_SERVER=192.168.255.0/24\nOVPN_SERVER_URL=''\nOVPN_TLS_CIPHER=''\n\n# Import existing configuration if present\n[ -r \"$OVPN_ENV\" ] && source \"$OVPN_ENV\"\n\n# Parse arguments\nwhile getopts \":a:e:E:C:T:r:s:du:bcp:n:k:DNm:f:tz2\" opt; do\n    case $opt in\n        a)\n            OVPN_AUTH=\"$OPTARG\"\n            ;;\n        e)\n            mapfile -t TMP_EXTRA_SERVER_CONFIG <<< \"$OPTARG\"\n            for i in \"${TMP_EXTRA_SERVER_CONFIG[@]}\"; do\n              OVPN_EXTRA_SERVER_CONFIG+=(\"$i\")\n            done\n            ;;\n        E)\n            mapfile -t TMP_EXTRA_CLIENT_CONFIG <<< \"$OPTARG\"\n            for i in \"${TMP_EXTRA_CLIENT_CONFIG[@]}\"; do\n              OVPN_EXTRA_CLIENT_CONFIG+=(\"$i\")\n            done\n            ;;\n        C)\n            OVPN_CIPHER=\"$OPTARG\"\n            ;;\n        T)\n            OVPN_TLS_CIPHER=\"$OPTARG\"\n            ;;\n        r)\n            mapfile -t TMP_ROUTES <<< \"$OPTARG\"\n            for i in \"${TMP_ROUTES[@]}\"; do\n              OVPN_ROUTES+=(\"$i\")\n            done\n            ;;\n        s)\n            OVPN_SERVER=\"$OPTARG\"\n            ;;\n        d)\n            OVPN_DEFROUTE=0\n            OVPN_DISABLE_PUSH_BLOCK_DNS=1\n            ;;\n        u)\n            OVPN_SERVER_URL=\"$OPTARG\"\n            ;;\n        b)\n            OVPN_DISABLE_PUSH_BLOCK_DNS=1\n            ;;\n        c)\n            OVPN_CLIENT_TO_CLIENT=1\n            ;;\n        p)\n            mapfile -t TMP_PUSH <<< \"$OPTARG\"\n            for i in \"${TMP_PUSH[@]}\"; do\n              OVPN_PUSH+=(\"$i\")\n            done\n            ;;\n        n)\n            mapfile -t TMP_DNS_SERVERS <<< \"$OPTARG\"\n            for i in \"${TMP_DNS_SERVERS[@]}\"; do\n              OVPN_DNS_SERVERS+=(\"$i\")\n            done\n            ;;\n        D)\n            OVPN_DNS=0\n            ;;\n        N)\n            OVPN_NAT=1\n            ;;\n        k)\n            OVPN_KEEPALIVE=\"$OPTARG\"\n            ;;\n        m)\n            OVPN_MTU=\"$OPTARG\"\n            ;;\n        t)\n            OVPN_DEVICE=\"tap\"\n            ;;\n        z)\n            OVPN_COMP_LZO=1\n            ;;\n        2)\n            OVPN_OTP_AUTH=1\n            ;;\n        f)\n            OVPN_FRAGMENT=\"$OPTARG\"\n            ;;\n        \\?)\n            set +x\n            echo \"Invalid option: -$OPTARG\" >&2\n            usage\n            exit 1\n            ;;\n        :)\n            set +x\n            echo \"Option -$OPTARG requires an argument.\" >&2\n            usage\n            exit 1\n            ;;\n    esac\ndone\n\n# Create ccd directory for static routes\n[ ! -d \"${OPENVPN:-}/ccd\" ] && mkdir -p ${OPENVPN:-}/ccd\n\n# Server name is in the form \"udp://vpn.example.com:1194\"\nif [[ \"${OVPN_SERVER_URL:-}\" =~ ^((udp|tcp|udp6|tcp6)://)?([0-9a-zA-Z\\.\\-]+)(:([0-9]+))?$ ]]; then\n    OVPN_PROTO=${BASH_REMATCH[2]};\n    OVPN_CN=${BASH_REMATCH[3]};\n    OVPN_PORT=${BASH_REMATCH[5]};\nelse\n    set +x\n    echo \"Common name not specified, see '-u'\"\n    usage\n    exit 1\nfi\n\n# Apply defaults. If dns servers were not defined with -n, use google nameservers\nset +u\n[ -z \"$OVPN_DNS_SERVERS\" ] && OVPN_DNS_SERVERS=(\"8.8.8.8\" \"8.8.4.4\")\n[ -z \"$OVPN_PROTO\" ] && OVPN_PROTO=udp\n[ -z \"$OVPN_PORT\" ] && OVPN_PORT=1194\nset -u\n[ \"${#OVPN_ROUTES[@]}\" == \"0\" ] && [ \"$OVPN_DEFROUTE\" == \"1\" ] && OVPN_ROUTES+=(\"192.168.254.0/24\")\n\n# Preserve config\nif [ -f \"$OVPN_ENV\" ]; then\n    bak_env=$OVPN_ENV.$(date +%s).bak\n    echo \"Backing up $OVPN_ENV -> $bak_env\"\n    mv \"$OVPN_ENV\" \"$bak_env\"\nfi\n\n# Save the current OVPN_ vars to the ovpn_env.sh file\n(set | grep '^OVPN_') | while read -r var; do\n  echo \"declare -x $var\"  >> \"$OVPN_ENV\"\ndone\n\nconf=${OPENVPN:-}/openvpn.conf\nif [ -f \"$conf\" ]; then\n    bak=$conf.$(date +%s).bak\n    echo \"Backing up $conf -> $bak\"\n    mv \"$conf\" \"$bak\"\nfi\n\n# Echo extra client configurations\nif [ ${#OVPN_EXTRA_CLIENT_CONFIG[@]} -gt 0 ]; then\n  for i in \"${OVPN_EXTRA_CLIENT_CONFIG[@]}\"; do\n    echo \"Processing Extra Client Config: $i\"\n  done\nfi\n\ncat > \"$conf\" <<EOF\nserver $(getroute $OVPN_SERVER)\nverb 3\nkey $EASYRSA_PKI/private/${OVPN_CN}.key\nca $EASYRSA_PKI/ca.crt\ncert $EASYRSA_PKI/issued/${OVPN_CN}.crt\ndh $EASYRSA_PKI/dh.pem\ntls-auth $EASYRSA_PKI/ta.key\nkey-direction 0\nkeepalive $OVPN_KEEPALIVE\npersist-key\npersist-tun\n\nproto $OVPN_PROTO\n# Rely on Docker to do port mapping, internally always 1194\nport 1194\ndev $OVPN_DEVICE$OVPN_DEVICEN\nstatus /tmp/openvpn-status.log\n\nuser nobody\ngroup nogroup\nEOF\n\nif [ \"${OVPN_DISABLE_PUSH_BLOCK_DNS}\" == \"1\" ]; then\n  echo \"Disable default push of 'block-outside-dns'\"\nelse\n  process_push_config \"block-outside-dns\"\nfi\n\n[ -n \"$OVPN_TLS_CIPHER\" ] && echo \"tls-cipher $OVPN_TLS_CIPHER\" >> \"$conf\"\n[ -n \"$OVPN_CIPHER\" ] && echo \"cipher $OVPN_CIPHER\" >> \"$conf\"\n[ -n \"$OVPN_AUTH\" ] && echo \"auth $OVPN_AUTH\" >> \"$conf\"\n\n[ -n \"${OVPN_CLIENT_TO_CLIENT:-}\" ] && echo \"client-to-client\" >> \"$conf\"\n[ \"$OVPN_COMP_LZO\" == \"1\" ] && echo \"comp-lzo\" >> \"$conf\"\n[ \"$OVPN_COMP_LZO\" == \"0\" ] && echo \"comp-lzo no\" >> \"$conf\"\n\n[ -n \"${OVPN_FRAGMENT:-}\" ] && echo \"fragment $OVPN_FRAGMENT\" >> \"$conf\"\n\n# Append route commands\nif [ ${#OVPN_ROUTES[@]} -gt 0 ]; then\n  for i in \"${OVPN_ROUTES[@]}\"; do\n    process_route_config \"$i\"\n  done\n  echo -e \"\\n### Route Configurations Below\" >> \"$conf\"\n  cat $TMP_ROUTE_CONFIGFILE >> \"$conf\"\nfi\n\n# Append push commands\n[ \"$OVPN_DNS\" == \"1\" ] && for i in \"${OVPN_DNS_SERVERS[@]}\"; do\n  process_push_config \"dhcp-option DNS $i\"\ndone\n\nif [ \"$OVPN_COMP_LZO\" == \"0\" ]; then\n    process_push_config \"comp-lzo no\"\nfi\n\n[ ${#OVPN_PUSH[@]} -gt 0 ] && for i in \"${OVPN_PUSH[@]}\"; do\n  process_push_config \"$i\"\ndone\n\necho -e \"\\n### Push Configurations Below\" >> \"$conf\"\ncat $TMP_PUSH_CONFIGFILE >> \"$conf\"\n\n# Append optional OTP authentication support\nif [ -n \"${OVPN_OTP_AUTH:-}\" ]; then\n    echo -e \"\\n\\n# Enable OTP+PAM for user authentication\" >> \"$conf\"\n    echo \"plugin /usr/lib/openvpn/plugins/openvpn-plugin-auth-pam.so openvpn\" >> \"$conf\"\n    echo \"reneg-sec 0\" >> \"$conf\"\nfi\n\n# Append extra server configurations\nif [ ${#OVPN_EXTRA_SERVER_CONFIG[@]} -gt 0 ]; then\n  for i in \"${OVPN_EXTRA_SERVER_CONFIG[@]}\"; do\n    process_extra_config \"$i\"\n  done\n  echo -e \"\\n### Extra Configurations Below\" >> \"$conf\"\n  cat $TMP_EXTRA_CONFIGFILE >> \"$conf\"\nfi\n\nset +e\n\n# Clean-up duplicate configs\nif diff -q \"${bak_env:-}\" \"$OVPN_ENV\" 2>/dev/null; then\n    echo \"Removing duplicate back-up: $bak_env\"\n    rm -fv \"$bak_env\"\nfi\nif diff -q \"${bak:-}\" \"$conf\" 2>/dev/null; then\n    echo \"Removing duplicate back-up: $bak\"\n    rm -fv \"$bak\"\nfi\n\necho \"Successfully generated config\"\n"
  },
  {
    "path": "bin/ovpn_getclient",
    "content": "#!/bin/bash\n\n#\n# Get an OpenVPN client configuration file\n#\n\nif [ \"$DEBUG\" == \"1\" ]; then\n    set -x\nfi\n\nset -e\n\nif [ -z \"$OPENVPN\" ]; then\n    export OPENVPN=\"$PWD\"\nfi\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\nif [ -z \"$EASYRSA_PKI\" ]; then\n    export EASYRSA_PKI=\"$OPENVPN/pki\"\nfi\n\ncn=\"$1\"\nparm=\"$2\"\n\nif [ ! -f \"$EASYRSA_PKI/private/${cn}.key\" ]; then\n    echo \"Unable to find \\\"${cn}\\\", please try again or generate the key first\" >&2\n    exit 1\nfi\n\nget_client_config() {\n    mode=\"$1\"\n    echo \"\nclient\nnobind\ndev $OVPN_DEVICE\nremote-cert-tls server\n\nremote $OVPN_CN $OVPN_PORT $OVPN_PROTO\"\n    if [ \"$OVPN_PROTO\" == \"udp6\" ]; then\n        echo \"remote $OVPN_CN $OVPN_PORT udp\"\n    fi\n    if [ \"$OVPN_PROTO\" == \"tcp6\" ]; then\n        echo \"remote $OVPN_CN $OVPN_PORT tcp\"\n    fi\n    for i in \"${OVPN_EXTRA_CLIENT_CONFIG[@]}\"; do\n      echo \"$i\"\n    done\n    if [ \"$mode\" == \"combined\" ]; then\n        echo \"\n<key>\n$(cat $EASYRSA_PKI/private/${cn}.key)\n</key>\n<cert>\n$(openssl x509 -in $EASYRSA_PKI/issued/${cn}.crt)\n</cert>\n<ca>\n$(cat $EASYRSA_PKI/ca.crt)\n</ca>\nkey-direction 1\n<tls-auth>\n$(cat $EASYRSA_PKI/ta.key)\n</tls-auth>\n\"\n    elif [ \"$mode\" == \"separated\" ]; then\n        echo \"\nkey ${cn}.key\nca ca.crt\ncert ${cn}.crt\ntls-auth ta.key 1\n\"\n    fi\n\n    if [ \"$OVPN_DEFROUTE\" != \"0\" ];then\n        echo \"redirect-gateway def1\"\n    fi\n\n    if [ -n \"$OVPN_MTU\" ]; then\n        echo \"tun-mtu $OVPN_MTU\"\n    fi\n\n    if [ -n \"$OVPN_TLS_CIPHER\" ]; then\n        echo \"tls-cipher $OVPN_TLS_CIPHER\"\n    fi\n\n    if [ -n \"$OVPN_CIPHER\" ]; then\n        echo \"cipher $OVPN_CIPHER\"\n    fi\n\n    if [ -n \"$OVPN_AUTH\" ]; then\n        echo \"auth $OVPN_AUTH\"\n    fi\n\n    if [ -n \"$OVPN_OTP_AUTH\" ]; then\n        echo \"auth-user-pass\"\n        echo \"auth-nocache\"\n    fi\n\n    if [ \"$OVPN_COMP_LZO\" == \"1\" ]; then\n        echo \"comp-lzo\"\n    fi\n\n    if [ -n \"$OVPN_OTP_AUTH\" ]; then\n        echo reneg-sec 0\n    fi\n}\n\ndir=\"$OPENVPN/clients/$cn\"\ncase \"$parm\" in\n    \"separated\")\n        mkdir -p \"$dir\"\n        get_client_config \"$parm\" > \"$dir/${cn}.ovpn\"\n        cp \"$EASYRSA_PKI/private/${cn}.key\" \"$dir/${cn}.key\"\n        cp \"$EASYRSA_PKI/ca.crt\" \"$dir/ca.crt\"\n        cp \"$EASYRSA_PKI/issued/${cn}.crt\" \"$dir/${cn}.crt\"\n        cp \"$EASYRSA_PKI/ta.key\" \"$dir/ta.key\"\n        ;;\n    \"\" | \"combined\")\n        get_client_config \"combined\"\n        ;;\n    \"combined-save\")\n        mkdir -p \"$dir\"\n        get_client_config \"combined\" > \"$dir/${cn}-combined.ovpn\"\n        ;;\n    *)\n        echo \"This script can produce the client configuration in two formats:\" >&2\n        echo \"    1. combined (default): All needed configuration and cryptographic material is in one file (Use \\\"combined-save\\\" to write the configuration file in the same path as the separated parameter does).\" >&2\n        echo \"    2. separated: Separated files.\" >&2\n        echo \"Please specify one of those options as second parameter.\" >&2\n        ;;\nesac\n"
  },
  {
    "path": "bin/ovpn_getclient_all",
    "content": "#!/bin/bash\n## @licence MIT <http://opensource.org/licenses/MIT>\n## @author Copyright (C) 2015 Robin Schneider <ypid@riseup.net>\n\nif [ -z \"$OPENVPN\" ]; then\n    export OPENVPN=\"$PWD\"\nfi\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\nif [ -z \"$EASYRSA_PKI\" ]; then\n    export EASYRSA_PKI=\"$OPENVPN/pki\"\nfi\n\npushd \"$EASYRSA_PKI\"\nfor name in issued/*.crt; do\n    name=${name%.crt}\n    name=${name#issued/}\n    if [ \"$name\" != \"$OVPN_CN\" ]; then\n        ovpn_getclient \"$name\" separated\n        ovpn_getclient \"$name\" combined-save\n    fi\ndone\npopd\n"
  },
  {
    "path": "bin/ovpn_initpki",
    "content": "#!/bin/bash\n\n#\n# Initialize the EasyRSA PKI\n#\n\nif [ \"$DEBUG\" == \"1\" ]; then\n  set -x\nfi\n\nset -e\n\nsource \"$OPENVPN/ovpn_env.sh\"\n\n# Specify \"nopass\" as arg[2] to make the CA insecure (not recommended!)\nnopass=$1\n\n# Provides a sufficient warning before erasing pre-existing files\neasyrsa init-pki\n\n# CA always has a password for protection in event server is compromised. The\n# password is only needed to sign client/server certificates.  No password is\n# needed for normal OpenVPN operation.\neasyrsa build-ca $nopass\n\neasyrsa gen-dh\nopenvpn --genkey --secret $EASYRSA_PKI/ta.key\n\n# Was nice to autoset, but probably a bad idea in practice, users should\n# have to explicitly specify the common name of their server\n#if [ -z \"$cn\"]; then\n#    #TODO: Handle IPv6 (when I get a VPS with IPv6)...\n#    ip4=$(dig +short myip.opendns.com @resolver1.opendns.com)\n#    ptr=$(dig +short -x $ip4 | sed -e 's:\\.$::')\n#\n#    [ -n \"$ptr\" ] && cn=$ptr || cn=$ip4\n#fi\n\n# For a server key with a password, manually init; this is autopilot\neasyrsa build-server-full \"$OVPN_CN\" nopass\n\n# Generate the CRL for client/server certificates revocation.\neasyrsa gen-crl\n"
  },
  {
    "path": "bin/ovpn_listclients",
    "content": "#!/bin/bash\n\nif [ -z \"$OPENVPN\" ]; then\n    export OPENVPN=\"$PWD\"\nfi\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\nif [ -z \"$EASYRSA_PKI\" ]; then\n    export EASYRSA_PKI=\"$OPENVPN/pki\"\nfi\n\ncd \"$EASYRSA_PKI\"\n\nif [ -e crl.pem ]; then\n    cat ca.crt crl.pem > cacheck.pem\nelse\n    cat ca.crt > cacheck.pem\nfi\n\necho \"name,begin,end,status\"\nfor name in issued/*.crt; do\n    path=$name\n    begin=$(openssl x509 -noout -startdate -in $path | awk -F= '{ print $2 }')\n    end=$(openssl x509 -noout -enddate -in $path | awk -F= '{ print $2 }')\n\n    name=${name%.crt}\n    name=${name#issued/}\n    if [ \"$name\" != \"$OVPN_CN\" ]; then\n        # check for revocation or expiration\n        command=\"openssl verify -crl_check -CAfile cacheck.pem $path\"\n        result=$($command)\n        if [ $(echo \"$result\" | wc -l) == 1 ] && [ \"$(echo \"$result\" | grep \": OK\")\" ]; then\n            status=\"VALID\"\n        else\n            result=$(echo \"$result\" | tail -n 1 | grep error | cut -d\" \" -f2)\n            case $result in\n                10)\n                    status=\"EXPIRED\"\n                    ;;\n                23)\n                    status=\"REVOKED\"\n                    ;;\n                *)\n                    status=\"INVALID\"\n            esac\n        fi\n        echo \"$name,$begin,$end,$status\"\n    fi\ndone\n\n# Clean\nrm cacheck.pem\n"
  },
  {
    "path": "bin/ovpn_otp_user",
    "content": "#!/bin/bash\n\n#\n# Generate OpenVPN users via google authenticator\n#\n\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\n\nif [ \"x$OVPN_OTP_AUTH\" != \"x1\" ]; then\n    echo \"OTP authentication not enabled, please regenerate configuration using -2 flag\"\n    exit 1\nfi\n\nif [ -z $1 ]; then\n    echo \"Usage: ovpn_otp_user USERNAME\"\n    exit 1\nfi\n\n# Ensure the otp folder is present\n[ -d /etc/openvpn/otp ] || mkdir -p /etc/openvpn/otp\n\n# Binary is present in image, save an $user.google_authenticator file in /etc/openvpn/otp\nif [ \"$2\" == \"interactive\" ]; then\n    # Authenticator will ask for other parameters. User can choose rate limit, token reuse policy and time window policy\n    # Always use time base OTP otherwise storage for counters must be configured somewhere in volume\n    google-authenticator --time-based --force -l \"${1}@${OVPN_CN}\" -s /etc/openvpn/otp/${1}.google_authenticator\nelse\n    # Skip confirmation if not running in interctive mode. Essential for integration tests.\n    google-authenticator --time-based --disallow-reuse --force --rate-limit=3 --rate-time=30 --window-size=3 \\\n        -l \"${1}@${OVPN_CN}\" -s /etc/openvpn/otp/${1}.google_authenticator --no-confirm\nfi\n"
  },
  {
    "path": "bin/ovpn_revokeclient",
    "content": "#!/bin/bash\n\n#\n# Revoke a client certificate\n#\n\nif [ \"$DEBUG\" == \"1\" ]; then\n    set -x\nfi\n\nset -e\n\nif [ -z \"$OPENVPN\" ]; then\n    export OPENVPN=\"$PWD\"\nfi\nif ! source \"$OPENVPN/ovpn_env.sh\"; then\n    echo \"Could not source $OPENVPN/ovpn_env.sh.\"\n    exit 1\nfi\nif [ -z \"$EASYRSA_PKI\" ]; then\n    export EASYRSA_PKI=\"$OPENVPN/pki\"\nfi\n\ncn=\"$1\"\n\nif [ ! -f \"$EASYRSA_PKI/private/${cn}.key\" ]; then\n    echo \"Unable to find \\\"${cn}\\\", please try again or generate the key first\" >&2\n    exit 1\nfi\n\nrevoke_client_certificate(){\n    easyrsa revoke \"$1\"\n    echo \"Generating the Certificate Revocation List :\"\n    easyrsa gen-crl\n    cp -f \"$EASYRSA_PKI/crl.pem\" \"$OPENVPN/crl.pem\"\n    chmod 644 \"$OPENVPN/crl.pem\"\n}\n\nrevoke_client_certificate \"$cn\"\n"
  },
  {
    "path": "bin/ovpn_run",
    "content": "#!/bin/bash\n\n#\n# Run the OpenVPN server normally\n#\n\nif [ \"$DEBUG\" == \"1\" ]; then\n  set -x\nfi\n\nset -e\n\ncd $OPENVPN\n\n# Build runtime arguments array based on environment\nUSER_ARGS=(\"${@}\")\nARGS=()\n\n# Checks if ARGS already contains the given value\nfunction hasArg {\n    local element\n    for element in \"${@:2}\"; do\n        [ \"${element}\" == \"${1}\" ] && return 0\n    done\n    return 1\n}\n\n# Adds the given argument if it's not already specified.\nfunction addArg {\n    local arg=\"${1}\"\n    [ $# -ge 1 ] && local val=\"${2}\"\n    if ! hasArg \"${arg}\" \"${USER_ARGS[@]}\"; then\n        ARGS+=(\"${arg}\")\n        [ $# -ge 1 ] && ARGS+=(\"${val}\")\n    fi\n}\n\n# set up iptables rules and routing\n# this allows rules/routing to be altered by supplying this function\n# in an included file, such as ovpn_env.sh\nfunction setupIptablesAndRouting {\n    iptables -t nat -C POSTROUTING -s $OVPN_SERVER -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null || {\n      iptables -t nat -A POSTROUTING -s $OVPN_SERVER -o $OVPN_NATDEVICE -j MASQUERADE\n    }\n    for i in \"${OVPN_ROUTES[@]}\"; do\n        iptables -t nat -C POSTROUTING -s \"$i\" -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null || {\n          iptables -t nat -A POSTROUTING -s \"$i\" -o $OVPN_NATDEVICE -j MASQUERADE\n        }\n    done\n}\n\n\naddArg \"--config\" \"$OPENVPN/openvpn.conf\"\n\nsource \"$OPENVPN/ovpn_env.sh\"\n\nmkdir -p /dev/net\nif [ ! -c /dev/net/tun ]; then\n    mknod /dev/net/tun c 10 200\nfi\n\nif [ -d \"$OPENVPN/ccd\" ]; then\n    addArg \"--client-config-dir\" \"$OPENVPN/ccd\"\nfi\n\n# When using --net=host, use this to specify nat device.\n[ -z \"$OVPN_NATDEVICE\" ] && OVPN_NATDEVICE=eth0\n\n# Setup NAT forwarding if requested\nif [ \"$OVPN_DEFROUTE\" != \"0\" ] || [ \"$OVPN_NAT\" == \"1\" ] ; then\n\t# call function to setup iptables rules and routing\n\t# this allows rules to be customized by supplying\n\t# a replacement function in, for example, ovpn_env.sh\n\tsetupIptablesAndRouting\nfi\n\n# Use a copy of crl.pem as the CRL Needs to be readable by the user/group\n# OpenVPN is running as.  Only pass arguments to OpenVPN if it's found.\nif [ \"$EASYRSA_PKI/crl.pem\" -nt \"$OPENVPN/crl.pem\" ]; then\n    cp -f \"$EASYRSA_PKI/crl.pem\" \"$OPENVPN/crl.pem\"\n    chmod 644 \"$OPENVPN/crl.pem\"\nfi\n\nif [ -r \"$OPENVPN/crl.pem\" ]; then\n    addArg \"--crl-verify\" \"$OPENVPN/crl.pem\"\nfi\n\nip -6 route show default 2>/dev/null\nif [ $? = 0 ]; then\n    echo \"Checking IPv6 Forwarding\"\n    if [ \"$(</proc/sys/net/ipv6/conf/all/disable_ipv6)\" != \"0\" ]; then\n        echo \"Sysctl error for disable_ipv6, please run docker with '--sysctl net.ipv6.conf.all.disable_ipv6=0'\"\n    fi\n\n    if [ \"$(</proc/sys/net/ipv6/conf/default/forwarding)\" != \"1\" ]; then\n        echo \"Sysctl error for default forwarding, please run docker with '--sysctl net.ipv6.conf.default.forwarding=1'\"\n    fi\n\n    if [ \"$(</proc/sys/net/ipv6/conf/all/forwarding)\" != \"1\" ]; then\n        echo \"Sysctl error for all forwarding, please run docker with '--sysctl net.ipv6.conf.all.forwarding=1'\"\n    fi\nfi\n\necho \"Running 'openvpn ${ARGS[@]} ${USER_ARGS[@]}'\"\nexec openvpn ${ARGS[@]} ${USER_ARGS[@]}\n"
  },
  {
    "path": "bin/ovpn_status",
    "content": "#!/bin/sh\n\n#\n# Get OpenVPN server status\n#\nif [ \"$DEBUG\" == \"1\" ]; then\n  set -x\nfi\n\nset -e\n\ntail -F /tmp/openvpn-status.log\n"
  },
  {
    "path": "docs/advanced.md",
    "content": "# Advanced Configurations\n\nThe [`ovpn_genconfig`](/bin/ovpn_genconfig) script is intended for simple configurations that apply to the majority of the users.  If your use case isn't general, it likely won't be supported.  This document aims to explain how to work around that.\n\n## Create host volume mounts rather than data volumes\n\n* Refer to the Quick Start document, and substitute `-v $OVPN_DATA:/etc/openvpn` with `-v /path/on/host/openvpn0:/etc/openvpn`\n* Quick example that is likely to be out of date, but here's how to get started:\n\n        mkdir openvpn0\n        cd openvpn0\n        docker run --rm -v $PWD:/etc/openvpn kylemanna/openvpn ovpn_genconfig -u udp://VPN.SERVERNAME.COM:1194\n        docker run --rm -v $PWD:/etc/openvpn -it kylemanna/openvpn ovpn_initpki\n        vim openvpn.conf\n        docker run --rm -v $PWD:/etc/openvpn -it kylemanna/openvpn easyrsa build-client-full CLIENTNAME nopass\n        docker run --rm -v $PWD:/etc/openvpn kylemanna/openvpn ovpn_getclient CLIENTNAME > CLIENTNAME.ovpn\n\n* Start the server with:\n\n        docker run -v $PWD:/etc/openvpn -d -p 1194:1194/udp --cap-add=NET_ADMIN kylemanna/openvpn\n"
  },
  {
    "path": "docs/backup.md",
    "content": "# Backing Up Configuration and Certificates\n\n## Security\n\nThe resulting archive from this backup contains all credential to impersonate the server at a minimum.  If the client's private keys are generated using the EasyRSA utility then it also contains the client certificates that could be used to impersonate said clients.  Most importantly, if the certificate authority key is in this archive (as it is given the quick start directions), then a adversary could generate certificates at will.\n\nI'd recommend encrypting the archive with something strong (e.g. gpg or openssl + AES).  For the paranoid keep backup offline.  For the [truly paranoid users](/docs/paranoid.md), never keep any keys (i.e. client and certificate authority) in the docker container to begin with :).\n\n\n**TL;DR Protect the resulting archive file.  Ensure there is very limited access to it.**\n\n## Backup to Archive\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn tar -cvf - -C /etc openvpn | xz > openvpn-backup.tar.xz\n\n## Restore to New Data Volume\n\nCreates an volume container named `$OVPN_DATA` to extract the data to.\n\n    docker volume create --name $OVPN_DATA\n    xzcat openvpn-backup.tar.xz | docker run -v $OVPN_DATA:/etc/openvpn -i kylemanna/openvpn tar -xvf - -C /etc\n"
  },
  {
    "path": "docs/clients.md",
    "content": "# Advanced Client Management\n\n## Client Configuration Mode\n\nThe [`ovpn_getclient`](/bin/ovpn_getclient) can produce two different versions of the configuration.\n\n1. combined (default): All needed configuration and cryptographic material is in one file (Use \"combined-save\" to write the configuration file in the same path as the separated parameter does).\n2. separated: Separated files.\n\nNote that some client software might be picky about which configuration format it accepts.\n\n## Client List\n\nSee an overview of the configured clients, including revocation and expiration status:\n\n    docker run --rm -it -v $OVPN_DATA:/etc/openvpn kylemanna/openvpn ovpn_listclients\n\n The output is generated using `openssl verify`. Error codes from the verification process different from `X509_V_ERR_CERT_HAS_EXPIRED` or `X509_V_ERR_CERT_REVOKED` will show the status `INVALID`.\n\n## Batch Mode\n\nIf you have more than a few clients, you will want to generate and update your client configuration in batch. For this task the script [`ovpn_getclient_all`](/bin/ovpn_getclient_all) was written, which writes out the configuration for each client to a separate directory called `clients/$cn`.\n\nExecute the following to generate the configuration for all clients:\n\n    docker run --rm -it -v $OVPN_DATA:/etc/openvpn --volume /tmp/openvpn_clients:/etc/openvpn/clients kylemanna/openvpn ovpn_getclient_all\n\nAfter doing so, you will find the following files in each of the `$cn` directories:\n\n    ca.crt\n    $cn-combined.ovpn # Combined configuration file format. If your client recognices this file then only this file is needed.\n    $cn.ovpn          # Separated configuration. This configuration file requires the other files ca.crt dh.pem $cn.crt $cn.key ta.key\n    $cn.crt\n    $cn.key\n    ta.key\n\n## Revoking Client Certificates\n\nRevoke `client1`'s certificate and generate the certificate revocation list (CRL) using [`ovpn_revokeclient`](/bin/ovpn_revokeclient) script :\n\n    docker run --rm -it -v $OVPN_DATA:/etc/openvpn kylemanna/openvpn ovpn_revokeclient client1\n\nThe OpenVPN server will read this change every time a client connects (no need to restart server) and deny clients access using revoked certificates.\n\nYou can optionally pass `remove` as second parameter to ovpn_revokeclient to remove the corresponding crt, key and req files :\n\n    docker run --rm -it -v $OVPN_DATA:/etc/openvpn kylemanna/openvpn ovpn_revokeclient client1 remove\n"
  },
  {
    "path": "docs/debug.md",
    "content": "# Debugging\n\nRandom things I do to debug the containers.\n\n## Login Shells\n\n* Create a shell in the running docker container with `docker exec`.\n* To modify the data, you can also mount the data container and modify it with\n\n        docker run --rm -it -v $OVPN_DATA:/etc/openvpn kylemanna/openvpn bash -l\n\n## Stream OpenVPN Logs\n\n1. Get the container's name or container ID:\n\n        root@vpn:~/docker-openvpn# docker ps\n        CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS                    NAMES\n        ed335aaa9b82        kylemanna/openvpn:latest   ovpn_run            5 minutes ago       Up 5 minutes        0.0.0.0:1194->1194/udp   sad_lovelace\n\n2. Tail the logs:\n\n        root@vpn:~/docker-openvpn# docker logs -f sad_lovelace\n        + mkdir -p /dev/net\n        + [ ! -c /dev/net/tun ]\n        + mknod /dev/net/tun c 10 200\n        + [ ! -d /etc/openvpn/ccd ]\n        + iptables -t nat -A POSTROUTING -s 192.168.254.0/24 -o eth0 -j MASQUERADE\n        + iptables -t nat -A POSTROUTING -s 192.168.255.0/24 -o eth0 -j MASQUERADE\n        + conf=/etc/openvpn/openvpn.conf\n        + [ ! -s /etc/openvpn/openvpn.conf ]\n        + conf=/etc/openvpn/udp1194.conf\n        + openvpn --config /etc/openvpn/udp1194.conf\n        Tue Jul  1 06:56:48 2014 OpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Mar 17 2014\n        Tue Jul  1 06:56:49 2014 Diffie-Hellman initialized with 2048 bit key\n        Tue Jul  1 06:56:49 2014 Control Channel Authentication: using '/etc/openvpn/pki/ta.key' as a OpenVPN static key file\n        Tue Jul  1 06:56:49 2014 Outgoing Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication\n        Tue Jul  1 06:56:49 2014 Incoming Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication\n        Tue Jul  1 06:56:49 2014 Socket Buffers: R=[212992->131072] S=[212992->131072]\n\n"
  },
  {
    "path": "docs/docker-compose.md",
    "content": "# Quick Start with docker-compose\n\n* Add a new service in docker-compose.yml\n\n```yaml\nversion: '2'\nservices:\n  openvpn:\n    cap_add:\n     - NET_ADMIN\n    image: kylemanna/openvpn\n    container_name: openvpn\n    ports:\n     - \"1194:1194/udp\"\n    restart: always\n    volumes:\n     - ./openvpn-data/conf:/etc/openvpn\n```\n\n\n* Initialize the configuration files and certificates\n\n```bash\ndocker-compose run --rm openvpn ovpn_genconfig -u udp://VPN.SERVERNAME.COM\ndocker-compose run --rm openvpn ovpn_initpki\n```\n\n* Fix ownership (depending on how to handle your backups, this may not be needed)\n\n```bash\nsudo chown -R $(whoami): ./openvpn-data\n```\n\n* Start OpenVPN server process\n\n```bash\ndocker-compose up -d openvpn\n```\n\n* You can access the container logs with\n\n```bash\ndocker-compose logs -f\n```\n\n* Generate a client certificate\n\n```bash\nexport CLIENTNAME=\"your_client_name\"\n# with a passphrase (recommended)\ndocker-compose run --rm openvpn easyrsa build-client-full $CLIENTNAME\n# without a passphrase (not recommended)\ndocker-compose run --rm openvpn easyrsa build-client-full $CLIENTNAME nopass\n```\n\n* Retrieve the client configuration with embedded certificates\n\n```bash\ndocker-compose run --rm openvpn ovpn_getclient $CLIENTNAME > $CLIENTNAME.ovpn\n```\n\n* Revoke a client certificate\n\n```bash\n# Keep the corresponding crt, key and req files.\ndocker-compose run --rm openvpn ovpn_revokeclient $CLIENTNAME\n# Remove the corresponding crt, key and req files.\ndocker-compose run --rm openvpn ovpn_revokeclient $CLIENTNAME remove\n```\n\n## Debugging Tips\n\n* Create an environment variable with the name DEBUG and value of 1 to enable debug output (using \"docker -e\").\n\n```bash\ndocker-compose run -e DEBUG=1 -p 1194:1194/udp openvpn\n```\n"
  },
  {
    "path": "docs/docker-openvpn.te",
    "content": "module docker-openvpn 1.0;\n\nrequire {\n\ttype svirt_lxc_net_t;\n\tclass tun_socket create;\n}\n\n#============= svirt_lxc_net_t ==============\nallow svirt_lxc_net_t self:tun_socket create;\n\n"
  },
  {
    "path": "docs/docker.md",
    "content": "# Install Latest Docker Service\n\nDocker included with some distributions lags far behind upstream.  This guide aims to provide a quick and reliable way to install or update it.\n\nIt is recommended to use platforms that support systemd as future versions of this docker image may require systemd to help with some tasks:\n\n* Fedora\n* Debian 8.1+\n\n## Debian / Ubuntu\n\n### Step 1 — Set Up Docker\n\nDocker is moving fast and Debian / Ubuntu's long term support (LTS) policy doesn't keep up. To work around this we'll install a PPA that will get us the latest version of Docker. For Debian Jessie users, just install docker.io from jessie-backports.\n\nEnsure dependencies are installed:\n\n    sudo apt-get update && sudo apt-get install -y apt-transport-https curl\n\nAdd the upstream Docker repository package signing key. The apt-key command uses elevated privileges via sudo, so a password prompt for the user's password may appear:\n\n    curl -L https://get.docker.com/gpg | sudo apt-key add -\n\nAdd the upstream Docker repository to the system list:\n\n    echo deb https://get.docker.io/ubuntu docker main | sudo tee /etc/apt/sources.list.d/docker.list\n\nUpdate the package list and install the Docker package:\n\n    sudo apt-get update && sudo apt-get install -y lxc-docker\n\nAdd your user to the `docker` group to enable communication with the Docker daemon as a normal user, where `$USER` is your username. Exit and log in again for the new group to take effect:\n\n    sudo usermod -aG docker $USER\n\nAfter **re-logging in** verify the group membership using the id command. The expected response should include docker like the following example:\n\n    uid=1001(test0) gid=1001(test0) groups=1001(test0),27(sudo),999(docker)\n\n### Step 2 — Test Docker\n\nRun a Debian jessie docker container:\n\n    docker run --rm -it debian:jessie bash -l\n\nOnce inside the container you'll see the `root@<container id>:/#` prompt signifying that the current shell is in a Docker container. To confirm that it's different from the host, check the version of Debian running in the container:\n\n    cat /etc/issue.net\n\nExpected result:\n\n    Debian GNU/Linux 8\n"
  },
  {
    "path": "docs/faqs.md",
    "content": "# Frequently Asked Questions\n\n## How do I edit `openvpn.conf`?\n\nUse a Docker image with an editor and connect the volume container:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn vi /etc/openvpn/openvpn.conf\n\n\n## Why not keep everything in one image?\n\nThe run-time image (`kylemanna/openvpn`) is intended to be an ephemeral image. Nothing should be saved in it so that it can be re-downloaded and re-run when updates are pushed (i.e. newer version of OpenVPN or even Debian). The data container contains all this data and is attached at run time providing a safe home.\n\nIf it was all in one container, an upgrade would require a few steps to extract all the data, perform some upgrade import, and re-run. This technique is also prone to people losing their EasyRSA PKI when they forget where it was.  With everything in the data container upgrading is as simple as re-running `docker pull kylemanna/openvpn` and then `docker run ... kylemanna/openvpn`.\n\n## How do I set up a split tunnel?\n\nSplit tunnels are configurations where only some of the traffic from a client goes to the VPN, with the remainder routed through the normal non-VPN interfaces. You'll want to disable a default route (-d) when you generate the configuration, but still use NAT (-N) to keep network address translation enabled.\n\n    ovpn_genconfig -N -d ...\n\n## I need to add some extra configurations to openvpn.conf, How can I do that ?\n\nYou can pass multiple (**-e**) options to `ovpn_genconfig`. For example, if you need to add _'duplicate-cn'_ and _'topology subnet'_ to the server configuration you could do something like this:\n\n    ovpn_genconfig -e 'duplicate-cn' -e 'topology subnet' -u udp://VPN.SERVERNAME.COM\n"
  },
  {
    "path": "docs/ipv6.md",
    "content": "# IPv6 Support\n\nThis is a work in progress, more polish to follow.\n\n## Tunnel IPv6 Address To OpenVPN Clients\n\nThis feature is advanced and recommended only for those who already have a functioning IPv4 tunnel and know how IPv6 works.\n\nSystemd is used to setup a static route and Debian 8.1 or later is recommended as the host distribution.  Others probably work, but haven't been tested.\n\n\n### Step 1 — Setup IPv6 on the Host Machine\n\nThe tutorial uses a free tunnel from [tunnelbroker.net](https://tunnelbroker.net/) to get a /64 and /48 prefix allocated to me.  The tunnel endpoint is less then 3 ms away from Digital Ocean's San Francisco datacenter.\n\nPlace the following in `/etc/network/interfaces`.  Replace `PUBLIC_IP` with your host's public IPv4 address and replace 2001:db8::2 and 2001:db8::1 with the corresponding tunnel endpoints:\n\n    auto he-ipv6\n    iface he-ipv6 inet6 v4tunnel\n        address 2001:db8::2\n        netmask 64\n        endpoint 72.52.104.74\n        local PUBLIC_IP\n        ttl 255\n        gateway 2001:db8::1\n\nBring the interface up:\n\n    ifup he-ipv6\n\nTest that IPv6 works on the host:\n\n    ping6 google.com\n\nIf this doesn't work, figure it out.  It may be necessary to add an firewall rule to allow IP protocol 41 through the firewall.\n\n\n### Step 2 — Update Docker's Init To Enable IPv6 Support\n\nAdd the `--ipv6` to the Docker daemon invocation.\n\nOn **Ubuntu** and old versions of Debian Append the `--ipv6` argument to the `DOCKER_OPTS` variable in:\n\n    /etc/default/docker\n\nOn modern **systemd** distributions copy the service file and modify it and reload the service:\n\n    sed -e 's:^\\(ExecStart.*\\):\\1 --ipv6:' /lib/systemd/system/docker.service | tee /etc/systemd/system/docker.service\n    systemctl restart docker.service\n\n\n### Step 3 — Setup the systemd Unit File\n\nCopy the systemd init file from the docker-openvpn /init directory of the repository and install into `/etc/systemd/system/docker-openvpn.service`\n\n    curl -o /etc/systemd/system/docker-openvpn@.service 'https://raw.githubusercontent.com/kylemanna/docker-openvpn/dev/init/docker-openvpn%40.service'\n\nEdit the file, replace `IP6_PREFIX` value with the value of your /64 prefix.\n\n    vi /etc/systemd/system/docker-openvpn@.service\n\nFinally, reload systemd so the changes take affect:\n\n    systemctl daemon-reload\n\n### Step 4 — Start OpenVPN\n\nEnsure that OpenVPN has been initialized and configured as described in the top level `README.md`.\n\nStart the systemd service file specifying the volume container suffix as the instance.  For example, `INSTANCE=test0` has a docker volume container named `ovpn-data-test0` and service will create `ovpn-test0` container:\n\n    systemctl start docker-openvpn@test0\n\nVerify logs if needed:\n\n    systemctl status docker-openvpn@test0\n    docker logs ovpn-test0\n\n### Step 4 — Modify Client Config for IPv6 Default Route\n\nAppend the default route for the public Internet:\n\n    echo \"route-ipv6 2000::/3\" >> clientname.ovpn\n\n### Step 5 — Start up Client\n\nIf all went according to plan, then `ping6 2600::` and `ping6 google.com` should work.\n\nFire up a web browser and attempt to navigate to [https://ipv6.google.com](https://ipv6.google.com).\n\n\n## Connect to the OpenVPN Server Over IPv6\n\nThis feature requires a docker daemon with working IPv6 support.\n\nThis will allow connections over IPv4 and IPv6.\n\nGenerate server configuration with the udp6 or tcp6 protocol:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u udp6://VPN.SERVERNAME.COM\n    docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u tcp6://VPN.SERVERNAME.COM\n"
  },
  {
    "path": "docs/otp.md",
    "content": "# Using two factor authentication for users\n\nInstead of relying on complex passwords for client certificates (that usually get written somewhere) this image\nprovides support for two factor authentication with OTP devices.\n\nThe most common app that provides OTP generation is Google Authenticator ([iOS](https://itunes.apple.com/it/app/google-authenticator/id388497605?mt=8) and\n[Android](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=it)) you can download it\nand use this image to generate user configuration.\n\n## Usage\n\nIn order to enable two factor authentication the following steps are required.\n\n* Choose a more secure [cipher](https://community.openvpn.net/openvpn/wiki/SWEET32) to use because since [OpenVPN 2.3.13](https://community.openvpn.net/openvpn/wiki/ChangesInOpenvpn23#OpenVPN2.3.13) the default openvpn cipher BF-CBC will cause a renegotiated connection every 64 MB of data\n\n* Generate server configuration with `-2` and `-C $CIPHER` options\n\n        docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u udp://vpn.example.com -2 -C $CIPHER\n\n* Generate your client certificate (possibly without a password since you're using OTP)\n\n        docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn easyrsa build-client-full <user> nopass\n\n* Generate authentication configuration for your client. -t is needed to show QR code, -i is optional for interactive usage\n\n        docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn ovpn_otp_user <user>\n\nThe last step will generate OTP configuration for the provided user with the following options\n\n```\ngoogle-authenticator --time-based --disallow-reuse --force --rate-limit=3 --rate-time=30 --window-size=3 \\\n    -l \"${1}@${OVPN_CN}\" -s /etc/openvpn/otp/${1}.google_authenticator\n```\n\nIt will also show a shell QR code in terminal you can scan with the Google Authenticator application. It also provides\na link to a google chart url that will display a QR code for the authentication.\n\n**Do not share QR code (or generated url) with anyone but final user, that is your second factor for authentication\n  that is used to generate OTP codes**\n\nHere's an example QR code generated for an hypotetical user@example.com user.\n\n![Example QR Code](https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/user@example.com%3Fsecret%3DKEYZ66YEXMXDHPH5)\n\nGenerate client configuration for `<user>` and import it in OpenVPN client. On connection it will prompt for user and password.\n Enter your username and a 6 digit code generated by Authenticator app and you're logged in.\n\n## TL;DR\n\nUnder the hood this configuration will setup an `openvpn` PAM service configuration (`/etc/pam.d/openvpn`)\nthat relies on the awesome [Google Authenticator PAM module](https://github.com/google/google-authenticator).\nIn this configuration the `auth` part of PAM flow is managed by OTP codes and the `account` part is not enforced\n because you're likely dealing with virtual users and you do not want to create a system account for every VPN user.\n\n`ovpn_otp_user` script will store OTP credentials under `/etc/openvpn/otp/<user>.google_authentication`. In this\n way when you take a backup OTP users are included as well.\n\nFinally it will enable the openvpn plugin `openvpn-plugin-auth-pam.so` in server configuration and append the\n`auth-user-pass` directive in client configuration.\n\n## Debug\n\nIf something is not working you can verify your PAM setup with these commands\n\n```\n# Start a shell in container\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn bash\n# Then in container you have pamtester utility already installed\nwhich pamtester\n# To check authentication use this command that will prompt for a valid code from Authenticator APP\npamtester -v openvpn <user> authenticate\n```\n\nIn the last command `<user>` should be replaced by the exact string you used in the ovpn_otp_user command.\n\nIf you configured everything correctly you should get authenticated by entering a OTP code from the app.\n"
  },
  {
    "path": "docs/paranoid.md",
    "content": "# Advanced security\n\n## Keep the CA root key safe\nAs mentioned in the [backup section](/docs/backup.md), there are good reasons to not generate the CA and/or leave it on the server. This document describes how you can generate the CA and all your certificates on a secure machine and then copy only the needed files (which never includes the CA root key obviously ;) ) to the server(s) and clients.\n\nExecute the following commands. Note that you might want to change the volume `$PWD` or use a data docker container for this.\n\n    docker run --net=none --rm -t -i -v $PWD:/etc/openvpn kylemanna/openvpn ovpn_genconfig -u udp://VPN.SERVERNAME.COM\n    docker run --net=none --rm -t -i -v $PWD:/etc/openvpn kylemanna/openvpn ovpn_initpki\n    docker run --net=none --rm -t -i -v $PWD:/etc/openvpn kylemanna/openvpn ovpn_copy_server_files\n\nThe [`ovpn_copy_server_files`](/bin/ovpn_copy_server_files) script puts all the needed configuration in a subdirectory which defaults to `$OPENVPN/server`. All you need to do now is to copy this directory to the server and you are good to go.\n\n## Crypto Hardening\n\nIf you want to select the ciphers used by OpenVPN the following parameters of the `ovpn_genconfig` might interest you:\n\n    -T    Encrypt packets with the given cipher algorithm instead of the default one (tls-cipher).\n    -C    A list of allowable TLS ciphers delimited by a colon (cipher).\n    -a    Authenticate  packets with HMAC using the given message digest algorithm (auth).\n\n\nThe following options have been tested successfully:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --net=none --rm kylemanna/openvpn ovpn_genconfig -C 'AES-256-CBC' -a 'SHA384'\n\nChanging the `tls-cipher` option seems to be more complicated because some clients (namely NetworkManager in Debian Jessie) seem to have trouble with this. Running `openvpn` manually also did not solve the issue:\n\n    TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)\n    TLS Error: TLS handshake failed\n\n## EasyRSA and 4096 bit RSA Keys\n\nEasyRSA will generate 4096 bit RSA keys when the `-e EASYRSA_KEY_SIZE=4096` argument is added to `ovpn_initpki` and `easyrsa build-client-full` commands.\n\n    docker run -e EASYRSA_KEY_SIZE=4096 -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn ovpn_initpki\n    docker run -e EASYRSA_KEY_SIZE=4096 -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn easyrsa build-client-full CLIENTNAME nopass\n\n## Logging and stdout\n\nBecause you are running within Docker, remember that any command that generates output to stdout may also log that output through Docker's log-driver mechanism. That may mean that e.g. keying material generated by `ovpn_getclient` will be logged somewhere that you don't want it to be logged.\n\nA simple way to avoid having Docker log output for a given command is to run with `--log-driver=none`, e.g\n\n    docker run -v $OVPN_DATA:/etc/openvpn --log-driver=none --rm kylemanna/openvpn ovpn_getclient USER > USER.ovpn\n\n## Additional Resources\n\nHave a look at the [Applied-Crypto-Hardening](https://github.com/BetterCrypto/Applied-Crypto-Hardening/tree/master/src/configuration/VPNs/OpenVPN) project for more examples.\n"
  },
  {
    "path": "docs/selinux.md",
    "content": "# For hosts that use SELinux\n\nTry this [policy file](docker-openvpn.te)\n\nRun these commands to compile and load it:\n\n```\ncheckmodule -M -m -o docker-openvpn.mod docker-openvpn.te\nsemodule_package -o docker-openvpn.pp -m docker-openvpn.mod\nsudo semodule -i docker-openvpn.pp\n```\n\nAlso, some configurations don't allow containers to load kernel modules, so on the host run this:\n\n```\nsudo modprobe tun\n```\n\nSo the container doesn't have to load the `tun` module.\n\n\n# Still having issues?\n\nIn January 2016, Fedora based systems got an update that fixed an issue for labeling namespaced net objects under /proc\nto fix, make sure that you have run `sudo dnf update` and you need to reboot to load the new policies\n"
  },
  {
    "path": "docs/static-ips.md",
    "content": "# Static IP Addresses\n\nThe docker image is setup for static client configuration on the 192.168.254.0/24 subnet.  To use it follow the Quick Start section below.  Note that the IP addresses octets need to be picked special, see [OpenVPN Documentation](https://openvpn.net/index.php/open-source/documentation/howto.html#policy) for more details.\n\n## Quick Start\n\n1. Create a client specific configuration:\n\n        $ echo \"ifconfig-push 192.168.254.1 192.168.254.2\" | docker run -v $OVPN_DATA:/etc/openvpn -i --rm kylemanna/openvpn tee /etc/openvpn/ccd/CERT_COMMON_NAME\n        ifconfig-push 192.168.254.1 192.168.254.2\n\n2. Wait for client to reconnect if necessary\n\n## Advanced Admin\n\nLogin to the data volume with a `bash` container, note only changes in /etc/openvpn will persist:\n\n    docker run -v $OVPN_DATA:/etc/openvpn -it --rm kylemanna/openvpn bash -l\n\n## Upgrading from Old OpenVPN Configurations\n\nIf you're running an old configuration and need to upgrade it to pull in the ccd directory run the following:\n\n    docker run  -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig\n"
  },
  {
    "path": "docs/systemd.md",
    "content": "# Docker + OpenVPN systemd Service\n\nThe systemd service aims to make the update and invocation of the\n`docker-openvpn` container seamless.  It automatically downloads the latest\n`docker-openvpn` image and instantiates a Docker container with that image.  At\nshutdown it cleans-up the old container.\n\nIn the event the service dies (crashes, or is killed) systemd will attempt to\nrestart the service every 10 seconds until the service is stopped with\n`systemctl stop docker-openvpn@NAME.service`.\n\nA number of IPv6 hacks are incorporated to workaround Docker shortcomings and\nare harmless for those not using IPv6.\n\nTo use and enable automatic start by systemd:\n\n1. Create a Docker volume container named `ovpn-data-NAME` where `NAME` is the\n   user's choice to describe the use of the container.  In this example\n   configuration, `NAME=example`.\n   \n        OVPN_DATA=\"ovpn-data-example\"\n        docker volume create --name $OVPN_DATA\n   \n2. Initialize the data container, but don't start the container :\n   \n       docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u udp://VPN.SERVERNAME.COM\n       docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn ovpn_initpki\n   \n3. Download the [docker-openvpn@.service](https://raw.githubusercontent.com/kylemanna/docker-openvpn/master/init/docker-openvpn%40.service)\n   file to `/etc/systemd/system`:\n\n        curl -L https://raw.githubusercontent.com/kylemanna/docker-openvpn/master/init/docker-openvpn%40.service | sudo tee /etc/systemd/system/docker-openvpn@.service\n\n4. Enable and start the service with:\n\n        systemctl enable --now docker-openvpn@example.service\n\n5. Verify service start-up with:\n\n        systemctl status docker-openvpn@example.service\n        journalctl --unit docker-openvpn@example.service\n\nFor more information, see the [systemd manual pages](https://www.freedesktop.org/software/systemd/man/index.html).\n"
  },
  {
    "path": "docs/tcp.md",
    "content": "# TCP Protocol\n\n## TCP vs. UDP - Pros & Cons\nBy default, OpenVPN is configured to use the UDP protocol.  Because UDP incurs minimal protocol overhead (for example, no acknowledgment is required upon successful packet receipt), it can sometimes result in slightly faster throughput.  However, in situations where VPN service is needed over an unreliable connection, the user experience can benefit from the extra diagnostic features of the TCP protocol.\n\nAs an example, users connecting from an airplane wifi network may experience high packet drop rates, where the error detection and sliding window control of TCP can more readily adjust to the inconsistent connection.\n\nAnother example would be trying to open a VPN connection from within a very restrictive network. In some cases port 1194, or even UDP traffic on any port, may be restricted by network policy. Because TCP traffic on port 443 is used for normal TLS (https) web browsing, it is very unlikely to be blocked.\n\n## Using TCP\nThose requiring TCP connections should initialize the data container by specifying the TCP protocol and port number:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig -u tcp://VPN.SERVERNAME.COM:443\n    docker run -v $OVPN_DATA:/etc/openvpn --rm -it kylemanna/openvpn ovpn_initpki\n\nBecause the server container always exposes port 1194, regardless of the\nspecified protocol, adjust the mapping appropriately:\n\n    docker run -v $OVPN_DATA:/etc/openvpn -d -p 443:1194/tcp --cap-add=NET_ADMIN kylemanna/openvpn\n\n## Running a Second Fallback TCP Container\nInstead of choosing between UDP and TCP, you can use both. A single instance of OpenVPN can only listen for a single protocol on a single port, but this image makes it easy to run two instances simultaneously. After building, configuring, and starting a standard container listening for UDP traffic on 1194, you can start a second container listening for tcp traffic on port 443:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm -p 443:1194/tcp --cap-add=NET_ADMIN kylemanna/openvpn ovpn_run --proto tcp\n\n`ovpn_run` will load all the values from the default config file, and `--proto tcp` will override the protocol setting.\n\nThis allows you to use UDP most of the time, but fall back to TCP on the rare occasion that you need it.\n\nNote that you will need to configure client connections manually. At this time it is not possible to generate a client config that will automatically fall back to the TCP connection.\n\n## Forward HTTP/HTTPS connection to another TCP port\nYou might run into cases where you want your OpenVPN server listening on TCP port 443 to allow connection behind a restricted network, but you already have a webserver on your host running on that port. OpenVPN has a built-in option named `port-share` that allow you to proxy incoming traffic that isn't OpenVPN protocol to another host and port.\n\nFirst, change the listening port of your existing webserver (for instance from 443 to 4433).\n\nThen initialize the data container by specifying the TCP protocol, port 443 and the port-share option:\n\n    docker run -v $OVPN_DATA:/etc/openvpn --rm kylemanna/openvpn ovpn_genconfig \\\n    -u tcp://VPN.SERVERNAME.COM:443 \\\n    -e 'port-share VPN.SERVERNAME.COM 4433'\n    \nThen proceed to initialize the pki, create your users and start the container as usual.\n    \nThis will proxy all non OpenVPN traffic incoming on TCP port 443 to TCP port 4433 on the same host. This is currently only designed to work with HTTP or HTTPS protocol.\n"
  },
  {
    "path": "init/docker-openvpn@.service",
    "content": "#\n# Docker + OpenVPN systemd service\n#\n# Author: Kyle Manna <kyle@kylemanna.com>\n# Source: https://github.com/kylemanna/docker-openvpn\n#\n# This service aims to make the update and invocation of the docker-openvpn\n# container seamless.  It automatically downloads the latest docker-openvpn\n# image and instantiates a Docker container with that image.  At shutdown it\n# cleans-up the old container.\n#\n# In the event the service dies (crashes, or is killed) systemd will attempt\n# to restart the service every 10 seconds until the service is stopped with\n# `systemctl stop docker-openvpn@NAME`.\n#\n# A number of IPv6 hacks are incorporated to workaround Docker shortcomings and\n# are harmless for those not using IPv6.\n#\n# To use:\n# 1. Create a Docker volume container named `ovpn-data-NAME` where NAME is the\n#    user's choice to describe the use of the container.\n# 2. Initialize the data container according to the docker-openvpn README, but\n#    don't start the container. Stop the docker container if started.\n# 3. Download this service file to /etc/systemd/service/docker-openvpn@.service\n# 4. Enable and start the service template with:\n#    `systemctl enable --now docker-openvpn@NAME.service`\n# 5. Verify service start-up with:\n#    `systemctl status docker-openvpn@NAME.service`\n#    `journalctl --unit docker-openvpn@NAME.service`\n#\n# For more information, see the systemd manual pages.\n#\n[Unit]\nDescription=OpenVPN Docker Container\nDocumentation=https://github.com/kylemanna/docker-openvpn\nAfter=network.target docker.service\nRequires=docker.service\n\n[Service]\nRestartSec=10\nRestart=always\n\n# Modify IP6_PREFIX to match network config\n#Environment=\"IP6_PREFIX=2001:db8::/64\"\n#Environment=\"ARGS=--config openvpn.conf --server-ipv6 2001:db8::/64\"\nEnvironment=\"NAME=ovpn-%i\"\nEnvironment=\"DATA_VOL=ovpn-data-%i\"\nEnvironment=\"IMG=kylemanna/openvpn:latest\"\nEnvironment=\"PORT=1194:1194/udp\"\n\n# To override environment variables, use local configuration directory:\n# /etc/systemd/system/docker-openvpn@foo.d/local.conf\n# http://www.freedesktop.org/software/systemd/man/systemd.unit.html\n\n# Clean-up bad state if still hanging around\nExecStartPre=-/usr/bin/docker rm -f $NAME\n\n# Attempt to pull new image for security updates\nExecStartPre=-/usr/bin/docker pull $IMG\n\n# IPv6: Ensure forwarding is enabled on host's networking stack (hacky)\n# Would be nice to use systemd-network on the host, but this doesn't work\n# http://lists.freedesktop.org/archives/systemd-devel/2015-June/032762.html\nExecStartPre=/bin/sh -c 'test -z \"$IP6_PREFIX\" && exit 0; sysctl net.ipv6.conf.all.forwarding=1'\n\n# Main process\nExecStart=/usr/bin/docker run --rm --cap-add=NET_ADMIN -v ${DATA_VOL}:/etc/openvpn --name ${NAME} -p ${PORT} ${IMG} ovpn_run $ARGS\n\n# IPv6: Add static route for IPv6 after it starts up\nExecStartPost=/bin/sh -c 'test -z \"${IP6_PREFIX}\" && exit 0; sleep 1; ip route replace ${IP6_PREFIX} via $(docker inspect -f \"{{ .NetworkSettings.GlobalIPv6Address }}\" $NAME ) dev docker0'\n\n# IPv6: Clean-up\nExecStopPost=/bin/sh -c 'test -z \"$IP6_PREFIX\" && exit 0; ip route del $IP6_PREFIX dev docker0'\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "init/upstart.init",
    "content": "# Copy to /etc/init/docker-openvpn.conf\ndescription \"Docker container for OpenVPN server\"\nstart on filesystem and started docker\nstop on runlevel [!2345]\nrespawn\nscript\n  exec docker run -v ovpn-data-example:/etc/openvpn --rm -p 1194:1194/udp --cap-add=NET_ADMIN kylemanna/openvpn\nend script\n"
  },
  {
    "path": "otp/openvpn",
    "content": "# Uses google authenticator library as PAM module using a single folder for all users tokens\n# User root is required to stick with an hardcoded user when trying to determine user id and allow unexisting system users\n# See https://github.com/google/google-authenticator-libpam#usersome-user\nauth required pam_google_authenticator.so secret=/etc/openvpn/otp/${USER}.google_authenticator user=root\n\n# Accept any user since we're dealing with virtual users there's no need to have a system account (pam_unix.so)\naccount sufficient pam_permit.so\n"
  },
  {
    "path": "test/README.md",
    "content": "# Tests\n\nPhilosophy is to not re-invent the wheel while allowing users to quickly test repository specific tests.\n\nExample invocation from top-level of repository:\n\n    docker build -t kylemanna/openvpn .\n    test/run.sh kylemanna/openvpn\n    # Be sure to pull kylemanna/openvpn:latest after you're done testing\n\nMore details: https://github.com/docker-library/official-images/tree/master/test\n\n## Continuous Integration\n\nThe set of scripts defined by `config.sh` are run every time a pull request or push to the repository is made.\n\n## Maintenance\n\nPeriodically these scripts may need to be synchronized with their upsteam source.  Would be nice to be able to just use them from upstream if it such a feature is added later to avoid having to copy them in place.\n"
  },
  {
    "path": "test/client/wait-for-connect.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\n\nOPENVPN_CONFIG=${1:-/client/config.ovpn}\n\n# For some reason privileged mode creates the char device and cap-add=NET_ADMIN doesn't\nmkdir -p /dev/net\nif [ ! -c /dev/net/tun ]; then\n    mknod /dev/net/tun c 10 200\nfi\n\n# Run in background using bash job management, setup trap to clean-up\ntrap \"{ jobs -p | xargs -r kill; wait; }\" EXIT\nopenvpn --config \"$OPENVPN_CONFIG\" --management 127.0.0.1 9999 &\n\n# Spin waiting for interface to exist signifying connection\ntimeout=10\nfor i in $(seq $timeout); do\n    # Allow to start-up\n    sleep 0.5\n\n    # Use bash magic to open tcp socket on fd 3 and break when successful\n    exec 3<>/dev/tcp/127.0.0.1/9999 && break\ndone\n\nif [ $i -ge $timeout ]; then\n    echo \"Error connecting to OpenVPN mgmt interface, i=$i, exiting.\"\n    exit 2\nfi\n\n# Consume all header input and echo, look for errors here\nwhile read -t 0.1 <&3; do echo $REPLY; done\n\n# Request state over mgmt interface\ntimeout=10\nfor i in $(seq $timeout); do\n    echo \"state\" >&3\n    state=$(head -n1 <&3)\n    echo -n \"$state\" | grep -q 'CONNECTED,SUCCESS' && break\n    sleep 1\ndone\n\nif [ $i -ge $timeout ]; then\n    echo \"Error connecting to OpenVPN, i=$i, exiting.\"\n    exit 3\nfi\n\nexec 3>&-\n"
  },
  {
    "path": "test/config.sh",
    "content": "#!/bin/bash\nset -e\n\ntestAlias+=(\n\t[kylemanna/openvpn]='openvpn'\n)\n\nimageTests+=(\n\t[openvpn]='\n\tparanoid\n        conf_options\n        client\n        basic\n        dual-proto\n        otp\n\tiptables\n\trevocation\n\t'\n)\n"
  },
  {
    "path": "test/run.sh",
    "content": "#!/bin/bash\nset -e\n\ndir=\"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\"\n\nself=\"$(basename \"$0\")\"\n\nusage() {\n\tcat <<EOUSAGE\n\nusage: $self [-t test ...] image:tag [...]\n   ie: $self debian:wheezy\n       $self -t utc python:3\n       $self -t utc python:3 -t python-hy\n\nThis script processes the specified Docker images to test their running\nenvironments.\nEOUSAGE\n}\n\n# arg handling\nopts=\"$(getopt -o 'ht:c:?' --long 'dry-run,help,test:,config:' -- \"$@\" || { usage >&2 && false; })\"\neval set -- \"$opts\"\n\ndeclare -A argTests=()\ndeclare -a configs=()\ndryRun=\nwhile true; do\n\tflag=$1\n\tshift\n\tcase \"$flag\" in\n\t\t--dry-run) dryRun=1 ;;\n\t\t--help|-h|'-?') usage && exit 0 ;;\n\t\t--test|-t) argTests[\"$1\"]=1 && shift ;;\n\t\t--config|-c) configs+=(\"$(readlink -f \"$1\")\") && shift ;;\n\t\t--) break ;;\n\t\t*)\n\t\t\t{\n\t\t\t\techo \"error: unknown flag: $flag\"\n\t\t\t\tusage\n\t\t\t} >&2\n\t\t\texit 1\n\t\t\t;;\n\tesac\ndone\n\nif [ $# -eq 0 ]; then\n\tusage >&2\n\texit 1\nfi\n\n# declare configuration variables\ndeclare -a globalTests=()\ndeclare -A testAlias=()\ndeclare -A imageTests=()\ndeclare -A globalExcludeTests=()\ndeclare -A explicitTests=()\n\n# if there are no user-specified configs, use the default config\nif [ ${#configs} -eq 0 ]; then\n\tconfigs+=(\"$dir/config.sh\")\nfi\n\n# load the configs\ndeclare -A testPaths=()\nfor conf in \"${configs[@]}\"; do\n\t. \"$conf\"\n\n\t# Determine the full path to any newly-declared tests\n\tconfDir=\"$(dirname \"$conf\")\"\n\n\tfor testName in ${globalTests[@]} ${imageTests[@]}; do\n\t\t[ \"${testPaths[$testName]}\" ] && continue\n\n\t\tif [ -d \"$confDir/tests/$testName\" ]; then\n\t\t\t# Test directory found relative to the conf file\n\t\t\ttestPaths[$testName]=\"$confDir/tests/$testName\"\n\t\telif [ -d \"$dir/tests/$testName\" ]; then\n\t\t\t# Test directory found in the main tests/ directory\n\t\t\ttestPaths[$testName]=\"$dir/tests/$testName\"\n\t\tfi\n\tdone\ndone\n\ndidFail=\nfor dockerImage in \"$@\"; do\n\techo \"testing $dockerImage\"\n\t\n\tif ! docker inspect \"$dockerImage\" &> /dev/null; then\n\t\techo $'\\timage does not exist!'\n\t\tdidFail=1\n\t\tcontinue\n\tfi\n\t\n\trepo=\"${dockerImage%:*}\"\n\ttagVar=\"${dockerImage#*:}\"\n\t#version=\"${tagVar%-*}\"\n\tvariant=\"${tagVar##*-}\"\n\t\n\ttestRepo=$repo\n\t[ -z \"${testAlias[$repo]}\" ] || testRepo=\"${testAlias[$repo]}\"\n\t\n\texplicitVariant=\n\tif [ \\\n\t\t\"${explicitTests[:$variant]}\" \\\n\t\t-o \"${explicitTests[$repo:$variant]}\" \\\n\t\t-o \"${explicitTests[$testRepo:$variant]}\" \\\n\t]; then\n\t\texplicitVariant=1\n\tfi\n\t\n\ttestCandidates=()\n\tif [ -z \"$explicitVariant\" ]; then\n\t\ttestCandidates+=( \"${globalTests[@]}\" )\n\tfi\n\ttestCandidates+=(\n\t\t${imageTests[:$variant]}\n\t)\n\tif [ -z \"$explicitVariant\" ]; then\n\t\ttestCandidates+=(\n\t\t\t${imageTests[$testRepo]}\n\t\t)\n\tfi\n\ttestCandidates+=(\n\t\t${imageTests[$testRepo:$variant]}\n\t)\n\tif [ \"$testRepo\" != \"$repo\" ]; then\n\t\tif [ -z \"$explicitVariant\" ]; then\n\t\t\ttestCandidates+=(\n\t\t\t\t${imageTests[$repo]}\n\t\t\t)\n\t\tfi\n\t\ttestCandidates+=(\n\t\t\t${imageTests[$repo:$variant]}\n\t\t)\n\tfi\n\t\n\ttests=()\n\tfor t in \"${testCandidates[@]}\"; do\n\t\tif [ ${#argTests[@]} -gt 0 -a -z \"${argTests[$t]}\" ]; then\n\t\t\t# skipping due to -t\n\t\t\tcontinue\n\t\tfi\n\t\t\n\t\tif [ \\\n\t\t\t! -z \"${globalExcludeTests[${testRepo}_$t]}\" \\\n\t\t\t-o ! -z \"${globalExcludeTests[${testRepo}:${variant}_$t]}\" \\\n\t\t\t-o ! -z \"${globalExcludeTests[:${variant}_$t]}\" \\\n\t\t\t-o ! -z \"${globalExcludeTests[${repo}_$t]}\" \\\n\t\t\t-o ! -z \"${globalExcludeTests[${repo}:${variant}_$t]}\" \\\n\t\t\t-o ! -z \"${globalExcludeTests[:${variant}_$t]}\" \\\n\t\t]; then\n\t\t\t# skipping due to exclude\n\t\t\tcontinue\n\t\tfi\n\t\t\n\t\ttests+=( \"$t\" )\n\tdone\n\t\n\tcurrentTest=0\n\ttotalTest=\"${#tests[@]}\"\n\tfor t in \"${tests[@]}\"; do\n\t\t(( currentTest+=1 ))\n\t\techo -ne \"\\t'$t' [$currentTest/$totalTest]...\"\n\t\t\n\t\t# run test against dockerImage here\n\t\t# find the script for the test\n\t\tscriptDir=\"${testPaths[$t]}\"\n\t\tif [ -d \"$scriptDir\" ]; then\n\t\t\tscript=\"$scriptDir/run.sh\"\n\t\t\tif [ -x \"$script\" -a ! -d \"$script\" ]; then\n\t\t\t\t# TODO dryRun logic\n\t\t\t\tif output=\"$(\"$script\" $dockerImage)\"; then\n\t\t\t\t\tif [ -f \"$scriptDir/expected-std-out.txt\" ] && ! d=\"$(echo \"$output\" | diff -u \"$scriptDir/expected-std-out.txt\" - 2>/dev/null)\"; then\n\t\t\t\t\t\techo 'failed; unexpected output:'\n\t\t\t\t\t\techo \"$d\"\n\t\t\t\t\t\tdidFail=1\n\t\t\t\t\telse\n\t\t\t\t\t\techo 'passed'\n\t\t\t\t\tfi\n\t\t\t\telse\n\t\t\t\t\techo 'failed'\n\t\t\t\t\tdidFail=1\n\t\t\t\tfi\n\t\t\telse\n\t\t\t\techo \"skipping\"\n\t\t\t\techo >&2 \"error: $script missing, not executable or is a directory\"\n\t\t\t\tdidFail=1\n\t\t\t\tcontinue\n\t\t\tfi\n\t\telse\n\t\t\techo \"skipping\"\n\t\t\techo >&2 \"error: unable to locate test '$t'\"\n\t\t\tdidFail=1\n\t\t\tcontinue\n\t\tfi\n\tdone\ndone\n\nif [ \"$didFail\" ]; then\n\texit 1\nfi\n"
  },
  {
    "path": "test/tests/basic/run.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\n\nOVPN_DATA=basic-data\nCLIENT=travis-client\nIMG=kylemanna/openvpn\nCLIENT_DIR=\"$(readlink -f \"$(dirname \"$BASH_SOURCE\")/../../client\")\"\n\nip addr ls\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_genconfig -u udp://$SERV_IP\n\n# nopass is insecure\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it -e \"EASYRSA_BATCH=1\" -e \"EASYRSA_REQ_CN=Travis-CI Test CA\" $IMG ovpn_initpki nopass\n\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it $IMG easyrsa build-client-full $CLIENT nopass\n\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_getclient $CLIENT | tee $CLIENT_DIR/config.ovpn\n\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_listclients | grep $CLIENT\n\n#\n# Fire up the server and setup a trap to always clean it up\n#\ntrap \"{ jobs -p | xargs -r kill; wait; }\" EXIT\ndocker run --name \"ovpn-test\" -v $OVPN_DATA:/etc/openvpn --rm -e DEBUG --cap-add=NET_ADMIN $IMG &\n\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"ovpn-test\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\nsed -i -e s:$SERV_IP:$SERV_IP_INTERNAL:g ${CLIENT_DIR}/config.ovpn\n\n#\n# Fire up a client in a container since openvpn is disallowed by Travis-CI\n#\ndocker run --rm --cap-add=NET_ADMIN -e DEBUG --volume $CLIENT_DIR:/client $IMG /client/wait-for-connect.sh\n\n#\n# Celebrate\n#\ncat <<EOF\n ___________\n< it worked >\n -----------\n        \\   ^__^\n         \\  (oo)\\_______\n            (__)\\       )\\/\\\\\n                ||----w |\n                ||     ||\nEOF\n"
  },
  {
    "path": "test/tests/client/container.sh",
    "content": "#!/bin/bash\n\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\nSERVER_CONF=\"/etc/openvpn/openvpn.conf\"\nTEST1_OVPN=\"/etc/openvpn/test1.ovpn\"\n\n# Function to fail\nabort() { cat <<< \"$@\" 1>&2; exit 1; }\n\n# Check a config (haystack) for a given line (needle) exit with error if not\n# found.\ntest_config() {\n\n    local needle=\"${2}\"\n    local file=\"${1}\"\n\n    busybox grep -q \"${needle}\" \"${file}\"\n    if [ $? -ne 0 ]; then\n        abort \"==> Config match not found: ${needle}\"\n    fi\n}\n\n# Check a config (haystack) for absence of given line (needle) exit with error\n# if found.\ntest_not_config() {\n\n    local needle=\"${2}\"\n    local file=\"${1}\"\n\n    busybox grep -vq \"${needle}\" \"${file}\"\n    if [ $? -ne 0 ]; then\n        abort \"==> Config match found: ${needle}\"\n    fi\n}\n\n\n#\n# Generate openvpn.config file\n#\n\novpn_genconfig \\\n    -u udp://$SERV_IP \\\n    -m 1337 \\\n\n\nEASYRSA_BATCH=1 EASYRSA_REQ_CN=\"Travis-CI Test CA\" ovpn_initpki nopass\n\neasyrsa build-client-full test1 nopass 2>/dev/null\n\novpn_getclient test1 > \"${TEST1_OVPN}\"\n\n\n#\n# Simple test cases\n#\n\n# 1. client MTU\ntest_config \"${TEST1_OVPN}\" \"^tun-mtu\\s\\+1337\"\n\n\n#\n# Test udp client with tcp fallback\n#\novpn_genconfig -u udp://$SERV_IP -E \"remote $SERV_IP 443 tcp\" -E \"remote vpn.example.com 443 tcp\"\n# nopass is insecure\nEASYRSA_BATCH=1 EASYRSA_REQ_CN=\"Travis-CI Test CA\" ovpn_initpki nopass\neasyrsa build-client-full client-fallback nopass\novpn_getclient client-fallback > \"${TEST1_OVPN}\"\n\ntest_config \"${TEST1_OVPN}\" \"^remote\\s\\+$SERV_IP\\s\\+443\\s\\+tcp\"\ntest_config \"${TEST1_OVPN}\" \"^remote\\s\\+vpn.example.com\\s\\+443\\s\\+tcp\"\n\n\n#\n# Test non-defroute config\n#\novpn_genconfig -d -u udp://$SERV_IP -r \"172.33.33.0/24\" -r \"172.34.34.0/24\"\n# nopass is insecure\nEASYRSA_BATCH=1 EASYRSA_REQ_CN=\"Travis-CI Test CA\" ovpn_initpki nopass\neasyrsa build-client-full non-defroute nopass\novpn_getclient non-defroute > \"${TEST1_OVPN}\"\n\n# The '!' inverts the match to test that the string isn't present\ntest_not_config \"${TEST1_OVPN}\" \"^redirect-gateway\\s\\+def1\"\n"
  },
  {
    "path": "test/tests/conf_options/container.sh",
    "content": "#!/bin/bash\n\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\nSERVER_CONF=\"/etc/openvpn/openvpn.conf\"\nTEST1_OVPN=\"/etc/openvpn/test1.ovpn\"\n\n# Function to fail\nabort() { cat <<< \"$@\" 1>&2; exit 1; }\n\n# Check a config (haystack) for a given line (needle) exit with error if not found.\ntest_config() {\n\n    local needle=\"${2}\"\n    local file=\"${1}\"\n\n    busybox grep -q \"${needle}\" \"${file}\"\n    if [ $? -ne 0 ]; then\n        abort \"==> Config match not found: ${needle}\"\n    fi\n}\n\n# Check a config (haystack) for absence of given line (needle) exit with error\n# if found.\ntest_not_config() {\n\n    local needle=\"${2}\"\n    local file=\"${1}\"\n\n    busybox grep -vq \"${needle}\" \"${file}\"\n    if [ $? -ne 0 ]; then\n        abort \"==> Config match found: ${needle}\"\n    fi\n}\n\n\n#\n# Generate openvpn.config file\n#\nread -d '' MULTILINE_EXTRA_SERVER_CONF << EOF\nmanagement localhost 7505\nmax-clients 10\nEOF\n\novpn_genconfig \\\n    -u udp://$SERV_IP \\\n    -f 1400 \\\n    -k '60 300' \\\n    -e \"$MULTILINE_EXTRA_SERVER_CONF\" \\\n    -e 'duplicate-cn' \\\n    -e 'topology subnet' \\\n    -p 'route 172.22.22.0 255.255.255.0' \\\n\n# Run ovpn_genconfig a second time with no arguments to test its repeatability.\novpn_genconfig\n\n#\n# Simple test cases\n#\n\n# 1. verb config\ntest_config \"${SERVER_CONF}\" \"^verb\\s\\+3\"\n\n# 2. fragment config\ntest_config \"${SERVER_CONF}\" \"^fragment\\s\\+1400\"\n\n## Tests for extra configs\n# 3. management config\ntest_config \"${SERVER_CONF}\" \"^management\\s\\+localhost\\s\\+7505\"\n\n# 4. max-clients config\ntest_config \"${SERVER_CONF}\" \"^max-clients\\s\\+10\"\n\n# 5. duplicate-cn config\ntest_config \"${SERVER_CONF}\" \"^duplicate-cn\"\n\n# 6. topology config\ntest_config \"${SERVER_CONF}\" \"^topology\\s\\+subnet\"\n\n## Tests for push config\n# 7. push route\ntest_config \"${SERVER_CONF}\" '^push\\s\\+\"route\\s\\+172.22.22.0\\s\\+255.255.255.0\"'\n\n## Test for default\n# 8. Should see default route if none provided\ntest_config \"${SERVER_CONF}\" \"^route\\s\\+192.168.254.0\\s\\+255.255.255.0\"\n\n# 9. Should see a push of 'block-outside-dns' by default\ntest_config \"${SERVER_CONF}\" '^push\\s\\+\"block-outside-dns\"'\n\n# 10. Should see a push of 'dhcp-option DNS' by default\ntest_config \"${SERVER_CONF}\" '^push\\s\\+\"dhcp-option\\s\\+DNS\\s\\+8.8.8.8\"'\ntest_config \"${SERVER_CONF}\" '^push\\s\\+\"dhcp-option\\s\\+DNS\\s\\+8.8.4.4\"'\n\n## Test for keepalive\n# 11. keepalive config\ntest_config \"${SERVER_CONF}\" '^keepalive\\s\\+60\\s\\+300'\n\n\n#\n# More elaborate route tests\n#\n\novpn_genconfig -u udp://$SERV_IP -r \"172.33.33.0/24\" -r \"172.34.34.0/24\"\n\ntest_config \"${SERVER_CONF}\" \"^route\\s\\+172.33.33.0\\s\\+255.255.255.0\"\ntest_config \"${SERVER_CONF}\" \"^route\\s\\+172.34.34.0\\s\\+255.255.255.0\"\n\n\n#\n# Block outside DNS test\n#\n\novpn_genconfig -u udp://$SERV_IP -b\n\ntest_not_config \"${SERVER_CONF}\" '^push \"block-outside-dns\"'\ncat ${SERVER_CONF} >&1\n"
  },
  {
    "path": "test/tests/docker-build.sh",
    "content": "#!/bin/bash\nset -e\n\n# wrapper around \"docker build\" that creates a temporary directory and copies files into it first so that arbitrary host directories can be copied into containers without bind mounts, but accepts a Dockerfile on stdin\n\n# usage: ./docker-build.sh some-host-directory some-new-image:some-tag <<EOD\n#        FROM ...\n#        COPY dir/... /.../\n#        EOD\n#    ie: ./docker-build.sh .../hylang-hello-world librarytest/hylang <<EOD\n#        FROM hylang\n#        COPY dir/container.hy /dir/\n#        CMD [\"hy\", \"/dir/container.hy\"]\n#        EOD\n\ndir=\"$1\"; shift\n[ -d \"$dir\" ]\n\nimageTag=\"$1\"; shift\n\ntmp=\"$(mktemp -t -d docker-library-test-build-XXXXXXXXXX)\"\ntrap \"rm -rf '$tmp'\" EXIT\n\ncat > \"$tmp/Dockerfile\"\n\nfrom=\"$(awk -F '[ \\t]+' 'toupper($1) == \"FROM\" { print $2; exit }' \"$tmp/Dockerfile\")\"\nonbuilds=\"$(docker inspect -f '{{len .Config.OnBuild}}' \"$from\")\"\nif [ \"$onbuilds\" -gt 0 ]; then\n\t# crap, the image we want to build has some ONBUILD instructions\n\t# those are kind of going to ruin our day\n\t# let's do some hacks to strip those bad boys out in a new fake layer\n\t\"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")/remove-onbuild.sh\" \"$from\" \"$imageTag\"\n\tawk -F '[ \\t]+' 'toupper($1) == \"FROM\" { $2 = \"'\"$imageTag\"'\" } { print }' \"$tmp/Dockerfile\" > \"$tmp/Dockerfile.new\"\n\tmv \"$tmp/Dockerfile.new\" \"$tmp/Dockerfile\"\nfi\n\ncp -RL \"$dir\" \"$tmp/dir\"\n\ndocker build -t \"$imageTag\" \"$tmp\" > /dev/null\n"
  },
  {
    "path": "test/tests/dual-proto/run.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\n\nOVPN_DATA=dual-data\nCLIENT_UDP=travis-client\nCLIENT_TCP=travis-client-tcp\nIMG=kylemanna/openvpn\nCLIENT_DIR=\"$(readlink -f \"$(dirname \"$BASH_SOURCE\")/../../client\")\"\n\nip addr ls\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\n\n# get temporary TCP config\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_genconfig -u tcp://$SERV_IP:443\n\n# nopass is insecure\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it -e \"EASYRSA_BATCH=1\" -e \"EASYRSA_REQ_CN=Travis-CI Test CA\" $IMG ovpn_initpki nopass\n\n# gen TCP client\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it $IMG easyrsa build-client-full $CLIENT_TCP nopass\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_getclient $CLIENT_TCP | tee $CLIENT_DIR/config-tcp.ovpn\n\n# switch to UDP config and gen UDP client\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_genconfig -u udp://$SERV_IP\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it $IMG easyrsa build-client-full $CLIENT_UDP nopass\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_getclient $CLIENT_UDP | tee $CLIENT_DIR/config.ovpn\n\n#Verify client configs\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_listclients | grep $CLIENT_TCP\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_listclients | grep $CLIENT_UDP\n\n#\n# Fire up the server\n#\n\n# Run in shell bg to get logs, setup trap to clean-up\ntrap \"{ jobs -p | xargs -r kill; wait; docker volume rm ${OVPN_DATA}; }\" EXIT\ndocker run --name \"ovpn-test-udp\" -v $OVPN_DATA:/etc/openvpn --rm --cap-add=NET_ADMIN -e DEBUG $IMG &\ndocker run --name \"ovpn-test-tcp\" -v $OVPN_DATA:/etc/openvpn --rm --cap-add=NET_ADMIN -e DEBUG $IMG ovpn_run --proto tcp --port 443 &\n\n# Update configs\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"ovpn-test-udp\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\nsed -i -e s:$SERV_IP:$SERV_IP_INTERNAL:g $CLIENT_DIR/config.ovpn\n\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"ovpn-test-tcp\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\nsed -i -e s:$SERV_IP:$SERV_IP_INTERNAL:g $CLIENT_DIR/config-tcp.ovpn\n\n#\n# Fire up a clients in a containers since openvpn is disallowed by Travis-CI\n#\ndocker run --rm --cap-add=NET_ADMIN -v $CLIENT_DIR:/client -e DEBUG $IMG /client/wait-for-connect.sh\ndocker run --rm --cap-add=NET_ADMIN -v $CLIENT_DIR:/client -e DEBUG $IMG /client/wait-for-connect.sh \"/client/config-tcp.ovpn\"\n\n#\n# Celebrate\n#\ncat <<EOF\n ____________               ___________\n< it worked! >             < both ways! >\n ------------               ------------\n        \\   ^__^        ^__^   /\n\t \\  (oo)\\______/(oo)  /\n\t    (__)\\      /(__)\n                ||w---w||\n                ||     ||\nEOF\n\n"
  },
  {
    "path": "test/tests/image-name.sh",
    "content": "#!/bin/bash\nset -e\n\n# usage: ./image-name.sh librarytest/something some/image:some-tag\n# output: librarytest/something:some-image-some-tag\n\nbase=\"$1\"; shift\ntag=\"$1\"; shift\n\necho \"$base:$(echo \"$tag\" | sed 's![:/]!-!g')\"\n"
  },
  {
    "path": "test/tests/iptables/run.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\nOVPN_DATA=basic-data\nIMG=\"kylemanna/openvpn\"\nNAME=\"ovpn-test\"\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\n\n# generate server config including iptables nat-ing\ndocker volume create --name $OVPN_DATA\ndocker run --rm -v $OVPN_DATA:/etc/openvpn $IMG ovpn_genconfig -u udp://$SERV_IP -N\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it -e \"EASYRSA_BATCH=1\" -e \"EASYRSA_REQ_CN=Travis-CI Test CA\" $IMG ovpn_initpki nopass\n\n# Fire up the server\ndocker run -d --name $NAME -v $OVPN_DATA:/etc/openvpn --cap-add=NET_ADMIN $IMG\n\n# check default iptables rules\nfor i in $(seq 10); do\n    docker exec -ti $NAME bash -c 'source /etc/openvpn/ovpn_env.sh; exec iptables -t nat -C POSTROUTING -s $OVPN_SERVER -o eth0 -j MASQUERADE' && break\n    echo waiting for server start-up\n    sleep 1\ndone\n\n# append new setupIptablesAndRouting function to config\ndocker exec -ti $NAME bash -c 'echo function setupIptablesAndRouting { iptables -t nat -A POSTROUTING -m comment --comment \"test\"\\;} >> /etc/openvpn/ovpn_env.sh'\n\n# kill server in preparation to modify config\ndocker rm -f $NAME\n\n# check that overridden function exists and that test iptables rules is active\ndocker run -d --name $NAME -v $OVPN_DATA:/etc/openvpn --cap-add=NET_ADMIN $IMG\ndocker exec -ti $NAME bash -c 'source /etc/openvpn/ovpn_env.sh; type -t setupIptablesAndRouting && iptables -t nat -C POSTROUTING -m comment --comment \"test\"'\n\n#\n# kill server\n#\n\ndocker rm -f $NAME\ndocker volume rm $OVPN_DATA\n"
  },
  {
    "path": "test/tests/otp/run.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\n\nOVPN_DATA=basic-data-otp\nCLIENT=travis-client\nIMG=kylemanna/openvpn\nOTP_USER=otp\nCLIENT_DIR=\"$(readlink -f \"$(dirname \"$BASH_SOURCE\")/../../client\")\"\n\n# Function to fail\nabort() { cat <<< \"$@\" 1>&2; exit 1; }\n\nip addr ls\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\n# Configure server with two factor authentication\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_genconfig -u udp://$SERV_IP -2\n\n# Ensure reneg-sec 0 in server config when two factor is enabled\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG cat /etc/openvpn/openvpn.conf | grep 'reneg-sec 0' || abort 'reneg-sec not set to 0 in server config'\n\n# nopass is insecure\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it -e \"EASYRSA_BATCH=1\" -e \"EASYRSA_REQ_CN=Travis-CI Test CA\" $IMG ovpn_initpki nopass\n\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it $IMG easyrsa build-client-full $CLIENT nopass\n\n# Generate OTP credentials for user named test, should return QR code for test user\ndocker run -v $OVPN_DATA:/etc/openvpn --rm -it $IMG ovpn_otp_user $OTP_USER | tee $CLIENT_DIR/qrcode.txt\n# Ensure a chart link is printed in client OTP configuration\ngrep 'https://www.google.com/chart' $CLIENT_DIR/qrcode.txt || abort 'Link to chart not generated'\ngrep 'Your new secret key is:' $CLIENT_DIR/qrcode.txt || abort 'Secret key is missing'\n# Extract an emergency code from textual output, grepping for line and trimming spaces\nOTP_TOKEN=$(grep -A1 'Your emergency scratch codes are' $CLIENT_DIR/qrcode.txt | tail -1 | tr -d '[[:space:]]')\n# Token should be present\nif [ -z $OTP_TOKEN ]; then\n  abort \"QR Emergency Code not detected\"\nfi\n\n# Store authentication credentials in config file and tell openvpn to use them\necho -e \"$OTP_USER\\n$OTP_TOKEN\" > $CLIENT_DIR/credentials.txt\n\n# Override the auth-user-pass directive to use a credentials file\ndocker run -v $OVPN_DATA:/etc/openvpn --rm $IMG ovpn_getclient $CLIENT | sed 's/auth-user-pass/auth-user-pass \\/client\\/credentials.txt/' | tee $CLIENT_DIR/config.ovpn\n\n# Ensure reneg-sec 0 in client config when two factor is enabled\ngrep 'reneg-sec 0' $CLIENT_DIR/config.ovpn || abort 'reneg-sec not set to 0 in client config'\n\n#\n# Fire up the server\n#\ntrap \"{ jobs -p | xargs -r kill; wait; }\" EXIT\ndocker run --name \"ovpn-test\" -v $OVPN_DATA:/etc/openvpn --rm --cap-add=NET_ADMIN $IMG &\n\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"ovpn-test\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\nsed -i -e s:$SERV_IP:$SERV_IP_INTERNAL:g $CLIENT_DIR/config.ovpn\n\n#\n# Fire up a client in a container since openvpn is disallowed by Travis-CI\ndocker run --rm --cap-add=NET_ADMIN --volume $CLIENT_DIR:/client -e DEBUG $IMG /client/wait-for-connect.sh\n\n#\n# Celebrate\n#\ncat <<EOF\n ___________\n< it worked >\n -----------\n        \\   ^__^\n         \\  (oo)\\_______\n            (__)\\       )\\/\\\\\n                ||----w |\n                ||     ||\nEOF\n"
  },
  {
    "path": "test/tests/paranoid/container.sh",
    "content": "#!/bin/bash\nset -e\n\nSERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\n\n#\n# Generate a simple configuration, returns nonzero on error\n#\novpn_genconfig -u udp://$SERV_IP 2>/dev/null\n\nexport EASYRSA_BATCH=1\nexport EASYRSA_REQ_CN=\"Travis-CI Test CA\"\n\n#\n# Initialize the certificate PKI state, returns nonzero on error\n#\novpn_initpki nopass 2>/dev/null\n\n#\n# Test back-up\n#\novpn_copy_server_files\n"
  },
  {
    "path": "test/tests/revocation/run.sh",
    "content": "#!/bin/bash\nset -e\n\n[ -n \"${DEBUG+x}\" ] && set -x\n\nOVPN_DATA=\"ovpn-revoke-test-data\"\nCLIENT1=\"travis-client1\"\nCLIENT2=\"travis-client2\"\nIMG=\"kylemanna/openvpn\"\nNAME=\"ovpn-revoke-test\"\nCLIENT_DIR=\"$(readlink -f \"$(dirname \"$BASH_SOURCE\")/../../client\")\"\nSERV_IP=\"$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)\"\n\n#\n# Initialize openvpn configuration and pki.\n#\ndocker volume create --name $OVPN_DATA\ndocker run --rm -v $OVPN_DATA:/etc/openvpn $IMG ovpn_genconfig -u udp://$SERV_IP\ndocker run --rm -v $OVPN_DATA:/etc/openvpn -it -e \"EASYRSA_BATCH=1\" -e \"EASYRSA_REQ_CN=Travis-CI Test CA\" $IMG ovpn_initpki nopass\n\n# Register clean-up function\nfunction finish {\n    # Stop the server and clean up\n    docker rm -f $NAME\n    docker volume rm $OVPN_DATA\n    jobs -p | xargs -r kill\n    wait\n}\ntrap finish EXIT\n\n# Put the server in the background\ndocker run -d -v $OVPN_DATA:/etc/openvpn --cap-add=NET_ADMIN --name $NAME $IMG\n\n#\n# Test that easy_rsa generate CRLs with 'next publish' set to 3650 days.\n#\ncrl_next_update=\"$(docker exec $NAME bash -c \"openssl crl -nextupdate -noout -in \\$EASYRSA_PKI/crl.pem | cut -d'=' -f2 | tr -d 'GMT'\")\"\ncrl_next_update=\"$(date -u -d \"$crl_next_update\" \"+%s\")\"\nnow=\"$(docker exec $NAME date \"+%s\")\"\ncrl_remain=\"$(( $crl_next_update - $now ))\"\ncrl_remain=\"$(( $crl_remain / 86400 ))\"\nif (( $crl_remain < 3649 )); then\n    echo \"easy_rsa CRL next publish set to less than 3650 days.\" >&2\n    exit 2\nfi\n\n#\n# Generate a first client certificate and configuration using $CLIENT1 as CN then revoke it.\n#\ndocker exec -it $NAME easyrsa build-client-full $CLIENT1 nopass\ndocker exec -it $NAME ovpn_getclient $CLIENT1 > $CLIENT_DIR/config.ovpn\ndocker exec -it $NAME bash -c \"echo 'yes' | ovpn_revokeclient $CLIENT1\"\n\n# Determine IP address of container running daemon and update config\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"$NAME\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\nsed -i -e s:$SERV_IP:$SERV_IP_INTERNAL:g $CLIENT_DIR/config.ovpn\n\n#\n# Test that openvpn client can't connect using $CLIENT1 config.\n#\nif docker run --rm -v $CLIENT_DIR:/client --cap-add=NET_ADMIN -e DEBUG $IMG /client/wait-for-connect.sh; then\n    echo \"Client was able to connect after revocation test #1.\" >&2\n    exit 2\nfi\n\n#\n# Generate and revoke a second client certificate using $CLIENT2 as CN, then test for failed client connection.\n#\ndocker exec -it $NAME easyrsa build-client-full $CLIENT2 nopass\ndocker exec -it $NAME ovpn_getclient $CLIENT2 > $CLIENT_DIR/config.ovpn\ndocker exec -it $NAME bash -c \"echo 'yes' | ovpn_revokeclient $CLIENT2\"\n\n# Determine IP address of container running daemon and update config\nfor i in $(seq 10); do\n    SERV_IP_INTERNAL=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' \"$NAME\" 2>/dev/null || true)\n    test -n \"$SERV_IP_INTERNAL\" && break\n    sleep 0.1\ndone\n\nif docker run --rm -v $CLIENT_DIR:/client --cap-add=NET_ADMIN -e DEBUG $IMG /client/wait-for-connect.sh; then\n    echo \"Client was able to connect after revocation test #2.\" >&2\n    exit 2\nfi\n\n#\n# Restart the server\n#\ndocker stop $NAME && docker start $NAME\n\n#\n# Test for failed connection using $CLIENT2 config again.\n#\nif docker run --rm -v $CLIENT_DIR:/client --cap-add=NET_ADMIN -e DEBUG $IMG /client/wait-for-connect.sh; then\n    echo \"Client was able to connect after revocation test #3.\" >&2\n    exit 2\nfi\n\n#\n# Celebrate\n#\ncat <<EOF\n ___________\n< it worked >\n -----------\n        \\   ^__^\n         \\  (oo)\\_______\n            (__)\\       )\\/\\\\\n                ||----w |\n                ||     ||\nEOF\n"
  },
  {
    "path": "test/tests/run-bash-in-container.sh",
    "content": "#!/bin/bash\nset -e\n\ntestDir=\"$(readlink -f \"$(dirname \"$BASH_SOURCE\")\")\"\nrunDir=\"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\"\n\nsource \"$runDir/run-in-container.sh\" \"$testDir\" \"$1\" bash ./container.sh\n"
  },
  {
    "path": "test/tests/run-in-container.sh",
    "content": "#!/bin/bash\nset -e\n\n# NOT INTENDED TO BE USED AS A TEST \"run.sh\" DIRECTLY\n# SEE OTHER \"run-*-in-container.sh\" SCRIPTS FOR USAGE\n\ntestDir=\"$1\"\nshift\n\nimage=\"$1\"\nshift\nentrypoint=\"$1\"\nshift\n\n# do some fancy footwork so that if testDir is /a/b/c, we mount /a/b and use c as the working directory (so relative symlinks work one level up)\nthisDir=\"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\"\ntestDir=\"$(readlink -f \"$testDir\")\"\ntestBase=\"$(basename \"$testDir\")\"\nhostMount=\"$(dirname \"$testDir\")\"\ncontainerMount=\"/tmp/test-dir\"\nworkdir=\"$containerMount/$testBase\"\n# TODO should we be doing something fancy with $BASH_SOURCE instead so we can be arbitrarily deep and mount the top level always?\n\nnewImage=\"$(\"$thisDir/image-name.sh\" librarytest/run-in-container \"$image--$testBase\")\"\n\"$thisDir/docker-build.sh\" \"$hostMount\" \"$newImage\" <<EOD\nFROM $image\nCOPY dir $containerMount\nWORKDIR $workdir\nENTRYPOINT [\"$entrypoint\"]\nEOD\n\nargs=( --rm )\n\n# there is strong potential for nokogiri+overlayfs failure\n# see https://github.com/docker-library/ruby/issues/55\ngemHome=\"$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' \"$newImage\" | awk -F '=' '$1 == \"GEM_HOME\" { print $2; exit }')\"\nif [ \"$gemHome\" ]; then\n\t# must be a Ruby image\n\tdriver=\"$(docker info | awk -F ': ' '$1 == \"Storage Driver\" { print $2; exit }')\"\n\tif [ \"$driver\" = 'overlay' ]; then\n\t\t# let's add a volume (_not_ a bind mount) on GEM_HOME to work around nokogiri+overlayfs issues\n\t\targs+=( -v \"$gemHome\" )\n\tfi\nfi\n\nexec docker run \"${args[@]}\" \"$newImage\" \"$@\"\n"
  }
]