Centos7+Openvpn使用用户及密码验证登陆
我们上一篇文章介绍了Centos7+Openvpn使用证书验证登陆介绍,今天我们介绍Centos7+Openvpn使用用户及密码登陆验证,具体就补多少了,环境还是基于上一篇的更改来完成。
我们使用Centos7+Openvpn使用用户及密码登陆验证小下载一个验证脚本来完成用户验证登陆。
/files/other/
#!/bin/sh ########################################################### #(C)2004MathiasSundman<mathias@> # #ThisscriptwillauthenticateOpenVPNusersagainst #aplaintextfile.Thepassfileshouldsimplycontain #onerowperuserwiththeusernamefirstfollowedby #oneormorespace(s)ortab(s)andthenthepassword. PASSFILE="/usr/local/openvpn/etc/psw-file" LOG_FILE="/usr/local/openvpn/var/openvpn-" TIME_STAMP=`date"+%Y-%m-%d%T"` ########################################################### if[!-r"${PASSFILE}"];then echo"${TIME_STAMP}:Couldnotopenpasswordfile\"${PASSFILE}\"forreading.">> ${LOG_FILE} exit1 fi CORRECT_PASSWORD=`awk'!/^;/&&!/^#/&&$1=="'${username}'"{print$2;exit}'${PASSFILE}` if["${CORRECT_PASSWORD}"=""];then echo"${TIME_STAMP}:Userdoesnotexist:username=\"${username}\",password= \"${password}\".">>${LOG_FILE} exit1 fi if["${password}"="${CORRECT_PASSWORD}"];then echo"${TIME_STAMP}:Successfulauthentication:username=\"${username}\".">>${LOG_FILE} exit0 fi echo"${TIME_STAMP}:Incorrectpassword:username=\"${username}\",password= \"${password}\".">>${LOG_FILE} exit1
我们然后进入openvpn的配置目录
cd/etc/openvpn/ vi
然后将脚本文件粘贴,然后需要修改PASSFILE和LOG_FILE的路劲,根据自己的真是路劲修改
保存退出,然后我们需要修改openvpn的 文件,然后添加以下配置字段
auth-user-pass-verify/etc/openvpn/userauthdir/via-env开启用户密码脚本: client-cert-not-@R_502_103@取消客户端的证书认证: username-as-common-name不要求客户端有证书 script-security3system消除以下警告
我们为了更好的体现配置,将原来的文件进行过滤注释的内容,然后拷贝出来新建一个文件,然后将没有注释的内容添加到新建的文件中这样为了更好的配置和拍错。
我们上一节是在默认的文件里面直接修改的,所以我们需要将没有注释的内容过滤出来,我们先看看默认的配置文件内容
[root@openvpnopenvpn]#cat ################################################# #SampleOpenVPNconfigfilefor# #multi-clientserver.# ## #Thisfileisfortheserverside# #ofamany-clients<->one-server# #OpenVPNconfiguration.# ## #OpenVPNalsosupports# #single-machine<->single-machine# #configurations(SeetheExamplespage# #onthewebsiteformoreinfo).# ## #ThisconfigshouldworkonWindows# #orLinux/BSDsystems.Rememberon# #Windowstoquotepathnamesanduse# #doublebackslashes,.:# #"C:\\ProgramFiles\\OpenVPN\\config\\"# ## #Commentsareprecededwith'#'or';'# ################################################# #WhichlocalIPaddressshouldOpenVPN #listenon?(optional) ;local #WhichTCP/UDPportshouldOpenVPNlistenon? #IfyouwanttorunmultipleOpenVPNinstances #onthesamemachine,useadifferentport #numberforeachone.Youwillneedto #openupthisportonyourfirewall. port1194 #TCPorUDPserver? prototcp #protoudp #"devtun"willcreatearoutedIPtunnel,#"devtap"willcreateanethernettunnel. #Use"devtap0"ifyouareethernetbridging #andhaveprecreatedatap0virtualinterface #andbridgeditwithyourethernetinterface. #Ifyouwanttocontrolaccesspolicies #overtheVPN,youmustcreatefirewall #rulesforthetheTUN/TAPinterface. #Onnon-Windowssystems,youcangive #anexplicitunitnumber,suchastun0. #OnWindows,use"dev-node"forthis. #Onmostsystems,theVPNwillnotfunction #unlessyoupartiallyorfullydisable #thefirewallfortheTUN/TAPinterface. ;devtap devtun #WindowsneedstheTAP-Win32adaptername #fromtheNetworkConnectionspanelifyou #havemorethanone.OnXPSP2orhigher,#youmayneedtoselectivelydisablethe #WindowsfirewallfortheTAPadapter. #Non-Windowssystemsusuallydon'tneedthis. ;dev-nodeMyTap #SSL/TLSrootcertificate(ca),certificate #(cert),andprivatekey(key).Eachclient #andtheservermusthavetheirowncertand #keyfile.Theserverandallclientswill #usethesamecafile. # #Seethe"easy-rsa"directoryforaseries #ofscriptsforgeneratingRSAcertificates #andprivatekeys.Remembertouse #auniqueCommonNamefortheserver #andeachoftheclientcertificates. # #AnyX509keymanagementsystemcanbeused. #OpenVPNcanalsouseaPKCS#12formattedkeyfile #(see"pkcs12"directiveinmanpage). ca cert key#Thisfileshouldbekeptsecret #Diffiehellmanparameters. #Generateyourownwith: #openssldhparam-out2048 dh #Networktopology #Shouldbesubnet(addressingviaIP) #unlessWindowsclientsandlowerhaveto #besupported(thennet30,.a/30perclient) #Defaultstonet30(notrecommended) ;topologysubnet #ConfigureservermodeandsupplyaVPNsubnet #forOpenVPNtodrawclientaddressesfrom. #Theserverwilltakeforitself,#therestwillbemadeavailabletoclients. #Eachclientwillbeabletoreachtheserver #on.Commentthislineoutifyouare #ethernetbridging.Seethemanpageformoreinfo. server #Maintainarecordofclient<->virtualIPaddress #associationsinthisfile.IfOpenVPNgoesdownor #isrestarted,reconnectingclientscanbeassigned #thesamevirtualIPaddressfromthepoolthatwas #prevIoUslyassigned. ifconfig-pool-persist #Configureservermodeforethernetbridging. #YoumustfirstuseyourOS'sbridgingcapability #tobridgetheTAPinterfacewiththeethernet #NICinterface.Thenyoumustmanuallysetthe #IP/netmaskonthebridgeinterface,herewe #assume/.Finallywe #mustsetasideanIPrangeinthissubnet #(start=end=)toallocate #toconnectingclients.Leavethislinecommented #outunlessyouareethernetbridging. ;server-bridge #Configureservermodeforethernetbridging #usingaDHCP-proxy,whereclientstalk #totheOpenVPNserver-sideDHCPserver #toreceivetheirIPaddressallocation #andDNSserveraddresses.Youmustfirstuse #yourOS'sbridgingcapabilitytobridgetheTAP #interfacewiththeethernetNICinterface. #Note:thismodeonlyworksonclients(suchas #Windows),wheretheclient-sideTAPadapteris #boundtoaDHCPclient. ;server-bridge #Pushroutestotheclienttoallowit #toreachotherprivatesubnetsbehind #theserver.Rememberthatthese #privatesubnetswillalsoneed #toknowtoroutetheOpenVPNclient #addresspool(/) #backtotheOpenVPNserver. push"route" ;push"route" #ToassignspecificIPaddressestospecific #clientsorifaconnectingclienthasaprivate #subnetbehinditthatshouldalsohaveVPNaccess,#usethesubdirectory"ccd"forclient-specific #configurationfiles(seemanpageformoreinfo). #EXAMPLE:Supposetheclient #havingthecertificatecommonname"ThelonIoUs" #alsohasasmallsubnetbehindhisconnecting #machine,suchas/. #First,uncommentouttheselines: ;client-config-dirccd ;route #Thencreateafileccd/ThelonIoUswiththisline: #iroute #ThiswillallowThelonIoUs'privatesubnetto #accesstheVPN.Thisexamplewillonlywork #ifyouarerouting,notbridging,.youare #using"devtun"and"server"directives. #EXAMPLE:Supposeyouwanttogive #ThelonIoUsafixedVPNIPaddressof. #Firstuncommentouttheselines: ;client-config-dirccd ;route #Thenaddthislinetoccd/ThelonIoUs: #ifconfig-push #Supposethatyouwanttoenabledifferent #firewallaccesspoliciesfordifferentgroups #ofclients.Therearetwomethods: #(1)RunmultipleOpenVPNdaemons,oneforeach #group,andfirewalltheTUN/TAPinterface #foreachgroup/daemonappropriately. #(2)(Advanced)Createascripttodynamically #modifythefirewallinresponsetoaccess #fromdifferentclients.Seeman #pageformoreinfoonlearn-addressscript. ;learn-address./script #Ifenabled,thisdirectivewillconfigure #allclientstoredirecttheirdefault #networkgatewaythroughtheVPN,causing #allIPtrafficsuchaswebbrowsingand #andDNSlookupstogothroughtheVPN #(TheOpenVPNservermachinemayneedtoNAT #orbridgetheTUN/TAPinterfacetotheinternet #inorderforthistoworkproperly). push"redirect-gatewaydef1bypass-dhcp" #CertainWindows-specificnetworksettings #canbepushedtoclients,suchasDNS #orWINSserveraddresses.CAVEAT: #/#dhcpcaveats #Theaddressesbelowrefertothepublic #DNSserversprovidedby. push"dhcp-optionDNS" push"dhcp-optionDNS" #Uncommentthisdirectivetoallowdifferent #clientstobeableto"see"eachother. #Bydefault,clientswillonlyseetheserver. #Toforceclientstoonlyseetheserver,you #willalsoneedtoappropriatelyfirewallthe #server'sTUN/TAPinterface. ;client-to-client #Uncommentthisdirectiveifmultipleclients #mightconnectwiththesamecertificate/key #filesorcommonnames.Thisisrecommended #onlyfortestingpurposes.Forproductionuse,#eachclientshouldhaveitsowncertificate/key #pair. # #IFYOUHAVENOTGENERATEDINDIVIDUAL #CERTIFICATE/KEYPAIRSFOREACHCLIENT,#EACHHAVINGITSOWNUNIQUE"COMMONNAME",#UNCOMMENTTHISLINEOUT. ;duplicate-cn #Thekeepalivedirectivecausesping-like #messagestobesentbackandforthover #thelinksothateachsideknowswhen #theothersidehasgonedown. #Pingevery10seconds,assumethatremote #peerisdownifnopingreceivedduring #a120secondtimeperiod. keepalive10120 #Forextrasecuritybeyondthatprovided #bySSL/TLS,createan"HMACfirewall" #tohelpblockDoSattacksandUDPportflooding. # #Generatewith: #openvpn--genkey--secret # #Theserverandeachclientmusthave #acopyofthiskey. #Thesecondparametershouldbe'0' #ontheserverand'1'ontheclients. ;tls-auth0#Thisfileissecret #Selectacryptographiccipher. #Thisconfigitemmustbecopiedto #theclientconfigfileaswell. #Notethatclient/serverwillautomatically #negotiateAES-256-GCMinTLSmode. #Seealsothencp-cipheroptioninthemanpage cipherAES-256-CBC #EnablecompressionontheVPNlinkandpushthe #optiontotheclient(+only,forearlier #versionsseebelow) ;compresslz4-v2 ;push"compresslz4-v2" #Forcompressioncompatiblewitholderclientsusecomp-lzo #Ifyouenableithere,youmustalso #enableitintheclientconfigfile. ;comp-lzo #Themaximumnumberofconcurrentlyconnected #clientswewanttoallow. max-clients100 #It'sagoodideatoreducetheOpenVPN #daemon'sprivilegesafterinitialization. # #Youcanuncommentthisouton #non-Windowssystems. usernobody groupnobody #Thepersistoptionswilltrytoavoid #accessingcertainresourcesonrestart #thatmaynolongerbeaccessiblebecause #oftheprivilegedowngrade. persist-key persist-tun #Outputashortstatusfileshowing #currentconnections,truncated #andrewritteneveryminute. statusopenvpn- #Bydefault,logmessageswillgotothesyslog(or #onWindows,ifrunningasaservice,theywillgoto #the"\ProgramFiles\OpenVPN\log"directory). #Uselogorlog-appendtooverridethisdefault. #"log"willtruncatethelogfileonOpenVPNstartup,#while"log-append"willappendtoit.USEOne #ortheother(butnotboth). log ;log-append #Settheappropriateleveloflog #fileverbosity. # #0issilent,exceptforfatalerrors #4isreasonableforgeneralusage #5and6canhelptodebugconnectionproblems #9isextremelyverbose verb5 #Silencerepeatingmessages.Atmost20 #sequentialmessagesofthesamemessage #categorywillbeoutputtothelog. ;mute20 #Notifytheclientthatwhentheserverrestartssoit #canautomaticallyreconnect. #explicit-exit-notify1
默认内容比较多,所以我们过滤一下
cat/etc/openvpn/|grep"^[^#|^;]" port1194 prototcp devtun ca cert key#Thisfileshouldbekeptsecret dh server ifconfig-pool-persist push"route" push"dhcp-optionDNS" push"dhcp-optionDNS" keepalive10120 max-clients100 usernobody groupnobody persist-key persist-tun statusopenvpn- log verb5
我们在修改前首先要需要将将原来默认的进行重命名一下作为备份。
mv/etc/openvpn//etc/openvpn/
然后我们在/etc/openvpn目录下vi 文件,然后将过滤的内容粘贴修改即可
vim local#监听地址 port1194#监听端口 prototcp#监听协议 devtun#采用路由隧道模式 ca#ca证书路径 cert#服务器证书 key#Thisfileshouldbekeptsecret服务器密钥 dh#密钥交换协议文件 server#给客户端分配地址池,注意:不能和VPN服务器内网网段有相同 ifconfig-pool-persist push"route"#允许客户端访问内网的网段。 push"dhcp-optionDNS"#dhcp分配dns client-to-client#客户端之间互相通信 keepalive10120#存活时间,10秒ping一次,120如未收到响应则视为断线 comp-lzo#传输数据压缩 max-clients100#最多允许100客户端连接 usernobody#用户 groupnobody#用户组 persist-key persist-tun status/var/log/openvpn/openvpn- log/var/log/openvpn/ verb5
然后我们需要是使用用户和密码验证登陆,所以还需要添加以下语句
auth-user-pass-verify/etc/openvpn/via-env client-cert-not-@R_502_103@ username-as-common-name
我们添加后
port1194#监听端口 prototcp#监听协议 devtun#采用隧道 ca#ca证书路劲 cert#服务器证书路劲 key#服务器秘钥 dh#秘钥交换协议文件 server#给客户端分配的地址,注意:不能和vpn服务器的内部地址相同 ifconfig-pool-persist#访问记录 push"route"#允许客户端访问的地址网段 #push"redirect-gatewaydef1bypass-dhcp" push"dhcp-optionDNS"#DHCP分配的DNS push"dhcp-optionDNS" keepalive10120#活动时间,10秒ping一次,120秒如果未收到响应视为断线 #cipherAES-256-CBC max-clients100#允许最大连接数 #usernobody#用户 #groupnobody#用户组 persist-key persist-tun statusopenvpn- log verb5 client-cert-not-@R_502_103@ username-as-common-name script-security3 auth-user-pass-verify/etc/openvpn/via-env
第三步:新建用户和密码认证文件,psw-file(这里的文件就是那个文件,注意存放时,路径和配置文件时的一致)
cd/etc/openvpn/ vimpsw-file test123456(前面是用户后面是密码)
注:这里 psw-file的权限,尽量小点
chmod400psw-file chmod+x
修改好后,我们重启openvpn服务
注销掉这两行
#cert #key
auth-user-pass
我们为了显示好看及好判断问题,所以我们需要把客户端的配置文件清空,然后编写有用的
client devtun prototcp remote1194 resolv-retryinfinite nobind persist-key persist-tun ca #cert #key #remote-cert-tlsserver verb5 auth-user-pass
保存会,我们单击openvpn客户端,然后连接,会提示输入账户及密码
最后我们可以查看log确认登陆情况
tail-f/etc/openvpn/
tail-f/etc/openvpn/openvpn-原文链接:https://www.f2er.com/centos/379026.html