GithubHelp home page GithubHelp logo

kyl191 / ansible-role-openvpn Goto Github PK

View Code? Open in Web Editor NEW
243.0 13.0 219.0 304 KB

Ansible Playbook for OpenVPN on CentOS/Fedora/RHEL clones

License: MIT License

Shell 16.16% Dockerfile 0.68% Jinja 83.16%

ansible-role-openvpn's Introduction

OpenVPN

Github Actions (PRs & mainline): Github CI

Travis CI (Actually launching openvpn): Build Status

This role installs OpenVPN, configures it as a server, sets up networking and firewalls (primarily firewalld, ufw and iptables are best effort), and can optionally create client certificates.

OSes in CI build:

  • Fedora 32+
  • CentOS 7 & 8

Note: I am providing code in the repository to you under an open source license. Because this is my personal repository, the license you receive to my code is from me and not my employer.

Requirements

OpenVPN must be available as a package in yum/dnf/apt! For CentOS users, this role will run yum install epel-release to ensure openvpn is available.

Ubuntu precise has a weird bug that might make the iptables-persistent install fail. There is a workaround.

Ansible 2.10 and higher

With the release of Ansible 2.10, modules have been moved into collections. With the exception of ansible.builtin modules, this means additonal collections must be installed in order to use modules such as seboolean (now ansible.posix.seboolean). This collections is now required: ansible.posix and this collection is required if using ufw: community.general. Installing the collections:

ansible-galaxy collection install ansible.posix
ansible-galaxy collection install community.general

Support Notes/Expectations

I personally use this role to manage OpenVPN on CentOS 8. I try to keep the role on that platform fully functional with the default config. Please recognise that I am a single person, and I have a full time job and other commitments.

Responses to any issues will be on a best effort basis on my part, including the possibility that I don't respond at all. Issues arising from use of the non-defaults (including any of the major community contributions) will be deprioritized.

Major community contributions:

  • Functionality to revoke certs
  • All of the LDAP support

Role Variables

Role options

These options change how the role works. This is a catch-all group, specific groups are broken out below.

Variable Type Choices Default Comment
clients list [] List of clients to add to OpenVPN
openvpn_base_dir string /etc/openvpn Path where your OpenVPN config will be stored
openvpn_client_config_no_log boolean true, false true Prevent client configuration files to be logged to stdout by Ansible
openvpn_key_dir string /etc/openvpn/keys Path where your server private keys and CA will be stored
openvpn_ovpn_dir string /etc/openvpn Path where your client configurations will be stored
openvpn_revoke_these_certs list [] List of client certificates to revoke.
openvpn_selinux_module string my-openvpn-server Set the SELinux module name
openvpn_service_name string openvpn Name of the service. Used by systemctl to start the service
openvpn_sync_certs boolean true, false false Revoke certificates not explicitly defined in 'clients'
openvpn_uninstall boolean true, false false Set to true to uninstall the OpenVPN service
openvpn_use_ldap boolean true, false false Active LDAP backend for authentication. Client certificate not needed anymore

Config fetching

Change these options if you need to adjust how the configs are download to your local system

Variable Type Choices Default Comment
openvpn_fetch_client_configs boolean true, false true Download generated client configurations to the local system
openvpn_fetch_client_configs_dir string /tmp/ansible If openvpn_fetch_client_configs is true, the local directory to download the client config files into
openvpn_fetch_client_configs_suffix string "" If openvpn_fetch_client_configs is true, the suffix to append to the downloaded client config files before the trailing .ovpn extension

Firewall

Change these options if you need to force a particular firewall or change how the playbook interacts with the firewall.

Variable Type Choices Default Comment
firewalld_default_interface_zone string public Firewalld zone where the "ansible_default_ipv4.interface" will be pushed into
iptables_service string iptables Override the iptables service name
manage_firewall_rules boolean true, false true Allow playbook to manage iptables
openvpn_firewall string auto, firewalld, ufw, iptables auto The firewall software to configure network rules. "auto" will attempt to detect it by inspecting the system
openvpn_masquerade_not_snat boolean true, false false Set to true if you want to set up MASQUERADE instead of the default SNAT in iptables.

OpenVPN Config Options

These options change how OpenVPN itself works.

Networking

