0% found this document useful (0 votes)
382 views15 pages

Top 20 Nginx WebServer Best Security Practices

Nginx is a lightweight, high performance web server / reverse proxy and email (IMAP / POP3) proxy. It runs on UNIX, GNU / Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows. This page collects hints how to improve the security of nginx web servers running on linux or UNIX like operating systems.

Uploaded by

nsitdce
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
382 views15 pages

Top 20 Nginx WebServer Best Security Practices

Nginx is a lightweight, high performance web server / reverse proxy and email (IMAP / POP3) proxy. It runs on UNIX, GNU / Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows. This page collects hints how to improve the security of nginx web servers running on linux or UNIX like operating systems.

Uploaded by

nsitdce
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

About Forum Howtos&FAQs Lowgraphics ShellScripts RSS/Feed nixcraftinsightintolinuxadminwork

Top20NginxWebServerBestSecurityPractices
byVivekGiteonMarch6,201025comments Nginxisalightweight,highperformancewebserver/reverseproxyandemail(IMAP/POP3)proxy.ItrunsonUNIX,GNU/Linux,BSDvariants,Mac OSX,Solaris,andMicrosoftWindows.AccordingtoNetcraft,6%ofalldomainsontheInternetusenginxwebserver.Nginxisoneofahandfulof serverswrittentoaddresstheC10Kproblem.Unliketraditionalservers,Nginxdoesn'trelyonthreadstohandlerequests.Insteaditusesamuchmorescalableeventdriven (asynchronous)architecture.Nginxpowersseveralhightrafficwebsites,suchasWordPress,Hulu,Github,andSourceForge.Thispagecollectshintshowtoimprovethe securityofnginxwebserversrunningonLinuxorUNIXlikeoperatingsystems.

DefaultConfigFilesandNginxPort
/usr/local/nginx/conf/Thenginxserverconfigurationdirectoryand/usr/local/nginx/conf/nginx.confismainconfigurationfile. /usr/local/nginx/html/Thedefaultdocumentlocation. /usr/local/nginx/logs/Thedefaultlogfilelocation. NginxHTTPdefaultport:TCP80 NginxHTTPSdefaultport:TCP443 Youcantestnginxconfigurationchangesasfollows:
#/s/oa/gn/bnnix urlclnixsi/gnt

Sampleoutputs:
tecniuainflurlclnixcn/gn.ofsnaso hofgrtoie/s/oa/gn/ofnixcnytxik cniuainflurlclnixcn/gn.oftssscesu ofgrtoie/s/oa/gn/ofnixcnetiucsfl

Toloadconfigchanges,type:
#/s/oa/gn/bnnixeod urlclnixsi/gnsrla

Tostopserver,type:
#/s/oa/gn/bnnixtp urlclnixsi/gnsso

#1:TurnOnSELinux
SecurityEnhancedLinux(SELinux)isaLinuxkernelfeaturethatprovidesamechanismforsupportingaccesscontrolsecuritypolicieswhichprovidesgreatprotection.It canstopmanyattacksbeforeyoursystemrooted.SeehowtoturnonSELinuxforCentOS/RHELbasedsystems.

DoBooleanLockdown
Runthegetseboolacommandandlockdownsystem:
gteoles esboa|ls gteolrpof esboa|gef gteolrpo esboa|ge

Tosecurethemachine,lookatsettingswhicharesetto'on'andchangeto'off'iftheydonotapplytoyoursetupwiththehelpofsetseboolcommand.SetcorrectSELinux booleanstomaintainfunctionalityandprotection.PleasenotethatSELinuxadds28%overheadstotypicalRHELorCentOSinstallation.

#2:AllowMinimalPrivilegesViaMountOptions
Serverallyourwebpages/html/phpfilesviaseparatepartitions.Forexample,createapartitioncalled/dev/sda5andmountatthe/nginx.Makesure/nginxismountedwith noexec,nodevandnosetuidpermissions.Hereismy/etc/fstabentryformounting/nginx:
LBL/gnnixx3dfut,oudnee,oe AE=nix/gnetealsnsi,oxcndv12

Noteyouneedtocreateanewpartitionusingfdiskandmkfs.ext3commands.

#3:Linux/etc/sysctl.confHardening
YoucancontrolandconfigureLinuxkernelandnetworkingsettingsvia/etc/sysctl.conf.
#Aodasufatc vimrtak ntiv.cpeh_goebodat e.p4im_coinr_racss=1

#Trnpoetooacperrmsae unortcinfrbdimroesgs ntiv.cpinr_ou_ro_epne e.p4im_goebgserrrsoss=1 #TrnsnokeoYlotakpoeto unoycoisfrSNfodatcrtcin ntiv.c_ycois=1 e.p4tpsnoke #Trnadlgsofdorerue,adrdrcakt unonopoe,sucotdneietpces ntiv.ofallgmrin e.p4cn.l.o_atas=1 ntiv.ofdfutlgmrin e.p4cn.eal.o_atas=1 #Norerueaktee osucotdpceshr ntiv.ofalacp_orerue=0 e.p4cn.l.cetsuc_ot ntiv.ofdfutacp_orerue=0 e.p4cn.eal.cetsuc_ot #Trnrvreptitrn unoeesahfleig ntiv.ofalr_itr=1 e.p4cn.l.pfle ntiv.ofdfutr_itr=1 e.p4cn.eal.pfle #Mkuennalehotnals aesrooecnatrteruigtbe ntiv.ofalacp_eiet e.p4cn.l.cetrdrcs=0 ntiv.ofdfutacp_eiet e.p4cn.eal.cetrdrcs=0 ntiv.ofalscr_eiet e.p4cn.l.euerdrcs=0 ntiv.ofdfutscr_eiet e.p4cn.eal.euerdrcs=0 #Dntataotr o'csarue ntiv.pfrad=0 e.p4i_owr ntiv.ofalsn_eiet e.p4cn.l.edrdrcs=0 ntiv.ofdfutsn_eiet e.p4cn.eal.edrdrcs=0 #Trneesid unoxchl kre.xcsil enleehed=1 kre.admz_asae=1 enlrnoiev_pc #TeP6 unIv ntiv.ofdfutrue_oiiain e.p6cn.eal.otrslcttos=0 ntiv.ofdfutacp_arrpe e.p6cn.eal.cetr_t_rf=0 ntiv.ofdfutacp_apno=0 e.p6cn.eal.cetr_if ntiv.ofdfutacp_adft e.p6cn.eal.cetr_err=0 ntiv.ofdfutatcn e.p6cn.eal.uoof=0 ntiv.ofdfutddtasis=0 e.p6cn.eal.a_rnmt ntiv.ofdfutmxadess=1 e.p6cn.eal.a_drse #OtmztoootueoB piiainfrprsfrLs #Icesytmflecitrlmt nraesseiedsrpoii f.iemx=655 sfla53 #AlwfrmrIs(ordcolvrpolm)araoeporm26 loooePDteuerloerbesmybeksmrgas378 kre.i_a53 enlpdmx=656 #IcesytmIotlmt nraessePpriis ntiv.plclpr_ag00600 e.p4i_oa_otrne=2050 #IcesCaufrszealsnescot) nraeTPmxbfeiestbeuigstokp( ntiv.c_mm=4978380 e.p4tpre068308868 ntiv.c_mm=4978380 e.p4tpwe068308868 #IcesiuuotnnCufrlmt nraeLnxatuigTPbfeiis #mneal,admxnmefbtsts i,dfutnaubroyeoue #stmxttlat4BrhgefyuuevrihBPpts eaoaesM,oihrioseyhgDah #TpWnosec cidwt ntcr.mmmx=8868 e.oere_a380 ntcr.mmmx=8868 e.oewe_a380 ntcr.edvmxbclg=50 e.oente_a_ako00 ntiv.c_idwsaig=1 e.p4tpwno_cln

