Graph Tutorial on building a vpn server using openvpn in CentOS

Source: Internet
Author: User
Tags vars
Today, I saw someone in the group talking about openvpn. I just had a holiday at home, so I just studied it. I used the openvpn client when I was a little white two years ago when I was in the old unit and connected to the headquarters OA. I felt that the project should be usable in the future, SOgoogle has a lot of pieces of information on the Internet, and it has been around for a long time. according to my own understanding, I have seen some people in the group mention openvpn. it's just a holiday at home, so I just studied it.
I used the openvpn client when I was a little white two years ago when I was in the old unit and connected to the headquarters OA. I felt that the project should be usable in the future, SOgoogle has a large number of pieces of information on the Internet and has spent a long time. according to his own understanding, he has organized the following documents and shared them with interested friends.

Recently, I have been trying to take a good look at my short board, that is, LINUX programming ..
Get started ..
------------------- Gorgeous split line -----------------------
Openvpn is an open-source VPN software used on LINUX gateway servers. as its name implies, openvpn is used to connect a secure virtual private channel, allowing users to remotely work and obtain intranet resources.
The software can be used across platforms in Linux, xBSD, Mac OSX, and Windows. openssl is used as the encryption library and the encrypted certificate or user name/password is used for identity authentication, is a rare open source VPN solution.
The purpose of this experiment is to simulate the need for outgoing staff from common companies to access the company's intranet OA to achieve remote office automation.
Solution:
System environment: Centos6.3x64
OPENVPN: openvpn-2.3.0 (attachment download)
Vpn server: eth0: 192.168.100.90, eth1: 172.24.30.1
Vpn client: 192.168.100.34
Intranet server: 172.24.30.10
650) this. width = 650; "src =" http://upload.server110.com/image/20131007/1016351G3-0.jpg "title =" openvpn.jpg "/>
Deployment environment:
1. clear the default policy and restart Iptables
# Iptables-t NAT-F
# Iptables-F
# Service iptables save
# Service iptables restart
2. disable SELINUX
# Setenforce 0
# Vi/etc/sysconfig/selinux
---------------
SELINUX = disabled
---------------

Server (routing mode ):
I. network settings
1. enable the server-side route forwarding function
# Vi/etc/sysctl. conf
---------------------
Net. ipv4.ip _ forward = 1
---------------------
# Sysctl-p
2. set nat forwarding:
Note: ensure that the VPN address pool can be routed out of the Internet
# Iptables-t nat-a postrouting-s 10.8.0.0/24-o eth0-jMASQUERADE
3. set the openvpn port to pass through:
# Iptables-a input-p TCP -- dport 1194-j ACCEPT
# Iptables-a input-m state -- state ESTABLISHED, RELATED-jACCEPT
Restart iptables:
Note: The INPUT policy takes effect immediately after execution. POSTROUTING needs to be saved and restarted to take effect.
# Service iptables save
# Service iptables restart
Note: If you want the server to only provide basic services such as openvpn, refer to the iptables script attached to this document.
3. time synchronization (important ):
# Ntpdate asia.pool.ntp.org

II. install the dependent Library
# Yum install-y openssl-devel lzo-devel pampam-devel automake pkgconfig

3. install openvpn:
# Wget-chttp: // swupdate.openvpn.org/community/releases/openvpn-2.3.0.tar.gz
# Tar zxvf openvpn-2.3.0.tar.gz
# Cd openvpn-2.3.0
#./Configure -- prefix =/usr/local/openvpn
# Make & make install
# Mkdir-p/etc/openvpn
Copy the template to the openvpn configuration Directory:
# Cp-rf sample/etc/openvpn/
Copy the openvpn configuration file to the main directory:
# Cp/etc/openvpn/sample-config-files/server. conf/etc/openvpn/
# Cd ..

