Centos7+Openvpn使用用户及密码验证登陆
我们上一篇文章介绍了Centos7+Openvpn使用证书验证登陆介绍,今天我们介绍Centos7+Openvpn使用用户及密码登陆验证,具体就补多少了,环境还是基于上一篇的更改来完成。
我们使用Centos7+Openvpn使用用户及密码登陆验证小下载一个验证脚本来完成用户验证登陆。
http://openvpn.se/files/other/checkpsw.sh
#!/bin/sh ########################################################### #checkpsw.sh(C)2004MathiasSundman<mathias@openvpn.se> # #ThisscriptwillauthenticateOpenVPNusersagainst #aplaintextfile.Thepassfileshouldsimplycontain #onerowperuserwiththeusernamefirstfollowedby #oneormorespace(s)ortab(s)andthenthepassword. PASSFILE="/usr/local/openvpn/etc/psw-file" LOG_FILE="/usr/local/openvpn/var/openvpn-password.log" 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/ vicheckpsw.sh
然后将脚本文件粘贴,然后需要修改PASSFILE和LOG_FILE的路劲,根据自己的真是路劲修改
保存退出,然后我们需要修改openvpn的server.conf 文件,然后添加以下配置字段
auth-user-pass-verify/etc/openvpn/userauthdir/checkpsw.shvia-env开启用户密码脚本: client-cert-not-required取消客户端的证书认证: username-as-common-name不要求客户端有证书 script-security3system消除以下警告
我们在修改前先看看上一篇的配置文件内容
我们为了更好的体现配置,将原来的server.conf文件进行过滤注释的内容,然后拷贝出来新建一个server.conf文件,然后将没有注释的内容添加到新建的server.conf文件中这样为了更好的配置和拍错。
我们上一节是在默认的server.conf文件里面直接修改的,所以我们需要将没有注释的内容过滤出来,我们先看看默认的配置文件内容
[root@openvpnopenvpn]#catserver.conf ################################################# #SampleOpenVPN2.0configfilefor# #multi-clientserver.# ## #Thisfileisfortheserverside# #ofamany-clients<->one-server# #OpenVPNconfiguration.# ## #OpenVPNalsosupports# #single-machine<->single-machine# #configurations(SeetheExamplespage# #onthewebsiteformoreinfo).# ## #ThisconfigshouldworkonWindows# #orLinux/BSDsystems.Rememberon# #Windowstoquotepathnamesanduse# #doublebackslashes,e.g.:# #"C:\\ProgramFiles\\OpenVPN\\config\\foo.key"# ## #Commentsareprecededwith'#'or';'# ################################################# #WhichlocalIPaddressshouldOpenVPN #listenon?(optional) ;locala.b.c.d #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). caca.crt certserver.crt keyserver.key#Thisfileshouldbekeptsecret #Diffiehellmanparameters. #Generateyourownwith: #openssldhparam-outdh2048.pem2048 dhdh2048.pem #Networktopology #Shouldbesubnet(addressingviaIP) #unlessWindowsclientsv2.0.9andlowerhaveto #besupported(thennet30,i.e.a/30perclient) #Defaultstonet30(notrecommended) ;topologysubnet #ConfigureservermodeandsupplyaVPNsubnet #forOpenVPNtodrawclientaddressesfrom. #Theserverwilltake10.8.0.1foritself,#therestwillbemadeavailabletoclients. #Eachclientwillbeabletoreachtheserver #on10.8.0.1.Commentthislineoutifyouare #ethernetbridging.Seethemanpageformoreinfo. server10.10.10.0255.255.255.0 #Maintainarecordofclient<->virtualIPaddress #associationsinthisfile.IfOpenVPNgoesdownor #isrestarted,reconnectingclientscanbeassigned #thesamevirtualIPaddressfromthepoolthatwas #previouslyassigned. ifconfig-pool-persistipp.txt #Configureservermodeforethernetbridging. #YoumustfirstuseyourOS'sbridgingcapability #tobridgetheTAPinterfacewiththeethernet #NICinterface.Thenyoumustmanuallysetthe #IP/netmaskonthebridgeinterface,herewe #assume10.8.0.4/255.255.255.0.Finallywe #mustsetasideanIPrangeinthissubnet #(start=10.8.0.50end=10.8.0.100)toallocate #toconnectingclients.Leavethislinecommented #outunlessyouareethernetbridging. ;server-bridge10.8.0.4255.255.255.010.8.0.5010.8.0.100 #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(10.8.0.0/255.255.255.0) #backtotheOpenVPNserver. push"route192.168.5.0255.255.255.0" ;push"route192.168.20.0255.255.255.0" #ToassignspecificIPaddressestospecific #clientsorifaconnectingclienthasaprivate #subnetbehinditthatshouldalsohaveVPNaccess,#usethesubdirectory"ccd"forclient-specific #configurationfiles(seemanpageformoreinfo). #EXAMPLE:Supposetheclient #havingthecertificatecommonname"Thelonious" #alsohasasmallsubnetbehindhisconnecting #machine,suchas192.168.40.128/255.255.255.248. #First,uncommentouttheselines: ;client-config-dirccd ;route192.168.40.128255.255.255.248 #Thencreateafileccd/Theloniouswiththisline: #iroute192.168.40.128255.255.255.248 #ThiswillallowThelonious'privatesubnetto #accesstheVPN.Thisexamplewillonlywork #ifyouarerouting,notbridging,i.e.youare #using"devtun"and"server"directives. #EXAMPLE:Supposeyouwanttogive #TheloniousafixedVPNIPaddressof10.9.0.1. #Firstuncommentouttheselines: ;client-config-dirccd ;route10.9.0.0255.255.255.252 #Thenaddthislinetoccd/Thelonious: #ifconfig-push10.9.0.110.9.0.2 #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: #http://openvpn.net/faq.html#dhcpcaveats #Theaddressesbelowrefertothepublic #DNSserversprovidedbyopendns.com. push"dhcp-optionDNS223.5.5.5" push"dhcp-optionDNS223.6.6.6" #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--secretta.key # #Theserverandeachclientmusthave #acopyofthiskey. #Thesecondparametershouldbe'0' #ontheserverand'1'ontheclients. ;tls-authta.key0#Thisfileissecret #Selectacryptographiccipher. #Thisconfigitemmustbecopiedto #theclientconfigfileaswell. #Notethat2.4client/serverwillautomatically #negotiateAES-256-GCMinTLSmode. #Seealsothencp-cipheroptioninthemanpage cipherAES-256-CBC #EnablecompressionontheVPNlinkandpushthe #optiontotheclient(2.4+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-status.log #Bydefault,logmessageswillgotothesyslog(or #onWindows,ifrunningasaservice,theywillgoto #the"\ProgramFiles\OpenVPN\log"directory). #Uselogorlog-appendtooverridethisdefault. #"log"willtruncatethelogfileonOpenVPNstartup,#while"log-append"willappendtoit.USEOne #ortheother(butnotboth). logopenvpn.log ;log-appendopenvpn.log #Settheappropriateleveloflog #fileverbosity. # #0issilent,exceptforfatalerrors #4isreasonableforgeneralusage #5and6canhelptodebugconnectionproblems #9isextremelyverbose verb5 #Silencerepeatingmessages.Atmost20 #sequentialmessagesofthesamemessage #categorywillbeoutputtothelog. ;mute20 #Notifytheclientthatwhentheserverrestartssoit #canautomaticallyreconnect. #explicit-exit-notify1