Seealso: LinuxTuningTheVM(memory)Subsystem LinuxTuneNetworkStack(BuffersSize)ToIncreaseNetworkingPerformance

#4:RemoveAllUnwantedNginxModules
Youneedtominimizesthenumberofmodulesthatarecompileddirectlyintothenginxbinary.Thisminimizesriskbylimitingthecapabilitiesallowedbythewebserver. Youcanconfigureandinstallnginxusingonlyrequiredmodules.Forexample,disableSSIandautoindexmoduleyoucantype:
#.cniuewtotht_uone_ouewtotht_s_oue /ofgrihutpatidxmdlihutpsimdl #mk ae #mkntl aeisal

Typethefollowingcommandtoseewhichmodulescanbeturnonoroffwhilecompilingnginxserver:
#.cniuehles /ofgrep|ls

Disablenginxmodulesthatyoudon'tneed.

(Optional)ChangeNginxVersionHeader

Editsrc/http/ngx_http_header_filter_module.c,enter:
#v4r/tpnxht_edrfle_ouec i+8scht/g_tphae_itrmdl.

Findline
saihrnxht_evrsrn[Sre:nixRF ttccag_tpsre_tig]="evrgn"CL saihrnxht_evrfl_tig]="evrGN_ERF ttccag_tpsre_ulsrn[Sre:"NIXVRCL

Changethemasfollows:
saihrnxht_evrsrn[Sre:NnaWbSre"CL ttccag_tpsre_tig]="evrijeevrRF saihrnxht_evrfl_tig]="evrijeevrRF ttccag_tpsre_ulsrn[Sre:NnaWbSre"CL

Saveandclosethefile.Now,youcancompiletheserver.Addthefollowinginnginx.conftoturnoffnginxversionnumberdisplayedonallautogeneratederrorpages:
sre_oesof evrtknf

#5:Usemod_security(onlyforbackendApacheservers)
mod_securityprovidesanapplicationlevelfirewallforApache.Installmod_securityforallbackendApachewebservers.Thiswillstopmanyinjectionattacks.

#6:InstallSELinuxPolicyToHardenTheNginxWebserver
BydefaultSELinuxwillnotprotectthenginxwebserver.However,youcaninstallandcompileprotectionasfollows.First,installrequiredSELinuxcompiletimesupport:
#ymntleiuoiytreeeiuoiydvl uyisalslnxplcagtdslnxplcee

DownloadtargetedSELinuxpoliciestohardenthenginxwebserveronLinuxserversfromtheprojecthomepage:
#cot d/p #weht:/onod.oreog.e/rjc/eiunixsgx101.a.zuemro=cc gt'tp/dwlassucfrentpoetslnxgn/eni___0trg?s_irrnh'

Untarthesame:
#trxfsgx101.a.z azveni___0trg

Compilethesame
#ceni___0nix dsgx101/gn #mk ae

Sampleoutputs:
Cmiigtreegnoue oplnagtdnixmdl /s/i/hcmdl:odnoiycniuainfom/gn.m urbncekouelaigplcofgrtormtpnixtp /s/i/hcmdl:oiycniuainlae urbncekoueplcofgrtoodd /s/i/hcmdl:rtniayrpeettovrin6otpnixmd urbncekouewiigbnrersnain(eso)tm/gn.o Cetnagtdnixpoiypcae raigtreegn.pplcakg rm/gn.o.ctpnixmd mtpnixmdfm/gn.o

Installtheresultingnginx.ppSELinuxmodule:
#/s/bnsmdlinixp ursi/eouegn.p

#7:RestrictiveIptablesBasedFirewall
Thefollowingfirewallscriptblockseverythingandonlyallows: IncomingHTTP(TCPport80)requests IncomingICMPpingrequests Outgoingntp(port123)requests Outgoingsmtp(TCPport25)requests

#/i/ah !bnbs IT"si/pals P=/bnitbe" ##P### ##IS### #Gtsreulci eevrpbip SRE_P$icnit0|geiedr'|ak'ntad:{pit$}w{pit$}) EVRI=(fofgehrp'ntad:wFiedr''rn2'|ak'rn1' L1I=245.." B_P"0.411 L2I=245.." B_P"0.412 #DoesatlgcshtwasamsrpnL2to osmmroiotaecnuedmcitoBo OHRL=" TE_B" SRE_P" EVRI=" [$EVRI"=$B_P]&TE_B"L2I"|TE_B"L1I" ["SRE_P="L1I"]&OHRL=$B_P|OHRL=$B_P [$TE_B="L2I"]&OPL=$B_P|OPL=$B_P ["OHRL"=$B_P]&P_B"L1I"|P_B"L2I" ##Is## #P# PBSHOL=12x.yz/9 U_S_NY"2.xy.z2" ##IE## ##FLS### BOKDI_D=ro/f/lce.ptt LCE_PTB/ot.wbokdi.x SOFP"2.../9.6../6121../21.../6.5../6000082000042525252536.5../62400042 POI=17000812180017.6001000081924001.../4.../5.5.5.5/218240012.../