4. download easy-rsa:
Note: This package is used to create ca certificates, server certificates, client certificates, and openvpn2.3.0. the source code of this version does not contain easy-rsa, so you need to download and install it separately to use openvpn for certificate generation.
# Wget-chttps: // github.com/OpenVPN/easy-rsa/archive/master.zip
# Unzip master
# Mv easy-rsa-master easy-rsa
# Cp-rf easy-rsa/etc/openvpn
# Cd/etc/openvpn/easy-rsa/2.0
Modify certificate variables
# Vi vars
Modify the following parameters:
Note: When the server ca certificate is generated later, the configuration here will be used as the default configuration
---------------------
Export KEY_COUNTRY = "CN"
Export KEY_PROVINCE = "SX"
Export KEY_CITY = "Xian"
Export KEY_ORG = "example"
Export KEY_EMAIL = "user01@example.com"
---------------------
Perform the SSL configuration file soft link:
# Ln-s openssl-1.0.0.cnf openssl. cnf
Modify the vars file executable and call
# Chmod + x vars
# Source./vars
-----------------
NOTE: If you run./clean-all, I will be doing a rm-rf on/etc/openvpn/easy-rsa/2.0/keys
-----------------
Note: If you execute./clean-all, all files under/etc/openvpn/easy-rsa/2.0/keys will be cleared.
Start configuring the certificate:
1. clear the original certificate:
#./Clean-all
Note: the following command can be run during the first installation and used with caution after the client is added, because this command will clear all generated certificate keys, which correspond to the above prompt.
2. generate a server-side ca certificate
#./Build-ca
Note: as the default configuration has been made before, press enter here.
3. Generate the server-side key certificate. the openvpn.example.com is the server name, which can be customized.
#./Build-key-server openvpn.example.com
---------------------------
Generating a 2048 bit RSA private key
........................................ ........... ++
.................................... ++
Writing new private key to 'openvpn .example.com. key'
-----
You are about to be asked to enter information that will be
Ininitialized ated
Into your certificate request.
What you are about to enter is what is called a DistinguishedName or
A DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [CN]:
State or Province Name (full name) [SX]:
Locality Name (eg, city) [Xian]:
Organization Name (eg, company) [example]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname)
[Openvpn.example.com]:
Name [EasyRSA]:
Email Address [user01@example.com]:
Please enter the following 'Extra 'attributes
To be sent with your certificate request
A challenge password []: 123456
An optional company name []: example
Using configuration from/etc/openvpn/easy-rsa/2.0/openssl-1.0.0.cnf
Check that the request matches the signature
Signature OK
The Subject's Distinguished Name is as follows
CountryName: PRINTABLE: 'cn'
StateOrProvinceName: PRINTABLE: 'SS'
LocalityName: PRINTABLE: 'xian'
OrganizationName: PRINTABLE: 'example'
CommonName: PRINTABLE: 'openvpn .example.com'
Name: PRINTABLE: 'easyrsa'
EmailAddress: IA5STRING: 'user01 @ example.com'
Certificate is to be certified until Jun 10 21:58:49 2023 GMT (3650 days)
Sign the certificate? [Y/n]: y
1 out of 1 certificate requests certified, commit? [Y/n] y
Write out database with 1 new entries
Data Base Updated
---------------------------
4. generate the required client certificate key file (the name is arbitrary. we recommend that you write it as the name of the person you want to send to facilitate management ):
#./Build-key client1
#./Build-key client2
Note: the configuration is similar to that used to generate a server certificate. you are prompted to enter the server password in the intermediate step. press enter as prompted by default.
5. Generate The diffie hellman parameter to enhance openvpn security (the generation takes a long wait)
#./Build-dh
6. pack keys
# Tar zcvf keys.tar.gz keys/
7. send the terminal to the client for backup
# Yum install lrzsz-y
# Sz keys.tar.gz