Variable Type Choices Default Comment
openvpn_client_register_dns boolean true, false true Add register-dns option to client config (Windows only).
openvpn_client_to_client boolean true, false false Set to true if you want clients to access each other.
openvpn_custom_dns list[string] [] List of DNS servers, only applied if openvpn_set_dns is set to true
openvpn_dualstack boolean true Whether or not to use a dualstack (IPv4 + v6) socket
openvpn_keepalive_ping int 5 Set keepalive ping interval seconds.
openvpn_keepalive_timeout int 30 Set keepalive timeout seconds
openvpn_local string unset Local host name or IP address for bind. If specified, OpenVPN will bind to this address only. If unspecified, OpenVPN will bind to all interfaces.
openvpn_port int 1194 The port you want OpenVPN to run on. If you have different ports on different servers, I suggest you set the port in your inventory file.
openvpn_proto string udp, tcp udp The protocol you want OpenVPN to use
openvpn_redirect_gateway boolean true, false true OpenVPN gateway push
openvpn_resolv_retry int/string any int, infinite 5 Hostname resolv failure retry seconds. Set "infinite" to retry indefinitely in case of poor connection or laptop sleep mode recovery etc.
openvpn_server_hostname string {{ inventory_hostname }} The server name to place in the client configuration file
openvpn_server_ipv6_network string unset If set, the network address and prefix of an IPv6 network to assign to clients. If True, IPv4 still used too.
openvpn_server_netmask string 255.255.255.0 Netmask of the private network
openvpn_server_network string 10.9.0.0 Private network used by OpenVPN service
openvpn_set_dns boolean true, false true Will push DNS to the client (Cloudflare and Google)
openvpn_tun_mtu int unset Set tun-mtu value. Empty for default.

Security

Variable Type Choices Default Comment
openvpn_auth_alg string SHA256 Set auth authentication algoritm.
openvpn_ca_key dict unset Contain "crt" and "key". If not set, CA cert and key will be automatically generated on the target system.
openvpn_cipher string AES-256-CBC Set cipher option for server and client.
openvpn_crl_path string unset Define a path to the CRL file for server revocation check.
openvpn_duplicate_cn boolean true, false false Add duplicate-cn option to server config - this allows clients to connect multiple times with the one key. NOTE: client ip addresses won't be static anymore!
openvpn_rsa_bits int 2048 Number of bits used to protect generated certificates
openvpn_script_security int 1 Set openvpn script security option
openvpn_tls_auth_key string unset Single item with a pre-generated TLS authentication key.
openvpn_use_crl boolean true, false false Configure OpenVPN server to honor certificate revocation list.
openvpn_use_hardened_tls boolean true, false true Require a minimum version of TLS 1.2
openvpn_use_modern_tls boolean true, false true Use modern Cipher for TLS encryption (Not recommended with OpenVPN 2.4)
openvpn_use_pregenerated_dh_params boolean true, false false DH params are generted with the install by default
openvpn_verify_cn boolean true, false false Check that the CN of the certificate match the FQDN
tls_auth_required boolean true, false true Ask the client to push the generated ta.key of the server during the connection

Operations

Variable Type Choices Default Comment
openvpn_addl_client_options list empty List of user-defined client options that are not already present in the client template. (e.g. - mssfix 1400)
openvpn_addl_server_options list empty List of user-defined server options that are not already present in the server template. (e.g. - ping-timer-rem)
openvpn_compression string lzo Set compress compression option. Empty for no compression.
openvpn_config_file string openvpn_{{ openvpn_proto }}_{{ openvpn_port }} The config file name you want to use (set in vars/main.yml)
openvpn_enable_management boolean true, false false
openvpn_ifconfig_pool_persist_file string ipp.txt
openvpn_management_bind string /var/run/openvpn/management unix The interface to bind on for the management interface. Can be unix or TCP socket.
openvpn_management_client_user string root Use this user when using a Unix socket for management interface.
openvpn_push list empty Set here a list of string that will be inserted into the config file as push "". E.g - route 10.20.30.0 255.255.255.0 will generate push "route 10.20.30.0 255.255.255.0"
openvpn_script_client_connect string unset Path to your openvpn client-connect script
openvpn_script_client_disconnect string unset Path to your openvpn client-disconnect script
openvpn_script_down string unset Path to your openvpn down script
openvpn_script_up string unset Path to your openvpn up script
openvpn_service_group string nogroup Set the openvpn service group.
openvpn_service_user string nobody Set the openvpn service user.
openvpn_status_version int 1, 2, 3 1 Define the formatting of the openvpn-status.log file where are listed current client connection
openvpn_topology string unset the "topology" keyword will be set in the server config with the specified value.

OpenVPN custom client config (server pushed)

Variable Type Choices Default Comment
openvpn_client_config Boolean false Set to true if enable client configuration directory
openvpn_client_config_dir string ccd Path of client-config-dir
openvpn_client_configs dict {} Dict of settings custom client configs

Logrotate

Set your own custom logrotate options

