Openvpn connect как настроить на windows

This How TO guide provides step-by-step instructions for configuration and set up of OpenVPN 2.x client/server VPN.

OpenVPN is a full-featured SSL VPN which implements OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol, supports flexible client authentication methods based on certificates, smart cards, and/or username/password credentials, and allows user or group-specific access control policies using firewall rules applied to the VPN virtual interface. OpenVPN is not a web application proxy and does not operate through a web browser.

OpenVPN 2.0 expands on the capabilities of OpenVPN 1.x by offering a scalable client/server mode, allowing multiple clients to connect to a single OpenVPN server process over a single TCP or UDP port. OpenVPN 2.3 includes a large number of improvements, including full IPv6 support and PolarSSL support.

This document provides step-by-step instructions for configuring an OpenVPN 2.x client/server VPN, including:

This HOWTO assumes that readers possess a prior understanding of basic networking concepts such as IP addresses, DNS names, netmasks, subnets, IP routing, routers, network interfaces, LANs, gateways, and firewall rules.

The original OpenVPN 1.x HOWTO is still available, and remains relevant for point-to-point or static-key configurations.

While this HOWTO will guide you in setting up a scalable client/server VPN using an X509 PKI (public key infrastruction using certificates and private keys), this might be overkill if you are only looking for a simple VPN setup with a server that can handle a single client.

If you would like to get a VPN running quickly with minimal configuration, you might check out the Static Key Mini-HOWTO.

OpenVPN source code and Windows installers can be downloaded here. Recent releases (2.2 and later) are also available as Debian and RPM packages; see the OpenVPN wiki for details.

The OpenVPN executable should be installed on both server and client machines, since the single executable provides both client and server functions.

If you are using a Linux distribution which supports RPM packages (SuSE, Fedora, Redhat, etc.), it’s best to install using this mechanism. The easiest method is to find an existing binary RPM file for your distribution. You can also build your own binary RPM file:

Furthermore, if you are building your own binary RPM package, there are several additional dependencies:

See the openvpn.spec file for additional notes on building an RPM package for Red Hat Linux 9 or building with reduced dependencies.

If you are using Debian, Gentoo, or a non-RPM-based Linux distribution, use your distro-specific packaging mechanism such as apt-get on Debian or emerge on Gentoo.

It is also possible to install OpenVPN on Linux using the universal ./configure method. First expand the .tar.gz file:

OpenVPN for Windows can be installed from the self-installing exe file on the OpenVPN download page. Remember that OpenVPN will only run on Windows XP or later. Also note that OpenVPN must be installed and run by a user who has administrative privileges (this restriction is imposed by Windows, not OpenVPN). The restriction can be sidestepped by running OpenVPN in the background as a service, in which case even non-admin users will be able to access the VPN, once it is installed. More discussion on OpenVPN + Windows privilege issues.

Official OpenVPN Windows installers include OpenVPN-GUI, which allows managing OpenVPN connections from a system tray applet. Other GUI applications are also available.

After you’ve run the Windows installer, OpenVPN is ready for use and will associate itself with files having the .ovpn extension. To run OpenVPN, you can:

method can be used, or you can search for an OpenVPN port or package which is specific to your OS/distribution.

See FAQ for an overview of Routing vs. Ethernet Bridging. See also the OpenVPN Ethernet Bridging page for more notes and details on bridging.

Overall, routing is probably a better choice for most people, as it is more efficient and easier to set up (as far as the OpenVPN configuration itself) than bridging. Routing also provides a greater ability to selectively control access rights on a client-specific basis.

I would recommend using routing unless you need a specific feature which requires bridging, such as:

Setting up a VPN often entails linking together private subnets from different locations.

The Internet Assigned Numbers Authority (IANA) has reserved the following three blocks of the IP address space for private internets (codified in RFC 1918):

While addresses from these netblocks should normally be used in VPN configurations, it’s important to select addresses that minimize the probability of IP address or subnet conflicts. The types of conflicts that need to be avoided are:

For example, suppose you use the popular 192.168.0.0/24 subnet as your private LAN subnet. Now you are trying to connect to the VPN from an internet cafe which is using the same subnet for its WiFi LAN. You will have a routing conflict because your machine won’t know if 192.168.0.1 refers to the local WiFi gateway or to the same address on the VPN.

As another example, suppose you want to link together multiple sites by VPN, but each site is using 192.168.0.0/24 as its LAN subnet. This won’t work without adding a complexifying layer of NAT translation, because the VPN won’t know how to route packets between multiple sites if those sites don’t use a subnet which uniquely identifies them.

The best solution is to avoid using 10.0.0.0/24 or 192.168.0.0/24 as private LAN network addresses. Instead, use something that has a lower probability of being used in a WiFi cafe, airport, or hotel where you might expect to connect from remotely. The best candidates are subnets in the middle of the vast 10.0.0.0/8 netblock (for example 10.66.77.0/24).

And to avoid cross-site IP numbering conflicts, always use unique numbering for your LAN subnets.

The first step in building an OpenVPN 2.x configuration is to establish a PKI (public key infrastructure). The PKI consists of:

OpenVPN supports bidirectional authentication based on certificates, meaning that the client must authenticate the server certificate and the server must authenticate the client certificate before mutual trust is established.

Both server and client will authenticate the other by first verifying that the presented certificate was signed by the master certificate authority (CA), and then by testing information in the now-authenticated certificate header, such as the certificate common name or certificate type (client or server).

Note that the server and client clocks need to be roughly in sync or certificates might not work properly.

In this section we will generate a master CA certificate/key, a server certificate/key, and certificates/keys for 3 separate clients.

For PKI management, we will use easy-rsa 2, a set of scripts which is bundled with OpenVPN 2.2.x and earlier. If you’re using OpenVPN 2.3.x, you need to download easy-rsa 2 separately from here.

For PKI management, we will use easy-rsa 2, a set of scripts which is bundled with OpenVPN 2.2.x and earlier. If you’re using OpenVPN 2.3.x, you may need to download easy-rsa 2 separately from the easy-rsa-old project page. On *NIX platforms you should look into using easy-rsa 3 instead; refer to its own documentation for details.

If you are using Linux, BSD, or a unix-like OS, open a shell and cd to the easy-rsa subdirectory. If you installed OpenVPN from an RPM or DEB file, the easy-rsa directory can usually be found in /usr/share/doc/packages/openvpn or /usr/share/doc/openvpn(it’s best to copy this directory to another location such as /etc/openvpn, before any edits, so that future OpenVPN package upgrades won’t overwrite your modifications). If you installed from a .tar.gz file, the easy-rsa directory will be in the top level directory of the expanded source tree.

If you are using Windows, open up a Command Prompt window and cd to Program FilesOpenVPNeasy-rsa. Run the following batch file to copy configuration files into place (this will overwrite any preexisting vars.bat and openssl.cnf files):

Now edit the vars file (called vars.bat on Windows) and set the KEY_COUNTRY, KEY_PROVINCE, KEY_CITY, KEY_ORG, and KEY_EMAIL parameters. Don’t leave any of these parameters blank.

Next, initialize the PKI. On Linux/BSD/Unix:

The final command (build-ca) will build the certificate authority (CA) certificate and key by invoking the interactive opensslcommand:

Note that in the above sequence, most queried parameters were defaulted to the values set in the varsor vars.bat files. The only parameter which must be explicitly entered is the Common Name. In the example above, I used «OpenVPN-CA».

Next, we will generate a certificate and private key for the server. On Linux/BSD/Unix:

As in the previous step, most parameters can be defaulted. When the Common Name is queried, enter «server». Two other queries require positive responses, «Sign the certificate? [y/n]» and «1 out of 1 certificate requests certified, commit? [y/n]».

Generating client certificates is very similar to the previous step. On Linux/BSD/Unix:

If you would like to password-protect your client keys, substitute the build-key-pass script.

Remember that for each client, make sure to type the appropriate Common Name when prompted, i.e. «client1», «client2», or «client3». Always use a unique common name for each client.

Diffie Hellman parameters must be generated for the OpenVPN server. On Linux/BSD/Unix:

Now we will find our newly-generated keys and certificates in the keys subdirectory. Here is an explanation of the relevant files:

The final step in the key generation process is to copy all files to the machines which need them, taking care to copy secret files over a secure channel.

Now wait, you may say. Shouldn’t it be possible to set up the PKI without a pre-existing secure channel?

The answer is ostensibly yes. In the example above, for the sake of brevity, we generated all private keys in the same place. With a bit more effort, we could have done this differently. For example, instead of generating the client certificate and keys on the server, we could have had the client generate its own private key locally, and then submit a Certificate Signing Request (CSR) to the key-signing machine. In turn, the key-signing machine could have processed the CSR and returned a signed certificate to the client. This could have been done without ever requiring that a secret .key file leave the hard drive of the machine on which it was generated.

It’s best to use the OpenVPN sample configuration files as a starting point for your own configuration. These files can also be found in

Note that on Linux, BSD, or unix-like OSes, the sample configuration files are named server.conf and client.conf. On Windows they are named server.ovpn and client.ovpn.

The sample server configuration file is an ideal starting point for an OpenVPN server configuration. It will create a VPN using a virtual TUN network interface (for routing), will listen for client connections on UDP port 1194 (OpenVPN’s official port number), and distribute virtual addresses to connecting clients from the 10.8.0.0/24 subnet.

Before you use the sample configuration file, you should first edit the cacertkey, and dh parameters to point to the files you generated in the PKI section above.

At this point, the server configuration file is usable, however you still might want to customize it further:

If you want to run multiple OpenVPN instances on the same machine, each using a different configuration file, it is possible if you:

The sample client configuration file (client.conf on Linux/BSD/Unix or client.ovpn on Windows) mirrors the default directives set in the sample server configuration file.

First, make sure the OpenVPN server will be accessible from the internet. That means:

To simplify troubleshooting, it’s best to initially start the OpenVPN server from the command line (or right-click on the .ovpn file on Windows), rather than start it as a daemon or service:

A normal server startup should look like this (output will vary across platforms):

Starting the client

As in the server configuration, it’s best to initially start the OpenVPN server from the command line (or on Windows, by right-clicking on the client.ovpn file), rather than start it as a daemon or service:

openvpn [client config file] 

A normal client startup on Windows will look similar to the server output above, and should end with the Initialization Sequence Completed message.

Now, try a ping across the VPN from the client. If you are using routing (i.e. dev tun in the server config file), try:

ping 10.8.0.1

If you are using bridging (i.e. dev tap in the server config file), try to ping the IP address of a machine on the server’s ethernet subnet.

If the ping succeeds, congratulations! You now have a functioning VPN.

Troubleshooting

If the ping failed or the OpenVPN client initialization failed to complete, here is a checklist of common symptoms and their solutions:

  • You get the error message: TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity). This error indicates that the client was unable to establish a network connection with the server.Solutions:
    • Make sure the client is using the correct hostname/IP address and port number which will allow it to reach the OpenVPN server.
    • If the OpenVPN server machine is a single-NIC box inside a protected LAN, make sure you are using a correct port forward rule on the server’s gateway firewall. For example, suppose your OpenVPN box is at 192.168.4.4 inside the firewall, listening for client connections on UDP port 1194. The NAT gateway servicing the 192.168.4.x subnet should have a port forward rule that says forward UDP port 1194 from my public IP address to 192.168.4.4.
    • Open up the server’s firewall to allow incoming connections to UDP port 1194 (or whatever TCP/UDP port you have configured in the server config file).
  • You get the error message: Initialization Sequence Completed with errors— This error can occur on Windows if (a) You don’t have the DHCP client service running, or (b) You are using certain third-party personal firewalls on XP SP2.Solution: Start the DHCP client server and make sure that you are using a personal firewall which is known to work correctly on XP SP2.
  • You get the Initialization Sequence Completedmessage but the ping test fails — This usually indicates that a firewall on either server or client is blocking VPN network traffic by filtering on the TUN/TAP interface.Solution: Disable the client firewall (if one exists) from filtering the TUN/TAP interface on the client. For example on Windows XP SP2, you can do this by going to Windows Security Center -> Windows Firewall -> Advanced and unchecking the box which corresponds to the TAP-Windows adapter (disabling the client firewall from filtering the TUN/TAP adapter is generally reasonable from a security perspective, as you are essentially telling the firewall not to block authenticated VPN traffic). Also make sure that the TUN/TAP interface on the server is not being filtered by a firewall (having said that, note that selective firewalling of the TUN/TAP interface on the server side can confer certain security benefits. See the access policies section below).
  • The connection stalls on startup when using a proto udpconfiguration, the server log file shows this line:
    TLS: Initial packet from x.x.x.x:x, sid=xxxxxxxx xxxxxxxx

    however the client log does not show an equivalent line.

    Solution: You have a one-way connection from client to server. The server to client direction is blocked by a firewall, usually on the client side. The firewall can either be (a) a personal software firewall running on the client, or (b) the NAT router gateway for the client. Modify the firewall to allow returning UDP packets from the server to reach the client.

See the FAQ for additional troubleshooting information.


Configuring OpenVPN to run automatically on system startup

The lack of standards in this area means that most OSes have a different way of configuring daemons/services for autostart on boot. The best way to have this functionality configured by default is to install OpenVPN as a package, such as via RPM on Linux or using the Windows installer.

Linux

If you install OpenVPN via an RPM or DEB package on Linux, the installer will set up an initscript. When executed, the initscript will scan for .conf configuration files in /etc/openvpn, and if found, will start up a separate OpenVPN daemon for each file.

Windows

The Windows installer will set up a Service Wrapper, but leave it turned off by default. To activate it, go to Control Panel / Administrative Tools / Services, select the OpenVPN service, right-click on properties, and set the Startup Type to Automatic. This will configure the service for automatic start on the next reboot.

When started, the OpenVPN Service Wrapper will scan the Program FilesOpenVPNconfig folder for .ovpn configuration files, starting a separate OpenVPN process on each file.


Controlling a running OpenVPN process

Running on Linux/BSD/Unix

OpenVPN accepts several signals:

  • SIGUSR1 — Conditional restart, designed to restart without root privileges
  • SIGHUP — Hard restart
  • SIGUSR2 — Output connection statistics to log file or syslog
  • SIGTERMSIGINT — Exit

Use the writepid directive to write the OpenVPN daemon’s PID to a file, so that you know where to send the signal (if you are starting openvpn with an initscript, the script may already be passing a —writepid directive on the openvpn command line).

Running on Windows as a GUI

See the OpenVPN GUI page.

Running in a Windows command prompt window

On Windows, you can start OpenVPN by right clicking on an OpenVPN configuration file (.ovpn file) and selecting «Start OpenVPN on this config file».

Once running in this fashion, several keyboard commands are available:

  • F1 — Conditional restart (doesn’t close/reopen TAP adapter)
  • F2 — Show connection statistics
  • F3 — Hard restart
  • F4 — Exit

Running as a Windows Service

When OpenVPN is started as a service on Windows, the only way to control it is:

  • Via the service control manager (Control Panel / Administrative Tools / Services) which gives start/stop control.
  • Via the management interface (see below).

Modifying a live server configuration

