docker를 이용한 openVPN 설정

컨테이너가 아닌 네이티브 설치는 다음 포스트를 참조
openVPN 서버구축 #1. 개요
openVPN 서버구축 #2. 서버 설치 및 설정

docker-compose.yaml 생성

version: '2'
services:
  openvpn:
    cap_add:
     - NET_ADMIN
    image: kylemanna/openvpn
    container_name: openvpn
    ports:
     - "1194:1194/udp" 
    restart: always
    volumes:
     - ./openvpn-data/conf:/etc/openvpn #.openvpn-data/conf 디렉토리를 생성해야 한다.

설정파일 및 인증서 초기화

docker-compose run --rm openvpn ovpn_genconfig -u udp://VPN.YOUR_HOST.NAME

# 아래는 수행 결과
reating network "vpn_default" with the default driver
Pulling openvpn (kylemanna/openvpn:)...
....중략....
Creating vpn_openvpn_run ... done
Processing PUSH Config: 'block-outside-dns'
Processing Route Config: '192.168.254.0/24'
Processing PUSH Config: 'dhcp-option DNS 8.8.8.8'
Processing PUSH Config: 'dhcp-option DNS 8.8.4.4'
Processing PUSH Config: 'comp-lzo no'
Successfully generated config
Cleaning up before Exit ...
docker-compose run --rm openvpn ovpn_initpki

# 아래는 수행 결과
Creating vpn_openvpn_run ... done

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/pki

Using SSL: openssl OpenSSL 1.1.1g  21 Apr 2020