5. configure openvpn server:
# Vi/etc/openvpn/server. conf
Note: the configuration can be performed according to the default template. In this example, the custom configuration file is used:
--------------------------
# Set the listening IP address. the default setting is to listen to all IP addresses.
; Local a. B. c. d
# Set the listening port, which must be enabled in the firewall
Port 1194
# Set TCP or UDP protocol?
; Proto tcp
Proto tcp
# Set the route IP channel for creating tun or the Ethernet channel for creating tap
# The Route IP address is easy to control, so it is recommended to use it. However, if IPX is required
# If the second layer is used for communication, you can use the tap method.
# Ethernet bridging
; Dev tap
Dev tun
# For Windows, you need to give the NIC a name. set this parameter here, which is not required for linux.
; Dev-node MyTap
# Here is the focus. you must specify SSL/TLS root certificate (ca ),
# Certificate (cert), and private key (key)
# Ca files are required by both the server and client, but do not require ca. key.
# Specify the respective. crt and. key for the server and client
# Note the path. you can use the relative path starting with the configuration file as the root,
# You can also use an absolute path.
# Store the. key file with caution
Ca/etc/openvpn/easy-rsa/2.0/keys/ca. crt
Cert/etc/openvpn/easy-rsa/2.0/keys/openvpn.example.com. crt
Key/etc/openvpn/easy-rsa/2.0/keys/openvpn.example.com. key
# This file shoshould be kept secret
# Specify Diffie hellman parameters.
Dh/etc/openvpn/easy-rsa/2.0/keys/dh2048.pem
# Configure the CIDR block used by the VPN. OpenVPN automatically provides DHCP based on the CIDR block.
# Service, but it cannot be the same as the LAN segment of any party. it must be unique.
Server 10.8.0.0 255.255.255.0
# Maintain a table corresponding to the client and virtual IP to facilitate the client to restart
# The same IP address can be obtained through the connection.
Ifconfig-pool-persist ipp.txt
# Configure the Ethernet bridge mode, but use the bridge function of the system.
# This is not required
Server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
# Create a route for the client to access the internal server of the company network
# But remember, the company's internal server also needs to have available routes to return to the client
; Push "route 192.168.20.0 255.255.255.0"
Push "route 172.24.30.0 255.255.255.0"
# Specify an IP address or route for a specific client. the route is usually after the client
# Intranet CIDR block, not the CIDR block connected to the server
# Ccd is the directory under/etc/openvpn, and the client Common with promising limitations is built in it
# Name is the file Name, and write a fixed IP address using the following command
# For example, if the Common Name is client1, write the following in/etc/openvpn/ccd/client1:
# Ifconfig-push 10.9.0.1 10.9.0.2
; Client-config-dir ccd
; Route 192.168.40.128 255.255.255.255.248
# Set firewall and other permissions for different clients
# Make the script run automatically. For more information, see man.
; Learn-address./script
# This statement can be used if the client wants all traffic to be transmitted over the VPN
# It will automatically change the gateway of the client to a VPN server. we recommend that you disable it.
# Be careful when configuring DHCP settings on the server.
; Push "redirect-gateway"
# Use the DHCP function of OpenVPN to provide the specified DNS and WINS for the client.
; Push "dhcp-option DNS 10.8.0.1"
; Push "dhcp-option WINS 10.8.0.1"
# The client cannot communicate directly by default unless the following statements are commented out.
Client-to-client
# If you want clients with the same Common Name to log on
# You can also comment out the following statements. we recommend that you use a Common Name that is not used by each client.
# Used for testing
; Duplicate-cn
# Set the server detection interval and timeout time
Keepalive 10 120
# The following are some security enhancement measures
# For extra security beyond that provided
# By SSL/TLS, create an "HMAC firewall"
# To help block DoS attacks and UDP port flooding.
#
# Generate:
# Openvpn -- genkey -- secret ta. key
#
# The server and each client must have
# A copy of this key.
# The second parameter shocould be 0
# On the server and 1 on the clients.
; Tls-auth ta. key 0 # This file is secret
# Select a cryptographic cipher.
# This config item must be copied
# The client config file as well.
; Cipher BF-CBC # Blowfish (default)
Cipher AES-128-CBC # AES
; Cipher DES-EDE3-CBC # Triple-DES
# For lzo compression communication, both the server and client must be configured
Comp-lzo
# Set the maximum number of users
Max-clients 100
# Enable OpenVPN to run with nobody Users and Groups (secure)
; User nobody
; Group nobody
# The persist options will try to avoid
# Accessing certain resources on restart
# That may no longer be accessible because
# Of the privilege downgrade.
Persist-key
Persist-tun
# Output short logs, refresh once every minute to display the current client
Status/var/log/openvpn/openvpn-status.log
# Default logs are recorded in system logs, but can also be directed to other places
# It is recommended that you do not set debugging before defining it.
Log/var/log/openvpn. log
Log-append/var/log/openvpn. log
# Set the log level
#
#0 is silent, cannot T for fatal errors
#4 is reasonable for general usage
#5 and 6 can help to debug connection problems
#9 is extremely verbose
Verb 3
# Silence repeating messages. At most 20
# Sequential messages of the same message
# Category will be output to the log.
; Mute 20
--------------------------
Create a log Directory:
# Mkdir-p/var/log/openvpn/
Start openvpn server
#/Usr/local/openvpn/sbin/openvpn -- config/etc/openvpn/server. conf &
Set boot start:
# Echo "/usr/local/openvpn/sbin/openvpn -- config/etc/openvpn/server. conf>/dev/null 2> & 1 & ">/etc/rc. local