While most configuration changes require you to restart the server, there are two directives in particular which refer to files which can be dynamically updated on-the-fly, and which will take immediate effect on the server without needing to restart the server process.

client-config-dir — This directive sets a client configuration directory, which the OpenVPN server will scan on every incoming connection, searching for a client-specific configuration file (see the the manual page for more information). Files in this directory can be updated on-the-fly, without restarting the server. Note that changes in this directory will only take effect for new connections, not existing connections. If you would like a client-specific configuration file change to take immediate effect on a currently connected client (or one which has disconnected, but where the server has not timed-out its instance object), kill the client instance object by using the management interface (described below). This will cause the client to reconnect and use the new client-config-dir file.

crl-verify — This directive names a Certificate Revocation List file, described below in the Revoking Certificates section. The CRL file can be modified on the fly, and changes will take effect immediately for new connections, or existing connections which are renegotiating their SSL/TLS channel (occurs once per hour by default). If you would like to kill a currently connected client whose certificate has just been added to the CRL, use the management interface (described below).

Status File

The default server.conf file has a line

status openvpn-status.log

which will output a list of current client connections to the file openvpn-status.log once per minute.

Using the management interface

The OpenVPN management interface allows a great deal of control over a running OpenVPN process. You can use the management interface directly, by telneting to the management interface port, or indirectly by using an OpenVPN GUI which itself connects to the management interface.

To enable the management interface on either an OpenVPN server or client, add this to the configuration file:

management localhost 7505

This tells OpenVPN to listen on TCP port 7505 for management interface clients (port 7505 is an arbitrary choice — you can use any free port).

Once OpenVPN is running, you can connect to the management interface using a telnet client. For example:

ai:~ # telnet localhost 7505
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
>INFO:OpenVPN Management Interface Version 1 -- type 'help' for more info
help
Management Interface for OpenVPN 2.0_rc14 i686-suse-linux [SSL] [LZO] [EPOLL] built on Feb 15 2005
Commands:
echo [on|off] [N|all]  : Like log, but only show messages in echo buffer.
exit|quit              : Close management session.
help                   : Print this message.
hold [on|off|release]  : Set/show hold flag to on/off state, or
                         release current hold and start tunnel.
kill cn                : Kill the client instance(s) having common name cn.
kill IP:port           : Kill the client instance connecting from IP:port.
log [on|off] [N|all]   : Turn on/off realtime log display
                         + show last N lines or 'all' for entire history.
mute [n]               : Set log mute level to n, or show level if n is absent.
net                    : (Windows only) Show network info and routing table.
password type p        : Enter password p for a queried OpenVPN password.
signal s               : Send signal s to daemon,
                         s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.
state [on|off] [N|all] : Like log, but show state history.
status [n]             : Show current daemon status info using format #n.
test n                 : Produce n lines of output for testing/debugging.
username type u        : Enter username u for a queried OpenVPN username.
verb [n]               : Set log verbosity level to n, or show if n is absent.
version                : Show current version number.
END
exit
Connection closed by foreign host.
ai:~ #

For more information, see the OpenVPN Management Interface Documentation.


Expanding the scope of the VPN to include additional machines on either the client or server subnet.

Including multiple machines on the server side when using a routed VPN (dev tun)

Once the VPN is operational in a point-to-point capacity between client and server, it may be desirable to expand the scope of the VPN so that clients can reach multiple machines on the server network, rather than only the server machine itself.

For the purpose of this example, we will assume that the server-side LAN uses a subnet of 10.66.0.0/24and the VPN IP address pool uses 10.8.0.0/24 as cited in the server directive in the OpenVPN server configuration file.

First, you must advertise the 10.66.0.0/24 subnet to VPN clients as being accessible through the VPN. This can easily be done with the following server-side config file directive:

push "route 10.66.0.0 255.255.255.0"

Next, you must set up a route on the server-side LAN gateway to route the VPN client subnet (10.8.0.0/24) to the OpenVPN server (this is only necessary if the OpenVPN server and the LAN gateway are different machines).

Make sure that you’ve enabled IP and TUN/TAP forwarding on the OpenVPN server machine.

Including multiple machines on the server side when using a bridged VPN (dev tap)

One of the benefits of using ethernet bridging is that you get this for free without needing any additional configuration.

Including multiple machines on the client side when using a routed VPN (dev tun)

In a typical road-warrior or remote access scenario, the client machine connects to the VPN as a single machine. But suppose the client machine is a gateway for a local LAN (such as a home office), and you would like each machine on the client LAN to be able to route through the VPN.

For this example, we will assume that the client LAN is using the 192.168.4.0/24 subnet, and that the VPN client is using a certificate with a common name of client2. Our goal is to set up the VPN so that any machine on the client LAN can communicate with any machine on the server LAN through the VPN.

Before setup, there are some basic prerequisites which must be followed:

  • The client LAN subnet (192.168.4.0/24 in our example) must not be exported to the VPN by the server or any other client sites which are using the same subnet. Every subnet which is joined to the VPN via routing must be unique.
  • The client must have a unique Common Name in its certificate («client2» in our example), and the duplicate-cn flag must not be used in the OpenVPN server configuration file.

First, make sure that IP and TUN/TAP forwarding is enabled on the client machine.

Next, we will deal with the necessary configuration changes on the server side. If the server configuration file does not currently reference a client configuration directory, add one now:

client-config-dir ccd

In the above directive, ccd should be the name of a directory which has been pre-created in the default directory where the OpenVPN server daemon runs. On Linux this tends to be /etc/openvpn and on Windows it is usually Program FilesOpenVPNconfig. When a new client connects to the OpenVPN server, the daemon will check this directory for a file which matches the common name of the connecting client. If a matching file is found, it will be read and processed for additional configuration file directives to be applied to the named client.

The next step is to create a file called client2 in the ccd directory. This file should contain the line:

iroute 192.168.4.0 255.255.255.0

This will tell the OpenVPN server that the 192.168.4.0/24 subnet should be routed to client2.

Next, add the following line to the main server config file (not the ccd/client2 file):

route 192.168.4.0 255.255.255.0

Why the redundant route and iroute statements, you might ask? The reason is that route controls the routing from the kernel to the OpenVPN server (via the TUN interface) while iroute controls the routing from the OpenVPN server to the remote clients. Both are necessary.

Next, ask yourself if you would like to allow network traffic between client2’s subnet (192.168.4.0/24) and other clients of the OpenVPN server. If so, add the following to the server config file.

client-to-client
push "route 192.168.4.0 255.255.255.0"

This will cause the OpenVPN server to advertise client2’s subnet to other connecting clients.

The last step, and one that is often forgotten, is to add a route to the server’s LAN gateway which directs 192.168.4.0/24 to the OpenVPN server box (you won’t need this if the OpenVPN server box is the gateway for the server LAN). Suppose you were missing this step and you tried to ping a machine (not the OpenVPN server itself) on the server LAN from 192.168.4.8? The outgoing ping would probably reach the machine, but then it wouldn’t know how to route the ping reply, because it would have no idea how to reach 192.168.4.0/24. The rule of thumb to use is that when routing entire LANs through the VPN (when the VPN server is not the same machine as the LAN gateway), make sure that the gateway for the LAN routes all VPN subnets to the VPN server machine.

Similarly, if the client machine running OpenVPN is not also the gateway for the client LAN, then the gateway for the client LAN must have a route which directs all subnets which should be reachable through the VPN to the OpenVPN client machine.

Including multiple machines on the client side when using a bridged VPN (dev tap)

This requires a more complex setup (maybe not more complex in practice, but more complicated to explain in detail):

  • You must bridge the client TAP interface with the LAN-connected NIC on the client.
  • You must manually set the IP/netmask of the TAP interface on the client.
  • You must configure client-side machines to use an IP/netmask that is inside of the bridged subnet, possibly by querying a DHCP server on the OpenVPN server side of the VPN.

Pushing DHCP options to clients

The OpenVPN server can push DHCP options such as DNS and WINS server addresses to clients (some caveats to be aware of). Windows clients can accept pushed DHCP options natively, while non-Windows clients can accept them by using a client-side up script which parses the foreign_option_nenvironmental variable list. See the man page for non-Windows foreign_option_n documentation and script examples.

For example, suppose you would like connecting clients to use an internal DNS server at 10.66.0.4 or 10.66.0.5 and a WINS server at 10.66.0.8. Add this to the OpenVPN server configuration:

push "dhcp-option DNS 10.66.0.4"
push "dhcp-option DNS 10.66.0.5"
push "dhcp-option WINS 10.66.0.8"

To test this feature on Windows, run the following from a command prompt window after the machine has connected to an OpenVPN server:

ipconfig /all

The entry for the TAP-Windows adapter should show the DHCP options which were pushed by the server.


Configuring client-specific rules and access policies

Suppose we are setting up a company VPN, and we would like to establish separate access policies for 3 different classes of users:

  • System administrators — full access to all machines on the network
  • Employees — access only to Samba/email server
  • Contractors — access to a special server only

The basic approach we will take is (a) segregate each user class into its own virtual IP address range, and (b) control access to machines by setting up firewall rules which key off the client’s virtual IP address.

In our example, suppose that we have a variable number of employees, but only one system administrator, and two contractors. Our IP allocation approach will be to put all employees into an IP address pool, and then allocate fixed IP addresses for the system administrator and contractors.

Note that one of the prerequisites of this example is that you have a software firewall running on the OpenVPN server machine which gives you the ability to define specific firewall rules. For our example, we will assume the firewall is Linux iptables.

First, let’s create a virtual IP address map according to user class:

Class Virtual IP Range Allowed LAN Access Common Names
Employees 10.8.0.0/24 Samba/email server at 10.66.4.4 [variable]
System Administrators 10.8.1.0/24 Entire 10.66.4.0/24 subnet sysadmin1
Contractors 10.8.2.0/24 Contractor server at 10.66.4.12 contractor1, contracter2

Next, let’s translate this map into an OpenVPN server configuration. First of all, make sure you’ve followed the steps above for making the 10.66.4.0/24 subnet available to all clients (while we will configure routing to allow client access to the entire 10.66.4.0/24 subnet, we will then impose access restrictions using firewall rules to implement the above policy table).

First, define a static unit number for our tun interface, so that we will be able to refer to it later in our firewall rules:

dev tun0

In the server configuration file, define the Employee IP address pool:

server 10.8.0.0 255.255.255.0

Add routes for the System Administrator and Contractor IP ranges:

route 10.8.1.0 255.255.255.0
route 10.8.2.0 255.255.255.0

Because we will be assigning fixed IP addresses for specific System Administrators and Contractors, we will use a client configuration directory:

client-config-dir ccd

Now place special configuration files in the ccd subdirectory to define the fixed IP address for each non-Employee VPN client.

ccd/sysadmin1

ifconfig-push 10.8.1.1 10.8.1.2

ccd/contractor1

ifconfig-push 10.8.2.1 10.8.2.2

ccd/contractor2

ifconfig-push 10.8.2.5 10.8.2.6

Each pair of ifconfig-push addresses represent the virtual client and server IP endpoints. They must be taken from successive /30 subnets in order to be compatible with Windows clients and the TAP-Windows driver. Specifically, the last octet in the IP address of each endpoint pair must be taken from this set:

[  1,  2] [  5,  6] [  9, 10] [ 13, 14] [ 17, 18]
[ 21, 22] [ 25, 26] [ 29, 30] [ 33, 34] [ 37, 38]
[ 41, 42] [ 45, 46] [ 49, 50] [ 53, 54] [ 57, 58]
[ 61, 62] [ 65, 66] [ 69, 70] [ 73, 74] [ 77, 78]
[ 81, 82] [ 85, 86] [ 89, 90] [ 93, 94] [ 97, 98]
[101,102] [105,106] [109,110] [113,114] [117,118]
[121,122] [125,126] [129,130] [133,134] [137,138]
[141,142] [145,146] [149,150] [153,154] [157,158]
[161,162] [165,166] [169,170] [173,174] [177,178]
[181,182] [185,186] [189,190] [193,194] [197,198]
[201,202] [205,206] [209,210] [213,214] [217,218]
[221,222] [225,226] [229,230] [233,234] [237,238]
[241,242] [245,246] [249,250] [253,254]

This completes the OpenVPN configuration. The final step is to add firewall rules to finalize the access policy. For this example, we will use firewall rules in the Linux iptables syntax:

# Employee rule
iptables -A FORWARD -i tun0 -s 10.8.0.0/24 -d 10.66.4.4 -j ACCEPT

# Sysadmin rule
iptables -A FORWARD -i tun0 -s 10.8.1.0/24 -d 10.66.4.0/24 -j ACCEPT

# Contractor rule
iptables -A FORWARD -i tun0 -s 10.8.2.0/24 -d 10.66.4.12 -j ACCEPT

Using alternative authentication methods

OpenVPN 2.0 and later include a feature that allows the OpenVPN server to securely obtain a username and password from a connecting client, and to use that information as a basis for authenticating the client.

To use this authentication method, first add the auth-user-pass directive to the client configuration. It will direct the OpenVPN client to query the user for a username/password, passing it on to the server over the secure TLS channel.

Next, configure the server to use an authentication plugin, which may be a script, shared object, or DLL. The OpenVPN server will call the plugin every time a VPN client tries to connect, passing it the username/password entered on the client. The authentication plugin can control whether or not the OpenVPN server allows the client to connect by returning a failure (1) or success (0) value.

Using Script Plugins

Script plugins can be used by adding the auth-user-pass-verify directive to the server-side configuration file. For example:

auth-user-pass-verify auth-pam.pl via-file

will use the auth-pam.pl perl script to authenticate the username/password of connecting clients. See the description of auth-user-pass-verify in the manual page for more information.

The auth-pam.pl script is included in the OpenVPN source file distribution in the sample-scriptssubdirectory. It will authenticate users on a Linux server using a PAM authentication module, which could in turn implement shadow password, RADIUS, or LDAP authentication. auth-pam.pl is primarily intended for demonstration purposes. For real-world PAM authentication, use the openvpn-auth-pamshared object plugin described below.

Using Shared Object or DLL Plugins

Shared object or DLL plugins are usually compiled C modules which are loaded by the OpenVPN server at run time. For example if you are using an RPM-based OpenVPN package on Linux, the openvpn-auth-pam plugin should be already built. To use it, add this to the server-side config file:

plugin /usr/share/openvpn/plugin/lib/openvpn-auth-pam.so login

This will tell the OpenVPN server to validate the username/password entered by clients using the loginPAM module.

For real-world production use, it’s better to use the openvpn-auth-pam plugin, because it has several advantages over the auth-pam.pl script:

  • The shared object openvpn-auth-pam plugin uses a split-privilege execution model for better security. This means that the OpenVPN server can run with reduced privileges by using the directives user nobodygroup nobody, and chroot, and will still be able to authenticate against the root-readable-only shadow password file.
  • OpenVPN can pass the username/password to a plugin via virtual memory, rather than via a file or the environment, which is better for local security on the server machine.
  • C-compiled plugin modules generally run faster than scripts.

If you would like more information on developing your own plugins for use with OpenVPN, see the README files in the plugin subdirectory of the OpenVPN source distribution.

To build the openvpn-auth-pam plugin on Linux, cd to the plugin/auth-pam directory in the OpenVPN source distribution and run make.