BDP=([f$BOKDI_D}]&erp^|${LCE_PTB) AIS$[{LCE_PTB]&gev"#^"$BOKDI_D} ##Itrae# #nefcs## PBI=eh"#pbinefc U_F"t0ulcitrae L_F"o#lobc OI=l"opak VNI=eh"#vn/piaent P_F"t1prvte ##satfrwl# #trieal## ehStigL1$hsnm)Frwl.. co"etnB(otaeieal." #DOnlsvrtig RPadcoeeeyhn $PPIPTDO ITNURP $PPOTURP ITUPTDO $PPFRADDO ITOWRRP #Ulmtdlces niieoacs $PAIPT{OI}CET ITNUi$L_FjACP $PAOTUo$L_FjACP ITUPT{OI}CET #Ulmtdvn/peces niiepntacs $PAIPT{P_FjACP ITNUi$VNI}CET $PAOTUo$VNI}CET ITUPT{P_FjACP #Doyc rpsn $PAIPT{U_Fptp!snttttEjDO ITNUi$PBI}cymsaesaeNWRP #Dorget rpFamns $PAIPT{U_FfRP ITNUi$PBI}jDO $PNUi$PBI}cclgLI,R,SjDO ITAIPT{U_FptptpfasALFNUGPHRP $PNUi$PBI}cclgLLjDO ITAIPT{U_FptptpfasALALRP #DoULpces rpNLakt $PNUi$PBI}cclgLOEiiii/iiusjLGlgpeiULPces" ITAIPT{U_FptptpfasALNNmlmtlmt5mlmtbrt7Oorfx"NLakt $PNUi$PBI}cclgLOERP ITAIPT{U_FptptpfasALNNjDO $PNUi$PBI}cclgY,SY,SjDO ITAIPT{U_FptptpfasSNRTSNRTRP #DoMS rpXA $PNUi$PBI}cclgY,IY,Imlmtlmt5mlmtbrt7Oorfx"XAakt ITAIPT{U_FptptpfasSNFNSNFNiiii/iiusjLGlgpeiMSPces" $PNUi$PBI}cclgY,IY,IjDO ITAIPT{U_FptptpfasSNFNSNFNRP #DoIaktsas rpFNpcecn $PNUi$PBI}cclgI,CImlmtlmt5mlmtbrt7Oorfx"FnPcesSa ITAIPT{U_FptptpfasFNAKFNiiii/iiusjLGlgpeiiaktcn" $PNUi$PBI}cclgI,CIjDO ITAIPT{U_FptptpfasFNAKFNRP $PNUi$PBI}cclgLY,S,C,I,RjDO ITAIPT{U_FptptpfasALSNRTAKFNUGRP #Lgadgtrdoracsutcsnnai oneifbodat/mliatadivld $PNUi$PBI}ktpkyebodatOorfx"Bodat" ITAIPT{U_FmptyepttpracsjLGlgpeiracs $PNUi$PBI}ktpkyebodatRP ITAIPT{U_FmptyepttpracsjDO $PNUi$PBI}ktpkyemliatOorfx"Mliat" ITAIPT{U_FmptyepttputcsjLGlgpeiutcs $PNUi$PBI}ktpkyemliatRP ITAIPT{U_FmptyepttputcsjDO $PNUi$PBI}ttttNAIjLGlgpeinai ITAIPT{U_FmsaesaeIVLDOorfx"Ivld" $PNUi$PBI}ttttNAIjDO ITAIPT{U_FmsaesaeIVLDRP #Lgadboksofdis onlcpoep $PNsofit ITpols fribokiSOFP oplcn$POI d o ITpolsi$PBI}ibokOorfx"SOFLslc $PAsofit{U_Fs$plcjLGlgpeiPOitBok" ITpolsi$PBI}ibokRP $PAsofit{U_Fs$plcjDO dn oe $PIIPTpols ITNUjsofit $PIOTUjsofit ITUPTpols $PIFRADpols ITOWRjsofit #Alwsholrmslceulcis losnyfoeetdpbip frin$PBSHOL} opi{U_S_NY d o $PAIPT{U_Fs$i}cd$SRE_Petntoot2jACP ITNUi$PBI}{pptp{EVRI}dsiainpr2CET $PAOTUo$PBI}{pptp{EVRI}sot2jACP ITUPT{U_Fd$i}cs$SRE_Ppr2CET dn oe #alwicmnCPpnogsuf lonoigIMigpntf $PAIPT{U_Fpimcptps00ttttE,SALSE,EAEmlmtlmt3/eCET ITNUi$PBI}cpimye8/msaesaeNWETBIHDRLTDiiii0scjACP $PAOTUo$PBI}cpimye0/msaesaeETBIHDRLTDCET ITUPT{U_Fpimcptpd00ttttSALSE,EAEjACP #alwicmnTPpr0 lonoigHTot8 $PAIPT{U_Fptp/pr04655dot8msaesaeNWETBIHDCET ITNUi$PBI}cs00sot12:53pr0ttttE,SALSEjACP $PAOTUo$PBI}cpr0/pr04655ttttSALSEjACP ITUPT{U_Fptpsot8d00dot12:53msaesaeETBIHDCET #alwotont lougignp $PAOTUo$PBI}dpr2msaesaeNWETBIHDCET ITUPT{U_Fpupdot13ttttE,SALSEjACP

