Proxmox – 解決在 LXC 無法啟動 OpenVPN

在 Proxmox LXC 安裝 OpenVPN,並設定完成啟動後,出現下面的錯誤訊息
# systemctl status openvpn@server.service
● openvpn@server.service – OpenVPN connection to server
   Loaded: loaded (/lib/systemd/system/openvpn@.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2017-02-20 19:17:06 CST; 6s ago
     Docs: man:openvpn(8)
           https://community.openvpn.net/openvpn/wiki/Openvpn23ManPage
           https://community.openvpn.net/openvpn/wiki/HOWTO
  Process: 1585 ExecStart=/usr/sbin/openvpn –daemon ovpn-%i –status /run/openvpn/%i.status 10 –cd /etc/openvpn –script-security 2 –config /etc/openvpn/%i.conf –writepid /run/openvpn/%i.pid (code=exited, st
 Main PID: 1586 (code=exited, status=1/FAILURE)

Feb 20 19:17:06 vpn systemd[1]: Starting OpenVPN connection to server…
Feb 20 19:17:06 vpn systemd[1]: openvpn@server.service: PID file /run/openvpn/server.pid not readable (yet?) after start: No such file or directory
Feb 20 19:17:06 vpn systemd[1]: Started OpenVPN connection to server.
Feb 20 19:17:06 vpn systemd[1]: openvpn@server.service: Main process exited, code=exited, status=1/FAILURE
Feb 20 19:17:06 vpn systemd[1]: openvpn@server.service: Unit entered failed state.
Feb 20 19:17:06 vpn systemd[1]: openvpn@server.service: Failed with result ‘exit-code’.[@more@]參考網站:
Setup OpenVPN on Proxmox LXC – Hungred Dot Com

登入 LXC 後
# cd /dev
# mkdir net
# mknod net/tun c 10 200
# chmod 0666 net/tun
# ls -l /dev/net/tun
crw-rw-rw- 1 root root 10, 200 Feb 20 19:24 /dev/net/tun

或直接寫在 /etc/rc.local 之中
# vim /etc/rc.local
加入下面幾行
mkdir /dev/net
mknod /dev/net/tun c 10 200
chmod 0666 /dev/net/tun

OpenVPN 可以正常執行
# systemctl status openvpn@server.service
● openvpn@server.service – OpenVPN connection to server
   Loaded: loaded (/lib/systemd/system/openvpn@.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2017-02-20 19:24:33 CST; 18s ago
     Docs: man:openvpn(8)
           https://community.openvpn.net/openvpn/wiki/Openvpn23ManPage
           https://community.openvpn.net/openvpn/wiki/HOWTO
  Process: 1600 ExecStart=/usr/sbin/openvpn –daemon ovpn-%i –status /run/openvpn/%i.status 10 –cd /etc/openvpn –script-security 2 –config /etc/openvpn/%i.conf –writepid /run/openvpn/%i.pid (code=exited, st
 Main PID: 1601 (openvpn)
   CGroup: /system.slice/system-openvpn.slice/openvpn@server.service
           mq1601 /usr/sbin/openvpn –daemon ovpn-server –status /run/openvpn/server.status 10 –cd /etc/openvpn –script-security 2 –config /etc/openvpn/server.conf –writepid /run/openvpn/server.pid

Feb 20 19:24:33 vpn systemd[1]: Starting OpenVPN connection to server…
Feb 20 19:24:33 vpn systemd[1]: openvpn@server.service: PID file /run/openvpn/server.pid not readable (yet?) after start: No such file or directory
Feb 20 19:24:33 vpn systemd[1]: Started OpenVPN connection to server.

server.pid 沒有找不到
# ls -l /var/run/openvpn/server.pid
-rw-r–r– 1 root root 5 Feb 20 19:24 /var/run/openvpn/server.pid
# ls -l /run/openvpn/server.pid
-rw-r–r– 1 root root 5 Feb 20 19:24 /run/openvpn/server.pid

執行 OpenVPN 後產生的 tun0 介面
# ifconfig tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.1.0.1  P-t-P:10.1.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

建置使用 LDAP Server 認證的 OpenVPN Server

僅列出與之前不同的地方
1. 安裝  openvpn-auth-ldap 套件
Ubuntu 16.04
# apt-get install openvpn-auth-ldap
CentOS 6.x/7.x
# yum install openvpn-auth-ldap

2. 修改 /etc/openvpn/server.conf
在檔案最後面加入下面的設定
# vim /etc/openvpn/server.conf
client-cert-not-required
username-as-common-name
plugin /usr/lib/openvpn/openvpn-auth-ldap.so /etc/openvpn/auth/auth-ldap.conf

# CentOS 7
plugin /usr/lib64/openvpn/plugin/lib/openvpn-auth-ldap.so /etc/openvpn/auth/ldap.conf

請確認 openvpn-auth-ldap.so 檔的位置[@more@]3. 建立目錄 /etc/openvpn/auth/
# mkdir /etc/openvpn/auth/

4. 建立 /etc/openvpn/auth/auth-ldap.conf 設定檔
# egrep -v ‘^#|^$’ /etc/openvpn/auth/auth-ldap.conf
<LDAP>
        # LDAP server URL
        #URL            ldap://ldap1.example.org
        URL             ldap://192.168.1.20
        # Bind DN (If your LDAP server doesn’t support anonymous binds)
         BindDN         cn=admin,dc=bpim3,dc=test,dc=org
        # Bind Password
        # Password      SecretPassword
         Password       123456
        # Network timeout (in seconds)
        Timeout         15
        # Enable Start TLS
        # Follow LDAP Referrals (anonymously)
        # TLS CA Certificate File
        # TLS CA Certificate Directory
        # Client Certificate and key
        # If TLS client authentication is required
        # Cipher Suite
        # The defaults are usually fine here
        # TLSCipherSuite        ALL:!ADH:@STRENGTH
</LDAP>
<Authorization>
        # Base DN
        BaseDN          “ou=People,dc=example,dc=com”
        # User Search Filter
        SearchFilter    “(&(uid=%u))”
        # Require Group Membership
        RequireGroup    false
        # Add non-group members to a PF table (disabled)
        #PFTable        ips_vpn_users
</Authorization>

5. 檢查 OpenVPN 設定檔是否正確
# openvpn –config /etc/openvpn/server.conf

6. 重新啟動 OpenVPN Server,並檢查是否有正常啟動
# systemctl restart openvpn@server.service;systemctl status openvpn@server.service

7. Client 端設定檔加入
auth-user-pass

建置使用帳號及密碼認證的 OpenVPN Server – 3

底下是在 CentOS 7.3 1611 下實作
1. 建立使用者及設定密碼
# useradd test -s /sbin/nologin
# passwd test

2. 修改 OpenVPN 設定檔 /etc/openvpn/server.conf
加入下面的設定
client-cert-not-required
username-as-common-name
plugin /usr/lib64/openvpn/plugins/openvpn-plugin-auth-pam.so /etc/pam.d/login

[@more@]3. 檢查 OpenVPN 設定檔是否正確
# openvpn –config /etc/openvpn/server.conf

4. 重新啟動 OpenVPN Server,並檢查是否有正常啟動
# systemctl restart openvpn@server.service;systemctl status openvpn@server.service

5. 安裝 cyrus-sasl
# yum install cyrus-sasl

6. 設定預設啟動  saslauthd 服務
# systemctl enable saslauthd.service

7.啟動 saslauthd 服務,並檢查是否有正常啟動
# systemctl start saslauthd.service;systemctl status saslauthd.service

8. 測試是否能使用本機帳號密碼進行認證
檢查帳號密碼是否能正常使用
# testsaslauthd -u test -p 123456 -s login
0: OK “Success.”
如果出現以上的訊息,代表正常

connect() : No such file or directory
0:
如果出現上面訊息,代表 saslauthd 沒有啟動,請做第 6~7 步驟

0: NO “authentication failed”
如果出現上面訊息,代表認證失敗,可能要查看一下 /var/log/secure 中的訊息

9. 在 OpenVPN Cleint 端的設定檔中,加入下面這一行
auth-user-pass

建置使用帳號及密碼認證的 OpenVPN Server – 2

試用了 OpenVPN AS 之後,發現其實也可以考慮使用 Unix-Like 本地端的帳號來進行認證。
參考網站:
Setup PAM authentication with OpenVPN’s auth-pam module – Linux Sysadmin Tutorials

1. 建立帳號及密碼
# useradd test -s /bin/false
# passwd test

2. 建立 /etc/pam.d/openvpn
# cat /etc/pam.d/openvpn
auth    required        pam_unix.so    shadow    nodelay
auth    requisite       pam_succeed_if.so uid >= 500 quiet
auth    required        pam_tally2.so deny=4 even_deny_root unlock_time=1200
account required        pam_unix.so[@more@]3. 安裝所需套件
# apt-get install libsasl2-2 sasl2-bin

4. 修改 OpenVPN 設定檔 /etc/openvpn/server.conf
加入下面幾行
client-cert-not-required
username-as-common-name
plugin /usr/lib/openvpn/openvpn-plugin-auth-pam.so openvpn

openvpn-plugin-auth-pam.so 檔案的位置要確認

5. 檢查 OpenVPN 設定檔是否正確
# openvpn –config /etc/openvpn/server.conf

6. 重新啟動 OpenVPN Server,並檢查是否有正常啟動
# systemctl restart openvpn@server.service;systemctl status openvpn@server.service

7. 修改 saslauthd 設定檔 /etc/default/saslauthd
# sed -i ‘s/START=no/START=yes/’ /etc/default/saslauthd

8. 建議重新啟動系統
# sync;sync;sync;reboot

9. 檢查帳號密碼是否能正常使用
# testsaslauthd -u test -p 123456 -s openvpn
0: OK “Success.”
如果出現以上的訊息,代表正常

connect() : No such file or directory
0:
如果出現上面訊息,代表 saslauthd 沒有啟動,請做第 7 步驟

0: NO “authentication failed”
如果出現上面訊息,代表認證失敗,可能要查看一下 /var/log/auth.log 中的訊息

10. 在 OpenVPN Cleint 端的設定檔中,加入下面這一行
auth-user-pass

使用 OpenVPN Acess Server Client 端

輸入 https://IP:943/ 連線畫面
Connect 透過 Web Browser 連上 VPN Server
Login 下載使用者可以使用的 Client 程式,或直接下載 設定檔 client.ovpn

[@more@]可以下載 整合好的 *.msi 檔下載下來安裝

下載下來的檔案

安裝完成可以在桌面上看到 OpenVPN Connect 圖示

程式會自動帶出 Server IP 資訊,輸入帳號及密碼,按 Connect 即可!

選擇 Yes

已正常連線,下方也可以看到一個 OpenVPN 的圖示,亮綠色的燈

如果要斷線,選擇 OpenVPN 圖示,並按滑鼠右鍵

選擇 Exit 即可

透過網頁來連線

也可以下載各個平台的 Client 端程式自行安裝

如果系統已有安裝 OpenVPN 程式,可以直接下載設定檔 client.ovpn

將 client.ovpn 複製到 C:Program FilesOpenVPNconfig 即可以使用原來的 OpenVPN 程式進行連線

連線時會要求輸入帳號及密碼

試用 OpenVPN Acess Server

OpenVPN Acess Server 除了可以使用 Web 介面來進行管理及設定外,也可以使用命令式的指令來進行管理。
# /usr/local/openvpn_as/bin/ovpn-init
Detected an existing OpenVPN-AS configuration.
Continuing will delete this configuration and restart from scratch.
Please enter ‘DELETE’ to delete existing configuration:

輸入 DELETE 可以刪除目前的設定檔,重新設定

以下改用 Web 介面來進行管理及設定
以 Firefox 連線為例
選擇 進階 / 新增例外網站 / 取得憑證 / 確認安全例外


[@more@]帳號 openvpn 密碼是之前所設定的密碼

軟體授權

登入畫面

功能說明
Status / Status Overview(系統狀態概述)

Status / Current Users(目前線上使用者)

Status / Log Reports(Log 報表)

Configuration / License(授權管理)

Configuration / SSL Settings(SSL 設定)

Configuration /  Server Netwok Settings(伺服器網路設定)

Configuration / VPN Mode(VPN 的模式 Bridge or Route)

Configuration / VPN Settings(VPN 設定)

Configuration / Advanced VPN(VPN 進階設定)

Configuration / Web Server(網路伺服器)

Configuration / Client Settings(使用者端設定)

Configuration / Failover(故障轉移)

User Management / User Permissions(使用者權限)

User Management / Group Permissions(群組權限)

User Management / Revoke Certificates(撤銷憑證)

Authentication / General(設定認證的方式)

Authentication / PAM(使用 PAM 系統帳號做認證)

Authentication / RADIUS(使用 RADIUS 做認證)

Authentication / LDAP(使用 LDAP 做認證)

Tools / Profiles 設定

Tools / Connectivity Test(測試網路連線狀態)

安裝 OpenVPN Acess Server

如果 VPN 的使用者不多,又不想花太多的時間安裝及設定 OpenVPN 或是 OpenConnect,則可以考慮改用 OpenVPN Access Server,底下簡稱 OpenVPN AS。
OpenVPN AS 是由開發 OpenVPN 的公司所開發的商業性版本,提供了簡單的 Web 設定介面,安裝完成之後幾乎就已經設定完成,防火牆的部分也會自動完成,非常容易使用,但免費的版本,只能同時提供二個 Client 端連線。

Access Server Overview 官方網站:
https://openvpn.net/index.php/access-server/overview.html
[@more@]支援的作業系統版本

CentOS
6.x
http://swupdate.openvpn.org/as/openvpn-as-2.1.4-CentOS6.i386.rpm
http://swupdate.openvpn.org/as/openvpn-as-2.1.4-CentOS6.x86_64.rpm
7.x
http://swupdate.openvpn.org/as/openvpn-as-2.1.4-CentOS7.x86_64.rpm

Ubuntu 16.04
http://swupdate.openvpn.org/as/openvpn-as-2.1.4b-Ubuntu16.i386.deb
http://swupdate.openvpn.org/as/openvpn-as-2.1.4b-Ubuntu16.amd_64.deb

Debian 8
http://swupdate.openvpn.org/as/openvpn-as-2.1.4-Debian8.i386.deb
http://swupdate.openvpn.org/as/openvpn-as-2.1.4-Debian8.amd_64.deb

3. 進行下載及安裝,以 CentOS 7.3 1611 x64 為例
# wget http://swupdate.openvpn.org/as/openvpn-as-2.1.4-CentOS7.x86_64.rpm

4. 進行安裝
# rpm -ivh openvpn-as-2.1.4-CentOS7.x86_64.rpm

The Access Server has been successfully installed in /usr/local/openvpn_as
Configuration log file has been written to /usr/local/openvpn_as/init.log
Please enter “passwd openvpn” to set the initial
administrative password, then login as “openvpn” to continue
configuration here: https://192.168.131.219:943/admin
To reconfigure manually, use the /usr/local/openvpn_as/bin/ovpn-init tool.

Access Server web UIs are available here:
Admin  UI: https://192.168.131.219:943/admin
Client UI: https://192.168.131.219:943/

192.168.131.219 是安裝時的主機 IP

5. 系統新增二個帳號
# tail -2 /etc/passwd
openvpn:x:1000:1000::/home/openvpn:/sbin/nologin
openvpn_as:x:1001:1001::/home/openvpn_as:/sbin/nologin

6. 設定 openvpn 管理帳號的密碼
# passwd openvpn
更改使用者 openvpn 的密碼。
新 密碼:
再次輸入新的 密碼:
passwd:所有驗證 token 都已成功更新。

建置使用帳號及密碼認證的 OpenVPN Server – 1

參考網站:
OpenVPN System Based On User/Password Authentication with mysql & Day Control (shell script)- Debian ~ Mr.TUM’s Blog

參考網站中,OpenVPN 和 MySQL 分別屬於不同主機,在這裡改用同一主機。

1. 安裝 MySQL Server
# apt-get install mariadb-server[@more@]2. 設定 root 密碼及一些安全性上的設定
# /usr/bin/mysql_secure_installation
還未設定 root 密碼,所以直接按 Enter 鍵
Enter current password for root (enter for none):
OK, successfully used password, moving on…

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

設定 MySQL root 密碼
Set root password? [Y/n]
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 … Success!

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

移除匿名使用者
Remove anonymous users? [Y/n]
 … Success!

Normally, root should only be allowed to connect from ‘localhost’.  This
ensures that someone cannot guess at the root password from the network.

取消 root 可以遠端登入
Disallow root login remotely? [Y/n]
 … Success!

By default, MariaDB comes with a database named ‘test’ that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

移除 測試的資料庫
Remove test database and access to it? [Y/n]
 – Dropping test database…
 … Success!
 – Removing privileges on test database…
 … Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

重新載入資料表權限
Reload privilege tables now? [Y/n]
 … Success!

Cleaning up…

3. 建立 openvpn 資料庫,並建立一個使用者及設定密碼來進行管理
# /usr/bin/mysql -u root -p
MariaDB [(none)]> CREATE DATABASE openvpn;
MariaDB [(none)]> GRANT ALL ON openvpn.* TO ‘pi’@”%” IDENTIFIED BY ‘123456’;
MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> exit;

4. 改用 pi 使用者來建立 openvpn 相關資料庫設定
# /usr/bin/mysql -u pi -p

5. 開啟 openvpn 資料庫
MariaDB [(none)]> USE openvpn;

6. 建立 user 資料表

CREATE TABLE IF NOT EXISTS `user` (
    `user_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
    `user_pass` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT ‘1234’,
    `user_mail` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
    `user_phone` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
    `user_online` tinyint(1) NOT NULL DEFAULT ‘0’,
    `user_enable` tinyint(1) NOT NULL DEFAULT ‘1’,
    `user_start_date` date NOT NULL,
    `user_end_date` date NOT NULL,
PRIMARY KEY (`user_id`),
KEY `user_pass` (`user_pass`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

7. 建立 log 資料表
CREATE TABLE IF NOT EXISTS `log` (
    `log_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `user_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
    `log_trusted_ip` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
    `log_trusted_port` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
    `log_remote_ip` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
    `log_remote_port` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
    `log_start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `log_end_time` timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’,
    `log_received` float NOT NULL DEFAULT ‘0’,
    `log_send` float NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`log_id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
8. 建立使用者資料
INSERT INTO `user` (
    `user_id`, `user_pass`, `user_mail`, `user_phone`,
    `user_online`, `user_enable`, `user_start_date`, `user_end_date`
)
VALUES (
    ‘test’, ‘123456’, ‘test@test.com’,
    ‘+66815447514’, 0, 1, ‘2012-01-01’, ‘0000-00-00’
);

9. 顯示資料庫中的資料表
MariaDB [openvpn]> show tables;
+————————–+
| Tables_in_openvpn |
+—————————+
| log                              |
| user                            |
+—————————-+
2 rows in set (0.00 sec)

10. 列出 user 資料表中的使用者資料
MariaDB [openvpn]> select user_id,user_pass from user;
+———-+—————-+
| user_id | user_pass   |
+———-+—————–+
| test       | 123456        |
+———-+—————–+
1 row in set (0.00 sec)

11. 退出資料庫
MariaDB [openvpn]> exit;

12 . 建立 Script 檔目錄 /etc/openvpn/script
# mkdir /etc/openvpn/script

13. 建立 /etc/openvpn/script/config.sh
# cat etc/openvpn/script/config.sh
#!/bin/bash
##Dababase Server
HOST=’127.0.0.1′
#Default port = 3306
PORT=’3306′
#Username
USER=’pi’
#Password
PASS=’123456′
#database name
DB=’openvpn’

14. 建立 /etc/openvpn/script/test_connect_db.sh
# cat /etc/openvpn/script/test_connect_db.sh
#!/bin/bash
. /etc/openvpn/script/config.sh
##Test Authentication
username=$1
password=$2
user_id=$(mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -sN -e “select user_id from user where user_id = ‘$username’ AND user_pass = ‘$password’ AND user_enable=1 AND user_start_date != user_end_date AND TO_DAYS(now()) >= TO_DAYS(user_start_date) AND (TO_DAYS(now()) <= TO_DAYS(user_end_date) OR user_end_date=’0000-00-00′)”)
##Check user
[ “$user_id” != ” ] && [ “$user_id” = “$username” ] && echo “user : $username” && echo ‘authentication ok.’ && exit 0 || echo ‘authentication failed.’; exit 1

15. 建立 /etc/openvpn/script/login.sh
# cat /etc/openvpn/script/login.sh
#!/bin/bash
. /etc/openvpn/script/config.sh
##Authentication
user_id=$(mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -sN -e “select user_id from user where user_id = ‘$username’ AND user_pass = ‘$password’ AND user_enable=1 AND user_start_date != user_end_date AND TO_DAYS(now()) >= TO_DAYS(user_start_date) AND (TO_DAYS(now()) <= TO_DAYS(user_end_date) OR user_end_date=’0000-00-00′)”)
##Check user
[ “$user_id” != ” ] && [ “$user_id” = “$username” ] && echo “user : $username” && echo ‘authentication ok.’ && exit 0 || echo ‘authentication failed.’; exit 1

16. 建立 /etc/openvpn/script/connect.sh
# cat /etc/openvpn/script/connect.sh
#!/bin/bash
. /etc/openvpn/script/config.sh
##insert data connection to table log
mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e “INSERT INTO log (log_id,user_id,log_trusted_ip,log_trusted_port,log_remote_ip,log_remote_port,log_start_time,log_end_time,log_received,log_send) VALUES(NULL,’$common_name’,’$trusted_ip’,’$trusted_port’,’$ifconfig_pool_remote_ip’,’$remote_port_1′,now(),’0000-00-00 00:00:00′,’$bytes_received’,’$bytes_sent’)”
##set status online to user connected
mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e “UPDATE user SET user_online=1 WHERE user_id=’$common_name'”

17. 建立 /etc/openvpn/script/disconnect.sh
# cat /etc/openvpn/script/disconnect.sh
#!/bin/bash
. /etc/openvpn/script/config.sh
##set status offline to user disconnected
mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e “UPDATE user SET user_online=0 WHERE user_id=’$common_name'”
##insert data disconnected to table log
mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -e “UPDATE log SET log_end_time=now(),log_received=’$bytes_received’,log_send=’$bytes_sent’ WHERE log_trusted_ip=’$trusted_ip’ AND log_trusted_port=’$trusted_port’ AND user_id=’$common_name’ AND log_end_time=’0000-00-00 00:00:00′”

18. 更改 Script 檔案權限
# chmod 755 /etc/openvpn/script/*.sh

19. 修改 /etc/openvpn/server.conf  設定檔
# vim /etc/openvpn/server.conf
加入以下設定
username-as-common-name
client-cert-not-required
auth-user-pass-verify /etc/openvpn/script/login.sh via-env

# 設定使用者登入及登出時要做的動作
##script connect-disconnect
script-security 3 system
client-connect /etc/openvpn/script/connect.sh
client-disconnect /etc/openvpn/script/disconnect.sh

20. 測試 MariaDB SQL Server 可否正常連線(帳號/密碼:test / 123456)
# /etc/openvpn/script/test_connect_db.sh test 123456
user : test
authentication ok.

如果是上面的訊息,則是連線成功!

21. 設定 OpenVPN Client 端 *.ovpn
加入以下設定
auth-user-pass
reneg-sec 0

22. 重新啟動 OpenVPN Server
# systemctl restart openvpn@server.service

23. 列出使用者的登入資料
MariaDB [openvpn]> select user_id,log_trusted_ip,log_remote_ip,log_start_time,log_end_time from log;
+———-+——————–+———————+——————————+—————————–+
| user_id | log_trusted_ip | log_remote_ip | log_start_time             | log_end_time              |
+———-+——————–+———————+——————————+——————————+
| test        | 1.162.15.9      | 10.8.0.6             | 2016-12-29 09:27:32 | 2016-12-29 10:27:36 |
+———-+——————–+———————+——————————+——————————+

建置使用帳號及密碼認證的 OpenVPN Server

參考網站:
CentOS7 搭建OpenVPN | HuaChao’s Blog

之前的設定可以參考  頭城國小資訊組 | 試用 Banana Pi R1 – Ubuntu minimal 16.04 上安裝 OpenVPN,這裡只針對剩餘的部份做修改
1. 修改 /etc/openvpn/server.conf 設定檔
     auth-user-pass-verify 指定要認證的程式碼,及使用何種帳密傳遞的方式
     client-cert-not-required
     username-as-common-name
# echo -e “n# 使用帳號密碼做認證nscript-security 3 systemnauth-user-pass-veri
fy /etc/openvpn/checkpsw.sh via-envn;client-cert-not-requirednusername-as-comm
on-name” >> /etc/openvpn/server.conf
[@more@]2. 建立密碼檢查程式
# vim /etc/openvpn/checkpsw.sh

#!/bin/sh
###########################################################
# checkpsw.sh (C) 2004 Mathias Sundman <mathias@openvpn.se>
#
# This script will authenticate OpenVPN users against
# a plain text file. The passfile should simply contain
# one row per user with the username first followed by
# one or more space(s) or tab(s) and then the password.

PASSFILE="/etc/openvpn/psw-file"
LOG_FILE="/etc/openvpn/openvpn-password.log"
TIME_STAMP=`date "+%Y-%m-%d %T"`

###########################################################

if [ ! -r "${PASSFILE}" ]; then
  echo "${TIME_STAMP}: Could not open password file "${PASSFILE}" for reading." >> ${LOG_FILE}
  exit 1
fi

CORRECT_PASSWORD=`awk '!/^;/&&!/^#/&&$1=="'${username}'"{print $2;exit}' ${PASSFILE}`

if [ "${CORRECT_PASSWORD}" = "" ]; then 
  echo "${TIME_STAMP}: User does not exist: username="${username}", password="${password}"." >> ${LOG_FILE}
  exit 1
fi

if [ "${password}" = "${CORRECT_PASSWORD}" ]; then 
  echo "${TIME_STAMP}: Successful authentication: username="${username}"." >> ${LOG_FILE}
  exit 0
fi

echo "${TIME_STAMP}: Incorrect password: username="${username}", password="${password}"." >> ${LOG_FILE}
exit 1

3. 更改檔案權限
# chmod +x /etc/openvpn/checkpsw.sh

4. 建立密碼檔 /etc/openvpn/psw-file
格式:帳號 密碼
# cat /etc/openvpn/psw-file
test 123123

5. 檢查 /etc/openvpn/server.conf 設定檔是否正確
# openvpn –config /etc/openvpn/server.conf

6. 重新啟動 OpenVPN Server
# systemctl restart openvpn@server.service

7. 修改使用端檔案 xxx.ovpn 加入下面幾行
resolv-retry infinite
nobind
auth-user-pass
auth-nocache
mute-replay-warnings
ns-cert-type server
reneg-sec 0

8. 測試

經過測試,似乎帳號認證無法與憑證認證併存!?

解決 OpenVPN Server 無法正常執行的問題

一直執行好好的 OpenVPN Server 突然無法啟動,出現錯誤的訊息。
# systemctl start openvpn@server.service
Job for openvpn@server.service failed because the control process exited with error code. See “systemctl status openvpn@server.service” and “journalctl -xe” for details.
# journalctl -xe |  grep Error
Options error: In [CMD-LINE]:1: Error opening configuration file: /etc/openvpn/server.srvice.conf

仔細查看設定檔 /etc/openvpn/server.conf 似乎沒有什麼特別[@more@]使用 OpenVPN 本身程式進行檢查
# openvpn –config /etc/openvpn/server.conf
Options error: –dh fails with ‘dh2048.pem’: No such file or directory
Options error: –ca fails with ‘ca.crt’: No such file or directory
Options error: –cert fails with ‘server.crt’: No such file or directory
Options error: –key fails with ‘server.key’: No such file or directory
Options error: –tls-auth fails with ‘ta.key’: No such file or directory
Options error: Please correct these errors.
Use –help for more information.

看起來是憑證和金鑰的位置找不到,重新指定後就正常了!