Using username/password authentication as the only form of client authentication

By default, using auth-user-pass-verify or a username/password-checking plugin on the server will enable dual authentication, requiring that both client-certificate and username/password authentication succeed in order for the client to be authenticated.

While it is discouraged from a security perspective, it is also possible to disable the use of client certificates, and force username/password authentication only. On the server:

client-cert-not-required

Such configurations should usually also set:

username-as-common-name

which will tell the server to use the username for indexing purposes as it would use the Common Name of a client which was authenticating via a client certificate.

Note that client-cert-not-required will not obviate the need for a server certificate, so a client connecting to a server which uses client-cert-not-required may remove the cert and key directives from the client configuration file, but not the ca directive, because it is necessary for the client to verify the server certificate.


How to add dual-factor authentication to an OpenVPN configuration using client-side smart cards

  • About dual-factor authentication
  • What is PKCS#11?
  • Finding PKCS#11 provider library.
  • How to configure a cryptographic token
  • How to modify an OpenVPN configuration to make use of cryptographic tokens
    • Determine the correct object.
    • Using OpenVPN with PKCS#11.
    • PKCS#11 implementation considerations.
    • OpenSC PKCS#11 provider.
  • Difference between PKCS#11 and Microsoft Cryptographic API (CryptoAPI).

About dual-factor authentication

Dual-factor authentication is a method of authentication that combines two elements: something you have and something you know.

Something you have should be a device that cannot be duplicated; such a device can be a cryptographic token that contains a private secret key. This private key is generated inside the device and never leaves it. If a user possessing this token attempts to access protected services on a remote network, the authorization process which grants or denies network access can establish, with a high degree of certainty, that the user seeking access is in physical possession of a known, certified token.

Something you know can be a password presented to the cryptographic device. Without presenting the proper password you cannot access the private secret key. Another feature of cryptographic devices is to prohibit the use of the private secret key if the wrong password had been presented more than an allowed number of times. This behavior ensures that if a user lost his device, it would be infeasible for another person to use it.

Cryptographic devices are commonly called «smart cards» or «tokens», and are used in conjunction with a PKI (Public Key Infrastructure). The VPN server can examine a X.509 certificate and verify that the user holds the corresponding private secret key. Since the device cannot be duplicated and requires a valid password, the server is able to authenticate the user with a high degree of confidence.

Dual-factor authentication is much stronger than password-based authentication, because in the worst-case scenario, only one person at a time can use the cryptographic token. Passwords can be guessed and can be exposed to other users, so in the worst-case scenario an infinite number of people could attempt to gain unauthorized access when resources are protected using password-only authentication.

If you store the secret private key in a file, the key is usually encrypted by a password. The problem with this approach is that the encrypted key is exposed to decryption attacks or spyware/malware running on the client machine. Unlike when using a cryptographic device, the file cannot erase itself automatically after several failed decryption attempts.

What is PKCS#11?

This standard specifies an API, called Cryptoki, to devices which hold cryptographic information and perform cryptographic functions. Cryptoki, pronounced «crypto-key» and short for cryptographic token interface, follows a simple object-based approach, addressing the goals of technology independence (any kind of device) and resource sharing (multiple applications accessing multiple devices), presenting to applications a common, logical view of the device called a cryptographic token.

Source: RSA Security Inc. https://www.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-11-cryptographic-token-interface-standard.htm.

To summarize, PKCS#11 is a standard that can be used by application software to access cryptographic tokens such as smart cards and other devices. Most device vendors provide a library that implements the PKCS#11 provider interface — this library can be used by applications in order to access these devices. PKCS#11 is a cross-platform, vendor-independent free standard.

Finding PKCS#11 provider library

The first thing you need to do is to find the provider library, it should be installed with the device drivers. Each vendor has its own library. For example, the OpenSC PKCS#11 provider is located at /usr/lib/pkcs11/opensc-pkcs11.so on Unix or at opensc-pkcs11.dll on Windows.

How to configure cryptographic token

You should follow an enrollment procedure:

  • Initialize the PKCS#11 token.
  • Generate RSA key pair on the PKCS#11 token.
  • Create a certificate request based on the key pair, you can use OpenSC and OpenSSL in order to do that.
  • Submit the certificate request to a certificate authority, and receive a certificate.
  • Load the certificate onto the token, while noting that the id and label attributes of the certificate must match those of the private key.

A configured token is a token that has a private key object and a certificate object, where both share the same id and label attributes.

A simple enrollment utility is Easy-RSA 2.0 which is part of OpenVPN 2.1 series. Follow the instructions specified in the README file, and then use the pkitool in order to enroll.

Initialize a token using the following command:

$ ./pkitool --pkcs11-slots /usr/lib/pkcs11/
$ ./pkitool --pkcs11-init /usr/lib/pkcs11/  

Enroll a certificate using the following command:

$ ./pkitool --pkcs11 /usr/lib/pkcs11/   client1

How to modify an OpenVPN configuration to make use of cryptographic tokens

You should have OpenVPN 2.1 or above in order to use the PKCS#11 features.

Determine the correct object

Each PKCS#11 provider can support multiple devices. In order to view the available object list you can use the following command:

$ openvpn --show-pkcs11-ids /usr/lib/pkcs11/

The following objects are available for use.
Each object shown below may be used as parameter to
--pkcs11-id option please remember to use single quote mark.

Certificate
       DN:             /CN=User1
       Serial:         490B82C4000000000075
       Serialized id:  aaaa/bbb/41545F5349474E415455524581D2A1A1B23C4AA4CB17FAF7A4600

Each certificate/private key pair have unique «Serialized id» string. The serialized id string of the requested certificate should be specified to the pkcs11-id option using single quote marks.

pkcs11-id 'aaaa/bbb/41545F5349474E415455524581D2A1A1B23C4AA4CB17FAF7A4600'

Using OpenVPN with PKCS#11

A typical set of OpenVPN options for PKCS#11
pkcs11-providers /usr/lib/pkcs11/
pkcs11-id 'aaaa/bbb/41545F5349474E415455524581D2A1A1B23C4AA4CB17FAF7A4600'

This will select the object which matches the pkcs11-id string.

Advanced OpenVPN options for PKCS#11
pkcs11-providers /usr/lib/pkcs11/provider1.so /usr/lib/pkcs11/provider2.so
pkcs11-id 'aaaa/bbb/41545F5349474E415455524581D2A1A1B23C4AA4CB17FAF7A4600'
pkcs11-pin-cache 300
daemon
auth-retry nointeract
management-hold
management-signal
management 127.0.0.1 8888
management-query-passwords

This will load two providers into OpenVPN, use the certificate specified on pkcs11-id option, and use the management interface in order to query passwords. The daemon will resume into hold state on the event when token cannot be accessed. The token will be used for 300 seconds after which the password will be re-queried, session will disconnect if management session disconnects.

PKCS#11 implementation considerations

Many PKCS#11 providers make use of threads, in order to avoid problems caused by implementation of LinuxThreads (setuid, chroot), it is highly recommend to upgrade to Native POSIX Thread Library (NPTL) enabled glibc if you intend to use PKCS#11.

OpenSC PKCS#11 provider

OpenSC PKCS#11 provider is located at /usr/lib/pkcs11/opensc-pkcs11.so on Unix or at opensc-pkcs11.dll on Windows.

Difference between PKCS#11 and Microsoft Cryptographic API (CryptoAPI)

PKCS#11 is a free, cross-platform vendor independent standard. CryptoAPI is a Microsoft specific API. Most smart card vendors provide support for both interfaces. In the Windows environment, the user should select which interface to use.

The current implementation of OpenVPN that uses the MS CryptoAPI (cryptoapicert option) works well as long as you don’t run OpenVPN as a service. If you wish to run OpenVPN in an administrative environment using a service, the implementation will not work with most smart cards because of the following reasons:

  • Most smart card providers do not load certificates into the local machine store, so the implementation will be unable to access the user certificate.
  • If the OpenVPN client is running as a service without direct interaction with the end-user, the service cannot query the user to provide a password for the smart card, causing the password-verification process on the smart card to fail.

Using the PKCS#11 interface, you can use smart cards with OpenVPN in any implementation, since PKCS#11 does not access Microsoft stores and does not necessarily require direct interaction with the end-user.


Routing all client traffic (including web-traffic) through the VPN

Overview

By default, when an OpenVPN client is active, only network traffic to and from the OpenVPN server site will pass over the VPN. General web browsing, for example, will be accomplished with direct connections that bypass the VPN.

In certain cases this behavior might not be desirable — you might want a VPN client to tunnel all network traffic through the VPN, including general internet web browsing. While this type of VPN configuration will exact a performance penalty on the client, it gives the VPN administrator more control over security policies when a client is simultaneously connected to both the public internet and the VPN at the same time.

Implementation

Add the following directive to the server configuration file:

push "redirect-gateway def1"

If your VPN setup is over a wireless network, where all clients and the server are on the same wireless subnet, add the local flag:

push "redirect-gateway local def1"

Pushing the redirect-gateway option to clients will cause all IP network traffic originating on client machines to pass through the OpenVPN server. The server will need to be configured to deal with this traffic somehow, such as by NATing it to the internet, or routing it through the server site’s HTTP proxy.

On Linux, you could use a command such as this to NAT the VPN client traffic to the internet:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

This command assumes that the VPN subnet is 10.8.0.0/24 (taken from the server directive in the OpenVPN server configuration) and that the local ethernet interface is eth0.

When redirect-gateway is used, OpenVPN clients will route DNS queries through the VPN, and the VPN server will need handle them. This can be accomplished by pushing a DNS server address to connecting clients which will replace their normal DNS server settings during the time that the VPN is active. For example:

push "dhcp-option DNS 10.8.0.1"

will configure Windows clients (or non-Windows clients with some extra server-side scripting) to use 10.8.0.1 as their DNS server. Any address which is reachable from clients may be used as the DNS server address.

Caveats

Redirecting all network traffic through the VPN is not entirely a problem-free proposition. Here are some typical gotchas to be aware of:

  • Many OpenVPN client machines connecting to the internet will periodically interact with a DHCP server to renew their IP address leases. The redirect-gateway option might prevent the client from reaching the local DHCP server (because DHCP messages would be routed over the VPN), causing it to lose its IP address lease.
  • Issues exist with respect to pushing DNS addresses to Windows clients.
  • Web browsing performance on the client will be noticably slower.

For more information on the mechanics of the redirect-gateway directive, see the manual page.


Running an OpenVPN server on a dynamic IP address

While OpenVPN clients can easily access the server via a dynamic IP address without any special configuration, things get more interesting when the server itself is on a dynamic address. While OpenVPN has no trouble handling the situation of a dynamic server, some extra configuration is required.

The first step is to get a dynamic DNS address which can be configured to «follow» the server every time the server’s IP address changes. There are several dynamic DNS service providers available, such as dyndns.org.

The next step is to set up a mechanism so that every time the server’s IP address changes, the dynamic DNS name will be quickly updated with the new IP address, allowing clients to find the server at its new IP address. There are two basic ways to accomplish this:

  • Use a NAT router appliance with dynamic DNS support (such as the Linksys BEFSR41). Most of the inexpensive NAT router appliances that are widely available have the capability to update a dynamic DNS name every time a new DHCP lease is obtained from the ISP. This setup is ideal when the OpenVPN server box is a single-NIC machine inside the firewall.
  • Use a dynamic DNS client application such as ddclient to update the dynamic DNS address whenever the server IP address changes. This setup is ideal when the machine running OpenVPN has multiple NICs and is acting as a site-wide firewall/gateway. To implement this setup, you need to set up a script to be run by your DHCP client software every time an IP address change occurs. This script should (a) run ddclientto notify your dynamic DNS provider of your new IP address and (b) restart the OpenVPN server daemon.

The OpenVPN client by default will sense when the server’s IP address has changed, if the client configuration is using a remote directive which references a dynamic DNS name. The usual chain of events is that (a) the OpenVPN client fails to receive timely keepalive messages from the server’s old IP address, triggering a restart, and (b) the restart causes the DNS name in the remote directive to be re-resolved, allowing the client to reconnect to the server at its new IP address.

More information can be found in the FAQ.


Connecting to an OpenVPN server via an HTTP proxy.

OpenVPN supports connections through an HTTP proxy, with the following authentication modes:

  • No proxy authentication
  • Basic proxy authentication
  • NTLM proxy authentication

First of all, HTTP proxy usage requires that you use TCP as the tunnel carrier protocol. So add the following to both client and server configurations:

proto tcp

Make sure that any proto udp lines in the config files are deleted.

Next, add the http-proxy directive to the client configuration file (see the manual page for a full description of this directive).

For example, suppose you have an HTTP proxy server on the client LAN at 192.168.4.1, which is listening for connections on port 1080. Add this to the client config:

http-proxy 192.168.4.1 1080

Suppose the HTTP proxy requires Basic authentication:

http-proxy 192.168.4.1 1080 stdin basic

Suppose the HTTP proxy requires NTLM authentication:

http-proxy 192.168.4.1 1080 stdin ntlm

The two authentication examples above will cause OpenVPN to prompt for a username/password from standard input. If you would instead like to place these credentials in a file, replace stdin with a filename, and place the username on line 1 of this file and the password on line 2.


This example is intended show how OpenVPN clients can connect to a Samba share over a routed dev tun tunnel. If you are ethernet bridging (dev tap), you probably don’t need to follow these instructions, as OpenVPN clients should see server-side machines in their network neighborhood.

For this example, we will assume that:

  • the server-side LAN uses a subnet of 10.66.0.0/24,
  • the VPN IP address pool uses 10.8.0.0/24 (as cited in the server directive in the OpenVPN server configuration file),
  • the Samba server has an IP address of 10.66.0.4, and
  • the Samba server has already been configured and is reachable from the local LAN.

If the Samba and OpenVPN servers are running on different machines, make sure you’ve followed the section on expanding the scope of the VPN to include additional machines.

Next, edit your Samba configuration file (smb.conf). Make sure the hosts allow directive will permit OpenVPN clients coming from the 10.8.0.0/24 subnet to connect. For example:

hosts allow = 10.66.0.0/24 10.8.0.0/24 127.0.0.1

If you are running the Samba and OpenVPN servers on the same machine, you may want to edit the interfaces directive in the smb.conf file to also listen on the TUN interface subnet of 10.8.0.0/24:

interfaces  = 10.66.0.0/24 10.8.0.0/24

If you are running the Samba and OpenVPN servers on the same machine, connect from an OpenVPN client to a Samba share using the folder name:

\10.8.0.1\sharename

If the Samba and OpenVPN servers are on different machines, use folder name:

\10.66.0.4sharename

For example, from a command prompt window:

net use z: \10.66.0.4sharename /USER:myusername

Implementing a load-balancing/failover configuration

Client

The OpenVPN client configuration can refer to multiple servers for load balancing and failover. For example:

remote server1.mydomain
remote server2.mydomain
remote server3.mydomain

will direct the OpenVPN client to attempt a connection with server1, server2, and server3 in that order. If an existing connection is broken, the OpenVPN client will retry the most recently connected server, and if that fails, will move on to the next server in the list. You can also direct the OpenVPN client to randomize its server list on startup, so that the client load will be probabilistically spread across the server pool.