Enter New CA Key Passphrase: CA_KEY의_Passphrase
Re-Enter New CA Key Passphrase: CA_KEY의_Passphrase
Generating RSA private key, 2048 bit long modulus (2 primes)
................................+++++
......................................................+++++
e is 65537 (0x010001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name 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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:vpn.haedongg.net

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/etc/openvpn/pki/ca.crt

Using SSL: openssl OpenSSL 1.1.1g  21 Apr 2020
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
..............................................................+...........................................+..........................................................
...중략...
........................................................+..+....................+................................................................+....+..++*++*++*++*

DH parameters of size 2048 created at /etc/openvpn/pki/dh.pem

Using SSL: openssl OpenSSL 1.1.1g  21 Apr 2020
Generating a RSA private key
.............+++++
............................+++++
writing new private key to '/etc/openvpn/pki/easy-rsa-74.akeLei/tmp.JBdIKe'
-----
Using configuration from /etc/openvpn/pki/easy-rsa-74.akeLei/tmp.BfJlok
Enter pass phrase for /etc/openvpn/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'vpn.haedongg.net'
Certificate is to be certified until Jul 30 00:51:51 2025 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Using SSL: openssl OpenSSL 1.1.1g  21 Apr 2020
Using configuration from /etc/openvpn/pki/easy-rsa-149.FPcifA/tmp.cjaMHC
Enter pass phrase for /etc/openvpn/pki/private/ca.key: 위_11_12_라인에서_입력했던_Passphrase

An updated CRL has been created.
CRL file: /etc/openvpn/pki/crl.pem

디렉토리 권한 변경

sudo chown -R $(whoami): ./openvpn-data

서버 프로세스 실행

docker-compose up -d openvpn

클라이언트 사용자 생성 및 인증서 생성

# 비밀번호화 함께 생성
docker-compose run --rm openvpn easyrsa build-client-full 사용자_이름

# 비밀번호 없이 생성
docker-compose run --rm openvpn easyrsa build-client-full 사용자_이름 nopass

# 인증서 파일 출력, 이 파일을 클라이언트 사용자에게 전달하면 된다.
docker-compose run --rm openvpn ovpn_getclient 사용자_이름 > 사용자_이름.ovpn

클라이언트 사용자 제거

# Keep the corresponding crt, key and req files.
docker-compose run --rm openvpn ovpn_revokeclient $CLIENTNAME

# Remove the corresponding crt, key and req files.
docker-compose run --rm openvpn ovpn_revokeclient $CLIENTNAME remove

OpenVPN 서버 구축 #2. 서버 설치 및 설정

설치

EPEL1Extra Package for Enterprise Linux 릴리즈 패키지가 필요하다.

[centos7:/home/haedong:]$ sudo  yum -y install epel-release
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be updated
---> Package epel-release.noarch 0:7-13 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
============================================================================================================================================================================================================================================
 Package                                                       Arch                                                    Version                                                  Repository                                             Size
============================================================================================================================================================================================================================================
Updating:
 epel-release                                                  noarch                                                  7-13                                                     epel                                                   15 k
Transaction Summary
============================================================================================================================================================================================================================================
Upgrade  1 Package
Total download size: 15 k
Downloading packages:
epel/x86_64/prestodelta                                                                                                                                                                                              |  539 B  00:00:01
epel-release-7-13.noarch.rpm                                                                                                                                                                                         |  15 kB  00:00:01
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Updating   : epel-release-7-13.noarch                                                                                                                                                                                                 1/2
  Cleanup    : epel-release-7-11.noarch                                                                                                                                                                                                 2/2
  Verifying  : epel-release-7-13.noarch                                                                                                                                                                                                 1/2
  Verifying  : epel-release-7-11.noarch                                                                                                                                                                                                 2/2

Updated:
  epel-release.noarch 0:7-13

Complete!

openvpn, easy-ras 패키지 설치

[centos7:/home/haedong:]$ sudo  yum -y install openvpn easy-rsa
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
Resolving Dependencies
--> Running transaction check
---> Package easy-rsa.noarch 0:3.0.8-1.el7 will be installed
---> Package openvpn.x86_64 0:2.4.9-1.el7 will be installed
--> Processing Dependency: libpkcs11-helper.so.1()(64bit) for package: openvpn-2.4.9-1.el7.x86_64
--> Running transaction check
---> Package pkcs11-helper.x86_64 0:1.11-3.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
============================================================================================================================================================================================================================================
 Package                                                      Arch                                                  Version                                                       Repository                                           Size
============================================================================================================================================================================================================================================
Installing:
 easy-rsa                                                     noarch                                                3.0.8-1.el7                                                   epel                                                 44 k
 openvpn                                                      x86_64                                                2.4.9-1.el7                                                   epel                                                524 k
Installing for dependencies:
 pkcs11-helper                                                x86_64                                                1.11-3.el7                                                    epel                                                 56 k
Transaction Summary
============================================================================================================================================================================================================================================
Install  2 Packages (+1 Dependent package)
Total download size: 624 k
Installed size: 1.5 M
Downloading packages:
(1/3): easy-rsa-3.0.8-1.el7.noarch.rpm                                                                                                                                                                               |  44 kB  00:00:02
(2/3): openvpn-2.4.9-1.el7.x86_64.rpm                                                                                                                                                                                | 524 kB  00:00:01
(3/3): pkcs11-helper-1.11-3.el7.x86_64.rpm                                                                                                                                                                           |  56 kB  00:00:00
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                       141 kB/s | 624 kB  00:00:04
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : pkcs11-helper-1.11-3.el7.x86_64                                                                                                                                                                                          1/3
  Installing : openvpn-2.4.9-1.el7.x86_64                                                                                                                                                                                               2/3
  Installing : easy-rsa-3.0.8-1.el7.noarch                                                                                                                                                                                              3/3
  Verifying  : easy-rsa-3.0.8-1.el7.noarch                                                                                                                                                                                              1/3
  Verifying  : openvpn-2.4.9-1.el7.x86_64                                                                                                                                                                                               2/3
  Verifying  : pkcs11-helper-1.11-3.el7.x86_64                                                                                                                                                                                          3/3
Installed:
  easy-rsa.noarch 0:3.0.8-1.el7                                                                                         openvpn.x86_64 0:2.4.9-1.el7
Dependency Installed:
  pkcs11-helper.x86_64 0:1.11-3.el7
Complete!

설정

config 파일 복사
/usr/share/doc/openvpn-VERSION/sample/sample-config-files/ 디렉토리 아래에 존재한다.

Config 수정

 # openvpn 사용 port
 # 운영 환경에 맞게 변경한다.
port 9411

 # 프로토콜 (UDP는 user defined protocol)
proto udp

 # 가상 Device 
dev tun

 # 인증 키 관련 정보 
 # 다음 단락에서 생성할 파일들이다. 경로를 맞춰줘야 한다.
ca   /etc/openvpn/easy-rsa/pki/ca.crt
cert /etc/openvpn/easy-rsa/pki/issued/server.crt
key  /etc/openvpn/easy-rsa/pki/private/server.key 
dh   /etc/openvpn/easy-rsa/pki/dh.pem
tls-auth /etc/openvpn/easy-rsa/pki/ta.key
key-direction 0

auth SHA512
cipher AES-256-CBC

topology subnet

 # vpn network 정보. 가상 device 인터페이스.
server 10.8.0.0 255.255.255.0

ifconfig-pool-persist ipp.txt

 # vpn을 연결하면 사용할 DNS
push "redirect-gateway def1 bypass-dhcp" 
push "dhcp-option DNS 192.168.4.254" 
push "dhcp-option DNS 8.8.8.8" 

 # 클라이언트간 연결을 허용할 때. 
 # 이 항목을 활성화 할 경우 iptables 정책도 수정 해야 한다.
;client-to-client

keepalive 10 120
comp-lzo

user nobody
group nobody

persist-key
persist-tun

verb 4

 # 로그를 저장할 경로. 디렉토리를 만들어줘야 한다.
status /var/log/openvpn/openvpn-status.log
log /var/log/openvpn/openvpn.log
log-append /var/log/openvpn/openvpn.log

키 생성

준비

 # easy-rsa 관련 
[centos7:/home/haedong:]$ sudo mkdir /etc/openvpn/easy-rsa
[sudo] haedong의 암호:
[centos7:/home/haedong:]$ sudo cp -r /usr/share/easy-rsa/3/* /etc/openvpn/easy-rsa
[centos7:/home/haedong:]$

키 생성을 위한 변수 설정
키를 생성하는 과정에서 직접 입력 할 수도 있다.

[centos7:/home/haedong:]$ sudo vi /etc/openvpn/easy-rsa/vars

 # 아래 내용을 붙여넣는다.

 # 국가 명
export KEY_COUNTRY="KR" 
 # 시/도 (경기도, 충청남도, 서울특별시, 광주광역시 등 광역시 이상)
export KEY_PROVINCE="Soeul" 
 # 시/군/구 (수원시, 속초시, 예산군, 강남구 등)
export CITY="GANGNAMGU" 
 # 회사명
export ORG="HaeDongcorp" 
 # Email
export KEY_EMAIL="haedonggang@naver.com" 
 # 부서 명
export KEY_OU="ITinfra" 
 # 서버 명
export KEY_NAME="centos7" 
 # 공통이름
export KEY_CN="vpn.haedongg.net" 

Setting up your own Certificate Authority – openvpn.net의 가이드

PKI 초기화

[centos7:/root:]# cd /etc/openvpn/easy-rsa
[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa clean-all
Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki

[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa init-pki
Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
WARNING!!!
You are about to remove the EASYRSA_PKI at: /etc/openvpn/easy-rsa/pki
and initialize a fresh PKI here.
Type the word 'yes' to continue, or any other input to abort.
  Confirm removal: yes
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki

ca 키 생성

[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa build-ca

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017

Enter New CA Key Passphrase: PASSPHRASE를 넣는다.
Re-Enter New CA Key Passphrase:  PASSPHRAS 확인
Generating RSA private key, 2048 bit long modulus
...............................................................+++
.........................................................+++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name 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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:  서버_이름

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/etc/openvpn/easy-rsa/pki/ca.crt

서버 키 생성

[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa build-server-full server

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating a 2048 bit RSA private key
..................................+++
.......................+++
writing new private key to '/etc/openvpn/easy-rsa/pki/easy-rsa-35432.9GPaYv/tmp.0beTT2'
Enter PEM pass phrase:  
Verifying - Enter PEM pass phrase:
-----
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-35432.9GPaYv/tmp.RTNa79
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key: CA_키_생성시_입력한_PASSPHRASE
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'server'
Certificate is to be certified until Mar 13 06:22:57 2023 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

DH 키교환 알고리즘을 위한 키 생성

[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa gen-dh

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
.................+......................................................
...한참 중략....
........................................................................++*++*

DH parameters of size 2048 created at /etc/openvpn/easy-rsa/pki/dh.pem

TLS 키 생성

[centos7:/etc/openvpn/easy-rsa:]# openvpn --genkey --secret /etc/openvpn/easy-rsa/pki/ta.key

사용자 키 생성

[centos7:/etc/openvpn/easy-rsa:]# ./easyrsa build-client-full haedong

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017
Generating a 2048 bit RSA private key
.............................................................+++
...................................+++
writing new private key to '/etc/openvpn/easy-rsa/pki/easy-rsa-35775.MjyGfQ/tmp.HL4Nlv'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-35775.MjyGfQ/tmp.VU7eke
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'haedong'
Certificate is to be certified until Mar 13 06:31:57 2023 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

OS(openvpn이 설치된 centos) 계정 정보를 이용한 인증 설정
옵션에 넣어줘야 하는 파일은 openvpn 패키지에 포함 되어있다. CentOS7 기준으로 /usr/lib64/openvpn/plugin 에 존재한다.

 # /etc/openvpn/server.conf 파일 끝에 아래 내용 추가

plugin /usr/lib64/openvpn/plugins/openvpn-plugin-auth-pam.so login
client-cert-not-required

서비스 시작

[centos7:/etc/openvpn/easy-rsa/pki:]#  systemctl start openvpn@server.service
Broadcast message from root@centos7 (Tue 2020-12-08 16:35:57 KST):

Password entry required for 'Enter Private Key Password:' (PID 37264).
Please enter password with the systemd-tty-ask-password-agent tool!


[centos7:/etc/openvpn/easy-rsa/pki:]# systemctl start openvpn@server.service
Enter Private Key Password: 개인키_PASSPHRASE

클라이언트 설정

Windows를 기준으로 다음과 같은 파일을 준비한다.
ca.crt / ta.key 파일은 키 생성 과정에서 생성했으니 다운로드 하면 된다.
VPN.ovpn 파일은 그냥 text 파일이다. 빈 파일을 만든다.
그리고 세 개 파일을 openvpn 클라이언트가 설치된 경로아래 config 디렉토리에 복사한다.
보통 C:\Program Files\OpenVPN\config 가 된다.

 # 다음의 내용을 삽입하고 저장한다.
client
dev tun
proto udp

resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
auth SHA512
cipher AES-256-CBC
comp-lzo
verb 4


 # 키 파일의 경로를 입력
 # 별도의 경로를 넣지 않으면 C:\Program Files\OpenVPN\config 디렉토리를 기본으로 인식한다.
 # openvpn client 인스톨 뒤 위 경로에 ca.crt파일과 ta.key 파일을 복사한다. 
ca ca.crt
tls-auth ta.key 1
key-direction 1 

auth-user-pass

#remote VPN-SERVER-IP 9411

클라이언트 실행

아래 아이콘에 마우스 오른쪽 버튼을 클릭하면 메뉴가 뜬다.
vpn 서버가 여러대 일 경우 각 서버마다 ovpn 파일을 생성해서 config에 넣어주면 선택하여 접속할 수 있다.

이렇게 접속이 된다.

OpenVPN 서버 구축 #1. 개요

OpenVPN 서버 구축 #2. 서버 설치 및 설정

가상사설망(假想私設網) 또는 VPN(영어: virtual private network)은 공중 네트워크를 통해 한 회사나 몇몇 단체가 내용을 바깥 사람에게 드러내지 않고 통신할 목적으로 쓰이는 사설 통신망이다.가상 사설망에서 메시지는 인터넷과 같은 공공망 위에서 표준 프로토콜을 써서 전달되거나, 가상 사설망 서비스 제공자와 고객이 서비스 수준 계약을 맺은 후 서비스 제공자의 사설망을 통해 전달된다.

가상 사설망의 등장배경은 인터넷을 기반으로 한 기업 업무환경의 변화에 기인한다. 즉, 소규모 지역에서 문서만을 전달하던 업무처리 기반에서 하나의 건물 내의 네트워크를 이용한 업무로, 다시 본사와 다수의 지사 관계, 또한 지사는 국내 지사와 국외 지사로 확장되었다. 이들이 하나의 네트워크 구축을 위해 기존 전용선을 사용하는 방법에는 비용을 포함한 여러가지 한계를 가지며, 전용선을 이용해서 네트워크가 구성되었다고 하더라도 네트워크 운영을 자체적으로 하는 것과 새로운 기술들을 도입하는 것 역시 기업의 입장에서는 상당한 부담이 될 수 있다. 또한 기존의 공중 네트워크는 보안과 관련해서는 서비스를 제공하지 않기 때문에 중요한 문서나 데이터를 전달하기에는 부족한 점이 있었다. 이러한 복합적인 이유가 가상 사설망이 등장한 계기가 되었다.1위키백과에서 발췌

왜 VPN이 생겨났는가는 단순하다.
A라는 회사가 있다고 생각해보자. 최첨단 산업을 선도하는 A사는 시간이 흐르면서 회사의 규모도 커지고 직원도 늘어나면서 서울에 본사 뿐 아니라 미국, 중국, 영국 등 세계 각국의 주요 거점에도 지사를 세우게 됐다.

서울 본사만 있을 때는 사내망 관리만 하면 됐지만 미국지사와 중요한 자료를 주고받으려니 일반망으로 데이터를 주고 받자니 중간에 패킷을 가로채거나 하는 공격의 위험이 크고, 서울에서 미국까지 전용선을 설치하자니 너무 비용이 많이 든다.

이러한 상황에서의 보안 요건을 충족하기 위한 것이 바로 Virtual Private Network 되시겠다.
즉, 일반망을 사용하되, 암호화 등의 조치를 통해 본사와 미국지사 사이의 연결이 사설망인 것 처럼 동작하게 하는 것, 그것이 VPN이다.


PPPTP / L2TP / IPSEC / SSL 등의 방식이 있으며, 근래에는 IPSEC, SSL 두 종류로 수렴하는 듯 한다.
가장 많이 쓰이는 IPSEC / SSL 방식 VPN의 차이를 찾자면
– SSL 방식이건 IPSEC이건 모두 암호화방식이나, 터널 개념에 있어서 큰 차이는 없다.

이건 SSL-VPN

– 클라이언트와 대상 망의 VPN 서버와 터널을 맺고 암호화 통신을 한다.

이건 IPSEC

– 양자간 각각의 VPN server를 두고 각 VPN 서버끼리 터널을 맺고 통신을 한다.