$PAIPT{U_Fpupsot13ttttSALSEjACP ITNUi$PBI}dpr2msaesaeETBIHDCET #alwotonmp lougigst $PAOTUo$PBI}cpr5ttttE,SALSEjACP ITUPT{U_Fptpdot2msaesaeNWETBIHDCET $PAIPT{U_Fptpsot2msaesaeETBIHDCET ITNUi$PBI}cpr5ttttSALSEjACP ##adyuteueee## #dorohrrlshr## ############ ########### #donovrtiges rpadlgeeyhnle $PAIPTiiii/iiusjLGlgpeiEALRP" ITNUmlmtlmt5mlmtbrt7Oorfx"DFUTDO $PAIPTRP ITNUjDO ei xt0

#8:ControllingBufferOverflowAttacks
Editnginx.confandsetthebuffersizelimitationsforallclients.
#vurlclnixcn/gn.of i/s/oa/gn/ofnixcn

Editandsetthebuffersizelimitationsforallclientsasfollows:
#SatieLmtufrOefos# #tr:Sziis&Bfevrlw# cin_oybfe_ieK letbd_ufrsz1 cin_edrbfe_ie1 lethae_ufrszk cin_a_oyszk letmxbd_ie1 lrecin_edrbfes21 ag_lethae_ufrk #EDieLmtufrOefos# #N:Sziis&Bfevrlw#

Where, 1. client_body_buffer_size1k(defaultis8kor16k)Thedirectivespecifiestheclientrequestbodybuffersize. 2. client_header_buffer_size1kDirectivesetstheheaderbuffersizefortherequestheaderfromclient.Fortheoverwhelmingmajorityofrequestsabuffersizeof1Kis sufficient.Increasethisifyouhaveacustomheaderoralargecookiesentfromtheclient(e.g.,wapclient). 3. client_max_body_size1kDirectiveassignsthemaximumacceptedbodysizeofclientrequest,indicatedbythelineContentLengthintheheaderofrequest.Ifsizeis greaterthegivenone,thentheclientgetstheerror"RequestEntityTooLarge"(413).IncreasethiswhenyouaregettingfileuploadsviathePOSTmethod. 4. large_client_header_buffers21kDirectiveassignsthemaximumnumberandsizeofbuffersforlargeheaderstoreadfromclientrequest.Bydefaultthesizeofone bufferisequaltothesizeofpage,dependingonplatformthiseither4Kor8K,ifattheendofworkingrequestconnectionconvertstostatekeepalive,thenthese buffersarefreed.2x1kwillaccept2kBdataURI.ThiswillalsohelpcombatbadbotsandDoSattacks. Youalsoneedtocontroltimeoutstoimproveserverperformanceandcutclients.Edititasfollows:
#Satieus# #tr:Tmot# cin_oytmot1 letbd_ieu0 cin_edrtmot1 lethae_ieu0 keaietmot55 eplv_ieu sn_ieu1 edtmot0 #n:Tmot# #Edieus#

1. client_body_timeout10Directivesetsthereadtimeoutfortherequestbodyfromclient.Thetimeoutissetonlyifabodyisnotgetinonereadstep.Ifafterthistime theclientsendnothing,nginxreturnserror"Requesttimeout"(408).Thedefaultis60. 2. client_header_timeout10Directiveassignstimeoutwithreadingofthetitleoftherequestofclient.Thetimeoutissetonlyifaheaderisnotgetinonereadstep.If afterthistimetheclientsendnothing,nginxreturnserror"Requesttimeout"(408). 3. keepalive_timeout55Thefirstparameterassignsthetimeoutforkeepaliveconnectionswiththeclient.Theserverwillcloseconnectionsafterthistime.The optionalsecondparameterassignsthetimevalueintheheaderKeepAlive:timeout=timeoftheresponse.Thisheadercanconvincesomebrowserstoclosethe connection,sothattheserverdoesnothaveto.Withoutthisparameter,nginxdoesnotsendaKeepAliveheader(thoughthisisnotwhatmakesaconnection"keep alive"). 4. send_timeout10Directiveassignsresponsetimeouttoclient.Timeoutisestablishednotonentiretransferofanswer,butonlybetweentwooperationsofreading,if afterthistimeclientwilltakenothing,thennginxisshuttingdowntheconnection.

#9:ControlSimultaneousConnections
YoucanuseNginxHttpLimitZonemoduletolimitthenumberofsimultaneousconnectionsfortheassignedsessionorasaspecialcase,fromoneIPaddress.Editnginx.conf:
##Drciedsrbstezn,ihchesottsaesoe..soeilmt.## #ietveciehoenwihtessinsaertrdietrnsiis# ##1aade300ssinih3ye/eso,sttmx300ssin## #mcnhnl20esoswt2btsssineo520eso# ii_oesiis$iayrmt_dr5 lmtznlmtbnr_eoeadm ##Cnrlmxmmnmefsmlaeuoncinoneso..## #otoaiuubroiutnoscnetosfroessinie# ##rsrcsteaonfcnetosfoigeidrs# #etithmutooncinrmasnlpades## lmtcnlmt ii_onsiis5

Theabovewilllimitsremoteclientstonomorethan5concurrently"open"connectionsperremoteipaddress.

#10:AllowAccessToOurDomainOnly
Ifbotisjustmakingrandomserverscanforalldomains,justdenyit.Youmustonlyallowconfiguredvirtualdomainorreverseproxyrequests.Youdon'twanttodisplay requestusinganIPaddress:
#nyrqetoorHsrloe..nxrf.nmgsnxrf.nadwwnxrf.n #Oleusstuotaealwdieicati,iae.icatinw.icati i$ot!(icati|w.icati|mgsnxrf.n$){ f(hs~^nxrf.nwwnxrf.niae.icati) eun44 rtr4 } # #

#11:LimitAvailableMethods
GETandPOSTarethemostcommonmethodsontheInternet.WebservermethodsaredefinedinRFC2616.Ifawebserverdoesnotrequiretheimplementationofall availablemethods,theyshouldbedisabled.ThefollowingwillfilterandonlyallowGET,HEADandPOSTmethods:
#nyalwteerqetmtos# #Ollohseusehd# f(rqetmto~^GTHA|OT$){ i$eus_ehd!(E|EDPS) eun44 rtr4 } #ontacpEEEERHadohrmtos# #DocetDLT,SACnteehd#