remote-random

If you would also like DNS resolution failures to cause the OpenVPN client to move to the next server in the list, add the following:

resolv-retry 60

The 60 parameter tells the OpenVPN client to try resolving each remote DNS name for 60 seconds before moving on to the next server in the list.

The server list can also refer to multiple OpenVPN server daemons running on the same machine, each listening for connections on a different port, for example:

remote smp-server1.mydomain 8000
remote smp-server1.mydomain 8001
remote smp-server2.mydomain 8000
remote smp-server2.mydomain 8001

If your servers are multi-processor machines, running multiple OpenVPN daemons on each server can be advantageous from a performance standpoint.

OpenVPN also supports the remote directive referring to a DNS name which has multiple A records in the zone configuration for the domain. In this case, the OpenVPN client will randomly choose one of the A records every time the domain is resolved.

Server

The simplest approach to a load-balanced/failover configuration on the server is to use equivalent configuration files on each server in the cluster, except use a different virtual IP address pool for each server. For example:

server1

server 10.8.0.0 255.255.255.0

server2

server 10.8.1.0 255.255.255.0

server3

server 10.8.2.0 255.255.255.0

Hardening OpenVPN Security

One of the often-repeated maxims of network security is that one should never place so much trust in a single security component that its failure causes a catastrophic security breach. OpenVPN provides several mechanisms to add additional security layers to hedge against such an outcome.

tls-auth

The tls-auth directive adds an additional HMAC signature to all SSL/TLS handshake packets for integrity verification. Any UDP packet not bearing the correct HMAC signature can be dropped without further processing. The tls-auth HMAC signature provides an additional level of security above and beyond that provided by SSL/TLS. It can protect against:

  • DoS attacks or port flooding on the OpenVPN UDP port.
  • Port scanning to determine which server UDP ports are in a listening state.
  • Buffer overflow vulnerabilities in the SSL/TLS implementation.
  • SSL/TLS handshake initiations from unauthorized machines (while such handshakes would ultimately fail to authenticate, tls-auth can cut them off at a much earlier point).

Using tls-auth requires that you generate a shared-secret key that is used in addition to the standard RSA certificate/key:

openvpn --genkey --secret ta.key

This command will generate an OpenVPN static key and write it to the file ta.key. This key should be copied over a pre-existing secure channel to the server and all client machines. It can be placed in the same directory as the RSA .key and .crt files.

In the server configuration, add:

tls-auth ta.key 0

In the client configuration, add:

tls-auth ta.key 1

proto udp

While OpenVPN allows either the TCP or UDP protocol to be used as the VPN carrier connection, the UDP protocol will provide better protection against DoS attacks and port scanning than TCP:

proto udp

user/group (non-Windows only)

OpenVPN has been very carefully designed to allow root privileges to be dropped after initialization, and this feature should always be used on Linux/BSD/Solaris. Without root privileges, a running OpenVPN server daemon provides a far less enticing target to an attacker.

user nobody
group nobody

Unprivileged mode (Linux only)

On Linux OpenVPN can be run completely unprivileged. This configuration is a little more complex, but provides best security.

In order to work with this configuration, OpenVPN must be configured to use iproute interface, this is done by specifying —enable-iproute2 to configure script. sudo package should also be available on your system.

This configuration uses the Linux ability to change the permission of a tun device, so that unprivileged user may access it. It also uses sudo in order to execute iproute so that interface properties and routing table may be modified.

OpenVPN configuration:

    • Write the following script and place it at: /usr/local/sbin/unpriv-ip:
#!/bin/sh
sudo /sbin/ip $*
    • Execute visudo, and add the followings to allow user ‘user1’ to execute /sbin/ip:
user1 ALL=(ALL)  NOPASSWD: /sbin/ip
    • You can also enable a group of users with the following command:
%users ALL=(ALL)  NOPASSWD: /sbin/ip
    • Add the following to your OpenVPN configuration:
dev tunX/tapX
iproute /usr/local/sbin/unpriv-ip
    • Please note that you must select constant X and specify tun or tap not both.

    • As root add persistant interface, and permit user and/or group to manage it, the following create tunX (replace with your own) and allow user1 and group users to access it.
openvpn --mktun --dev tunX --type tun --user user1 --group users
  • Run OpenVPN in the context of the unprivileged user.

Further security constraints may be added by examining the parameters at the /usr/local/sbin/unpriv-ip script.

chroot (non-Windows only)

The chroot directive allows you to lock the OpenVPN daemon into a so-called chroot jail, where the daemon would not be able to access any part of the host system’s filesystem except for the specific directory given as a parameter to the directive. For example,

chroot jail

would cause the OpenVPN daemon to cd into the jail subdirectory on initialization, and would then reorient its root filesystem to this directory so that it would be impossible thereafter for the daemon to access any files outside of jail and its subdirectory tree. This is important from a security perspective, because even if an attacker were able to compromise the server with a code insertion exploit, the exploit would be locked out of most of the server’s filesystem.

Caveats: because chroot reorients the filesystem (from the perspective of the daemon only), it is necessary to place any files which OpenVPN might need after initialization in the jail directory, such as:

  • the crl-verify file, or
  • the client-config-dir directory.

Larger RSA keys

The RSA key size is controlled by the KEY_SIZE variable in the easy-rsa/vars file, which must be set before any keys are generated. Currently set to 1024 by default, this value can reasonably be increased to 2048 with no negative impact on VPN tunnel performance, except for a slightly slower SSL/TLS renegotiation handshake which occurs once per client per hour, and a much slower one-time Diffie Hellman parameters generation process using the easy-rsa/build-dh script.

Larger symmetric keys

By default OpenVPN uses Blowfish, a 128 bit symmetrical cipher.

OpenVPN automatically supports any cipher which is supported by the OpenSSL library, and as such can support ciphers which use large key sizes. For example, the 256-bit version of AES (Advanced Encryption Standard) can be used by adding the following to both server and client configuration files:

cipher AES-256-CBC

Keep the root key (ca.key) on a standalone machine without a network connection

One of the security benefits of using an X509 PKI (as OpenVPN does) is that the root CA key (ca.key) need not be present on the OpenVPN server machine. In a high security environment, you might want to specially designate a machine for key signing purposes, keep the machine well-protected physically, and disconnect it from all networks. Floppy disks can be used to move key files back and forth, as necessary. Such measures make it extremely difficult for an attacker to steal the root key, short of physical theft of the key signing machine.


Revoking Certificates

Revoking a certificate means to invalidate a previously signed certificate so that it can no longer be used for authentication purposes.

Typical reasons for wanting to revoke a certificate include:

  • The private key associated with the certificate is compromised or stolen.
  • The user of an encrypted private key forgets the password on the key.
  • You want to terminate a VPN user’s access.

Example

As an example, we will revoke the client2 certificate, which we generated above in the «key generation» section of the HOWTO.

First open up a shell or command prompt window and cd to the easy-rsa directory as you did in the «key generation» section above. On Linux/BSD/Unix:

. ./vars
./revoke-full client2

On Windows:

vars
revoke-full client2

You should see output similar to this:

Using configuration from /root/openvpn/20/openvpn/tmp/easy-rsa/openssl.cnf
DEBUG[load_index]: unique_subject = "yes"
Revoking Certificate 04.
Data Base Updated
Using configuration from /root/openvpn/20/openvpn/tmp/easy-rsa/openssl.cnf
DEBUG[load_index]: unique_subject = "yes"
client2.crt: /C=KG/ST=NA/O=OpenVPN-TEST/CN=client2/emailAddress=me@myhost.mydomain
error 23 at 0 depth lookup:certificate revoked

Note the «error 23» in the last line. That is what you want to see, as it indicates that a certificate verification of the revoked certificate failed.

The revoke-full script will generate a CRL (certificate revocation list) file called crl.pem in the keyssubdirectory. The file should be copied to a directory where the OpenVPN server can access it, then CRL verification should be enabled in the server configuration:

crl-verify crl.pem

Now all connecting clients will have their client certificates verified against the CRL, and any positive match will result in the connection being dropped.

CRL Notes

  • When the crl-verify option is used in OpenVPN, the CRL file will be re-read any time a new client connects or an existing client renegotiates the SSL/TLS connection (by default once per hour). This means that you can update the CRL file while the OpenVPN server daemon is running, and have the new CRL take effect immediately for newly connecting clients. If the client whose certificate you are revoking is already connected, you can restart the server via a signal (SIGUSR1 or SIGHUP) and flush all clients, or you can telnet to the management interfaceand explicitly kill the specific client instance object on the server without disturbing other clients.
  • While the crl-verify directive can be used on both the OpenVPN server and clients, it is generally unnecessary to distribute a CRL file to clients unless a server certificate has been revoked. Clients don’t need to know about other client certificates which have been revoked because clients shouldn’t be accepting direct connections from other clientsin the first place.
  • The CRL file is not secret, and should be made world-readable so that the OpenVPN daemon can read it after root privileges have been dropped.
  • If you are using the chrootdirective, make sure to put a copy of the CRL file in the chroot directory, since unlike most other files which OpenVPN reads, the CRL file will be read after the chroot call is executed, not before.
  • A common reason why certificates need to be revoked is that the user encrypts their private key with a password, then forgets the password. By revoking the original certificate, it is possible to generate a new certificate/key pair with the user’s original common name.

Important Note on possible «Man-in-the-Middle» attack if clients do not verify the certificate of the server they are connecting to.

To avoid a possible Man-in-the-Middle attack where an authorized client tries to connect to another client by impersonating the server, make sure to enforce some kind of server certificate verification by clients. There are currently five different ways of accomplishing this, listed in the order of preference:

  • [OpenVPN 2.1 and above]Build your server certificates with specific key usage and extended key usage. The RFC3280 determine that the following attributes should be provided for TLS connections:
    Mode Key usage Extended key usage
    Client digitalSignature TLS Web Client Authentication
    keyAgreement
    digitalSignature, keyAgreement
    Server digitalSignature, keyEncipherment TLS Web Server Authentication
    digitalSignature, keyAgreement

    You can build your server certificates with the build-key-server script (see the easy-rsadocumentation for more info). This will designate the certificate as a server-only certificate by setting the right attributes. Now add the following line to your client configuration:

    remote-cert-tls server
  • [OpenVPN 2.0 and below] Build your server certificates with the build-key-server script (see the easy-rsa documentation for more info). This will designate the certificate as a server-only certificate by setting nsCertType=server. Now add the following line to your client configuration:
    ns-cert-type server

    This will block clients from connecting to any server which lacks the nsCertType=server designation in its certificate, even if the certificate has been signed by the ca file in the OpenVPN configuration file.

  • Use the tls-remotedirective on the client to accept/reject the server connection based on the common name of the server certificate.
  • Use a tls-verifyscript or plugin to accept/reject the server connection based on a custom test of the server certificate’s embedded X509 subject details.
  • Sign server certificates with one CA and client certificates with a different CA. The client configuration ca directive should reference the server-signing CA file, while the server configuration cadirective should reference the client-signing CA file.

Обновлено Обновлено: 09.12.2021
Опубликовано Опубликовано: 20.07.2017

Тематические термины: OpenVPN, VPN, Windows, Linux, CentOS, Ubuntu

В данной инструкции подробно описан процесс настройки клиента OpenVPN на примере операционных систем Windows и Linux. Также, с ее помощью можно настроить скиента на Android.

Установка
Настройка
    Пример конфигурационного файла
    Ключи
    Сертификаты
Запуск
Несколько конфигураций
Сертификаты внутри ovpn файла
Отзыв сертификата
Читайте также

Установка

Windows

Заходим на официальную страницу загрузки openvpn и скачиваем клиента для нужной Windows:

Скачиваем OpenVPN для Windows

Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».

Linux CentOS

Устанавливаем репозиторий EPEL:

yum install epel-release

Устанавливаем openvpn:

yum install openvpn

Linux Ubuntu

apt-get install openvpn

Android

Установка выполняется из Google Play. Набираем в поиске OpenVPN Connect — нажимаем установить и принимаем условия.

Настройка

После установки программы конфигурационный файл не создается автоматически и его нужно создать вручную.

В системах Windows создаем файл config.ovpn в папке %programfiles%OpenVPNconfig.

* имя файла может быть любым, расширение должно быть .ovpn.

Для создания конфигурационного файла в Linux выполняем команду:

vi /etc/openvpn/client.conf

* чтобы служба openvpn автоматически выполняла соединение, необходимо, чтобы конфигурационный файл назывался client.conf.

Пример конфигурационного файла

client
dev tun
proto udp
remote 192.168.0.15 443
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client.crt
key client.key
dh dh2048.pem
tls-client
tls-auth ta.key 1
float
keepalive 10 120
comp-lzo
verb 0

Параметры конфигурационного файла

Параметр Значения Описание
client   Строка говорит о том, что конфигурационный файл описывает клиентское подключение (программа сама устанавливает соединение, а не ждет, как сервер).
dev tap или tun Выбор виртуального сетевого драйвера. TUN — сетевой уровень модели OSI, оперирует IP-пакетами. TAP — эмулирует Ethernet устройство и работает на канальном уровне модели OSI, оперируя кадрами Ethernet. Настраивая OpenVPN клиента, в большинстве случаев, необходимо выбирать tun. TAP необходимо использовать для работы определенных сервисов, например DHCP.
dev-node любая строка Параметр используется в системах Windows в случаях, если имеется несколько сетевых интерфейсов. Значение этого параметра должно содержать название сетевого подключения, через который должен работать OpenVPN.
proto udp или tcp Указывает, какой протокол использовать для передачи данных. В большинстве случаев, лучше использовать UDP, так как данный протокол создает меньше нагрузки на сеть.
remote VPN-сервер и порт Задает сервер, к которому должен подключаться клиент, а также сетевой порт (по умолчанию 1194), на котором OpenVPN принимает запросы. Можно указать несколько строк.
remote-random   Если указано несколько строк remote, данный параметр говорит, что необходимо подключаться к удаленным серверам в случайном порядке.
resolv-retry количество секунд или infinite Используется в тех случаях, когда в качестве сервера указано доменное имя. Параметр задает время в секундах для повторного переподключения, если не удалось узнать имя сервера. infinite — держать связь с сервером постоянно.
nobind   Клиент использует динамический порт для подключения.
user учетная запись Задает определенного пользователя для работы клиента (только для UNIX-систем).
group группа Задает определенную группу для работы клиента (только для UNIX-систем).
persist-key   Не перечитывает ключи при перезагрузке сервиса OpenVPN.
persist-tun   Не перечитывает параметры туннеля при перезагрузке сервиса OpenVPN.
http-proxy сервер прокси и порт Использовать прокси-сервер для подключения.
http-proxy-retry   Переподключаться к прокси-серверу, если связь была разорвана.
http-proxy-timeout количество секунд Время, через которое выполнять попытки переподключения к прокси-серверу.
mute-replay-warnings   Параметр стоит задавать при использовании беспроводного соединения. Он отключит дублирование предупреждений пакетов.
ca пут к сертификату Корневой сертификат удостоверяющего центра. Генерируем на сервере.
cert пут к сертификату Открытый ключ клиента. Генерируем на сервере.
key пут к сертификату Закрытый ключ клиента. Генерируем на сервере.
dh пут к сертификату Ключ с алгоритмом Diffie-Hellman (Диффи-Хеллмана).
remote-cert-tls сервер Исключает возможность mitm атаки, включая верификацию сертификата сервера.
tls-client   Указание на то, что это клиент TLS.
tls-auth ta.key 1 Дополнительный уровень аутентификации посредством ключа TLS.
float   Удаленный хост может менять IP-адрес в процессе соединения, при этом последнее не будет разорвано.
keepalive секунд1 секунд2 Пинговать каждые секунд1 сервер и если в течение секунд2 не будут получены ответные пакеты, перезапустить подключение.
cipher алгоритм Указывает алгоритм шифрования. Примеры: AES-256-CBC, AES-128-CBC, BF-CBC, DES-EDE3-CBC.
comp-lzo   Использовать сжатие.
verb число от 0 до 9 Уровень детализации лога. 0 отключает отладочную информацию.
mute число Указывает сколько лог-сообщений может отображаться для каждой категории события.
auth-user-pass ничего или путь к файлу Говорит клиенту, что необходима аутентификация. Если не указан путь к файлу, клиент выкинет окно для авторизации, иначе прочитает данные из файла.
ipchange команда или путь к скрипту Выполняет команду при смене IP.
connect-retry секунд Переподключиться к серверу через указанное количество секунд, если соединение было разорвано.
connect-retry-max число Сколько раз повторять соединение, если оно было разорвано.
shaper байт Задает максимальную скорость передачи данных для исходящего трафика.
tun-mtu число Задает MTU.
status путь к файлу Путь к фалу хранения статуса.
log путь к файлу Путь к лог-файлу.
askpass путь к файлу Путь к файлу с паролем для приватного ключа (private key password).