Variable Type Choices Default Comment
openvpn_log_dir string /var/log Set location of openvpn log files. This parameter is a part of log-append configuration value.
openvpn_log_file string openvpn.log Set log filename. This parameter is a part of log-append configuration value.
openvpn_logrotate_config string rotate 4
weekly
missingok
notifempty
sharedscripts
copytruncate
delaycompress
Configure logrotate script.

Packaging

This role pulls in a bunch of different packages. Override the names as necessary.

Variable Type Choices Default Comment
epel_package_name string epel-release Name of the epel-release package to install from the package manager
iptables_persistent_package_name string iptables-persistent Name of the iptables-persistent package to install from the package manager
iptables_services_package_name string iptables-services Name of the iptables-services package to install from the package manager
openssl_package_name string openssl Name of the openssl package to install from the package manager
openvpn_ldap_plugin_package_name string openvpn-auth-ldap Name of the openvpn-auth-ldap package to install from the package manager
openvpn_package_name string openvpn Name of the openvpn package to install from the package manager
python_firewall_package_name string python-firewall Name of the python-firewall package to install from the package manager

LDAP object

Variable Type Choices Default Comment
ldap dict Dictionary that contain LDAP configuration
url string ldap://host.example.com Address of you LDAP backend with syntax ldap[s]://host[:port]
anonymous_bind string False , True False This is not an Ansible boolean but a string that will be pushed into the configuration file.
bind_dn string uid=Manager,ou=People,dc=example,dc=com Bind DN used if "anonymous_bind" set to "False"
bind_password string mysecretpassword Password of the bind_dn user
tls_enable string yes , no no Force TLS encryption. Not necessary with ldaps addresses
tls_ca_cert_file string /etc/openvpn/auth/ca.pem Path to the CA ldap backend. This must have been pushed before
tls_cert_file string Path to client authentication certificate
tls_key_file string Path to client authentication key
base_dn string ou=People,dc=example,dc=com Base DN where the backend will look for valid user
search_filter string (&(uid=%u)(accountStatus=active)) Filter the ldap search
require_group string False , True This is not an Ansible boolean but a string that will be pushed into the configuration file.
group_base_dn string ou=Groups,dc=example,dc=com Precise the group to look for. Required if require_group is set to "True"
group_search_filter string ((cn=developers)(cn=artists)) Precise valid groups
verify_client_cert string none , optional , require client-cert-not-required In OpenVPN 2.4+ client-cert-not-required is deprecated. Use verify-client-cert instead.

Dependencies

Does not depend on any other roles

Example Playbook

- hosts: vpn
  gather_facts: true
  roles:
    - role: kyl191.openvpn
      openvpn_port: 4300
      openvpn_sync_certs: true
      clients:
        - client1
        - client2

Note: As the role will need to know the remote used platform (32 or 64 bits), you must set gather_facts to true in your play.

License

MIT

Author Information

Written by Kyle Lexmond

ansible-role-openvpn's People

Contributors

aabouzaid avatar axkng avatar blaet avatar chilinot avatar daniellandau avatar dblaci avatar dobbymoodge avatar emfl avatar ernestas-poskus avatar hany avatar jamesjuran2 avatar janjurca avatar jbeyerstedt avatar john-p-potter avatar kelbyers avatar kyl191 avatar lucasboisserie avatar mabeett avatar martinnowak avatar memberit avatar michaelimfeld avatar rdeknijf avatar retraut avatar rodriguezsergio avatar shumkov avatar sispheor avatar spearcrow avatar utkuozdemir avatar xanderdin avatar zt-sv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-openvpn's Issues

had issue with duo 2 factor authentication

deployed openvpn using this role, and tred to use authentication plugin from duo.
no call to duo server when server.conf has "proto udp6". works fine when "proto udp"

content of crl-cron.sh

Hello,

I am curious about how crl-cron.sh is supposed to work.

Here is the content of the file

#!/bin/sh 
lastUpdate=$(date --date "$(openssl crl -in /etc/openvpn/keys/ca-crl.pem -noout -lastupdate | cut -d'=' -f2)" +%s) 
nextUpdate=$(date --date "$(openssl crl -in /etc/openvpn/keys/ca-crl.pem -noout -nextupdate | cut -d'=' -f2)" +%s) 
if [ $(( (nextUpdate - lastUpdate) / 86400 )) -le 10 ]; then 
    sh /etc/openvpn/keys/revoke.sh   
fi