MoreAboutHTTPMethods
TheGETmethodisusedtorequestdocumentsuchashttp://www.cyberciti.biz/index.php. TheHEADmethodisidenticaltoGETexceptthattheserverMUSTNOTreturnamessagebodyintheresponse. ThePOSTmethodmayinvolveanything,likestoringorupdatingdata,ororderingaproduct,orsendingEmailbysubmittingtheform.Thisisusuallyprocessed usingtheserversidescriptingsuchasPHP,PERL,Pythonandsoon.Youmustusethisifyouwanttouploadfilesandprocessformsonserver.

#12:HowDoIDenyCertainUserAgents?
Youcaneasilyblockuseragentsi.e.scanners,bots,andspammerswhomaybeabusingyourserver.
#lconodaet# #Bokdwlagns# f(ht_sraet~W:Sml|Biewe){ i$tpue_gn*LP:ipeBBk|gt rtr0 eun43 } # #

Blockrobotscalledmsnbotandscrapbot:
#lcoerbt# #Boksmoos# f(ht_sraet~sbtsrpo){ i$tpue_gn*mno|cabt rtr0 eun43 }

#12:HowDoIBlockReferralSpam?
Refererspamisdengerouns.ItcanharmyourSEOrankingviaweblogs(ifpublished)asrefererfieldrefertotheirspammysite.Youcanblockaccesstorefererspammers withtheselines.
#eycranRfrr# #Dnetieees## f($tprfrr~bbsfraegr|eer|oendtogncpkrpr|e|en iht_eee*(ae|osl|iljwlylv|ui|rai|oe|onsxte)) { eun44 #rtr0 eun43 rtr0 } # #

#13:HowDoIStopImageHotlinking?
ImageorHTMLhotlinkingmeanssomeonemakesalinktoyoursitetooneofyourimages,butdisplaysitontheirownsite.Theendresultyouwillenduppayingfor bandwidthbillsandmakethecontentlooklikepartofthehijacker'ssite.Thisisusuallydoneonforumsandblogs.Istronglysuggestyoublockandstopimagehotlinkingat yourserverlevelitself.
#Soeplnigooikn tpdeiknrhtlnig lctoiae/{ oain/mgs vldrfrroebokdwweapecmeapecm ai_eeesnnlcew.xml.oxml.o f(ivldrfrr i$nai_eee){ eun43 rtr0 } }

Example:RewriteAndDisplayImage
Anotherexamplewithlinktobannedimage:

vldrfrrlcew.xml.oxml.o ai_eeesbokdwweapecmeapecm f(ivldrfrr i$nai_eee){ rwie^iae/pod.\(i|p|pgpg$ht:/w.xmlscmbne.pat ert/mgsulas*.gfjgje|n)tp/wweape.o/andjgls }

Seealso: HowTo:Usenginxmaptoblockimagehotlinking.Thisisusefulifyouwanttoblocktonsofdomains.

#14:DirectoryRestrictions
Youcansetaccesscontrolforaspecifieddirectory.Allwebdirectoriesshouldbeconfiguredonacasebycasebasis,allowingaccessonlywhereneeded.