Наиболее полный и актуальный список параметров для OpenVPN можно получить командой openvpn —help (в Linux и Windows).

Сертификаты

Клиентские сертификаты генерируются на стороне сервера. Процедура следующая.

Для Linux:

cd /etc/openvpn/easy-rsa

. ./vars

./build-key client

Для Windows:

cd %ProgramFiles%OpenVPNeasy-rsa

vars.bat

build-key.bat client

* в выше приведенных примерах был сгенерирован клиентский сертификат client. Более подробно про создание сертификатов для клиентов читайте на страницах настройка openvpn на Windows и настройка openvpn на CentOS.

Сгенерированные ключи появятся в каталоге keys. Их необходимо скопировать на клиентский компьютер вместе с сертификатами сервера и разместить по каталогам, указанным в конфигурационном файле. В нашем примере они должны быть скопированы в ту же папку, в которой находится сам файл конфигурации.

В итоге мы получаем, примерно, следующее.

Для Windows:

Пример каталога config для настройки OpenVPN клиента

Для Linux:

ls /etc/openvpn/client/

ca.crt  client.crt  client.key  client.conf  dh2048.pem  ta.key

Запуск

Для проверки можно запустить клиента вручную. Но для повседневного использования стоит настроить автоматический запуск.

Вручную

На Windows:

Запускаем OpenVPN GUI от имени администратора — в правом нижнем углу появится иконка программы:

После запуска программы ее значок появится в правом нижнем углу

Кликаем по ней правой кнопкой мыши и выбираем Подключиться:

Подключаемся к OpenVPN серверу

На Linux:

Переходим в каталог с конфигурационным файлом:

cd /etc/openvpn

Вводим команду:

openvpn —config /etc/openvpn/client.conf

или:

systemctl start openvpn@client

* также служба может называться openvpn.

Автоматически

На Windows:

Выполняем 2 действия.

1. Наш конфигурационный файл с сертификатами переносим из каталога config в каталог config-auto:

Каталоги config и config-auto в папке OpenVPN

* в старых версиях клиента каталога config-auto нет — тогда оставляем файлы в config.

2. Открываем службы и находим OpenVPNService. Переводим его в режим автозапуска:

Настройка службы OpenVPN для автоматического старта

На Linux:

Разрешаем автозапуск службы:

systemctl enable openvpn@client

или для старых версий.

CentOS / Red Hat / Fedora:

chkconfig openvpn on

Ubuntu / Debian:

update-rc.d openvpn defaults

Несколько конфигурационных файлов

Позволит держать несколько конфигураций для подключения к различным VPN-серверам. Между последними можно переключаться из клиентской программы.

Для Windows:

В каталоге config создаем для каждого сервера свою папку и помещаем в нее рабочие файлы (файл конфигурации, сертификаты и так далее). В каждой папке называем конфигурационные файлы ovpn своими именами (даже если файлы будут находиться в разных папках, но с одинаковыми именами, клиент OpenVPN будет воспринимать их как один конфиг).

Пример каталога config:

Каталог config с несколькими папками для разных подключений

Пример файлов в одном из каталогов:

Содержимое каталога с настройками подключения к серверу VPN

Теперь при подключении клиентом к можно выбрать конкретный VPN-сервер:

Возможность выбора сервера для подключения OpenVPN

Для Linux:

Также как для Windows, создаем для каждого сервера свой каталог, куда скопируем рабочие файлы:

mkdir /etc/openvpn/server1

А в каталоге /etc/openvpn создаем для каждого подключения свой конфиг:

vi /etc/openvpn/client1.conf

* в конфигурационном файле все пути до файлов должны вести в соответствующий каталог (в нашем примере, /etc/openvpn/server1).

Запускаем OpenVPN:

openvpn —config /etc/openvpn/server1/client.conf

Для автоматического запуска мы уже ранее применяли команду:

systemctl enable openvpn@client

… где @client — указатель на использование конфигурационного файла client внутри папки openvpn (/etc/openvpn). Таким образом, если мы создали 2 файла client1.conf и client2.conf, команды для разрешения автозапуска бelen такие:

systemctl enable openvpn@client1

systemctl enable openvpn@client2

Сертификаты внутри конфигурационного файла

Ключи сертификатов можно хранить не в отдельных файлах, а внутри конфигурационного файла ovpn.

<ca>
——BEGIN CERTIFICATE——

——END CERTIFICATE——
</ca>

<tls-auth>
——BEGIN OpenVPN Static key V1——

——END OpenVPN Static key V1——
</tls-auth>

<cert>
——BEGIN CERTIFICATE——

——END CERTIFICATE——
</cert>

<key>
——BEGIN PRIVATE KEY——

——END PRIVATE KEY——
</key>

<dh>
——BEGIN DH PARAMETERS——

——END DH PARAMETERS——
</dh>

key-direction 1 — необходим для tls-auth, в противном случае, работать не будет; ca — ключ центра сертификации (ca.crt); tls-auth — ta.key; cert — открытый сертификат клиента (clients.crt); key — закрытый сертификат клиента (clients.key); dh — сертификат, созданный на базе протокола Диффи Хеллмана.

Отзыв сертификата

Для Linux:

cd /etc/openvpn/easy-rsa

. ./vars

./revoke-full client

Для Windows:

cd %ProgramFiles%OpenVPNeasy-rsa

vars.bat

revoke-full.bat client

* с помощью данных манипуляций мы отзываем сертификат client.

Читайте также

Настройка сервера OpenVPN на Windows

Установка и настройка OpenVPN на Linux CentOS 7

Настройка OpenVPN сервера с включением аутентификации через LDAP (Active Directory)

Настройка доступа к локальной сети клиентам OpenVPN в CentOS 7

OpenVPN – это набор open source программ, который заслуженно является одним из самых популярных и легких решений для реализации защищенной VPN сети. OpenVPN позволяет объединить в единую сеть сервер и клиентов (даже находящиеся за NAT или файерволами), или объединить сети удаленных офисов. Серверную часть OpenVPN можно развернуть практически на всех доступных операционных системах (пример настройки OpenVPN на Linux). Вы можете установить OpenVPN сервер даже на обычный компьютер с десктопной редакцией Windows 10.

В этой статье, мы покажем, как установить OpenVPN сервер на компьютер с Windows 10, настроить OpenVPN клиент на другом Windows хосте и установить защищенное VPN подключение.

Содержание:

  • Установка службы OpenVPN сервера в Windows
  • Создаем ключи шифрования и сертификаты для OpenVPN
  • Конфигурационный файл OpenVPN сервера в Windows
  • Настройка OpenVPN клиента в Windows

Установка службы OpenVPN сервера в Windows