lastupdate and nextupdate are static values ; they are both not changing unless explicitely modified (see
https://community.openvpn.net/openvpn/wiki/CertificateRevocationListExpired ).

that's why I am not understanding the if statement. It will systematically be 30 (days) ?

Can someone explain?

Today I had to manually launch the script /etc/openvpn/keys/revoke.sh because there nextUpdate < now.

Thanks

Deprecated cypher options used

Openvpn server is throwing this warning on the logs:

DEPRECATED OPTION: --cipher set to 'AES-256-CBC' but missing in --data-ciphers (AES-256-GCM:AES-128-GCM). Future OpenVPN version will ignore --cipher for cipher negotiations. Add 'AES-256-CBC' to --data-ciphers or change --cipher 'AES-256-CBC' to --data-ciphers-fallback 'AES-256-CBC' to silence this warning.

There do not seem to be options to set up this on the module.

Access rights to push

Hi, I want to send you PR, but
ERROR: Permission to kyl191/ansible-role-openvpn.git denied to de1ayer. fatal: Could not read from remote repository.
May I ask to grant some access?

"command: command -v " cannot be executed as become.

several tasks use the internal bash utility 'command' which cannot be executed by sudo, e.g. the following task on Ubuntu 18.04:

- name: Check for iptables
  command: command -v iptables
...

can trigger the following error:

TASK [openvpn : Check for iptables] ***************************************************************
task path: /home/ubuntu/git/clusterops/ansible/roles/openvpn/tasks/firewall.yml:15
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: ubuntu
<localhost> EXEC /bin/sh -c 'echo ~ubuntu && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550 `" && echo ansible-tmp-1564654912.301547-91073605449550="` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550 `" ) && sleep 0'
Using module file /home/ubuntu/miniconda3/lib/python3.7/site-packages/ansible/modules/commands/command.py
<localhost> PUT /home/ubuntu/.ansible/tmp/ansible-local-12565unktj_z2/tmpl43quayn TO /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550/AnsiballZ_command.py
<localhost> EXEC /bin/sh -c 'chmod u+x /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550/ /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550/AnsiballZ_command.py && sleep 0'
<localhost> EXEC /bin/sh -c 'sudo -H -S  -p "[sudo via ansible, key=hlycgfpiptyjmgxvykfljpqyuoalticm] password:" -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-hlycgfpiptyjmgxvykfljpqyuoalticm ; /usr/bin/python /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550/AnsiballZ_command.py'"'"' && sleep 0'
<localhost> EXEC /bin/sh -c 'rm -f -r /home/ubuntu/.ansible/tmp/ansible-tmp-1564654912.301547-91073605449550/ > /dev/null 2>&1 && sleep 0'
ok: [localhost] => {
    "changed": false,
    "cmd": "command -v iptables",
    "failed_when_result": false,
    "invocation": {
        "module_args": {
            "_raw_params": "command -v iptables",
            "_uses_shell": false,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "msg": "[Errno 2] No such file or directory",
    "rc": 2
}

TASK [openvpn : Fail on both firewalld & ufw] *****************************************************
task path: /home/ubuntu/git/clusterops/ansible/roles/openvpn/tasks/firewall.yml:22
skipping: [localhost] => {
    "changed": false,
    "skip_reason": "Conditional result was False"
}

TASK [openvpn : Fail on no firewall detected] *****************************************************
task path: /home/ubuntu/git/clusterops/ansible/roles/openvpn/tasks/firewall.yml:27
fatal: [localhost]: FAILED! => {
    "changed": false,
    "msg": "No firewall detected, install one before proceeding (firewalld||ufw||iptables)"
}

PLAY RECAP ****************************************************************************************
localhost                  : ok=34   changed=0    unreachable=0    failed=1    skipped=16   rescued=0    ignored=0   

Can we replace them with programs that are less dependent on bash environment, e.g. 'which iptables' instead of 'command -v iptables'?

remove the user

@kyl191 what if I want to remove the user, I didn't find anything related to it over the net. Do you have an idea about it. Thanks

/etc/init.d/iptables-persistent-save doesn't exist

When I run the playbook I get:

TASK [etc : iptables - save everything (Debian/Ubuntu)] ************************
fatal: [vpn_germany1]: FAILED! => {"changed": false, "cmd": "/etc/init.d/iptables-persistent save", "failed": true, "msg": "[Errno 2] No such file or directory", "rc": 2}

I verified the installation of iptables-persistent:

root@DEBIAN-TEST:~# apt-get install iptables-persistent
Reading package lists... Done
Building dependency tree
Reading state information... Done
iptables-persistent is already the newest version (1.0.4).
The following packages were automatically installed and are no longer required:
linux-headers-4.4.0-21 linux-headers-4.4.0-21-generic linux-headers-4.4.0-31
linux-headers-4.4.0-31-generic linux-image-4.4.0-21-generic
linux-image-4.4.0-31-generic linux-image-extra-4.4.0-21-generic
linux-image-extra-4.4.0-31-generic
Use 'apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 79 not upgraded.

LDAP compile - commands not found

What happened:

Currently, I installed the role with an LDAP configuration. However, during the compiling in compile_ldap_plugin.yml it results in:

{
    "changed": true,
    "cmd": "autoconf\nautoheader\n./configure --prefix=/usr/lib64/openvpn/plugin --with-openvpn=/sbin/openvpn CFLAGS=\"-fPIC\" OBJCFLAGS=\"-std=gnu11\"\nmake\nmake install\n",
    "delta": "0:00:00.050354",
    "end": "2022-01-11 09:39:29.705113",
    "msg": "non-zero return code",
    "rc": 127,
    "start": "2022-01-11 09:39:29.654759",
    "stderr_lines": [
        "/bin/sh: autoconf: command not found",
        "/bin/sh: line 1: autoheader: command not found",
        "./configure: line 473: sed: command not found",
        "./configure: line 472: expr: command not found",
        "./configure: line 473: sed: command not found",
        "./configure: line 487: sed: command not found",
        ": error: cannot create .lineno; rerun with a POSIX shell",
        "/bin/sh: line 3: make: command not found",
        "/bin/sh: line 4: make: command not found"
    ],
    "stdout": "",
    "stdout_lines": []
}

Are there any ideas why I ran into that problem?

What you expected to happen:

Compilation should run through

Anything else we need to know?:

I checked the $PATH variable and I don't see any misconfiguration: /home/centos/.local/bin:/home/centos/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin

  • sed: /usr/bin/sed (which sed)
  • autoconf /usr/bin/autoconf
  • autoheader /usr/bin/autoheader
  • make /usr/bin/make

System

CentOS Linux release 8.3.2011

can you update README ?

I need some examples on how to use your repository for:

  1. install the server,
  2. create 2 users (user and password)
  3. install a client to use user1 and password1

Client CSR is not deleted CentOS 7

When revoking the clients the CA cert is not removed from the server.

Current Code

- name: Revoke certificates
  command: sh revoke.sh {{ item }}.crt
  changed_when: true
  args:
    chdir: "{{ openvpn_key_dir }}"
  with_items:
    - '{{ openvpn_revoke_these_certs }}'
    - '{{ openvpn_cert_sync_revoke | default([]) }}'

New Code

- name: Revoke client crt
  file:
    path: "{{ openvpn_key_dir }}/{{ item }}.crt"
    state: absent
    force: true
  with_items:
    - '{{ openvpn_revoke_these_certs }}'
    - '{{ openvpn_cert_sync_revoke | default([]) }}'

Clients' CSR and private keys are kept

When providing items in the clients variable, the role creates the client's private key, CSR and certificate on the target. However, the target only needs the certificate in order to add the client to the revocation list later on.

The best scenario would be to generate the clients' key on their own side, but it is out of scope of this role. However, the role should at least remove the private key, CSR and ovpn files at the end of the client_keys task.

Test latest changes on AWS

Ubuntu (https://cloud-images.ubuntu.com/locator/ec2/):
16.10: ubuntu/images/hvm-ssd/ubuntu-yakkety-16.10-amd64-server-20170103 - ami-4ae1fb5d
16.04: ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20170202 - ami-f0768de6
14.04: ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-20170202.1 - ami-af22d9b9
12.04: ubuntu/images/hvm-ssd/ubuntu-precise-12.04-amd64-server-20170202 - ami-a49e65b2

Debian (user: admin, https://wiki.debian.org/Cloud/AmazonEC2Image/Jessie):
8.7: debian-jessie-amd64-hvm-2017-01-15-1221-ebs - ami-b14ba7a7
7.8: debian-wheezy-amd64-hvm-2015-01-28-ebs - ami-e0efab88

Fedora:
25: Fedora-Cloud-Base-25-20170214.0.x86_64-us-east-1-HVM-gp2-0 - ami-ef70bff9
24: Fedora-Cloud-Base-24-20161207.0.x86_64-us-east-1-HVM-gp2-0 - ami-a11c1ab6
23: Fedora-Cloud-Base-23-20160626.x86_64-us-east-1-HVM-gp2-0 - ami-ec458981

CentOS:
7 (1602): https://aws.amazon.com/marketplace/pp/B00O7WM7QW
6 (2014-09-29): https://aws.amazon.com/marketplace/pp/B00A6KUVBW
Other point releases not available?

Maybe improve tests by using molecule?

It looks like it's design for running a role in a Docker image, which is the tests do right now, except Github Actions don't allow us to actually start containers with the proper entrypoint (systemd).
And there's something about the docker create && docker start and docker run cycle that doesn't allow containers to last on GH infra, despite docker run working fine on other platforms.
Maybe molecule will overcome that?

Crib liberally from https://github.com/diodonfrost/ansible-role-podman/blob/master/.github/workflows/molecule.yml

Timeout errors

Hi all,

I'm having a few issues, when running this playbook I'm getting the following error when running the handlers at the end (specifically restart openvpn & save iptables).
ERROR! Timeout (12s) waiting for privilege escalation prompt
and when I tried running using "-c paramiko" i got this:
UNREACHABLE! => {"changed": false, "msg": "Authentication timeout.", "unreachable": true}

Any ideas what's going on here?
I can manually SSH to the server and perform both tasks (restart openvpn & save iptables) with no issue.

LDAP configuration

Hi Team,

I tried to configure the ldap authentication but auth/ldap.conf file is not getting updated.

Below is my setup-openvpn.yml file. Could you please suggest what is wrong in it.


  • hosts: vpn01
    become: true
    gather_facts: true
    roles:
    • role: kyl191.openvpn
      openvpn_port: 1194
      clients:
      • client1
        openvpn_push:
      • route 10.20.30.0 255.255.255.225
      • route 10.x.x.0 255.255.255.0
      • dhcp-option DNS 10.x.x.46
        iptables_service: firewalld
        openvpn_use_ldap: true
        ldap:
        url: 'ldaps://ldap01'
        bind_dn: cn=Manager,dc=example,dc=uk
        bind_password: test
        tls_ca_cert_file: /etc/openldap/certs/ca_certs.pem
        base_dn: dc=example,dc=uk
        search_filter: (&(uid=%u))
        require_group: true
        group_base_dn: ou=vpn,dc=example,dc=uk
        group_search_filter: (|(cn=DevOps)(cn=users))

VERIFY ERROR: depth=0, error=CRL has expired: CN=xxxxxxxxxx

Hi, I just got this error on Raspbian Stretch (raspberry pi) when connecting to my server.

Was connecting fine until today (been using it for 2-3 months now)

How can I fix this problem, tried running the role again to no avail

Thanks !

Optionally use MASQUERADE instead of SNAT?

I want to use OpenVPN to talk from the server to clients (clients are behind NAT behind a dynamic IP address). It turned out that I needed MASQUERADE instead of SNAT to achieve that, how would you feel about adding an option for that? I can do the actual work if it's something you'd accept.

Move compilation steps to copr/epel

Interestingly, the ldap plugin is natively available for Fedora: https://src.fedoraproject.org/rpms/openvpn-auth-ldap

But the CentOS versions aren't updated, looks like dependencies are the issue.

Trying a copr version of it isn't too helpful: https://copr.fedorainfracloud.org/coprs/kyl191/openvpn-auth-ldap/
gcc-objc was removed in RHEL8, there's no EPEL replacement, so it has to be pulled in from an external repo. (copr supports this, thankfully)

re2c just isn't updated: https://src.fedoraproject.org/rpms/re2c
I can build it locally on CentOS 8, so that should be easier to solve.

Centos 8 seems ok

I just tested the role on a Centos8 VM and it seems to work perfectly.
Maybe you can add this OS to the list of supported one. And add it to Travis Ci as well.

Allow TCP management interface

If you try make management interface listen via TCP (setting openvpn_management_bind to something like "localhost 7505"), the resulting config still contains management-client-user option, which results in OpenVPN server failing to start with this error message:
Options error: --management-client-(user|group) can only be used on unix domain sockets

SELinux Support

ansible-role-openvpn should run on systems with SELinux enabled

compress lzo is deprecated in OpenVPN 2.4 and removed in 2.5

The template sets compress lzo, this configuration option is deprecated in 2.4 and was removed in 2.5.

I suggest to make including this setting configurable and maybe not activate it by default. Maybe setting lz4 compression should be made possible.

Using a random port in Ansible breaks systemd in Docker

Made this change (and fixed a syntax error) and all the systemd-based docker images fell over.

Commented out the port randomization and systemd docker images started working again.

Can't replicate it on a local docker image, but Travis fails with

TASK [ansible-role-openvpn : setup openvpn auto-start & start] *****************
task path: /etc/ansible/roles/ansible-role-openvpn/tasks/config.yml:37
fatal: [127.0.0.1]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to start service openvpn@openvpn_udp_49295.service: Job for openvpn@openvpn_udp_49295.service failed because the control process exited with error code.\nSee \"systemctl status openvpn@openvpn_udp_49295.service\" and \"journalctl -xe\" for details.\n"}

and no logs are written to /var/log/openvpn.log.

โ„๏ธ

Setup autovpn autostart failing

Great work !
Just having a small issue at the end. Any clue ?
On Ubuntu 16.04 LTS

TASK [kyl191.openvpn : Setup openvpn auto-start & start] ************************************************************************************************************************************************************************************************************
fatal: [47.254.156.204]: FAILED! => {"changed": false, "msg": "Unable to start service openvpn@openvpn_udp_1194.service: Job for openvpn@openvpn_udp_1194.service failed because the control process exited with error code. See "systemctl status openvpn@openvpn_udp_1194.service" and "journalctl -xe" for details.\n"}

openvpn_custom_dns option does not work

The openvpn_custom_dns option which is described in the README file does not actually work. Even if I set openvpn_custom_dns to a list of servers and also set openvpn_set_dns to true, my custom DNS server is not pushed to the clients.

I think the problem is that templates/server.conf.j2 uses the openvpn_dns_servers variable (in https://github.com/kyl191/ansible-role-openvpn/blob/master/templates/server.conf.j2#L64) rather than using the values from openvpn_custom_dns.

I see two solutions:

  • document the current behavior, which in my understanding is this:

    • openvpn_dns_servers is the list of DNS servers to use
    • openvpn_custom_dns is a bool value that must be set to true to actually use the entries from openvpn_dns_servers (rather than the Google/Cloudflare servers)
    • openvpn_set_dns must be set to true as well to use the values from openvpn_dns_servers
  • simplify the current behavior: remove openvpn_custom_dns from code and documentation, and use only openvpn_dns_servers

Allow apt version pinning on the installed packages

It would be good to be able to pin the openvpn package and the other packages to a specific version to make sure that installations are identical even if new versions of the packages are released. For example:

- name: Install openvpn
  package:
   name: "{{ item }}"
   state: present
  with_items:
    - openvpn=2.4.7-1ubuntu2
    - openssl=1.1.1f-1ubuntu2.2

Rocky 8: openvpn-auth-ldap.so No such file or directory

Hello there,
It's been a while ๐Ÿ™‚.

I'm deploying on Rocky Linux 8. I got an issue with the ldap auth module.
Here the log

PLUGIN_INIT: could not load plugin shared object /usr/lib64/openvpn/plugin/lib/openvpn-auth-ldap.so: /usr/lib64/openvpn/plugin/lib/openvpn-auth-ldap.so: cannot open shared object file: No such file or directory: No such file or directory (errno=2)

On Rocky 8 (and on RHEL 8) the correct path is /usr/lib64/openvpn/plugins/openvpn-auth-ldap.so (just a 's' added to 'plugin' actually).

sync_certs fails

Hello,

I tried to provision openvpn on Amazon Linux 2 AMI (ami-02f9ea74050d6f812) and Centos 7.

- hosts: all
  gather_facts: true
  roles:
    - role: kyl191.openvpn
      openvpn_sync_certs: true # BUG
      openvpn_duplicate_cn: true
      openvpn_server_hostname: xxx.xxx.com
      become: true
      clients:
        - victor
        - celine
      openvpn_push:
        - dhcp-option DNS X.X.X.X

When enabling openvpn_sync_certs I have an error when there is no client and another if there are already clients.
Error when there are no clients yet:


TASK [kyl191.openvpn : Get existing certs] *******************************************************************************************************
fatal: [172.31.11.150]: FAILED! => {"changed": true, "cmd": "set -o pipefail\nls /etc/openvpn/keys | grep '\\.csr' | grep -v 'server.csr' | sort | cut -f1 -d'.' > /tmp/existing-certs\n", "delta": "0:00:00.006633", "end": "2021-05-10 09:10:32.823718", "msg": "non-zero return code", "rc": 1, "start": "2021-05-10 09:10:32.817085", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

Error when there are already clients:

TASK [kyl191.openvpn : Get difference between 'clients' variable and existing certs] ***********************************************************************************************************************
fatal: [172.31.15.142]: FAILED! => {"changed": true, "cmd": "set -o pipefail\nsort -o /tmp/client-list /tmp/client-list\ndiff /tmp/client-list /tmp/existing-certs | grep '>' | awk '{print $2}'\n", "delta": "0:00:00.021649", "end": "2021-05-10 07:55:40.363357", "msg": "non-zero return code", "rc": 1, "start": "2021-05-10 07:55:40.341708", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

Cheers and thanks

leverage multiple server config

Currently the role can handle only one configuration per server.

It would be usefull to allow the configuration of multiple config.

Client private keys are logged to stdout on the step "generate client config"

On the step "generate client config", the client cert and private key of the client is outputted to the console, despite being a sensitive info. Example:

TASK [kyl191.openvpn : generate client config] ***********************************************************************************************************************************************************
changed: [server] => (item=[{'content': 'LS0tLS1CR.......redacted.........EUtLS0tLQo=', 'source': '/etc/openvpn/keys/client.crt', 'encoding': 'base64', 'invocation': {'module_args': {'src': '/etc/openvpn/keys/client.crt'}}, 'failed': False, 'changed': False, 'item': 'client', 'ansible_loop_var': 'item'}, {'content': 'LS0tLS1C.....redacted......0tLS0K', 'source': '/etc/openvpn/keys/client.key', 'encoding': 'base64', 'invocation': {'module_args': {'src': '/etc/openvpn/keys/client.key'}}, 'failed': False, 'changed': False, 'item': 'client', 'ansible_loop_var': 'item'}])

This should not be printed to stdout. I suggest adding no_log: true to that task, maybe overridable using a variable in defaults.

Crontab failed

Centos 7 minimal 2003 don't have installed crontab

Role application stops on error

TASK [kyl191.openvpn : Add cron to check every Saturday if the CRL needs to be renewed] ***************************************************************************************************************************** fatal: [vpn-server-01]: FAILED! => {"changed": false, "msg": "Failed to find required executable crontab in paths: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin"}

Decision
yum install cronie

Add version tags

Please add version tags, so one can lock role version when using it from Galaxy. Thanks

Could not find the requested service iptables: cannot enable

The install fails with the following error
{"changed": false, "failed": true, "msg": "Could not find the requested service iptables: cannot enable"}

Ansible version: 2.2.2.0 tested on 2.2.1.0 also
OS: Mac OSX
External Host: Centos 7 AWS AMI ami-7abd0209

CRL not working as intended.

templates/ca.conf.j2:

default_crl_days = 30

Which means that upon "gencrl" "lastupdate" is set to the run timestamp and "nextupdate" is set to 30 days in the future.
After that, nothing in ansible-role-openvpn seems to update "nextupdate" other than doing an actual manual revoke / manual running revoke.sh .
When more than 30 days have passed since either the initial creation or the last revoke,
openvpn 2.4 or later then freaks out because the CRL has expired and doesn't let anyone connect with crl-verify enabled. (https://community.openvpn.net/openvpn/wiki/CertificateRevocationListExpired)

templates/crl-cron.sh.j2:
only checks there's a less than 10 days difference between "lastupdate" and "nextupdate", but my impression is that difference will always be "default_crl_days", so it never triggers the regenerate/renew.
Was the intention to do a check of current timestamp (date +%s) vs "nextupdate" instead?
Straight up having crl-cron.sh run revoke.sh without the "less than 10 days" check should probably work OK instead, since that would do a weekly regenerate/renew instead of 20-27 days after the last revoke/renew.
(keeping the short renew period should from what I could google be a bit safer (shorter caching, shorter keeping antique revoked cerificates listed in it) than the often used workaround of throwing default_crl_days to 3650 (10 years)...)

templates/server.conf.j2:

{% if openvpn_crl_path is defined %}
crl-verify {{openvpn_crl_path}}
{% endif %}
{% if openvpn_use_crl|bool %}
crl-verify {{openvpn_key_dir}}/ca-crl.pem
{% endif %}

I'm guessing that was meant to be "openvpn_use_crl" as boolean on/off toggle with
"{{openvpn_key_dir}}/ca-crl.pem" as default if "openvpn_crl_path" isn't defined?
In its current form it writes 2 "crl-verify" lines if both options are defined...

(I'm decent at reading/decoding programming languages, but a newbie at writing ansible/jinja2, so unfortunately couldn't put the above in the form of a pull request...)

TLS key in client config file

When the option

tls_auth_required

is disabled, the tls_auth key still gets to the client config. Because of this, the Windows client cannot connect to the server.

Bug:

There is a bad var usage in the task server_keys.yml.

fatal: [vpn-test.mylab.com]: FAILED! => {"msg": "The conditional check 'file_result.state == 'absent'' failed. The error was: error while evaluating conditional (file_result.state == 'absent'): 'dict object' has no attribute 'state'\n\nThe error appears to be in '/home/lmaurice/ws/infra/ansible-infrastructure/galaxy_roles/openvpn/tasks/server_keys.yml': line 137, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: create certificate revocation list database if required\n  ^ here\n"}

I solved the problem replacing in tasks/server_keys.yml line 137 :
This

- name: create certificate revocation list database if required
  file:
    path: "{{openvpn_key_dir}}/index.txt"
    state: touch
  when: file_result.state == 'absent'

By this

- name: create certificate revocation list database if required
  file:
    path: "{{openvpn_key_dir}}/index.txt"
    state: touch
  when: '"absent" in file_result'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.