LimitingAccessByIpAddress
Youcanlimitaccesstodirectorybyipaddressto/docs/directory:
lctodc/{ oain/os #lcnoktto #bokoewrsain dn121811 ey9.6.. #lonoei9.6../4 #alwaynn1218102 alw1218102 lo9.6../4 #rprsftewrd #doetohol dnal eyl }

PasswordProtectTheDirectory
Firstcreatethepasswordfileandaddausercalledvivek:
#mdr/s/oa/gn/of.tasd kiurlclnixcn/hpsw/ #hpswc/s/oa/gn/of.tasdpswie tasdurlclnixcn/hpsw/asdvvk

Editnginx.confandprotecttherequireddirectoriesasfollows:
##Pswrrtcproamgsndlaietre# #asodPoet/esnliae/ad/et/drcois## lcto(esnliae/*dla.){ oain~/proamgs.|et/* at_ai"etitd uhbscRsrce" at_ai_srflurlclnixcn/hpsw/asd uhbscue_ie/s/oa/gn/of.tasdpsw }

Onceapasswordfilehasbeengenerated,subsequentuserscanbeaddedwiththefollowingcommand:
#hpsws/s/oa/gn/of.tasdpswsrae tasdurlclnixcn/hpsw/asdueNm

#15:NginxSSLConfiguration
HTTPisaplaintextprotocolanditisopentopassivemonitoring.YoushoulduseSSLtotoencryptyourcontentforusers.

CreateanSSLCertificate
Typethefollowingcommands:
#curlclnixcn d/s/oa/gn/of #oeslgnsdsotsre.e04 pnserae3uevrky12 #oeslrqekysre.eotsre.s pnsenweevrkyuevrcr #cevrkysre.e.r psre.eevrkyog #oeslransre.e.rotsre.e pnssievrkyoguevrky #oeslx0rqas35nsre.ssgkysre.eotsre.r pns59edy6ievrcrineevrkyuevrct

Editnginx.confandupdateitasfollows:
sre evr{ sre_aeeapecm evrnmxml.o lse4 itn43 slo sn slcriiae/s/oa/gn/ofsre.r s_etfcturlclnixcn/evrct slcriiaeky/s/oa/gn/ofsre.e s_etfct_eurlclnixcn/evrky acs_ourlclnixlg/s.ceslg ceslg/s/oa/gn/osslacs.o errlg/s/oa/gn/osslerrlg ro_ourlclnixlg/s.ro.o }

Restartthenginx:
#/s/oa/gn/bnnixeod urlclnixsi/gnsrla

Seealso: Formoreinformation,readtheNginxSSLdocumentation.

#16:NginxAndPHPSecurityTips
PHPisoneofthepopularserversidescriptinglanguage.Edit/etc/php.iniasfollows:

#Dsloagruucin ialwdneosfntos dsbefntos=ppnoytmalxc ial_ucinhif,sse,mi,ee #rolmtrsucs# #Tytiieore# #Mxmmeeuintmfeccitnscns aiuxctoieoahsrp,ieod mxeeuintm0 a_xcto_ie=3 #Mxmmaonftmahsrpapnasneusaa aiumutoieeccitmysedprigrqetdt mxipttm0 a_nu_ie=6 #Mxmmaonfmmrcitmycnue(M) aiumutoeoyasrpaosm8B mmr_iiM eoylmt=8 #MxmmszfPSaataHilacp. aiuieoOTdthtPPwlcet ps_a_ie=8 otmxszM #WehrtloTPflpod. hteoalwHTieulas fl_podf ieulas=Of #Mxmmalwdszopoddfls aiuloeiefrulaeie. ula_a_ieie=2 podmxflszM #DoxoePPerrmsaeoetrasr ontepsHroesgstxenlues dslyerrf ipa_ros=Of #Trnsfoe unoaemd sf_oe=O aemdn #Ollocestxctbenioaeietr nyalwacsoeeualsisltddrcoy sf_oeee_iheurdeeualspt aemd_xcdr=pprqiexctbeah #LmtetracestHniomn iixenlacsoPPevrnet sf_oealwdevvrH_ aemd_loe_n_as=PP #RsrcHnomtoekg etitPPifrainlaae eps_hf xoepp=Of #Lgalerr olros lgerrn o_ros=O #Doeitrgoasfriptdt ontrgselblonuaa rgse_lblf eitrgoas=Of #MnmzloalHotsz iiiealwbePPpsie ps_a_ie=1 otmxszK #EsrHeietprpitl nuePPrdrcsaporaey cifrerdrc g.oc_eiet=0 #Dslopodnnesncsay ialwulaigulseesr fl_podf ieulas=Of #EalQaemd nbeSLsfoe slsf_oe=O q.aemdn #AodOeigrmtie vipnneoefls alwulfpn=Of lo_r_oef

Seealso: PHPSecurity:LimitResourcesUsedByScript PHP.INIsettings:Disableexec,shell_exec,system,popenandOtherFunctionsToImproveSecurity

#17:RunNginxInAChrootJail(Containers)IfPossible
Puttingnginxinachrootjailminimizesthedamagedonebyapotentialbreakinbyisolatingthewebservertoasmallsectionofthefilesystem.Youcanusetraditionalchroot kindofsetupwithnginx.IfpossibleuseFreeBSDjails,XEN,orOpenVZvirtualizationwhichusestheconceptofcontainers.

#18:LimitsConnectionsPerIPAtTheFirewallLevel
Awebservermustkeepaneyeonconnectionsandlimitconnectionspersecond.Thisisserving101.Bothpfandiptablescanthrottleendusersbeforeaccessingyournginx server.

LinuxIptables:ThrottleNginxConnectionsPerSecond
ThefollowingexamplewilldropincomingconnectionsifIPmakemorethan15connectionattemptstoport80within60seconds:
/bnitbeAIPTcpr0t0ttttEmrcne si/palsNUptpdot8iehmsaesaeNWeetst /bnitbeAIPTcpr0t0ttttEmrcnpaescns6hton5RP si/palsNUptpdot8iehmsaesaeNWeetudteod0icut1jDO

srieitbeae evcpalssv

BSDPF:ThrottleNginxConnectionsPerSecond
Edityour/etc/pf.confandupdateitasfollows.Thefollowingwilllimitsthemaximumnumberofconnectionspersourceto100.15/5specifiesthenumberofconnectionsper secondorspanofsecondsi.e.ratelimitthenumberofconnectionsto15ina5secondspan.Ifanyonebreaksourrulesaddthemtoourabusive_ipstableandblockthemfor makinganyfurtherconnections.Finally,flushkeywordkillsallstatescreatedbythematchingrulewhichoriginatefromthehostwhichexceedstheselimits.

wbevri=225.." esre_p"0.411 tbe<bsv_p>prit alauieisess bokiucrm<bsv_p> lcnqikfoauieis psnoetirtco$esre_pprwlg/Akettmxsccn0,mxsccnae1/,oelaauieisl asin$x_fpootptwbevriotwwfasSSepsae(aron10aronrt55vrod<bsv_p>f

Pleaseadjustallvaluesasperyourrequirementsandtraffic(browsersmayopenmultipleconnectionstoyoursite).Seealso: 1. SamplePFfirewallscript. 2. SampleIptablesfirewallscript.

#19:ConfigureOperatingSystemtoProtectWebServer
TurnonSELinuxasdescribedabove.Setcorrectpermissionson/nginxdocumentroot.Thenginxrunsasausernamednginx.However,thefilesintheDocumentRoot (/nginxor/usr/local/nginx/html)shouldnotbeownedorwritablebythatuser.Tofindfileswithwrongpermissions,use:
#fnnixsrnix id/gnuegn #fnurlclnixhmuegn id/s/oa/gn/tlsrnix

Makesureyouchangefileownershiptorootorotheruser.Atypicalsetofpermission/usr/local/nginx/html/
#ll/s/oa/gn/tl surlclnixhm/

Sampleoutputs:
wrotro2a30:0errx.tl rr1root95Jn05ro4xhm wrotro5a31:0errx.tl rr1root2Jn00ro5xhm wrotro3a30:2idxhm rr1root14Jn05ne.tl

Youmustdeleteunwatedbackupfilescreatedbyviorothertexteditor:
#fnnixae'?'onmh*rae'~onm*bk'rae'.l* id/gnnm.*ntae.tonm*'rae'.a*onm*od' #fnurlclnixhm/ae'?'onmh*rae'~onm*bk'rae'.l* id/s/oa/gn/tlnm.*ntae.tonm*'rae'.a*onm*od'

Passdeleteoptiontofindcommandanditwillgetridofthosefilestoo.

#20:RestrictOutgoingNginxConnections
Thecrackerswilldownloadfilelocallyonyourserverusingtoolssuchaswget.Useiptablestoblockoutgoingconnectionsfromnginxuser.Theipt_ownermoduleattempts tomatchvariouscharacteristicsofthepacketcreator,forlocallygeneratedpackets.ItisonlyvalidintheOUTPUTchain.Inthisexample,allowvivekusertoconnectoutside usingport80(usefulforRHNaccessortograbCentOSupdatesviarepos):
/bnitbeAOTUoehmonrudonrvvkcpr0ttttE,SALSECET si/palsUPTt0weiweieptpdot8msaesaeNWETBIHDjACP

Addaboveruletoyouriptablesbasedshellscript.Donotallownginxwebserverusertoconnectoutside.

BounceTip:WatchingYourLogs&Auditing
ChecktheLogfiles.Theywillgiveyousomeunderstandingofwhatattacksisthrownagainsttheserverandallowyoutocheckifthenecessarylevelofsecurityispresentor not.
#ge/oi.h?"/s/oa/gn/osacs_o rp"lgnpp?urlclnixlg/ceslg #ge..t/asdurlclnixlg/ceslg rp".ecpsw"/s/oa/gn/osacs_o #erpdne|ro|anurlclnixlg/ro_o gei"eiderrwr"/s/oa/gn/oserrlg

Theauditdserviceisprovidedforsystemauditing.TurnitontoauditserviceSELinuxevents,autheticationevents,filemodifications,accountmodificationandsoon.As usualdisableallservicesandfollowour"LinuxServerHardening"securitytips.

Conclusion
Yournginxserverisnowproperlyhardenandreadytoserverwebpages.However,youshouldbeconsultedfurtherresourcesforyourwebapplicationssecurityneeds.For example,wordpressoranyotherthirdpartyappshasitsownsecurityrequirements. References: HowTo:SetupnginxreverseproxyandHAcluserwiththehelpofkeepalived. nginxwikiTheofficialnginxwiki. OpenBSDspecificNginxinstallationandsecurityhowto. FeaturedArticles:

20LinuxSystemMonitoringToolsEverySysAdminShouldKnow 20LinuxServerHardeningSecurityTips My10UNIXCommandLineMistakes TheNoviceGuideToBuyingALinuxLaptop 10GreatestOpenSourceSoftwareOf2009 Top5EmailClientForLinux,MacOSX,andWindowsUsers Top20OpenSSHServerBestSecurityPractices Top10OpenSourceWebBasedProjectManagementSoftware Top5LinuxVideoEditorSoftware

Sharethiswithothersysadmins! DownloaditEmailitFacebookitGoogle+itPrintitTweetit We'reheretohelpyoumakethemostofsysadminwork.So,subscribe! {25commentsreadthembeloworaddone} 1LeoMarch6,2010 Verynicepost Reply 2tiptopMarch6,2010 CanyouaddApachespecificsecuritytips? Reply 3VivekGiteMarch6,2010 Apache?Ydaystechnology?Justkidding..IwilladdwhenIvesomefreetimebutnoETA. Reply 4MC.SpringMarch6,2010 Verygoodjob Thanksforshare! Reply 5RobinMarch6,2010 Ifinditironicthatyourefertoapacheasyesterdaystechnology,indirectlyimplyingthatyouneedtobeabletohandlemassiveloadsonyourserver,andthenseta veryrestrictivesourcethrottlingforPFofacrazy15connectionsper5secondsdoyouevenknowhowmanyconnectionsabrowser,evenwithkeepalive,willspit outwhendigestingf.e.anhtmlfilewith50tagsinit?Obviouslynot.Also,youshouldautoflushthatblockedtableregularly,becauseyouwillhave_alot_offalse positiveswitharestrictiverulelikethat.Verybadadvicethere. Ialsofinditoddthatyouhaventgottenuptospeedontheremovalofsafe_modeinPHP,and,thatyouinyourSSLcertificategenerationmakeuseof3DES,which isanythingbutsecure.Alsoprettybadadvice. Reply 6JuanGiordanaMarch6,2010 Theresanicenginxhowtothatmaycomplementthesetipsathttps://calomel.org/nginx.html Reply 7AymanFekriMarch7,2010 veryGoodpost. But:whyuconsidermail()asdangerousfunctions? Reply 8EminMarch7,2010 Re:#10 Ifinditmuchmorecleanandconvenienttosimplycreateadefaultwebsitewithblankwebpage(orreturnerrorifpreferred)thatwillrespondtoallnonmatched

queries. Reply 9AmrElSharnobyMarch7,2010 Hello,Thanksalot Ivealreadyimplementednginxonmultipleserverstoservemorethan200TBofdatamonthly..yesTerabytenotGigabye,Iknowit. HereissomecommentsIve Re:#17:RunNginxInAChrootJail(Containers)IfPossible YouCAN,ofcourse,usetraditionalchrootkindofsetupwithnginx.Itsjustalittlebittricky,Imalreadysettingitupwithphpfastcgiserverchrootedtoo.youcan contactmeifyouneedthesteps. Re:#18:LimitsConnectionsPerIPAtTheFirewallLevel YoucanusesomethinglikethefollowinginnginxthisisalreadywhatIuseonheavilyloadedserverswithmanyvisitorsbehindproxies limit_req_zone$binary_remote_addrzone=ratezone:20mrate=16r/s limit_reqzone=ratezoneburst=160nodelay Ibelievethatnginxcandoitbetterthaniptables,speciallyunderaDDoSattack,becausetheiptablesrecentmodulehaveamaximummemorylimitof8MB,asIcan remeberit,andafterthatitseithercompletelyfailordropeverythingnginxwilldoalwaysbehavebetter. Re:#20:RestrictOutgoingNginxConnections IthinkthatItsbettertodothatusingselinuxpolicyifyouuseseedit,youcanaddsomelinelikethistothenginx_t.sp.. allownetprotocoltcpport21,25,80,110,143,443client Thanksalot Reply 10js&cMarch8,2010 @Amr, CanyoushareyourinstructionsonchrootingNginxinachrootjail? Reply 11VivekGiteMarch8,2010 @js&c, YoucanchrootnginxusingchrootcommandunderCentOS/RHELoranyLinuxdisroasfollows.Youneedtocopy/usr/local/nginxtoyour$D.Nextcopy /etc/{passwd,group,hosts,resolv.conf,php.ini}to$D/etc,Youneedtocopyrequiredlibsto$D.Oncedonecopy/lib64/*to$Dtoo.Copyphpcgito$D/usr/bin. Finally,copyrequiredphpmodulessuchgd,phpmysqlto$D/usr/lib64/php/modulesdirectory.Runphpcgiin$Dusingthefollowingsyntax
/s/i/pwciD9.6..000vrrnppcifscipdgngnixurbnppci urbnsanfgc$a121811p90P/a/u/hg.atg.iunixgn/s/i/hg

Where, D=/jail.dir Youneedtoplace/dev/nullandafewmoreentriesin$D/dev.Donotaddharddiskand/oranyotherblockdeviceentriesin$D/dev.Thisisthemainproblemwith chrootanditcanbeeasilyescapedifpropercareisnottaken,henceIrecommendpropertools. Updatenginx.confandpointfastcgito192.168.1.10:9000.Oncedonestartnginxas


croD/s/oa/gn/bnnix hot$urlclnixsi/gn

HTH Reply 12edogawaconanAugust9,2010 Theresnoneedtochrootbothphpcgiandnginxinoneplace.Additionally,phpfpmhaschrootfunctionalitybuiltin. Reply 13robertMarch15,2010 Hi, Itsgreattoseethecompletestepbysteponhardeningnginxwebserver. Wouldyouconsiderinwritingsomethinglikethatforlighttpdwebserver?:)

Reply 14VivekGiteApril12,2010 Yes,bothApacheandLighttpdareonmyTODOlists.Sostaytuned. Reply 15VamsiKrishnaMarch15,2010 Thankyouverymuchsir:) Reply 16AlokKumarApril14,2010 nicearticle,quiteaninformative Reply 17vinodApril17,2010 quitenicearticle..butIhavenotunderstoodyetwhyselinuxisimportant:)IhavebeenaFreeBSDguyandnowstartedworkingonCentOStoo Ivesetupavideostreamingserver,usingNginxandphpfpm(thisservertransmits@34mbpsataverage)Iamseeingalotoferroslikeconnectiontoupstream timedoutetc,whichthrowsaBadGatewayattimes.AfteralotofgooglingIincreasedthetimeoutoffcgiandthatseemtoalleviatetheissue,butIamseeing suchentriesinthelogsoften.IassumetheissueiswithnginxgettingfailedtocommunicatewithPHPengine Iwonderiftheerroriscommonanddowehavehotfixfortheissue?Idoubtifthatisanissuewithanycompiledmodule? Thanks! Vinod! Reply 18ruo91April25,2010 Verygood!! Reply 19edogawaconanAugust9,2010 #10shouldbedoneusingserver{}block.