Скачайте MSI установщик OpenVPN для вашей версии Windows с официального сайта (https://openvpn.net/community-downloads/). В нашем случае это OpenVPN-2.5.5-I602-amd64.msi (https://swupdate.openvpn.org/community/releases/OpenVPN-2.5.5-I602-amd64.msi).

Запустите установку.

Если вы планируете, OpenVPN сервер работал в автоматическом режиме, можно не устанавливать OpenVPN GUI. Обязательно установите OpenVPN Services.

установка openvpn сервера в windows 10

Начиная с версии OpenVPN 2.5, поддерживается драйвер WinTun от разработчиков WireGuard. Считается, что этот драйвер работает быстрее чем классический OpenVPN драйвер TAP. Установите драйвер Wintun, откажитесь от установки TAP-Windows6.

Установите OpenSSL утилиту EasyRSA Certificate Management Scripts.

WinTun драйвер openvpn

Запустите установку.

По умолчанию OpenVPN устаналивается в каталог C:Program FilesOpenVPN.

После окончания установки появится новый сетевой адаптер типа Wintun Userspace Tunnel. Этот адаптер отключен, если служба OpenVPN не запущена.

сетевой адаптер Wintun Userspace Tunnel

Создаем ключи шифрования и сертификаты для OpenVPN

OpenVPN основан на шифровании OpenSSL. Это означает, что для обмена трафиком между клиентом и серверов VPN нужно сгенерировать ключи и сертификаты с использованием RSA3.

Откройте командную строку и перейдите в каталог easy-rsa:

cd C:Program FilesOpenVPNeasy-rsa

Создайте копию файла:

copy vars.example vars

Откройте файл vars с помощью любого текстового редактора. Проверьте пути к рабочим директориям.

Обязательно поправьте переменную EASYRSA_TEMP_DIR следующим образом:

set_var EASYRSA_TEMP_DIR "$EASYRSA_PKI/temp"

EASYRSA_TEMP_DIR

Можете заполнить поля для сертификатов (опционально)

set_var EASYRSA_REQ_COUNTRY "RU"
set_var EASYRSA_REQ_PROVINCE "MSK"
set_var EASYRSA_REQ_CITY "MSK"
set_var EASYRSA_REQ_ORG "IT-Company"
set_var EASYRSA_REQ_EMAIL " [email protected] "
set_var EASYRSA_REQ_OU " IT department "

конфигурационный файл vars при установке сертфикатов easyrsa

Срок действия сертификатов задается с помощью:

#set_var EASYRSA_CA_EXPIRE 3650
#set_var EASYRSA_CERT_EXPIRE 825

Сохраните файл и выполните команду:

EasyRSA-Start.bat

Следующие команды выполняются в среде EasyRSA Shell:

Инициализация PKI:

./easyrsa init-pki

Должна появится надпись:

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: C:/Program Files/OpenVPN/easy-rsa/pki

Теперь нужно сгенерировать корневой CA:

./easyrsa build-ca

Задайте дважды пароль для CA:

CA creation complete and you may now import and sign cert requests.

Данная команда сформировала:

  • Корневой сертификат центра сертификации: «C:Program FilesOpenVPNeasy-rsapkica.crt»
  • Ключ центра сертификации «C:Program FilesOpenVPNeasy-rsapkiprivateca.key»

Теперь нужно сгенерировать запрос сертификата и ключ для вашего сервера OpenVPN:

./easyrsa gen-req server nopass

Утилита сгенерирует два файла:

req: C:/Program Files/OpenVPN/easy-rsa/pki/reqs/server.req
key: C:/Program Files/OpenVPN/easy-rsa/pki/private/server.key

Подпишем запрос на выпуск сертификата сервера с помощью нашего CA:

./easyrsa sign-req server server

Подтвердите правильность данных, набрав yes.

Затем введите пароль CA от корневого CA.

В каталоге issued появится сертификат сервера («C:Program FilesOpenVPNeasy-rsapkiissuedserver.crt»)

сертификат сервера openvpn

Теперь можно создать ключи Диффи-Хеллмана (займет длительное время):
./easyrsa gen-dh

Для дополнительной защиты VPN сервера желательно включить tls-auth. Данная технология позволяет использовать подписи HMAC к handshake-пакетам SSL/TLS, инициируя дополнительную проверку целостности. Пакеты без такой подписи будут отбрасываться VPN сервером. Это защитит вас от сканирования порта VPN сервера, DoS атак, переполнения буфера SSL/TLS.

Сгенерируйте ключ tls-auth:

cd C:Program FilesOpenVPNbin
openvpn --genkey secret ta.key

Должен появиться файл «C:Program FilesOpenVPNbinta.key». Переместите его в каталог C:Program FilesOpenVPNeasy-rsapki

Теперь можно сформировать ключи для клиентов OpenVPN. Для каждого клиента, который будет подключаться к вашему серверу нужно создать собственные ключи.

Есть несколько способов генерации ключей и передачи их клиентам. В следующем примере, мы создадим на сервере ключ клиента и защитим его паролем:

./easyrsa gen-req kbuldogov
./easyrsa sign-req client kbuldogov

пароль для защиты ключа клиента easyrsa

Данный ключ («C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov.key») нужно передать клиенту и сообщить пароль. Клиент может снять защиту паролем для ключа:

openssl rsa -in "C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov.key"-out "C:Program FilesOpenVPNeasy-rsapkiprivatekbuldogov_use.key"

снять защиту паролем с ключа клиента

Если вы хотите сгенерировать ключ, не защищенный паролем, нужно выполнить команду:

./easyrsa gen-req имяклиента nopass

На сервере с OpenVPN вы можете создать неограниченное количество ключей и сертификатов для пользователей. Аналогичным образом сформируйте ключи и сертфикаты для других клиентов.

Вы можете отохвать скомпрометированные сертификаты клиентов:
cd C:Program FilesOpenVPNeasy-rsa
EasyRSA-Start.bat
./easyrsa revoke kbuldogov

Итак, мы сгенерировали набор ключей и сертификатов для OpenVPN сервера. Теперь можно настроить и запустить службу OpenVPN.

Конфигурационный файл OpenVPN сервера в Windows

Скопируйте типовой конфигурационный файл OpenVPN сервера:

copy "C:Program FilesOpenVPNsample-configserver.ovpn" "C:Program FilesOpenVPNconfig-autoserver.ovpn"

Откройте файл server.ovpn в любом текстовом редакторе и внесите свои настройки. Я использую следующий конфиг для OpenVPN:

# Указываем порт, протокол и устройство
port 1194
proto udp
dev tun
# Указываем пути к сертификатам сервера
ca "C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt"
cert "C:\Program Files\OpenVPN\easy-rsa\pki\issued\server.crt"
key "C:\Program Files\OpenVPN\easy-rsa\pki\private\server.key"
dh "C:\Program Files\OpenVPN\easy-rsa\pki\dh.pem"
# Указываем настройки IP сети, адреса из которой будет будут получать VPN клиенты
server 10.24.1.0 255.255.255.0
#если нужно разрешить клиентам подключаться под одним ключом, нужвно включить опцию duplicate-cn (не рекомендуется)
#duplicate-cn
# TLS защита
tls-auth "C:\Program Files\OpenVPN\easy-rsa\pki\ta.key" 0
cipher AES-256-GCM
# Другая параметры
keepalive 20 60
persist-key
persist-tun
status "C:\Program Files\OpenVPN\log\status.log"
log "C:\Program Files\OpenVPN\log\openvpn.log"
verb 3
mute 20
windows-driver wintun

Сохраните файл.

OpenVPN позволяет использовать как TCP, так и UDP для подключения. В этом примере я запустил OpenVPN на 1194 UDP. Рекомендуется использовать протокол UDP, это оптимально как с точки зрения производительности, так и безопасности.

Не забудьте открыть на файерволе порты для указанного вами порта OpenVPN на клиенте и на сервере. Можно открыть порты в Windows Defender с помощью PowerShell.
Правило для сервера:

New-NetFirewallRule -DisplayName "AllowOpenVPN-In" -Direction Inbound -Protocol UDP –LocalPort 1194 -Action Allow

Правило для клиента:

New-NetFirewallRule -DisplayName "AllowOpenVPN-Out" -Direction Outbound -Protocol UDP –LocalPort 1194 -Action Allow

Теперь нужно запустить службу OpenVPN и изменить тип ее запуска на автоматический. Воспользуйтесь таким командами PowerShell, чтобы включить службу:

Set-Service OpenVPNService –startuptype automatic –passthru
Get-Service OpenVPNService| Start-Service

запуск службы OpenVPNService

Откройте панель управления, и убедитесь, что виртуальный сетевой адаптер OpenVPN Wintun теперь активен. Если нет, смотрите лог «C:Program FilesOpenVPNlogserver.log»

сетевой адаптер openvpn wintun

Если при запуске OpenVPN вы видите в логе ошибку:

Options error: In C:Program FilesOpenVPNconfig-autoserver.ovpn:1: Maximum option line length (256) exceeded, line starts with..

Смените в файле server.ovpn символы переноса строки на Windows CRLF (в notepad++ нужно выбрать Edit -> EOL Conversion -> Windows CR LF). Сохраните файл, перезапустите службу OpevVPNService.

Данный конфиг позволит удаленным клиентам получить доступ только к серверу, но другие компьютеры и сервисы в локальной сети сервера для них недоступны. Чтобы разрешить клиентам OpenVPN получить доступ к внутренней сети нужно:

Включить опцию IPEnableRouter в реестре (включает IP маршрутизацию в Windows, в том числе включает маршрутизацию меду сетями Hyper-V): reg add «HKLMSYSTEMCurrentControlSetServicesTcpipParameters» /v IPEnableRouter /t REG_DWORD /d 1 /f

Добавьте в конфгурационный файл сервера OpenVPN маршруты до внутренней IP сети:

push "route 10.24.1.0 255.255.255.0"
push "route 192.168.100.0 255.255.255.0"

Если нужно, назначьте клиенту адреса DNS серверов:

push "dhcp-option DNS 192.168.100.11"
push "dhcp-option DNS 192.168.100.12"

Если нужно завернуть все запросы клиента (в том числе Интернет трафик) на ваш OpenVPN сервер, добавьте опцию:

push "redirect-gateway def1"

Настройка OpenVPN клиента в Windows

Создайте на сервере шаблонный конфигурационный файла для клиента VPN (на базе iшаблона client.ovpn) со следующими параметрами (имя файла kbuldovov.ovpn)

client
dev tun
proto udp
remote your_vpn_server_address 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert kbuldogov.crt
key kbuldogov.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-GCM
connect-retry-max 25
verb 3

В директиве remote указывается публичный IP адрес или DNS имя вашего сервера OpenVPN.

Скачайте и установите клиент OpenVPN Connect для Windows (https://openvpn.net/downloads/openvpn-connect-v3-windows.msi).

установка openvpn connect в windows

Теперь на компьютер с клиентом OpenVPN нужно с сервера скопировать файлы:

  • ca.crt
  • kbuldogov.crt
  • kbuldogov.key
  • dh.pem
  • ta.key
  • kbuldogov.ovpn

импорт конфигурации клиента ovpn в openvpn клиент

Теперь импортируйте файл с профилем *.ovpn и попробуйте подключиться к вашему VPN серверу.

Если все настроено правильно, появится такая картинка. подключение к openvpn установлено

Проверьте теперь лог OpenVPN на клиенте «C:Program FilesOpenVPN Connectagent.log»

Mon Dec 27 08:09:30 2021 proxy_auto_config_url
Mon Dec 27 08:09:31 2021 TUN SETUP
TAP ADAPTERS:
guid='{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}' index=22 name='Local Area Connection'
Open TAP device "Local Area Connection" PATH="\.Global{25EE4A55-BE90-45A0-88A1-8FA8FEF24C42}.tap" SUCCEEDED
TAP-Windows Driver Version 9.24
ActionDeleteAllRoutesOnInterface iface_index=22
netsh interface ip set interface 22 metric=1
Ok.
netsh interface ip set address 22 static 10.24.1.6 255.255.255.252 gateway=10.24.1.5 store=active
IPHelper: add route 10.24.1.1/32 22 10.24.1.5 metric=-1

Клиент успешно подключится к OpenVPN серверу и получил IP адрес 10.24.1.6.

Проверьте теперь лог на сервере («C:Program FilesOpenVPNlogopenvpn.log»). Здесь также видно, что клиент с сертификатом kbuldogov успешно подключится к вашему серверу.

2021-12-27 08:09:35 192.168.13.202:55648 [kbuldogov] Peer Connection Initiated with [AF_INET6]::ffff:192.168.13.202:55648
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI_sva: pool returned IPv4=10.24.1.6, IPv6=(Not enabled)
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI: Learn: 10.24.1.6 -> kbuldogov/192.168.13.202:55648
2021-12-27 08:09:35 kbuldogov/192.168.13.202:55648 MULTI: primary virtual IP for kbuldogov/192.168.13.202:55648: 10.24.1.6

Пошаговая инструкция по настройке OpenVPN GUI в Windows 10. The OpenVPN GUI это бесплатная программа с открытым кодом, доступная для всех версий Windows.

Содержание

  • Установка OpenVPN GUI
  • Настройка OpenVPN GUI
  • Подключение к VPN-серверу

Установка OpenVPN GUI

Зайдите на оффициальный сайт OpenVPN https://openvpn.net/index.php/open-source/downloads.html. Скачайте установочный файл .exe себе на компьютер.

Или скачайте установочный файл для вашей версии Windows по следующим ссылкам:

  • Скачать для Windows 7, 8, 8.1
  • Скачать для Windows 10

Запустите скачанный установочный файл openvpn-install-2.4.8-I602-Win*.exe.

Windows спросит, «Do you want to allow the following program to make changes to this computer?» Нажмите Yes.

Установщик запущен. Нажмите Next для начала установки!

Далее вы увидите лицензионное солашение. Прочитайте его, если хотите, и нажмите I Agree.

На экране выбора компонентов нажмите Next.

На экране выбора места установки нажмите Install.

Windows спросит: «Would you like to install this device software?» Нажмите Install.

Когда появится экран завершения установки (Installation Complete) нажмите Next.

Далее вы увидите сообщение о том, что OpenVPN успешно установлен. Уберите галочку «Show Readme» и нажмите Finish.

Настройка OpenVPN GUI

В процессе установки, ярлык OpenVPN GUI будет добавлен на рабочий стол Windows. Нажмите правой кнопкой мыши по нему OpenVPN GUI и выберите в меню пункт «Открыть разположение файла».

Откроется папка C:Program FilesOpenVPNbin. Вам нужно перейти на уровень выше — C:Program FilesOpenVPN.

Теперь нужно перейти в папку C:Program FilesOpenVPNconfig.

Теперь нужно перенасти конфигурационный файл OpenVPN в папку C:Program FilesOpenVPNconfig. Перетащите файл SnowdenVPN.ovpn из папки Загрузки, в папку, которая была открыта ранее.

После этого вы увидите предупреждение «Destination Folder Access Denied». Windows попросит вас предоставить права администратора для перемещения файла. Согласитесь.

Отлично! Ваш конфигурационный файл SnowdenVPN.ovpn находится в C:Program FilesOpenVPNconfig и теперь вы можете подключиться к серверу.

Подключение в VPN-серверу

Дважды нажмите мышью на ярлык OpenVPN GUI на рабочем столе.

Когда OpenVPN GUI запустится, на панеле уведомлений появится его значок.

Нажмите правой кнопкой мыши по значку OpenVPN GUI на панеле уведомлений.

В выпадающем меню выбирите пункт Подключиться.

После этого появится окно подключения.

Когда OpenVPN GUI подключится в серверу, значок станет зеленого цвета.

Создать VPN-сервер бесплатно

OpenVPN - установка и настройка

В этой статье я рассмотрю процесс настройки OpenVPN клиента (client) и сервера (server) на примере версии 2.4.7. используемая операционная система — Windows 10, но таким же образом можно настроить OpenVPN на Windows 7.

OpenVPN – механизм реализации виртуальных частных сетей (Virtual Private Network, VPN) с открытым исходным кодом. Используется для создания защищенных (шифрованных) каналов связи между сервером и клиентом, а так же между двумя точками.

OpenVPN позволяет создавать безопасные соединения между компьютерами, которые находятся за пределами фаервола, при этом не требуется изменять настройки фаервола.

Создателем системы является Джеймсом Йонаном (James Yonan).

Что бы создать защищенный канал используется библиотека OpenSSL. Весь набор шифров доступный в библиотеке используется в системе.

Система предлагает пользователю несколько способов аутентификации:

  • Аутентификация с помощью предустановленного ключа – наиболее простой метод.
  • Серверная аутентификация – более сложный, но при этом более гибкий в настройках метод.
  • При помощи ввода логина и пароля. Может использоваться без создания сертификата клиента, при этом сертификат сервера все равно необходим.

Давайте разберемся на примере. Я настрою OpenVPN на двух компьютерах под управлением Windows 10. Они будут находиться в одной локальной сети. Так как для настроек через интернет необходим хотя бы один статический IP-адрес.

На этом примере мы разберемся, как создавать ключи и сертификаты безопасности, а так же научимся настраивать конфигурационный файл VPN-сервера и VPN-клиента.

Установка и настройка OpenVPN

Один компьютер будет играть роль сервера. Второй – клиента. На сервере при установке OpenVPN нужно установить флажок EasyRSA – для генерации сертификатов и ключей.

Переходим на официальный сайт OpenVPN http://openvpn.net/community-downloads/ и скачиваем программу. В моем случае OpenVPN 2.4.7 для Windows 10 (openvpn-install-2.4.7-I607-Win10).

В теории можно скачать и более поздний релиз, но лучше скачивать проверенную версию. Так как я не настраивал последние версии. Если дойдут руки, то дополню статью.

После запуска программы установки включаем EasyRSA (на сервере) и устанавливаем. Программа устанавливается просто и не требует каких-либо специфических настроек при установке.

Затем устанавливаем программу втором компьютере который будет играть роль клиента.

Далее нужно настроить компьютеры, что бы они видели друг друга в сети. Этот процесс зависит от установленной у вас операционной системы. Фактически вам нужно включить сетевое обнаружение.

Создание сертификатов и генерация ключей

Ключи и сертификаты создаются на сервере OpenVPN. Для их создания необходимо выполнить следующие действия:

Запустите командную строку от имени администратора.

Запуск командной строки от имени администратора

С помощью команды cd перейдите в папку C:Program FilesOpenVPNeasy-rsa и выполните команду init-config.bat, после чего в папке easy-rsa появиться файл vars.bat.

Откройте vars.bat с помощью блокнота или иного текстового редактора. Я открыл в Notepad++. Укажите свои данные.

Данные в var.bat

Данные можно указывать в процессе работы с OpenVPN.

Указание данных в процессе

Вернитесь в командную строку и по очереди выполните команды vars и clean-all поочередно.

Команды vars и clean-all

Выполните команду build-dh. Если у вас появиться ошибка «openssl» не является внутренней или внешней командой, исполняемой программой или пакетный файлом, то нужно добавить в переменные среды путь OpenVPNbin.

Изменение системных переменных сред

Для этого нужно в переменную среды Path создать путь C:Program FilesOpenVPNbin.

Переменная path

Затем заново откройте командную строку и выполните пункты 4-5 заново.

Подождите до завершения процесса. В результате в паке OpenVPNeasy-rsakeys появиться файл dh2048.pem.

Создайте новый сертификат Certificate Authority (CA) и ключ, для чего введите команду build-ca. После завершения процесса в папке keys появятся два файла ca.crt и ca.key.

Создайте сертификат и ключ сервера. Для этого введите команду build-key-server к которой нужно добавить [CommonName] (в моем случае abuzov-name), то есть моя команда будет build-key-server abuzov-name. В конце дайте положительный ответ (y) на два вопроса.

Создайте сертификат и ключ для клиента. Введите команду build-key [CommonNameClient], например build-key ClientVPN1.

Создайте ключ для аутентификации пакетов, для этого выполните команду openvpn —genkey —secret keys/ta.key. В результате в папке easy-rsakeys появится файл ta.key

Таблица соответствия сертификатов и ключей

Имя Где применяется Назначение Секретность
ca.crt Сервер + все клиенты Корневой сертификат (Root CA certificate) Нет
ta.key Сервер + все клиенты Файл аутентификации пакетов Да
ca.key Сервер Корневой ключ (Root CA key) Да
dh2048.pem Сервер Файл параметров Нет
abuzov-name.csr Сервер Сертификат сервера Нет
abuzov-name.key Сервер Ключ сервера Да
ClientVPN1.csr Только на ClientVPN1 Сертификат клиента Нет
ClientVPN1.key Только на ClientVPN1 Ключ клиента Да

Теперь нужно скопировать соответствующие ключи на сервер и клиент в папку config (в моем случае это C:Program FilesOpenVPNconfig).

Создание и настройка файлов конфигурации OpenVPN

Конфигурация основывается на файлах типовой конфигурации, которые находятся в C:Program FilesOpenVPNsample-config.

Настройка конфигурации сервера

Копируете файл server.ovpn из папки sample-config в папку config. Открываете и редактируете его. Обратите внимание на двойные слеши.

  1. Найдите строку, которая начинается на ca и укажите путь к своему ca файлу. В моем случае это ca «C:\Program Files\OpenVPN\config\ca.crt».
  2. Найдите cert и отредактируйте соответственно, в моем случае это cert «C:\Program Files\OpenVPN\config\abuzov-name.crt».
  3. По аналогии с key — key «C:\Program Files\OpenVPN\config\abuzov-name.key».
  4. Аналогично с dh — dh «C:\Program Files\OpenVPN\config\dh2048.pem»
  5. Аналогично tls-auth — «C:\Program Files\OpenVPN\config\ta.key».

Я приведу полный код конфигурации сервера, на всякий случай, что бы его можно было просто скопировать. Так как знаю что такое первая настройка OpenVPN.

mode server
port 1194
dev tap
proto tcp-server
tls-server
tls-auth "C:\Program Files\OpenVPN\config\ta.key" 0
duplicate-cn
auth MD5
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
ca "C:\Program Files\OpenVPN\config\ca.crt"
cert "C:\Program Files\OpenVPN\config\abuzov-name.crt"
key "C:\Program Files\OpenVPN\config\abuzov-name.key" # This file should be kept secret
dh "C:\Program Files\OpenVPN\config\dh2048.pem"
server 10.10.10.0 255.255.255.0
client-to-client
keepalive 10 120
comp-lzo
persist-key
persist-tun
verb 3
route-delay 10
route-method exe
route 10.10.10.0 255.255.255.0
route 192.168.0.0 255.255.0.0
route-gateway 10.10.10.1

Сохраните файл конфигурации сервера.

Запустите OpenVPN от имени администратора (и сразу сделайте так, что бы он всегда запускался от имени администратора).

После этого подключитесь к северу как показано на рисунке.

Подключение к серверу OpenVPN

Настройка конфигурации клиента

Копируете файл client.ovpn из папки sample-config в папку config. Открываете и редактируете его аналогии. В моем случае это:

  1. ca «C:\Program Files\OpenVPN\config\ca.crt»
  2. cert «C:\Program Files\OpenVPN\config\ClientVPN1.crt»
  3. key «C:\Program Files\OpenVPN\config\ClientVPN1.key»
  4. remote IP_адрес_сервера

Опять, лучше приведу полный код.

remote IP-адрес-вашего-сервера
client
port 1194
dev tap
proto tcp-client
tls-client
tls-auth "C:\Program Files\OpenVPN\config\ta.key" 1
remote-cert-tls server
route-delay 2
auth MD5
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
ca ca.crt
cert ClientVPN.crt
key ClientVPN.key
pull
cipher AES-128-CBC
comp-lzo
persist-key
persist-tun
verb 3
route-method exe
route-delay 3

Единственное что нужно сделать — указать IP-адрес сервера.

Далее подключаем клиент OpenVPN.

Если клиент не подключается к серверу, тогда нужно на сервере необходимо запустить regedit.exe, затем перейти по адресу: «КомпьютерHKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters» и изменить IPEnableRouter на 1. После чего перезагрузить сервер и подключиться к OpenVPN заново.

После этого можно подключаться по защищенному соединению.

Подключение openvpn

  • Коллективные
  • Персональные

И снова здравствуйте.
Эта последняя статья посвященная OpenVPN в целом и настройке клиента в частности. В этот раз мы настроим с вами клиента под Windows 10 но на предыдущих версиях этой операционной системы все это тоже будет работать. Задача следующая, обеспечить подключение клента к нашему OpenVPN серверу, который мы настраивали в с статье: Настраиваем OpenVPN сервер Linux на примере Ubuntu мы уже можем настраивать клиента Ubuntu, осталось дело за малым, чем мы сейчас и займемся.
Чтобы приступить к настройке, нам необходимо скачать, этого самого, клиента для Windows, я качал под 64 разрядную ОС.
Тут все просто, качаем клиента с сайта openvpn.net/index.php/download/community-downloads.html
Запускаем установку и следуем указаниям инсталятора, по принципу Next -> Next -> OK

Переходим в директорию с установленным OpenVPN

C:Program FilesOpenVPNconfig

Нам необходимо создать там файл, назовем его client.ovpn с содержимым:


# Тип подключения -клиент
client

# Через какое устройство подключаемся
dev tun

По какому протоколу будем работать
proto tcp
#proto udp

# Адрес OpenVPN сервера и его порт (можно указать IP или URL)
remote openvpn.example.org 1194

# Тип шифрования, как на OpenVPN сервере
cipher AES-256-CBC

# Сертификат удостоверяющего центра
ca ca.crt

# Сертификат и ключ клиента
cert user.crt
key user.key

# Клиент поддерживает шифрование
tls-client

# Указываем путь к ключу TLS
tls-auth ta.key 1

# Включаем компрессию данных
comp-lzo

# Не использовать специфический порт для работы
nobind

persist-key
persist-tun

# Уровень логирования если нужно подробнее, то выставляем 9 для дебагинга
verb 3
# Количество записей после которых будет производиться запись в лог
#mute 20

Нам необходимо получить с OpenVPN сервера 4 файла:

ca.crt
ta.key
user.crt
user.key

Где:
ca.crt и ta.key первый является сертификатом удостоверяющего центра, второй это ключ шифрования OpenVPN сервера, они должны быть у каждого пользователя!
user.crt и user.key ключ и сертификат пользователя, у каждого пользователя они свои т.е. создаются персонально

Дальше на остается запустить OpenVPN клиента:

Нажимаем подключиться:

Появится лог подключения, который при установке соединения исчезнет:

Иконка подключения станет зеленой, значит соединение установлено и работает нормально, также появится плашка в которой будет написан присвоенный IP адрес

Для клиентов Windows есть особенность, необходимо указывать IP адреса из диапазона в 4 адреса т.е. если вы хотите присвоить клиенту адрес 172.16.10.4 то соединение на другом конце должны быть из диапазона:

172.16.10.1 172.16.10.2 172.16.10.3 172.16.10.4
172.16.10.5 172.16.10.6 172.16.10.7 172.16.10.8
172.16.10.9 172.16.10.10 172.16.10.11 172.16.10.12

Иначе соединение обрывается, во так все просто.

На этой оптимистической ноте я закончу свое повествование, если возникли вопросы, задавайте их в комментариях.

Есть что добавить? Регистрируйся и оставляй комментарии!

Skip to content

Cloud Orchestration Logo

How to Install and Configure OpenVPN on Windows 10

How to Install and Configure OpenVPN on Windows 10

  • View Larger Image

Introduction

In this blog article we are going to discuss about How to Install and Configure OpenVPN on Windows 10. A VPN is short form of virtual private network, which gives us a privacy, anonymity and security over public internet. A VPN service masks our ISP IP so your online actions are virtually untraceable. A VPN can also be used to connect computers to isolated remote computer networks that is usually inaccessible, by using the Internet or another intermediate network.

We can define OpenVPN as a full-featured SSL VPN. OpenVPN uses OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol. OpenVPN supports flexible client authentication methods based on certificates, smart cards and username/password credentials. OpenVPN is not a web application proxy and does not operate through a web browser. OpenVPN server process over a single TCP or UDP port. The default port number is 1194. OpenVPN 2.3 includes a large number of improvements, including full IPv6 support and PolarSSL support.

OpenVPN is also the name of the open source project started by our co-founder and which uses the GPL license. He developed the OpenVPN project that used to encrypt and secure point-to-point or site-to-site connection between two machines over the public Internet. In other word using OpenVPN we can create a secure Private network over public Internet and will have Remote access to internal services of your IT infrastructure.

Use Cases of OpenVPN

Secure Remote Access
Site-to-site , Users-to-Site or Users-to-Users connectivity to bring networks together
Protect screen sharing and remote desktop communications
Encrypt sensitive IoT communications
Secure Access to Cloud-Based Systems

OpenVPN available as Below.

  1. OpenVPN Community Edition, which is a free and open-source version
  2. OpenVPN Access Server (OpenVPN-AS), is based on the Community Edition, but provides additional paid and proprietary features like LDAP integration, Easy Management Admin Portal ,cluster option etc.
  3. OpenVPN-as-a-Service, solution eliminates the need for VPN server installation. By Purchasing OpenVPN Cloud we can simply connect to our hosted service with regions around the globe.

Apart from OpenVPN Community Edition, the other two OpenVPN editions has Economical licensing model that is based only on the number of simultaneous VPN connecting users or devices.

The OpenVPN Community Edition totally free to use and there is no user limitations. OpenVPN community edition server can be installed on Linux or Windows Based systems.

OpenVPN for Windows

It can be installed from the self-installing exe file which is called OpenVPN GUI. OpenVPN GUI is a graphical fronted for OpenVPN running on Windows. It creates an icon in the notification area from which you can control OpenVPN to start/stop your VPN tunnels, view the log and do other useful things.

OpenVPN Connect client

It is the OpenVPN client software packages installing on client PC. This client package used to connect to the OpenVPN server. OpenVPN Connect client supported on Windows, Linux, MacOS, IOS and Android.

Setting Up OpenVPN Server.

In this article will show you how to Setup up a OpenVPN Server ( Community Edition) On Windows 10 to forward incoming traffic to the internet, then route the responses back to the client. This is a Users-to-Site Model.Which means settings up a OpenVPN  Server to tunnel clients internet traffic through OpenVPN server. Those clients that successfully connected to the OpenVPN server will have their ISP IP Address will show as servers Public IP address.Commonly, a VPN tunnel is used to privately access the internet, evading censorship or Geo location by shielding your computer’s web traffic when connecting through entrusted hotspots, or connections.

Section 1. Installing OpenVPN Server

Let’s get Started. First thing is Download the latest Windows 64-bit MSI installer for OpenVPN Community edition from official OpenVPN Website, under community section.

The OpenVPN executable should be installed on both server and client machines, since the single executable provides both client and server functions.

Once Downloaded right click the installer exe file and choose install option.

The following screen will appear, click “Customise”  to start the installation.

Make sure to choose all features by clicking the icon next to each features and selecting the option “Entire feature will be installed on local hard drive”.  Below are the two features which will not be installed by default and we need to select during install.

Openssl utilities , EasyRSA 3 Certificate Management scripts

OpenVPN service.

Click Install Now button after selecting all features.

The install will get completed and we will get below screen. Click Close. The default  install location will be C:Program FilesOpenVPN

We will get a warning message as ” No readable connection profiles ( config files ) found. Its fine , click OK.

This Completes the OpenVPN MSI Package install. After the install,  Under Windows 10 “Network and Internet ” settings  >>  Under Ethernet >> Change adaptor options >> We can see a new network adaptor named OpenVPN TAP device created.

Now we can manage  the OpenVPN service either  from Windows Start Menu -> Control Panel -> Administrative Tools -> Services section.

As of OpenVPN version 2.5.0,While starting the OpenVPN wrapper service the OpenVPN will look for .ovpn configuration file under folder “C:Program FilesOpenVPNconfig-auto” to auto-start OpenVPN service when ever our Windows 10 reboots.

Another option to start/stop OpenVPN service is  Click on Windows hidden notification area from task bar , there we can see the OpenVPN icon, right click on it and you will see multiple options including Connect and Disconnect.

If you don’t see the OpenVPN icon in the Windows task bar notification area, double click the OpenVPN icon available in the desktop and that will make the OpenVPN icon available at the windows task bar notification area.

For better understanding refer below screenshot.

As I mentioned earlier As of OpenVPN version 2.5.0,  when we start the OpenVPN service using the GUI component under windows task bar notification area, the OpenVPN will look for .ovpn configuration file under folder “C:Program FilesOpenVPNconfig”.

This Concludes the OpenVPN Package install on Windows 10 for Server and for the Client PC. Now lets move to the next section.

Section 2. Setup Master Certificate Authority (CA) and Generate Certificates and keys for OpenVPN Server and Clients.

OpenVPN uses public-key infrastructure (PKI) for certificate generation and Management. It is the technology behind digital certificates. There for, PKI is the technology that allows you to encrypt data, digitally sign documents, and authenticate yourself using certificates.

The PKI consists of:

  1. A separate certificate (also known as a public key) and private key for the server and each client, and
  2. A master Certificate Authority (CA) certificate and key which is used to sign each of the server and client certificates.

For PKI management,  The latest version of OpenVPN packages provided  easy-rsa 3, a set of scripts which is bundled with OpenVPN MSI.

The easy-rsa3 scripts folder location should be “C:Program FilesOpenVPNeasy-rsa”.  Also the Easy-RSA 3 runs POSIX shell code, so use on Windows has some additional
requirements such as  an OpenSSL installation, and a usable shell environment but  Windows packages of EasyRSA 3.0.7+ include an OpenSSL binary and libraries that will be used by default. So basically we don’t need to perform the OpenSSL install separately in our Windows Install.

Additionally The Easy-RSA 3 Windows release includes a ready-to-use shell environment  where we can run the commands that needed to issue SSL/TSL certificates. So lets proceed with the SSL/TLS certificate creation along with CA certificate using easy-rsa3 scripts.

First thing is go the folder “C:Program FilesOpenVPNeasy-rsa” using Windows File explorer.  Copy the file named “vars.example” to file named “vars“.

The “vars “ file contains built-in  Easy-RSA configuration settings.  The default settings are fine unless if we need any custom changes.  Few configurable options given in below table.

Variables Default Value Usage
set_var EASYRSA
C:Program FilesOpenVPNeasy-rsa Defines the folder location of easy-rsa scripts
set_var EASYRSA_OPENSSL C:Program FilesOpenVPNbinopenssl.exe Defines the OpenSSL binary path
set_var EASYRSA_PKI C:Program FilesOpenVPNeasy-rsapki The folder location of SSL/TLS file exists after creation
set_var EASYRSA_DN
cn_only
This is used to adjust what elements are included in the Subject field as the DN
set_var EASYRSA_REQ_COUNTRY “US” Our Organisation Country
set_var EASYRSA_REQ_PROVINCE “California” Our Organisation Province
set_var EASYRSA_REQ_CITY “San Francisco” Our Organisation City
set_var EASYRSA_REQ_ORG “Copyleft Certificate Co” Our Organisation Name
set_var EASYRSA_REQ_EMAIL “me@example.net” Our Organisation contact email
set_var EASYRSA_REQ_OU “My Organizational Unit” Our Organisation Unit name
set_var EASYRSA_KEY_SIZE
2048
Define the key pair size in bits
set_var EASYRSA_ALGO
rsa The default crypt mode
set_var EASYRSA_CA_EXPIRE
3650 The CA key expire days
set_var EASYRSA_CERT_EXPIRE
825 The Server certificate key expire days
set_var EASYRSA_NS_SUPPORT
“no” Support deprecated Netscape extension
set_var EASYRSA_NS_COMMENT “HAKASE-LABS CERTIFICATE AUTHORITY” Defines NS comment
set_var EASYRSA_EXT_DIR
"$EASYRSA/x509-types"
Defines the x509 extension directory
set_var EASYRSA_SSL_CONF
"$EASYRSA/openssl-easyrsa.cnf"
Defines the openssl config file location
set_var EASYRSA_DIGEST
"sha256"
Defines the cryptographic digest to use

So if you need to edit above default values, un-comment corresponding lines and make necessary changes. The “var”  also have other configurable options but I only mentioned few important variables.  So in our case we are fine with the default values and the default values  will be used  during certificate generation.

Now Open the windows command prompt and go the directory “C:Program FilesOpenVPNeasy-rsa”.  After that Launch EasyRSA shell. For that issue below commands.

Now we have entered the easy-rsa3 shell prompt and from there we will be able to issue easy-rsa3 scripts. Attached  a screenshot for reference.

Now Initiate the Public Key Infrastructure PKI directory. For that issue below command in the EasyRSA Shell.

Below the screenshot for reference. From there we can see the PKI directory is set to “C:Program FilesOpenVPNeasy-rsapki”

Now build the certificate authority (CA ) key using the command below.  This CA root certificate file later will be used to sign other certificates and keys. The option “nopass”  we  used is to disable password locking the CA certificate.

The command will be asked to enter the common name. Here I entered my VPN server Hostname which is OPENVPNSERVER, and it is a common practice. Here we are free to use any name or values.  Also the created the CA certificate will be saved to folder “C:Program FilesOpenVPNeasy-rsapki” with file name as “ca.crt”.  Refer below screenshot.

Now Build a server certificate and key using below command.   Here Replace <SERVER> with your own server name.  Also I used Option nopass for disabling password locking the key.

Attached a screenshot for your reference.  The issued server certificate will be in the folder “C:Program FilesOpenVPNeasy-rsapkiissued” with file name as SERVER.crt.

After that we can verify the issued server certificate using below openssl command in the EasyRSA shell itself. The Status Ok indicate that the certificate is fine.

Now Build a client certificate and key using below command. From that Replace <CLIENT> with your client name.  Also used Option nopass for disabling password locking the key.

Attached a screenshot for your reference. The issued client certificate will also be saved to folder “C:Program FilesOpenVPNeasy-rsapkiissued” with file name as “CLIENT.crt”.

After that we can verify the issued client certificate using below openssl command. The Ok indicate that the certificate is fine.

This Completed the CA certificate, Sever and Client Certificate Generation along with Key. These keys will be used to authenticate between OpenVPN server and with the Client.

Now Generate a shared-secret key that is used in addition to the standard RSA certificate/key. The file name is tls-auth.key.

Using this key we enable  tls-auth directive Which adds an additional HMAC signature to all SSL/TLS handshake packets for integrity verification. Any UDP packet not bearing the correct HMAC signature can be dropped without further processing.

Enabling the tls-auth will protect us from

  • DoS attacks or port flooding on the OpenVPN UDP port.
  • Port scanning to determine which server UDP ports are in a listening state.
  • Buffer overflow vulnerabilities in the SSL/TLS implementation.
  • SSL/TLS handshake initiations from unauthorised machines.

So first Download Easy-TLS   using the GitHub link https://github.com/TinCanTech/easy-tls. It is an Easy-RSA extension utility that we are using to generate tls-auth key.

Click the Download zip option which is available under code tab.  Refer below screenshot.

After that unzip the easy-tls-master folder and copy the files named “easytls”and “easytls-openssl.cnf” file to “C:Program FilesOpenVPNeasy-rsa” directory. Check below screenshot for reference.

Now go back to the EasyRSA  shell prompt and issue below command. This will initialise the easy-tls script utility.

Now after that generate the tls-auth key using below command.

The command will generate the tls-auth key file named “tls-auth.key”  under the folder “C:Program FilesOpenVPNeasy-rsapkieasytls”.  Refer below screenshot.

Now we need to Generate Diffie Hellman parameters.

Diffie Hellman parameters must be generated for the OpenVPN server.

These parameters define how OpenSSL performs the Diffie-Hellman (DH) key-exchange. Diffie–Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel

Issue below command for generating Diffie Hellman parameters from the EasyRSA shell.

The command will create the DH file under folder “C:Program FilesOpenVPNeasy-rsapki” with file name as “dh.pem”.  Refer below screenshot.

This completes the generation of necessary SSL/TLS key files needed for OpenVPN service. We will be able to find the created files under below folders.

Folder Path Content
C:Program FilesOpenVPNeasy-rsapki CA file, DH file and other OpenSSL related files like config file
C:Program FilesOpenVPNeasy-rsapkiprivate Include the private key files of CA, Server and Client certificates
C:Program FilesOpenVPNeasy-rsapkieasytls Contains the tls-auth key
C:Program FilesOpenVPNeasy-rsapkiissued Contains issued Server and Client certificates

Refer below screenshot.

Also below is the short explanation of the relevant files.

Filename Needed By Purpose Secret
ca.crt server + all clients Root CA certificate No
ca.key Server Only Root CA key YES
dh.pem server only Diffie Hellman parameters No
SERVER.crt server only Server Certificate No
SERVER.key server only Server Key Yes
CLIENT.crt Client only Client Certificate No
CLIENT.key client only Client Key Yes
tls-auth.key server + all clients Used for tls-auth directive No

Now its the time to copy Certificate files ca.crt, CLIENT.crt, CLIENT.key  and tls-auth.key  from OpenVPN server to the OpenVPN client PC.  Make sure to copy secret files over a secure channel like SFTP.

Okay, this completes the creation of SSL/TLS certificates for the OpenVPN service. Now lets move to the next section.

Section 3 . Create configuration files for server

In this section, we create the OpenVPN Server configuration file and Make Necessary changes in it.

First Open Windows Explorer and go the folder “C:Program FilesOpenVPNsample-config” and copy file named “server.ovpn” to “C:Program FilesOpenVPNconfig”.

Refer Below Screenshot.

Now open the config file using any Text editor and make changes to below values accordingly.

ca “C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt”

cert “C:\Program Files\OpenVPN\easy-rsa\pki\issued\SERVER.crt”

key “C:\Program Files\OpenVPN\easy-rsa\pki\private\SERVER.key”

dh “C:\Program Files\OpenVPN\easy-rsa\pki\dh.pem”

push “redirect-gateway def1 bypass-dhcp”

push “dhcp-option DNS 208.67.222.222”

push “dhcp-option DNS 208.67.220.220”

tls-auth “C:\Program Files\OpenVPN\easy-rsa\pki\easytls\tls-auth.key” 0

cipher AES-256-CBC

In that first four values defines the location of ca, cert , key and Diffie hellman parameters certificate locations.

The Next three lines enforce the clients to redirect their all traffic through OpenVPN server once they successfully connected to OpenVPN server.

Using “tls-auth” parameter, we enable HMAC firewall. Its an extra layer of security used to prevent DDos attack.

The last one “data-ciphers AES-256-CBC” enables a cryptographic cipher.

Refer below screenshots and then you will get an idea about how these parameters looks in server.ovpn config file.

This Completes the OpenVPN config file Setup. Now open the UDP Port 1194 in the Windows firewall using below power shell command.

Now start the OpenVPN server service by click on Windows Show hidden icons section >> right click the OpenVPN icon >> Choose Connect.

The OpenVPN service will start automatically and you will see a green colour inside OpenVPN icon. This means that our OpenVPN service is running.

Another Option to confirm the running of OpenVPN service is , take windows cmd and list all network interfaces. We will see now the OpenVPN TUN/TAP interface is assigned with private IP 10.8.0.1, which is the default private IP address range assigned to server and with clients as per the config settings.

Section 4. Enable Internet Connection Sharing (ICS) in Windows 10

As I mentioned in the introduction section we are setting up our OpenVPN server , to route clients all IP traffic such as Web browsing and DNS lookups through VPN Server itself. For that we need to share  the  public internet through OpenVPN server Public Interface that already have internet access to OpenVPN TUN/TAP Network interface.

  • So lets see how this can be accomplished. For that first go to the windows services section and Right-click “Routing and Remote Access” service. Choose Properties and make the startup type as Automatic. After that start the service.
  • After that go to VPN Server “Network and Internet ” settings >> Under Ethernet >> Change adaptor options >>  Right click the Network Adaptor name which is having Public Internet access and choose properties.

  • Choose Sharing tab and from there Tick the box “Allow other network users to connect through this computer’s Internet connection” option
  • From the drop-down list select “OpenVPN Tap-Windows6”, or whatever is the connection name of your TAP server connection.
  • Also if you needed you can tick the box next to ” Allow other network users to control or disable the shared internet connection” option
  • Click Ok and confirm the changes

  • Now edit the below registry  key value. For that run the  “regedit” in Windows Run.
Key Value Type Data
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters IPEnableRouter REG_DWORD 0x00000001 (1)

Okay, this completes Enable Internet Connection Sharing (ICS) in Windows 10. Now lets move to the next section. Also reconnect the OpenVPN connection again to take effect the changes.

Section 5 . Setup OpenVPN Client.

In this section we first install the OpenVPN MSI installer on Client PC like Windows 10. After that we will setup OpenVPN client config files.  Finally start the the OpenVPN connection and test it out.

Section 5 a . OpenVPN Client MSI Install

For OpenVPN MSI installation on Client PC, follow the same steps described on Section 1. The OpenVPN Community Edition MSI Installer can be used on both Server side and with the client side.

After the OpenVPN MSI installation. Open Windows Explorer and go the folder “C:Program FilesOpenVPNsample-config” and copy file named “client.ovpn” to “C:Program FilesOpenVPNconfig”.

Move already downloaded ca.crt, CLIENT.crt, CLIENT.key and tls-auth.key to folder “C:Program FilesOpenVPNconfig”.

Refer below screenshot for better understanding on file structure.

Section 5 b . Configure Client Config File.

Go to the folder “C:Program FilesOpenVPNconfig” and open client.ovpn file using any text editor and define below parameters accordingly.

remote 185.210.137.214 1194

ca “C:\Program Files\OpenVPN\config\ca.crt”

cert “C:\Program Files\OpenVPN\config\CLIENT.crt”

key “C:\Program Files\OpenVPN\config\CLIENT.key”

remote-cert-tls server

tls-auth “C:\Program Files\OpenVPN\config\tls-auth.key” 1

cipher AES-256-CBC

In that first value defines The hostname/IP and port of the OpenVPN server

The Next three ca, cert , key values defines the location of CA and client certificate locations.

Using “remote-cert-tls server” , the OpenVPN client will verify the server certificate extendedKeyUsage.

Using “tls-auth” parameter, we enable HMAC firewall. Its an extra layer of security used to prevent DDos attack.

The last one “cipher AES-256-CBC” enables a cryptographic cipher.

Below picture shows how these parameters looks in the client config file.

This Completes the Client Setup. Now test the VPN Connection from client side. Make sure to open UDP port 1194 in the client side windows firewall too.

Section 5 c . Testing the OpenVPN connection.

Under windows Hidden Notification area , right click on OpenVPN icon and Click Connect.

The OpenVPN connection will establish automatically. After the successful connection , try to ping to the private IP of OpenVPN server and make sure its reachable. Also test the internet connection of your client PC.

Also on a Successfully connected OpenVPN Client PC, if we lookup the what is my IP on web browser, we will see its our VPN Server IP. This means that all our web traffic is routing through OpenVPN server.

Conclusion.

We have successfully completed the OpenVPN setup On Windows 10 and successfully connected from a Windows 10 OpenVPN client PC. Also we have seen how to route all IP traffic from client side through OpenVPN server. I hope this article is informative. Leave your thoughts at the comment box.

Share This Story, Choose Your Platform!

Related Posts

17 Comments

  1. darp
    February 20, 2022 at 2:18 pm — Reply

    Hi,
    Cannot find easytls-openssl.cnf in zip.
    Thx.

    • admin
      March 13, 2022 at 4:44 am — Reply

      Yes, correct. Its not available in the updated zip and we don’t need to copy that file now. The command easytls will work with out that file.

  2. JJ
    March 14, 2022 at 6:10 pm — Reply

    Thank you for this clear tutorial, I followed every step, but am stuck with these errors in the log file:
    Can you please help!?

    2022-03-14 14:01:00 WARNING: –topology net30 support for server configs with IPv4 pools will be removed in a future release. Please migrate to –topology subnet as soon as possible.

    2022-03-14 14:01:00 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.

    2022-03-14 14:01:00 Cannot pre-load keyfile (“C:Users[removed]OpenVPNtls-auth.key”)
    [ in server.ovpn it is with \, but the .log file shows !?]

    2022-03-14 14:01:00 Exiting due to fatal error

    • admin
      March 23, 2022 at 11:24 am — Reply

      As suggested try to use –data-ciphers-fallback ‘AES-256-CBC’. Normally it should work.
      Cannot preload the tls-auth key, some how the path is not correct or may be related to permission related or may be the double quotes symbol is wrong somehow.

  3. DoctorMagic
    March 22, 2022 at 9:43 pm — Reply

    All ok, I follow all instructions but when i connect give me an error:
    Unrecognized option or missing or extra parameter(s) is server.ovpn:78: ca (2.5.6)
    why?

    • admin
      March 23, 2022 at 11:25 am — Reply

      It could be possible that the double quotes symbol got changed somehow. Try to manually type it.

    • Alan Tibbetts
      April 2, 2022 at 11:59 pm — Reply

      Regarding the error
      Unrecognized option or missing or extra parameter(s) is server.ovpn:78: ca (2.5.6)
      why?

      I found that using Notepad++ to replace all the standalone n symbols in the sample server and client files cured the problem. It took two passes. Replace n with rn first, followed by replace rnn with rn. I also changed the encoding from UTF-8-BOM to ANSI. It really looks like the samples were really not tested well, perhaps being copied from another OS without changing the end of line syntax appropriately.

  4. DoctorMagic
    March 23, 2022 at 9:34 am — Reply

    this is the line 78
    ca “C:\Program Files\OpenVPN\easy-rsa\pki\ca.crt”

  5. DoctorMagic
    March 23, 2022 at 1:08 pm — Reply

    it works
    the problem is “(keyboard input) not ” (web copy)
    Thanks
    Idol

  6. DoctorMagic
    March 24, 2022 at 6:28 pm — Reply

    Hello again
    Routing is enabled
    i ping 10.8.0.1 and 172.16.1.11 (ip windows 10) correctly from client
    but i not surf in internet on client.
    I don’t ping any address of server 172.16.1.11
    Where is the error?
    Thanks again

  7. DoctorMagic
    March 24, 2022 at 6:43 pm — Reply

    Hello again.
    I disable the iCS and then enable
    Its works
    all ok

  8. Alan Tibbetts
    April 2, 2022 at 11:47 pm — Reply

    I had these same problems. I just copied the line above into Notepad++ and used the HEX-editor plugin to look at it in hex, I saw that the double quotes were e2 80 9c for the leading quote and e2 80 9d for the trailing quote, not the ANSI double quote (hex 22) with which they are visually identical. My solution was to replace the bogus quotes with the ANSI apostrophe (hex 27). It takes two passes through the file to replace the leading and then the trailing offensive characters. Not offensive to me, offensive to OpenVPN.

  9. DoctorMagic
    April 3, 2022 at 11:57 am — Reply

    Hello, can i execute a script on server when a client is connected?
    For example when a generic client is connected i send a message to admin
    Thanks

    • admin
      April 12, 2022 at 6:20 am — Reply

      Yes, from my understanding its possible and I believe you need to look at the –script-security option available for openvpn

  10. Vlad
    August 11, 2022 at 2:27 pm — Reply

    Awesome! Thanks for the detailed explanation, all works fine.

  11. Vlad
    September 9, 2022 at 5:56 pm — Reply

    It connects, but can’t open websites in a browser. Any clues?

    • admin
      September 15, 2022 at 2:05 pm — Reply

      Try to restart the openvpn service and see if that helps.

Page load link

Go to Top

Like this post? Please share to your friends:
  • Openvpn client windows 7 x32 скачать
  • Openvpn client windows 10 64 bit скачать
  • Openvpn auth user pass verify windows
  • Opentrack скачать 64 bit на русском windows 10
  • Opentoonz скачать бесплатно на русском для windows