Client:
6. install WINDOWS client (WIN7 64bit)
1. download the client and install it by default:
Http://vpntech.googlecode.com/files/openvpn-2.1.1-gui-1.0.3-install-cn-64bit.zip
2. decompress the server package file, and copy ca. crt, client1.crt, and client1.key in the package to the client C: \ ProgramFiles \ OpenVPN \ config.
3. create the client. ovpn file under C: \ Program Files \ OpenVPN \ config
The content is as follows:
-----------------------
# Define a client
Client
# Define the use of the routing IP mode, consistent with the server
; Dev tap
Dev tun
# Define the name of the NIC used in Windows, which is not required in linux
; Dev-node MyTap
# Define the used protocol, which is consistent with the server
; Proto tcp
Proto tcp
# Specify the server address and port. you can use multiple lines to specify multiple servers.
# Implementation Server load balancer(Try from top down)
Remote 192.168.100.90 1194
; Remote my-server-2 1194
# If multiple servers are configured above, the client can be connected randomly.
; Remote-random
# Resolving server domain names
# Keep trying indefinitely to resolve
# Host name of the OpenVPN server. Very useful
# On machines which are not permanently connected
# To the internet such as laptops.
Resolv-retry infinite
# The client does not need to bind a port
# Most clients do not need to bind
# A specific local port number.
Nobind
# It is also used to make Openvpn run nobody (secure)
# Note: Windows cannot be set.
; User nobody
; Group nobody
# Try to preserve some state when SS restarts.
Persist-key
Persist-tun
# If the client uses HTTP Proxy, set
# To use Proxy, do not use UDP as the VPN communication protocol
; Http-proxy-retry # retry on connection failures
; Http-proxy [proxy server] [proxy port #]
# The wireless network has many redundant header files and is set to ignore them.
; Mute-replay-warnings
# The key point is to specify the ca and client certificates
Ca. crt
Cert client1.crt
Key client1.key
# If the PAM authentication module is enabled on the server, the client must be valid
; Auth-user-pass
# Some security measures
# Verify server certificate by checking
# That the certicate has the nsCertType
# Field set to "server". This is
# Important precaution to protect against
# A potential attack discussed here:
# Http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# Your server certificates with the nsCertType
# Field set to "server". The build-key-server
# Script in the easy-rsa folder will do this.
; Ns-cert-type server
# If a tls-auth key is used on the server
# Then every client must also have the key.
; Tls-auth ta. key 1
# Select a cryptographic cipher.
# If the cipher option is used on the server
# Then you must also specify it here.
; Cipher x
# Use lzo compression, consistent with the server
Comp-lzo
# Set log file verbosity.
Verb 3
# Silence repeating messages
; Mute 20
-----------------------
5. connection:
Right-click the openvpn icon in the lower-right corner and select "Connect". if an IP address can be allocated properly, the connection is successful.

6. final test:
C: \ Users \ Administrator> ipconfig/all
---------------------------------------
...............
Ethernet adapter Local connection * 12:
Connection to a specific DNS suffix .......:
Description ......: TAP-Win32 AdapterV9
Physical address ......: 00-FF-45-FB-F5-E2
DHCP enabled... yes
Automatic configuration is enabled... yes
Local IPv6 address ......: fe80: 848d: bd1d: c1f4: fb51 % 27 (preferred)
IPv4 address ......: 10.8.0.6 (preferred)
Subnet mask ......: 255.255.255.252
Time for obtaining the lease...: June 15, 2013 22:36:59
Lease expiration time ......: 22:36:59, January 1, June 15, 2014
Default Gateway .............:
DHCP server ......: 10.8.0.5
DHCPv6 IAID ......: 453050181
.....................
----------------------------------
Ping the intranet server host IP address on the vpn client: 172.24.30.10
C: \ Users \ Administrator> ping 172.24.30.10
-------------------------
Pinging 172.24.30.10 with 32 bytes of data:
Reply from 172.24.30.10: Byte = 32 time = 2 ms TTL = 63
Reply from 172.24.30.10: Byte = 32 time <1 ms TTL = 63
Reply from 172.24.30.10: Byte = 32 time <1 ms TTL = 63
Reply from 172.24.30.10: Byte = 32 time <1 ms TTL = 63
--------------------------
Success...

7. notes:
(Here, I would like to refer to and thank our guest for his book "building high-availability LINUX servers)

1. how to cancel the VPN certificate of a user if a company employee leaves the company:
Note: the openvpn service must be enabled properly.
# Cd/etc/openvpn/easy-rsa/2.0
#./Revoke-full client2
If an error is reported, comment out several lines of the openssl. cnf file in this directory, as shown below:
(You can log out of the user after performing the preceding operations)
-------------------------
# [Pkcs11_section]
# Engine_id = pkcs11
# Dynamic_path =/usr/lib/engines/engine_pkcs11.so
# MODULE_PATH = $ EVN: PKCS11_MODULE_PATH
# PIN = $ EVN: PKCS !! _ PIN
# Init = 0
-------------------------
Cancel again:
#./Revoke-full client2
If error23 is returned for the last row, the account is successfully logged out, but the following configuration is required to completely log out:
# Vi/etc/openvpn/server. conf
The following content is added at the end of the line to ensure that the crl. pem file is reloaded every time the openvpn configuration file is restarted:
-----------------------
Crl-verify/etc/openvpn/easy-rsa/2.0/keys/crl. pem
-----------------------
Note: crl. pem is the blacklist of logged-out users. it can be understood that each time openvpn is started, a blacklist operation is loaded to ensure that the latest revoked certificate cannot be used.
Restart openvpn:
# Killall openvpn
#/Usr/local/openvpn/sbin/openvpn -- config/etc/openvpn/server. conf &
Use the client2 certificate on the client server to verify whether the certificate can be used
The certificate cannot be connected to the openvpn Server.
2. change the certificate validity period to improve certificate security:
The default certificate is valid for 3650 days, that is, 10 years.
# Cd/etc/openvpn/easy-rsa/2.0
# Vi pkitool
The default validity period "3650" is found. you can save the number of days you need to set.
The next time you execute this script to create a client certificate, the duration will be changed to the new number of days.

Advanced:
Openvpn provides a remote VPN service solution as an intranet server:
Companies with ample budgets can build an openvpn Server load balancer. two servers can be mounted to an intranet switch to isolate the intranet and internet using a firewall, the two openvpn servers are mapped to the intranet to ensure that the two servers are in the same network segment as the other intranet servers, and the two openvpn servers are configured in the same way.
650) this. width = 650; "src =" http://upload.server110.com/image/20131007/1016352156-1.jpg "title =" openvpn1.jpg "/>
This solution is actually suitable for later projects. if a firewall has been set up and you want to remotely access intranet resources while retaining the existing firewall, in fact, you can use the original firewall to create a ING to Port 1194 of the openvpn Server on the intranet. as long as the openvpn Server and other intranet resources are in the same network segment or can be routed to the network segment, to enable remote VPN access.
(Openvpn-server)
1. open ip_forward (omitted)
2. the eth0 port can be forwarded to the network segment data of the openvpn address pool.
# Iptables-t nat-a postrouting-s 10.8.0.0/24-o eth0-jMASQUERADE
3. ensure that the openvpn configuration file is routed to the intranet.
---------------------
Push "route 192.168.100.0 255.255.255.0"
---------------------
Other configurations are consistent with the openvpn mode of the Gateway.
Finally, add the following content to the client configuration file (C: \ ProgramFiles \ OpenVPN \ config \ client. ovpn:
------------------
Remote 172.24.30.40 1194
Remote 172.24.30.40 1195
.....
Remote-random
------------------
This line of clients will randomly connect to these two server addresses and use them as proxies to access other resources in the network.
-------- Success ----------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.