sre evr{ lse0dfut itn8eal rtr0 eun43 }

#11,Idoubtnginxsupportsanyothermethods And#12Idoubttheresanyspambotsleftrunningusingnoncommonuseragent. Additionally,runningphpcgiandnginxdaemonsasdifferentuserisrecommended.Settingownerofthefilestorootandmakingitnongroup/worldwritableexcept forsomedirectoriesusedbyphp(inwhichshouldbesettophpownedandnotgroup/worldwritable)isalsorecommended. Reply 20AhmedOctober24,2010 #12:HowDoIBlockReferralSpam? Pleaseremovethat!ItcantmakeanythingjustgettingCPUloadaveragefrom3to8itmakesnginxsloweranditsnotgoodforseoalso. Reply 21v13November23,2010 nicenginxsecuritypractices Reply 22BangonKaliJune26,2011 Thankyouverymuch!Theseareveryhelpful!

Reply 23guntOctober6,2011 Hi, Thankyouforthispost.Itreallyhelpmealot. Ineedyourhelpwiththehotlinkingpart,couldyoupleasetellmeexactlywhichfile doIneedtoedittostopthebadguysusingmyimages. IllappreciateyourhelpcauseIcantfindanywherethisinfo! thanks Reply 24jakeOctober18,2011 THANKYOUSOOOOOOOOOOOOMUCH. Myserverhassufferedfromsocketportexhaustionfor2yearsnow. Ivetriedeverysysctlvariableandahundredconfigurationsfromvariouslinuxadministrators,andonlyYOURsysctl.conffiledidthetrick. Imnotsurewhy,iveusedalltheseparametersbefore,butitfinallyfixedtheproblemoncentosandnowIcanrunaloadtestforhoursandneversufferfromport exhaustion. YOUARETHEMAN! Reply 25SuilAmhainNovember26,2011 Hi, Justaquickquestiononpoint#7RestrictiveIptablesBasedFirewall Imtryingtogetanunderstandingofiptablesandindoingsoyouroutputrulesconfuseme. Pleseseebelowexample: $IPTAINPUTi${PUB_IF}s${ip}ptcpd${SERVER_IP}destinationport22jACCEPT $IPTAOUTPUTo${PUB_IF}d${ip}ptcps${SERVER_IP}sport22jACCEPT Iinterpretthatasbeing AcceptaSSHintoserverfromIPasdefinedin$PUB_SSH_ONLY. AllowasshconnectionouttoanIPasdefinedin$PUB_SSH_ONLY. Whydoyouneedtheoutputrule? IsitsimplytoallowaSSHconnectiontoanIPdefinedin$PUB_SSH_ONLYor istheoutputrequiredaspartofahandshakingprocess? IknowIshouldexperimentandseebutImcurioustotheanswerandthatImayhaveagapinmyiptablesunderstanding. Thanks, SuilAmhain Reply LeaveaComment Name* Email* Website

YoucanusetheseHTMLtagsandattributesforyourcodeandcommands:<strong><em><ol><li><u><ul><blockquote><pre><ahref=""title=""> Notifymeoffollowupcommentsviaemail.
Submit

Taggedas:macosx,nginx,nginxsecurity,reverseproxy,reverseproxysecurity

Previouspost:Arrrggg:OpenSourceUsersArePirates Nextpost:HowTo:ConfigureWordPressToUseAContentDeliveryNetwork(CDN)

GETFREEUPDATES
MakethemostofLinuxSysadminwork! Enteryouremail Join

42k+Subscribers|Twitter|Google+

Search

RelatedPosts
FAQUpdate10/Aug/2010 Poll:WhichWebserverdoyouuse? FAQUpdates:July/12/2011

20042011nixCraft.Allrightsreserved.Cannotbereproducedwithoutwrittenpermission. PrivacyPolicy|TermsofService|QuestionsorComments|CopyrightInfo|Sitemap

You might also like