Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Copyright
AllofthedocumentationwillbelicensedunderaOpenGovernmentLicenceasspecified
http://www.data.gc.ca/eng/opengovernmentlicencecanada
Executive summary
ThisdocumentdescribesbestpracticesforsettingupandmaintainingaDrupalsite.Itwas
writtenfortheGovernmentofCanada,butnothinginitisspecifictothisgovernmentanditis
veryapplicabletootherinstitutions.
Drupalisaverypopular,opensourceContentManagementSystem(CMS).Thissoftwarehasa
strongsecuritymodel,butwhenconsideringthesecurityofasiteanorganizationneedstobe
awareofthedangersofnotfollowingagoodprocess.Furthermore,Drupalisonlyonepieceof
softwarethatisrequiredtorunyoursite,andoneneedstoconsiderthesecurityoftheentire
serverecosystem.
Thisisnotacomprehensivedocument,asITsecurityisacomplexfield.Wehavetriedtofocus
onbroadareastohelpexplaintheimportanceandapproachestoimprovingsecurity.Wehave
includedmanygreatmanylinksandexpectthatpeoplewilllearnmoreaboutthetoolsthatwe
havelistedhere.
Wedonotbelievethattherewilleverbea100%securesystem.Therearealwaysbugsin
softwareandweknowthatnewtypesofexploitsarebeingfoundallofthetime.Wearelisting
optionstoconsider,buteachorganizationwillneedtoweighwhichcombinationtheyaregoingto
use.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page1
Table of Contents
A)Introduction
B)PrinciplesofSecurity
C)SecurityConcernsforManagers
D)ServerSecurity
1)ServerProcurement
2)ImmediatelyAfterReceivingRootAccess
3)Createabaseline
4)LimitAccessfromOutside
5)InitialInstalls
6)ServerMaintenance
7)RoughServerEcosystemImage
E)WebServers
1)RestrictingAccess
2)RemovingCode
3)HTTPHeaders
4)EverythingElse
F)PHP
G)Database(MySQLorPostgreSQL)
H)Drupal
1)Files
2)Drush
3)Errors
4)Administration
5)Modules
6)DrupalDistributions
7)Miscellaneous
I)Development,StagingandProduction
J)RegularMaintenance
K)AdditionalResources
1)Generalguidelines
Drupalsecurity
Securehosting
2)Videos
3)Thirdpartytools
4)Books
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page2
A) Introduction
Drupal7isaleadingContentManagementSystem,particularlyintheGovernmentofCanada.It
iswidelyusedbygovernmentsaroundtheworldwhoarelookingtomeetincreasingcitizen
demands,largerchallengeswithaccessibilityandmobilerequirements,andeversmaller
budgets.
Withgovernmentsincreasinglytargetedforcyberattacks,itisimportantthatbestpracticesare
keptuptodatesothatpersonalinformationandgovernmentassetsareprotected.
Thisguideprovidesanoverviewofimportantsecurityprinciples,bestpracticesforbasic
securityplusextrastepstobeconsidered,ifbudgetallows.Wherepossiblewewillbe
providingsomedetailedinstructions.ManagersshouldreadsectionsBandC.System
AdministratorswillneedtofocusonsectionsD,E,F,G,I&J.Drupaldeveloperscanfocuson
sectionH,butshouldbefamiliarwiththeimpactoftheothersectionstoo.
Itshouldbeclearthatnotallofthestepsoutlinedherewillneedtobetakenonallsites.The
principlesshouldbefollowedbutnotallofthesecuritysuggestionsdescribedwillneedtobe
followedbyallorganizations.Eachpracticeortoolshouldbecarefullyevaluatedtounderstand
thepotentialcosts,risksandbenefits.
Thisdocumentraisesissuestoconsiderbeforeyouprocureaserverandwhenyoufirstgain
accesstoyourserver.Itprovidessuggestionsonwhatadditionalsoftwareyoucanaddtoyour
sitewhichcanhelpimproveitssecurity.Italsohighlightsconfigurationoptionsthatyoucanadd
toApache,PHP&MySQLtoimprovetheinitialdefaults.Finallywetalkaboutthingsthatyoucan
dotoenhanceDrupalssecurity.
Thecodesnippetswhichareincludedarenotalwaysacomprehensiveguide,butthereare
alwayslinksinthedescriptiveparagraphwithmoreinformationwhichyoushouldconsultbefore
installingprogramsonyourliveserver.
Forinformationonbuildingsecuremodulesandthemes,seethedocumentationonDrupal.org.
ThisdocumentstronglyrecommendsagainsttheuseofMicrosoftWindowsserversfor
Internetfacingwebsites.Windowssecuritywillnotbeaddressed.
Securitycannotbejustabuzzword,itisaprocess.Thereneedstobeclearunderstanding
aboutlinesofresponsibilityandultimatelymanagementneedstoprovidethebudgetrequiredto
ensurethatsystemscanbemaintainedandregularlyreevaluated.
Eternalvigilanceisimportantasthosesearchingforyourvulnerabilitiesareworkingaroundthe
clockandarewellfinanced.Thisdocumentwill,itself,needtoevolvetokeeppacewithnew
vulnerabilities.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page3
B) Principles of Security
1. ThereisSafetyintheHerd:Leveragelarge,wellmaintainedopensourcelibraries
(packages)withacriticalmassofusersanddevelopers.Usecompiledpackagesandcheck
dataintegrityofdownloadedcode.StartwithastandardDebian/UbuntuorRedHat/CentOS
installation.
2. OrderMatters:DontopenupservicestotheInternetbeforeyourserverisproperlysecured.
3. LimitExposure:Onlyinstallandmaintainwhatisnecessary.Reducetheamountofcode
installed.Reviewserverconfigurationregularlytoseeifitcanbestreamlined.
4. DenyAccessbyDefault:Onlyallowaccesswhereitisneeded,andmakeallaccess
policiesdenybydefault.
5. UseWellKnownSecurityTools:Therearewellsupportedlibrariesthatlimitexposure,and
checkforintrusion.Suggestionsareprovidedlater.
6. AvoidWritingCustomCode:Evenlargegovernmentdepartmentsdontinvestproperlyin
regular,ongoingcodereviews.Minimizetheuseofanycustomcode.
7. ContributeBack:Nosoftwareiseverperfect.Thereisalwaysroomforimprovement.Make
thecodeyouusebetterandgiveitbacktothecommunity.Ifyoudoititproperlyyouwont
havetorewriteyourcodewiththenextsecurityreleaseandyouwillgetfreepeerreview
andongoingmaintenance.
8. LimitAccess:Thereneedtobeclear,documentedrolesofwhohasaccesstowhat.Only
usesetupandusesudowhenrootaccessisrequired.Isolatedistinctroleswherepossible.
Everyonewithaccessneedstheirownaccount,sharedaccountsareinsecure.
9. MakeYourApplicationHappy:Whenrunningsmoothlyyourservershouldnotbe
generatingerrors.Monitoryourservertheninvestigateandresolveerrors.
10. DocumentEverything:Makesureyouhaveanoverviewofanycustomizationswhichmay
havebeendoneoranyadditionalsoftwarethatmayhavebeenadded.
11. LimitUseofPasswords:Havesaneorganizationalpoliciesonpasswordrequirements.
Keeptrackofyourpasswordsincontrolled,encryptedprograms.Wherepossibleuse
passwordlessapproachessuchassshkeypairswhicharemoresecure.
12. DontTrustYourBackup:Define,reviewproceduresanddotestthatyoucanrestoreyour
siteregularly.
13. ObscurityisntSecurity:Organizationsneedtohavetheirsecuritypolicieswelldocumented
andinternallytransparent.SectionKdiscussesthisissueindetail.
14. SecurityisBig:Itisamistaketoassumethatonepersoncandoitwellinisolation.Having
accesstoateam(evenoutsideoftheorganization)willhelp.
15. Remember,YoureStillNotSafe:Haveanaudittrailstoredonanothersystem.Ifyoursite
iscompromised,takethetimetofindouthow.Useproperversioncontrolforallcodeand
configuration.
16. NotJustforTechs:Uppermanagementneedstotakethetimetounderstandthese
generalprinciplesofITsecurityastheyhaveprofoundimplicationstotheworkofthe
wholeorganization.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page4
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page5
D) Server Security
Anywebsiteisacomplexecosystemofsoftware.Eachaspectcanbetighteneddownmore
throughproperconfigurationandadditionalsoftwarethanitcomeswithinitially.Thisdocument
providessomeexamples,butmostlyreliesonlinkssothatyoucanreadthespecificdetailson
howthisshouldbedone.ThereareotherlistsofconsiderationsforServerSecurity,likeRobert
Hansenslistof10majortenantsofasecurehostingmodel,butwherepossibleIwillbereferring
backtothelistabove.
1) Server Procurement
Startserverdocumentationwiththeinformationabouttheoriginalparametersofyourserver
contract.Thereareoftentechnicaldetailsandnotesaboutwhotocontactwhenthingsgo
wrong.
Itisimportanttodeterminethatthereisastrongsecuritycommunitybehindthedistributionyou
choose,andthatyouhavethenecessaryhumanresourcesinyourdepartmenttomaintainit.
OpenConceptpreferseitherDebian/Ubuntu,butRedHat/CentOSarereallysolidaswell.The
advantageofaDebianorRedHatbasedsolutionisthatthereisextensivedocumentationand
largecommunitiesofuserswhovesharedtheirexperiencesthroughforums,issuetrackers,
andblogposts.UbuntuisbasedonDebian,CentOSisbasedonRedHat,anyreferences
tooneortheothershouldbeinterchangeable.
IfyouuseaRedHatEnterpriseLinux(RHEL)system,youwillneedtohavesubscriptiontotheir
serviceinordertoapplysecurityupgradesandinstalltheadditionalpackagesmentionedinthis
document.BeforeprocuringaRedHatserver,checkthatyourpackageincludesasubscription.
Inouropinion,distributionsofLinuxlikeSuSEsimplydonothaveacriticalmassofusersand
developerstomaintainthecodeanddocumentationrequiredforasecureenvironment.Microsoft
WindowsisnotastandardplatformforhostingDrupalandisgenerallyfrownedupon.
CommunitysupportforhostingonWindowsissparseandisthereforenotrecommended.Itis
verydifficulttolimitexposureonaWindowsServersincetherearemanyunneededpiecesof
theoperatingsystemwhichyoucannoteasilyuninstall.
Ifyouareworriedabouttheserversphysicalsecurity,youcanalsosetupanencryptedpartition
onyourharddrive.Thismayintroduceperformanceissueswhichmightcauseproblemsfor
yourserver.Thisdocumentwillnotbecoveringhowtosetupanencrypteddrivebutdepending
ontheperceivedthreats,itmaybeworthimplementing.
WhenenablingencryptedtrafficusingHTTPS,itisimportanttoknowhowmanydomainnames
youwillbehostingonasinglewebserver.Eachdomainneedsitsowncertificate.Althoughitis
nolongerrequired,ofteneachcertificatewillhaveitsownIPaddress.Itiscommontohaveany
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page6
numberofunencryptedHTTPsiteshostedonasingleIPaddress.
Finally,dontgetaserverthatcomeswithaserveradmincontrolpanel.Theypromiseto
makemanagingyoursiteeasierbutpresentsecurityproblems.Thereareanumberof
commercialpackages,likecPanelorPLESK,thatdomakeiteasiertochangesettingsonyour
site.Thisseemsparticularlyattractiveiflesstechnicalusersareresponsibleforserver
administration.OurrecentexperiencewithcPanel,madeitdifficulttoapplymanyofthe
suggestionsdescribedhere.BecauseyoucantsimplydisablecPanel,wehadtoreinstallthe
siteonanewserver.Ifyouchooseaserverwithone,youwillneedtoexperimentwithwhichof
thefollowingsuggestionsyouareabletoimplement.Somecontrolpanelsarealsoknownto
overwritesettingsthataremadetoconfigfiles.Itisimportanttoworktominimizetheattack
surfaceandasthesedashboardsaremanagedthroughtheweb,itisyetanotherpointwhere
yourservercanbecompromised.Ultimatelyacontrolpanelcouldproveconvenientbothforyou
andforthoselookingtohackintoyoursystem.
Youwillinevitablyhaveanumberofpasswordstomaintain.Werecommendstoringtheseina
newKeePassPassworddatabase.Ithasanicepasswordgeneratorwhichmakesitveryeasy
togeneratelong(20+characters)andcomplexpasswordsandstorethemimmediately.If
yougetanyotherpasswordssuppliedviaemail,resetthemimmediately.Youremailaddressis
alsoapointofvulnerability.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page7
Themostcommonaccountthatcrackers1 trytocompromiseistherootuser,sodisableroot
logins.Furthermore,setupuseraccountswithsudoaccessandusesshkeyssothatnobody
accessingthesiteisusingapassword.Protectyoursshkeysbyensuringthatyourprivatekeys
arepasswordprotectedandusing2048bits.Bydisablingtheuseofpasswordsforsshuser
loginsacommonservervulnerabilityissimplyeliminated.Whenyouturnoffpasswordlogins
scriptkiddiessimplycannotcompromiseyourserverwithcommondictionaryorbruitforce
attacks.Thereareexplanationsonhowtoeffectivelydisablepasswordloginsbutcheckthat
/etc/ssh/sshd_confighasthetextPasswordAuthenticationno
3) Create a baseline
Recordabaselineofyourserverthatyoucanreview,knowingthatthisistheminimumnumber
ofprocesseswhicharerunningwithacleansystem.Likewiserecordthebaselinefroma
netstatreporttoseewhatportsareopen:
psafx
sudonetstatlpn
ThemanagementofportsonthenetworkismanagedthroughIPTables.Itisimportanttoreview
anddocumentthemtoseethattheyareproperlyrestrictive.Fromthecommandlineyoucan
listthemwith:
iptablesLvn
Youcanload/savetheIPTableseasilyusingtheiptablespersistentpackage`sudoaptgetinstall
iptablespersistent`.WiththatyoucansimplysavetheexistingIPtablesfromthecommand
line:
Debian:serviceiptablespersistentsave
CentOS:serviceiptablessave
Recordthelistofinstalledpackagesontheserver.Savethisinformationinatextfileinyour
managementcoderepository.Ifyourserveriscompromiseditisusefultoknowwhatpackages
wereinstalledandrunningwhenyoustarted:
Debian:dpkgl
CentOS:yumlistinstalled
Wehaveusedthetermcrackerratherthanthemorecommonlyusedtermhackerasthereareboth
positiveandnegativedefinitionsofthetermhacker.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page8
ports.ItcanalsobeusefultousefirewallrulestorestrictoutgoingconnectionsfromtheApache
user.Thepossibleexceptiontothisisdrupal.orgsIPaddressasyouwillwanttoregularlyuse
drush(Drupalscommandlineshellandscriptinginterface)toupdatemodules(seeH2below).
Youcaneasilyseewhatportsareopenbyusingaportscannersuchasnmapfromanexternal
machine:
nmapsSSERVER_ADDRESS
WerecommendrunningperiodicTCPportscansonyourserver.MXToolboxoffersanoptionto
dothisthroughtheirsite,butyoucanalsousetoolslikenmapwhichoffersyoumore
finegrainedcontrols.
ManyserverscomewithBINDonUDPport53.Thisprogramcanprobablyberemovedinmost
instancesorshouldberestrictedwithafirewallifrequired.Therearesomedetailedinstructions
hereonhowtoremoveit,whichareparticularlyimportantifyouarentsureifyouneeditornot.
Tocheckifbindisrunning,runthisfromthecommandline:
psAl|grepbind
chkconfig|grepbind
YoucanobscureyourSSHportbyreassigningittootherthanthedefault(22).Thismightfoola
lazycrackerwhoisntusingaportscannerfirst,butwontstoptheseriousfolks.
Oneofthebestwaystolimitsshaccesstoaserveristorestrictaccesstoadozenorso/24
networkswhereadministratorsactuallywork.Don'tbeafraidtoaddtothislistmakeiteasyfor
yourpeopletoworkwherevertheyneedto.Securityisnottheenemy.
YoucanalsorestrictwhocansshintotheservertoalimitednumberofIPaddress.Bevery
carefulwhenconfiguringthisasyoudontwanttoblockyourselffromaccessingtheserver.
Debiansadmindocumentationoffersthefollowingchangeswhichcanbemadetotheiptables
firewall:
# All connectsion from address 1.2.3.4 to SSH (port 22)
iptables -A INPUT -p tcp -m state --state NEW --source 1.2.3.4 --dport 22 -j
ACCEPT
# Deny all other SSH connections
iptables -A INPUT -p tcp --dport 22 -j DROP
IfyoualreadyhaveestablishedaVirtualPrivateNetwork(VPN)thenyoucanrestrictSSH
accesstowithinthatprivatenetwork.ThiswayyouneedtofirstlogintotheVPNbeforebeing
abletoaccesstheport.LeveraginganexistingVPNhassomeadditionalcostsbutalsosome
securityadvantages.IfanorganizationisntalreadyusingaVPNhowever,thentheusability
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page9
problemswithforcingpeopletouseitmayencouragedeveloperstofindwaystocircumventit.
5) Initial Installs
TherearesometoolstohardenyourLinuxsystem.Theprogramgrsecurityaddressesa
numberofmemoryandpermissionsissueswiththeKernel.SELinuxprovidessupportfor
mandatoryaccesscontrols(MAC)policies,suchasthoserequiredbytheUnitedStates
DepartmentofDefense.BastilleLinuxguidestheadministratorthroughaninteractiveprocessto
limitaccessontheserver.NOTE:Ubuntu,whichisaDebianbaseddistribution,reliesonthe
DebianSELinuxpolicies.SeetheUbuntuWikiformoreinformation.
Debian:aptgetinstallperltkbastilleselinuxbasicsselinuxpolicydefaultauditd
ItisntcurrentlyrecommendedtoaddthesecuritytoolAppArmourasitoftencaninterfere
withothersecurityenhancements.IfitisnotinstalledbydefaultbyyourLinuxdistribution,
addingitmayconflictwithothersecurityprograms.AppArmourisinstalledbydefaultbyUbuntu
andthereisnoneedtouninstallit,butitisimportanttobeawarethatothersecuritytoolswill
probablybeaffectedbyAppArmourssettings.
UsinganintrusiondetectionsystemsuchasOSSECHostbasedIntrusionDetectionSystem
(HIDS)orPHPIDS(PHPIntrusionDetectionSystem)isagoodpractice.Therearegoodhowto
documentsavailableforbothPHPIDSandOSSEC.TripwireandSnortareotherIDSswhich
monitortheintegrityofcorefilesandwillalertyoutosuspiciousactivity(availableforCentOS
andDebian).
Crackerswilloftentrytouseabruteforceattacktoguessusernamesandpasswords.Usinga
servicelikeFail2bancanblockIPaddressesthataremakinganunreasonablenumberoflogin
attempts.Thiswontpreventdistributedattacks,butcouldbeusedinconjunctionwithOSSEC.
Fail2banisalsoaneffectivemeasureforfloodcontrolandcanstopmostdenialofservice
attacks.Distributeddenialofserviceattacks(DDoS)aremoredifficulttoaddress,buttheresa
greatdefenseplanlaidoutonStackOverflow.
Debian:aptgetinstallfail2ban
CentOS:yuminstallfail2ban
Placethe/etcdirectoryunderVersionControlsothatyoucaneasilytrackwhichconfigurations
havechanged.Theprogrametckeeperautomatesthisprocessnicelyandhooksintoyour
packagemanagerandcrontodoitsworkwhenyourserverisupgradedornewsoftware
installed.
Debian:aptgetinstalletckeeperbzr&&etckeeperinit&&etckeepercommit"initialcommit"
CentOS:yuminstalletckeeper&&etckeeperinit&&etckeepercommit"initialcommit"
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page10
YouwillprobablywanttoinstallAPCandMemcache(orRedis)toensurethatyoursiteis
respondingquickly.APCisaPHPbytecodecompilerandMemcachedisageneralpurpose
distributedmemorycachingsystem.Bothworktomakeyourservermoreresponsiveby
minimizingtheloadontheserverandimprovingcaching.Thiswillhelpwhenthereisan
unexpectedserverload.
Asidefromtheperformanceadvantages,therecanbesecurityimprovementsbyusingVarnish
orMemcachetocachethepublicdisplay.Therearehugesecurityadvantagestorestricting
accesstotherenderinglogic(Drupalsadmin)sothatthepublicisonlyinteractingwithacache
servingfrontendcontent.
Noteifyouaregoingtobehostingseveralsitesonthesameserverandwanttogivedifferent
clientsaccesstotheirsiteonthatserveritwouldbeworthinvestigatingFastCGItoisolate
individualprocessesfromasharedserver.Weexpectmostgovernmentdepartmentstohave
accesstoeitheravirtual(ex:Xen)orcloudbased(ex:AmazonEC2)server.
6) Server Maintenance
Securityrequiresconstantvigilance.Someoneshouldbetaskedwithensuringthattheserver
iskeptuptodateatleastweekly.Thisisntusuallyacomplextask,butitdoesrequirethat
someonesubscribetothesecurityupdatemailinglistforthedistribution(e.g.Ubuntuand
CentOS),applytheupdates,andreviewthelogstoensureeverythingisstillrunningproperly.
Upgradescanbedonewiththefollowingcommands:
Debian:aptgetupdate&&aptgetupgrade
CentOS:yumupgrade
ItisveryusefultohaveaservicelikeNagiosmonitoringyourproductionservertoalertyouifany
problemsarise.TheconfigurationofNagioscanbequitecomplex,butyoucansetitupeasily
enoughonyourstagingserver.Youwillneedtograntaccessonyourproductionenvironmentto
thisserverandyoumustenableCGIaccessonthisserver.Togettheserverinstalledinyour
stagingenvironment,executethefollowingfromthecommandline:
Debian:sudoaptgetinstallnagios3nagiosnrpeplugin
AndforeachserveryouwishtomonitorwithNagios:
Debian:sudoaptgetinstallnagiosnrpeplugin
Munincanberunontheproductionenvironmenttogiveyouasenseoftherelativeloadof
variouskeyelementsoverthepasthour,day,weekandmonth.Thiscanbeusefulwhen
debuggingissueswithyourserver.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page11
Debian:aptgetinstallmuninmuninnode
Accesstothisinformationisavailablethroughyourwebserverbutyouwillwanttoconfigure
yoursitetoensurethatthisdataisnotpubliclyavailable.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page12
E) Web Servers
Apachehasanumberofmodulesthatcanbeinstalledtotightensecurityofthewebserver.We
recommendinstallingModSecurityandmod_evasive.ThiscanbesettoleveragetheOpenWeb
ApplicationSecurityProject's(OWASP)ModSecurityCoreRuleSet.
Debian:aptgetinstalllibapache2modevasivelibapache2modsecurity
CentOS:yuminstallmod_evasivemod_security
TherearealsoApachemoduleslikeProjectHoneyPotthatmakeitharderforpeopletohack
yoursystem.HoneyPotcanalsobeinstalledonDrupal,butApacheisoftenmoreefficientat
addressingattackslikethisbeforeithitsPHP
Debian:aptgetinstallmod_httpbl
CentOS:yuminstallmod_httpbl
AllfilesanddirectoriesinyourDocumentRootshouldbeeditablebyanonrootuser,and
shouldalsonotbewritablebytheApacheuser,excepttheDrupalfiles/directory.Pleasereferto
DrupalsSecuringfilepermissionsandownershipforthecompletediscussion.
suPHPisatoolwhichrunsPHPscriptswiththepermissionsoftheirownerslettingyou
"sandbox"aPHPapplicationandsimplifyingfile/folderpermissions.Becarefultoconfigureboth
theUNIXuseraccountandsuPHPproperly.ItshouldnotbepossibletoCHOWNafiletoanother
userwithhigherprivileges,andyoushouldrestrictwhichuserssuPHPcanrunscriptsas.
SSLversions2and3arenolongerrecommendedaccordingtotheSSL/TLSDeploymentBest
Practices.ChangethewebserverSSLconfigurationtopermitonlyTLSv1.2andhigher.Check
iftheSSLservicesemployonlyAESwithkeylengths128bitsandhigher.Youcaninstall
GnuTLSfromthecommandlinetoenablethis:
Debian:sudoaptgetinstallgnutlsbin
ThereisacollectionofconfigurationscriptsonGitHubwhichprovidesexamplesofhardened
configurationfilesforSSL/TLSservices.IntheApacheconfigyoucansethardenedSSL
configurationsfortheHTTPSprotocolwith:
SSLProtocolAllSSLv2SSLv3
SSLHonorCipherOrderon
SSLCipherSuite"EECDH+ECDSA+AESGCMEECDH+aRSA+AESGCM
EECDH+ECDSA+SHA384EECDH+ECDSA+SHA256EECDH+aRSA+SHA384
EECDH+aRSA+SHA256EECDH+aRSA+RC4EECDHEDH+aRSARC4!aNULL!eNULL!LOW
BEASTattack!3DES!MD5!EXP!PSK!SRP!DSS"
AfterrestartingApache,youcanchecktheSSLinformationinabrowserbydoubleclickingon
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page13
thelockiconintheaddressbaronhttps://sitestogetinformationontheencryptionchanneland
confirmitsusingTLS.
AtthispointyoucantestyourSSLconfigurationthroughQualysSSLLabsServerTest.Thisis
afreeonlineserviceperformsadeepanalysisoftheconfigurationofanySSLwebserveronthe
publicInternet.ThiswillgradeyourSSLcomplianceanddothingslikeconfirmthatyouareusing
thelatestversionofTLSandverifythatyouareprotectedfromBEASTattacks.
Onyourstaging/devserveritisfinetoprovideaselfsignedSSLcertificatetoensurethatthe
trafficisencrypted.Settingupa3rdpartyverifiedSSLcertificateonyourproduction
environmentwillbeimportantasotherwiseyouruserswillbeaskedtoverifytheexceptionwhen
accessingtheHTTPSversionofyoursite.Alistingofcertificateauthoritiesisavailableatthe
bottomofthiswikipediapage.YoucanreviewthevalidityofyourSSLcertificatethroughafree
SSLTestconstructedbySSLLabsorwiththefollowingopensslcommand:
openssls_clientconnectSERVER:443
Tocheckaspecificprotocolusingopenssl:
openssls_clientconnectSERVER:443ssl2
openssls_clientconnectSERVER:443ssl3
1) Restricting Access
AnotherusefulApachemoduleismod_authz_hostwhichcanrestrictaccessto/user,/admin
andnode/*/edit.Itcanalsorestrictaccesstononproductionenvironmentswhichshouldalways
besecuredfromboththesearchenginesandespeciallyfromcrackers.
ExampleApacheconfigurationusingmod_authz_host:
<Location~/node/.*/edit>
OrderDeny,Allow
Denyfromall
Allowfrom206.47.13.64174.142.104.5399.241.125.191
</Location>
ExampleApacheconfigurationusingmod_rewrite:
<IfModulemod_rewrite.c>
RewriteEngineon
#Allowonlyinternalaccesstoadmin
RewriteCond%{REMOTE_ADDR}!^(206\.47\.13\.64|174\.142\.104\.53|99\.241\.125\.191)$
RewriteRule^admin/.*[F]
</IfModule>
DrupalhasanumberofprocessesthatcanbetriggeredbyURLs.Youmaywishtoblocksome
oftheseusingApachesothattheysimplycannotbeloadedfromthewebbrowser.Common
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page14
processestosecureareupdate,installandcronwhichcanallbeaccomplishedusingdrush:
ExampleApacheconfiguration:
RedirectMatch403"/(install|update|cron|xmlrpc).php"
2) Removing Code
CGIshavebeenusedextensivelyinwebdevelopmentandthereareagreatmanygoodserver
executablesthatyoumaywanttoconsiderrunning.However,manyCGIsthatmaybeinstalled
onaserverarenotactuallyneededandexposeyoutoanadditionalsecurityrisk.Ifyouarenot
runninganyCGIs,youshoulddisableCGIaccessbyremovingLoadModulecgi_moduleand
AddHandlercgiscript.cgifromyourApacheconfig.Youcanalsodothisfromthecommandline
with:
Debian:sudoa2dismodcgi
Ifyoudontneedit,removeit.Allsoftwareisasourceofpotentialrisk,solistallApache
modulesandlookforunneededmodules.Therearesomegooddiscussionsondrupal.orgabout
whichmodulesarenecessaryandwhicharenot.
Debian:apache2ctltDDUMP_MODULES
CentOS:apachectltDDUMP_MODULES
3) HTTP Headers
TheAustralianGovernmenthasproducedanimpressivereportInformationSecurityAdvicefor
AllLevelsofGovernmentwhichissadlyabitoutdatedasithasntbeenupdatedsinceearly
2012.Mostofthatreportisfocusedoncontentsecuritypolicy,HTTPstricttransportsecurity
andframeoptions.
TheSecurityKitDrupalmoduleaddressesmanysecurityproblemsassociatedwithHTTP
Headers,butitisgoodtohavethemaddressedattheApachelayerwherepossible.
TheW3Cisbuildingastandardcontentsecuritypolicy(CSP)toprovidesecuritycontrolswhich
canmitigateattackssuchasCrossSiteScripting(XSS).Mozillahasproducedagood
descriptionofhowtowriteaCSPandandtherearemanycommonalitieswiththeAustralian
Governmentreportabove.Toallowcontentfromatrusteddomainandallitssubdomains,you
canaddthefollowingtoyourApacheconfiguration:
ExampleApacheconfiguration:
ContentSecurityPolicy:defaultsrc'self'*.example.gc.ca
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page15
YourwebsiteanditsvisitorsaregoingtobemoresecureifyouuseHTTPStoensurethatall
informationpassingbetweenthewebserverandtheusersbrowserisencrypted.Thereare
performanceimplicationsfordoingthisasitdoestakeadditionalprocessingpower.You
certainlywanttoensurethatallauthenticationhappensthroughasecureHTTPSconnectionso
thatusernamesandpasswordscannotbeintercepted.
ExampleApacheconfiguration:
<VirtualHost*:80>
ServerAlias*
RewriteEngineOn
RewriteRule^(.*)$https://%{HTTP_HOST}$1[redirect=301]
</VirtualHost>
ThiscanbefurtherenhancedbyoptingintotheHTTPStrictTransportSecurity(HSTS)
enhancementwhichsendsaspecialresponseheadertothebrowser,whichthenpreventsany
communicationsfrombeingsentoverHTTPtothespecifieddomain.
ExampleHTTPSApacheconfiguration(seeexample):
HeadersetStrictTransportSecurity"maxage=16070400includeSubDomains"
WiththeuseofFrameOptions,userscanbeexposedtoClickjackingwhenaniframeis
injectedinyoursite.Ifyouknowthatyouarentgoingtoneedtouseiframesinyoursiteyoucan
disableitbymodifyingtheForceXFrameoptionsintheApacheconfiguration.Asusual,
OWASPhasanextremelyusefulguideonavoidingClickjacking.
ExampleApacheconfiguration:
HeaderalwaysappendXFrameOptionsSAMEORIGIN
4) Everything Else
ModifythewebserverconfigurationtodisabletheTRACE/TRACKmethodseitherbyemploying
theTraceEnabledirectiveorbyaddingthefollowinglinestoyourApacheconfiguration:
RewriteCond%{REQUEST_METHOD}^(TRACE|TRACK)
RewriteRule.*[F]
Youshouldkeepyourserveruptodate.Securitybyobscuritymaydelaysomecrackers,but
notpreventthemfromaccessingyoursystem.Broadcastinginformationaboutyourserver
environmentisntlikelytocauseanyharm,butifyouchoosetodisableityoucansimplyaddthis
toyourApacheconfiguration:
ServerSignatureOff
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page16
ServerTokensProductOnly
OneofthenicethingsaboutUbuntu/DebianisthattheApachefilestructureisclean.Bydefault
itallowsyoustoreavarietyofdifferentconfigurationsforsitesormodulesthatarestoredin
logicaldirectories.Thatsnotcritical,buthavingawelldefinedApacheconfigfileis.There
shouldbeinlinecommentsaboutallchangedvariablesexplainingwhytheywereaddedor
modified.
Itispossibletorestricttheoutgoingaccessofthewebserverbyleveragingiptables
uidowneroptionontheOUTPUTtable.Firstyoushouldknowwhichuser/UIDyourweb
serverrunsas.Typicallythisiswwwdata(uid33)inDebian/Ubuntuandnobody(uid65534)
inCentOS.Doublecheckbyviewingtheoutputof
Debian:psaux|grepapache
CentOS:psaux|grephttp
InordertorestrictApachetoconnectonlytohttps://drupal.org(withIPaddresses140.211.10.62
and140.211.10.16atthetimeofwriting)insertthefollowingfirewallrules:
iptablesAOUTPUTmowneruidowner${APACHE_UID}pudpdport53j
ACCEPT
iptablesAOUTPUTd140.211.10.62/32ptcpmowneruidowner${APACHE_UID}
mtcpdport443jACCEPT
iptablesAOUTPUTd140.211.10.16/32ptcpmowneruidowner${APACHE_UID}
mtcpdport443jACCEPT
iptablesAOUTPUTmowneruidowner${APACHE_UID}mstatestateNEWj
DROP
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page17
F) PHP
TherearelotsofgoodresourcesonhowtotightendownPHP.Itisaverycommonlyused
scriptinglanguageanditisrunningsomeofthebiggestandmostimportantsitesontheInternet.
WerecommendinstallingaPHPhardeningtoolcalledSuhosinwhichtightensupPHPsexisting
configurationsothatitismorerobust.Itisdesignedtoprotectserversandusersfromknown
andunknownflawsinPHPapplicationsandthePHPcore.
Ubuntu:Enableuniverserepoin/etc/apt/sources.listand`aptgetupdateaptgetinstall
php5suhosin`
Debian:aptgetinstallphp5suhosin
CentOS:yuminstallphpsuhosin
AgoodcomprehensivelistisfromJustinC.KleinsblogpostHardeningPHPfromphp.ini.Other
thanhiscommentsonsafe_mode,wethinkhesgotitright.Drupalneedssafe_modeenabled
inPHPanditreallyisntconsideredmuchofasecurityenhancementtodisableit.
AswithApacheModules,lookforwhatyoucanremove.YoucandisplayalistofenabledPHP
modulesandlookforthosewhichcanberemoved.Fromthecommandlineyoucangetalistof
phpmoduleswith:
phpm
SettingPHP.iniVariables
ManyPHPvariablescanbesetviaApacheaswellasinthePHPconfiguration.Werecommend
keepingPHPspecificsecurityconfigurationcentrallylocatedinthephp.inifile.
AnotherexploitisSessionfixationwhereauser'sbrowsersessioncanbehijackedbya3rd
party.OWASPgoesintomuchmoredetail,butusingtheHttpOnlyflagwhengeneratingacookie
youcanreducetheriskofanXSSattackbylimitingaccesstoprotectedcookies.Itisadvisedto
stopJavascriptfromaccessingcookiedata.Sessioninformationshouldonlyeverbepassedto
theserverwiththesamedomain.Youcanalsosetasecurecookieattributeandrestrictall
transmissionofcookiedatatoanHTTPSconnectiontoensurethatthecookieislesslikelytobe
exposedtocookietheftviaeavesdropping.Furthermore,youcancontrolthehashalgorithm
usedtogeneratethesessionIDandchoosefromanumberofalgorithmsliketheNSAsSHA2
protocolorwhirlpool.Addthefollowingtoyourphp.inifile:
session.cookie_httponly=1
session.use_only_cookies=1
session.cookie_secure=1
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page18
session.hash_function=whirlpool
Youcanobtainalistoftheavailablehashfunctionsonyoursystembyexecuting:
phprprint_r(hash_algos())
LimityourexposuretojustwhatonlythesystemresourcesyouwanttomakeavailabletoaPHP
page.Youcancontrolyourresourcesbylimitingtheupload_max_filesize,max_execution_time,
max_input_time,memory_limitvariablessothatascriptisntaslikelytomonopolizeresources.
php_valuememory_limit=128M
php_valuemax_input_time=60
php_valuemax_execution_time=30
php_valueupload_max_filesize=2M
Bykeepingupwithsecurityreleasessomewillarguethatthereisnoneedtohidewhichversion
ofPHPyouarerunning.ThereisabroaderdiscussionofthisdebateinSectionK.InthePHP
settingyoucanalsolimitinformationaboutPHPwhichisexposedbyaddingthistoyourphp.ini
file:
expose_php=Off
YoucanalsoexplicitlydisablePHPfunctionswhichallowscriptstoreferenceotherURLs.
allow_url_include=Off
allow_url_fopen=Off
YoucanalsodisablePHPfunctionswhichareconsidereddangerous.Youwillwanttotestto
seethatyourDrupalinstalldoesntrequireanyofthesefunctions.YoucangrepfromtheDrupal
roottofindoutifyoursiteusesanyofthesefunctions.DrupalsPHPfilterleveragestheexec()
function,howevertherearelotsofgoodreasonsnottousethePHPfilter.Youcanaddthisto
yourphp.inifile:
disable_functions=php_uname,getmyuid,getmypid,passthru,leak,listen,diskfreespace,
tmpfile,link,ignore_user_abord,shell_exec,dl,set_time_limit,exec,system,highlight_file,
source,show_source,fpaththru,virtual,posix_ctermid,posix_getcwd,posix_getegid,
posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,
posix_getpgid,posix_getpgrp,posix_getpid,posix,_getppid,posix_getpwnam,posix_getpwuid,
posix_getrlimit,posix_getsid,posix_getuid,posix_isatty,posix_kill,posix_mkfifo,posix_setegid,
posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setuid,posix_times,
posix_ttyname,posix_uname,proc_open,proc_close,proc_get_status,proc_nice,
proc_terminate,popen
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page19
Drupalsstatuspagehasalinktotheoutputofphpinfo()andyoushoulddecidewhetherornot
youwanttoexcludethatfunctioninthislist.
YouwanttobeabletolimitwhatPHPhasaccesstointhefilesystem.Notethatyoumaywant
togiveslightlymoreaccesstoPHPthanjusttheDrupalrootdirectoryasitcanbebeneficialto
putsomefiles(likeasalt.txtfile)outsideofthebasedirectory.ThiscanalsobesetinApache,
butIvetriedtokeepthePHPspecificinformationinsidethephp.inifile:
open_basedir=/var/www
Makesurethesessionpathisoutsidetherootwebdirectoryandnotreadableorwritable
byanyothersystemusers.Youwillalsowanttosetatemporaryuploadfiledirectorythatis
outsideofthewebroot.Thiscanbespecifiedinthephp.inifile:
session.save_path="/tmp"
upload_tmp_dir="/tmp"
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page20
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page21
fullaccesstoyourdatabases.ItcanbebeneficialtoputphpMyAdmininit'sownVirtualHostand
evenrunitonanonstandardport.ForceHTTPSconnectionstophpMyAdmindonotuse
regularHTTP.Alsoconsidertheimplicationsofallowingdatabaseaccessviathewebserver:
ThereislittlebenefitifyouhaverestrictedwhichinterfacesMySQLwilllistenon,asdescribed
above,butthenallowcontrolofthedatabasefromanInternetfacingwebpage.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page22
H) Drupal
1) Files
VerifyDrupalfilepermissionsontheserver.Youreallyneedtorestrictwriteaccesstothe
serverandverifythattherightusers/groupshavetheaccessthattheyneedforDrupaltooperate
effectively.
Drupalneedstobeabletowritetotheservertobeabletoperformcertaintaskslikemanaging
fileuploadsandcompressing/cachingCSS/JSfiles.EnsurethatApachehaswriteaccessto
/tmpandalsotothepublicsitesfolder:
Debian:chownRwwwdata:wwwdatasites/default/files
CentOS:chownRnobody:nobodysites/default/files
Makesurethatyouareonlyallowinguserstouploadfiletypesthathavelimitedsecurity
problemswiththem.Textandimagesareusuallyquitesafe.Therehavebeensomeexploitson
PDFfiles,buttheyarequiterare.MicrosoftOfficedocumentsshouldbescannediftheyare
goingtobeuploadedontotheserver.ClamAVcanbeincorporatedintoDrupaltoscanuploaded
filesforvirusesandothermaliciouscode.
2) Drush
DrushisacommandlineshellandscriptinginterfaceforDrupal.Westronglyrecommendusing
Drushonbothstagingandproductionserversbecauseitsimplifiesdevelopmentand
maintenance.NotethattheversionofDrushpackagedwithyourOSislikelytobeextremelyout
ofdate.Forthelateststableversion,itshouldbeinstalledusingPHPsPEAR:
pearchanneldiscoverhttp://pear.drush.org/
pearinstalldrush/drush
ThereisaSecurityCheckmoduleavailableforDrushwhichisabasicsanitytestforyour
configuration.Whenthemoduleisadded,youcanrunthisagainstyoursitefromthedocrooton
thecommandlineusing:
drush secchk
Aswiththeserverconfigurationingeneral,documentwhatyouareusing.Drushmakesthis
fairlystraightforwardasyoucansimplyexportalistfromthecommandline:
drushpmlisttype=Modulestatus=enabled
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page23
CronistheLinuxtimebasedjobscheduleranditisusedforalotofkeyDrupalfunctions.
Checktoseethatyouarerunningcronseveraltimesaday.Thestatuspagewilltellyouwhen
thelasttimecronwasrunonthesite.Tosetcronyoushouldbeabletouseavariationofthis
usingDrush.Fromthecommandlineentercrontabeandtheninsert:
302,6,11,18***cd/home/drupal&&drush@sitescorecrony>/dev/null
Youwillneeddevelopermodulestohelpyoubuildyoursite,buttheyareasecurityriskonyour
productionsiteandneedtobedisabled.Manymodules(suchasViews)haveseparate
administrationscreensthatcanalsobedisabledonaproductionenvironment.Theyare
absolutelyrequiredwhenbuildingthesite,butcanbedisabledwhentheyarenotinuse.This
alsooffersperformancebenefits.
Viewsisanincrediblypowerfulquerybuildingtool.Becauseofthat,itisimportantthatallViews
haveexplicitaccesspermissionssetat/admin/build/views
3) Errors
ChecktheStatusReportandWatchdogpagesregularlyandresolveissuesDrupalshouldbe
happy!Thisneedstobedoneregularly,evenafterlaunch.
Onyourproductionserver,makesuretodisablethedisplayofPHPerrors.Theseshouldbe
recordedtoyourlogs,butnotvisibletoyourvisitors.Onyourstagingsiteyouwillwanttosee
thoseerrorstohelpyoudebugPHPproblems,butitisapotentialvulnerabilitytohavethose
exposed.
Beforelaunchingyoursite(andperiodicallyafterwards)itisusefultoruntheHacked!moduleto
checkwhatcodediffersfromwhatwasreleasedonDrupal.org.Particularlywhenthediff
moduleisenabledthisisapowerfultooltoevaluateyourcode.Therearemillionsoflinesof
codeinagivenDrupalsite,soHacked!isareallyvaluableanalysistool.Ifyouneedtoapply
patchesagainstthestablereleasedversionofthecode,thepatchshouldbeinaclearly
documenteddirectory.
ItisunfortunatelyacommonpracticeforlessexperiencedDrupaldeveloperstocutcornersand
hackcoretoprovidesomefunctionalitythatisrequired.Therearelotsofreasonswhythisisa
badideaandwhyresponsibledevelopersdonthackCore.Forthepurposesofthisdocumentit
issufficienttosayitmakesithardertosecure.Thesameistrueforcontributedmodules,you
shouldnthavetoalterthecodetocustomizeitmostofthetime.TheHacked!moduleisvery
usefulinidentifyingwhenmodulesnolongerarethesameastheirreleasesonDrupal.org.
Beingabletoquicklyscanthroughhundredsofthousandsoflinesofcodeandfinddifferences
againstknownreleasesisahugesecurityadvantage.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page24
ItisrecommendedtorunallmodulesyouusethroughtheCodermodule,butespeciallyany
custombuiltmodulesandthemes.Thismodulecangiveyousuggestionsonhowtofollowthe
Drupalcommunitiescodingstandards.Itcanalsohelpyouidentifyothercodingerrorsthatmay
affectyoursite.ParticularlywhenbuildingcustommodulestheCodermodulecanhelpidentify
unsanitizeduserinput,SQLinjectionvulnerabilitiesandCrossSiteRequestForgery(CSRF)
problems.
4) Administration
Drupalhasaveryfinegrainedandcustomizablepermissionsmodel.Initssimplestform,users
areassignedrolesandeachroleisgivenpermissionstovariousfunctions.Takethetimeto
reviewroleswithaccesstoanyofAdministerfilters,Administerusers,Administerpermissions,
Administercontenttypes,Administersite,Administerconfiguration,Administerviewsand
translateinterface.Itisusefultoreviewthepermissionsafterupgradestoverifyifanynew
permissionshavebeenadded.
Dontuseadminasyouruser/1adminname.Itsthefirstonethatacrackerisgoingtotry,so
beabitmoreunique.Obscurityisntthesameassecurity,butnoneedtogivethemtheirfirst
guesswhenchoosingusernames.Aswithotherserveruseraccounts,youwillwanttorestrict
whohasaccesstoservers.Makesuretodeleteanytestaccountsontheproductionserver.
DontrunDrupalwithoutenablingtheUpdatemodulethatcomeswithCore.DrupalCoreand
contributedmodulesuseastructuredreleaseprocessthatallowsyouradministratorstobe
proactivelyalertedwhenoneofthosemoduleshasasecurityrelease.Anypieceofcodeis
susceptibletoasecurityissue,andhavingacentralrepositorythataDrupalsitecancompare
againstiskeytothesecurityparadigm.Asidefromthereleasesthathavefixesforknown
securityproblems,somemodules(oraversionofthatmodule)maybecomeunsupported.This
isalsoasecurityproblem,inthatyouwillnotreceiveupdatesiftherearesecurityproblemsthat
areidentifiedwiththemodule.TheUpdatemodulealsoallowsyoutogetadailyorweeklyemail
iftherearesecurityupgradesthatneedtobeapplied.
ItisunfortunatelyquitecommonfordeveloperstoextendDrupalbyforkingexistingprojectsand
notprovideenhancementsbacktothecommunity.Doingthisbreaksassumptionswithinthe
Updatemodulebutmoreimportantlymakesupgradesmuchmoredifficult.Evenwithaproperly
documentedpatch,itisalotofworktoupgrade,patchandrewriteafunctioninalivewebsite.
Bycontributingtheimprovedcodeupstream,youcanavoidthatoftenpainfulprocess.Thepeer
reviewthatcomeswithcontributingyourcodebacktothecommunityislargelyasecondary
benefit:youcontributeinordertoreduceyourbuscount.
Drupalsinputfiltersareverypowerful,butcanprovideavulnerability.DontenablethePHP
filterwhichisavailableinDrupalcore.Itmakesdebuggingmoredifficultandexposesyoursite
toagreaterriskthanitisworth.AllPHPcodeshouldbewrittentothefilesystemandnotstored
inthedatabase.AnotherinputfilterthatcanbeproblematicisFullHTMLwhichshouldonlybe
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page25
grantedtotrustedroles.Ifneeded,youcanaddsomeadditionaltagstotheFilteredHTMLinput
formatbutbecautious.
5) Modules
TherearealotofDrupalsecuritymodules.Dependingonyourneedsyouwillwanttoaddmore
orlessthanthoselistedhere.
ParanoiaLimitsPHPfunctionalityandothercontrols
SettingsauditlogLogswhodidwhat,when
SecurePermissionsDisablestheUItoset/changefilepermissions
PasswordpolicyEnforcesyouruserpasswordpolicy
LoginSecurityEnforcesHTTPSconnectionstoparticularlocations
ClearPasswordFieldStopsformsfromprepopulatingapassword
SecurityReviewProducesaquickreviewofyoursitessecurityconfiguration
ShieldProtectsyournonproductionenvironmentfrombeingaccessed
LocalimageinputfilterAvoidsCSRFattacksthroughexternalimagereferences
SecurityKitHardensvariouspiecesofDrupal
DrupalTinyIDSAnalternativetoaserverbasedIntrusionDetectionService
6) Drupal Distributions
DrupaldistributionsarestartingpointsforDrupalmodulesandoftentheirconfigurationswhich
areoptimizedforspecificpurposes.Therearenowtwodistributionswhichhavebeen
specificallybuiltforsecurity,GuardrandHardenedDrupal.GuardrisbuilttofollowtheCIA
informationsecuritytriad:confidentiality,integrityandavailability.Itisworthwatchingthe
evolutionofthesedistributionsandinstallingthemfromtimetotimeifonlytohaveacomparison
ofmodulesandconfigurationoptions.
7) Miscellaneous
ReviewthediscussioninSectionKanddecideifyouaregoingtoremovetheCHANGELOG.txt
file.Ensurethatyoucankeepupsecurityupgradesonaweeklybasisanddonothackcore!
Ifyouplantobeabletodistributeyourlivesitesothatyoucandotestingordevelopmentoutside
ofacontrolledenvironment,considerbuildingasanitizedversionofthedatabase.Thisis
especiallyimportantifyouhaveuserinformationstoredinthedatabase.Formanygovernment
sitesthismaynotbenecessary.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page26
Theroleofthestagingserveristodocumentandtestthemigrationprocesstoverifythatthe
codeandconfigurationcanmoveontoanotherserver.Formoreinformationreferto
OpenConceptsblogpostonthepathofcodevscontent.
ThecodeforyourDrupalsiteshouldbestoredinacentralrepository.TheDrupalcommunity
hasgenerallyadoptedGit,butthereareothervalidoptionsforversioncontrol.Adeveloperwill
pull/push/clone/branchto/fromthatrepository.Newcodeiscommittedandpushedfromthe
developmentenvironmentintothecentralrepository,andcanthenbepulledontothestaging
environment,andifitpassestestingtherecanthenbepulledonproduction.Thedatabaseon
thestagingservercansimplybeclonedfromtheproductionserverusingDrush.Assumingthat
thenewcodeworkswellwiththeproductiondatabase,youcanbereasonablycertainthatyou
willbeabletomigratethatcodeandconfigurationtotheproductionsite.Thisisdefinitelymore
complicated,butboththestagingandproductionenvironmentswillneedtobeaccessiblevia
DrushandtheGitrepository.
YouwillneedtosetupanSSHuserwithitsownSSHkeystoallowyoutouseDrushaliasesto
transferdatabasesbetweenstagingandproduction.Youmayalsowanttohaveanother
accounttobeabletotransferuploadedfileswhichprobablywouldnotbemanagedunder
versioncontrol.
UsinganexternalsitelikeGitHubprovidessomegreatadditionaltoolslikeTraviswhichprovides
simplecontinuousintegrationwithasolidsecureframework.Youcanalsosetituponyour
stagingordevelopmentserver.
Limitaccessbetweenservers.Thereisapotentialriskfromhavingasemiporousboundary
betweentheseenvironments,buttherisksarefaroutweighedbythebenefits.Havingacentral
Gitrepositorygivesyoucontrolacrossallenvironmentsatonetime.Beingabletodiffany
changeallowsyoutoquicklyidentifywherechangeshavebeenmadeandknowwhy.Drushis
certainlypowerful,butonlyexperiencedusersshouldhaveaccesstoit.Withasolidbackup
plan,evenifthisiscompromised,itcanbequicklyrestored.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page27
J) Regular Maintenance
Nosecurityplanisfoolproof.Youneedregularbackupstoensurethatyoucanrestoreyour
systemquicklyifrequired.Withboththedatabaseandfilesystemitisimportanttohaveboth
localandremotebackups.Youwantthelocalbackupbecausethatallowsyoutoquicklyrestore
thesiteifthereisaproblem.Youwantaremotebackupincaseoftotalsystemfailure.There
aremanywaystosetupandconfigurethis.Somehelpfulbackupsolutionsinclude:
Bacula
rsync/rsnapshot
mysqldump
Rememberthatabackupisonlygoodifitcanberestored.Itsabestpracticetomakeuseof
RAIDdrives,butRAIDshouldbeusedasafailsafeandnotconsideredabackupstrategy.
Backupsshouldbestoredregularlylocally,buttherealsoneedtoberegular,longtermbackups
storedoffsite.Makesuretoevaluateyourbackupproceduresandtestyourrestorestoverify
thattheyareworkingeffectively.
Drupal.orgreleasessecurityupdatesonWednesdayswhenneededwhicharebroadcastbyan
emaillist,RSSfeedsandTwitter.Subscribetothesecuritynewsletterforupdates(youwillneed
aDrupal.orgaccountandtheinstructionsareonthesidebarofthepreviouslink).Itisalso
usefultochecktheStatuspageandWatchdogpagesinyourDrupalsite.
SELinuxprovidesauditingserviceswhichareworthmonitoring.Youshouldbewatchingyour
serverlogs,particularlyyourApacheerrorlog:
tail -f /var/log/httpd/error_log
grep 'login.php' /var/log/httpd/error_log
egrep -i "denied|error|warn" /var/log/httpd/error_log
Securitybestpracticesareconstantlychanging.EarlierthisyearOWASPreleasedtheirTop10
for2013anditissomewhatsimilartothe2010list.TheTop10for2010wasleveragedtolook
athowitappliestoDrupal.Thisneedstobeupdated,andreviewed,particularlyifyouarewriting
anycustomcode.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page28
1) Make it Obscure
LeavingaCHANGELOG.txtfilevisibledoesnothingtoimprovesecurity,ratheritonlyhelps
informanattackerhowtofocustheirresearcheffortstofindazerodayattack,acontribmodule
vulnerabilityevenfaster,orjustdisableanyscriptedattacksthatmightbedesignedtobeJoomla
orWordpressspecific.JustinC.KleinKeaneinhisblogOpensourcesoftwaresecuritystrongly
recommendshidingboththeDrupalandserveridentification.
2) Make it Transparent
InmanycaseswheretheCHANGELOG.txthasbeenremoved,itisbecausethewebmaster
hasntdoneaDrupalCoreupgradeandtheyarelookingforawaytoobscurethatfact.By
keepingtheCHANGELOG.txtuptodateattheveryleastitindicatesthatsomeoneispaying
attentiontosecurityupdates.
ThereareeasywaystofingerprintDrupalandthesecurityteamcouldhideaccesstothisfilein
the.htaccessfilethatcomeswithDrupalCoreiftheywereconcerned.
Bymakingittransparent,thereisanadditionalreasonfordeveloperstomakeitapriorityto
upgradeCorewhenthereisasecurityrelease.
3) Be consistent
Ultimatelyonehastoknowtheorganizationandindividualsthataremaintainingthesite
determineifitisbettertohidetheCHANGELOG.txtormakeitvisible.Whatthereisagreement
onisthatwhensecurityreleasesareannounced,thatdevelopersapplythemquicklysuchthat
thesitecannotbecompromised.
TheLinuxdistribution,Apache&PHPalsoannounceinformationbydefaultwhichcanbeturned
offintheirconfigurationfiles.Itisgoodtobeconsistentandhaveyourreasoningdocumented
sothatitisclearlyunderstood.
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page29
L) Additional Resources
1) General guidelines
Drupalsecurity
Standards,securityandbestpracticesDrupal.orgwiki
WritingsecurecodeDrupal.orgwiki
SecuringyoursiteDrupal.orgwiki
DrupalSecurityGroupDiscussion
DrupalSecurityReportAcquia
DrupalSecurityAcquia
Security:Howtheworld'slargestopensourceCMScombinesopen&securityAcquia
Drupal,SSLandPossibleSolutionsAcquia
DrupalWatchdogMagazineSecurityEdition
Securehosting
Linux:25PHPSecurityBestPracticesForSysAdminsNixcraft
HardeninganSSLserveragainsttheNSAxin.at
SecurityinaBoxTacticalTechnologyCollective
LinuxSecurity.com
COTSSecurityGuidance(CSG)(CSG09\G)IntrusionPreventionSystem(IPS)CSEC
COTSSecurityGuidance(CSG)(CSG10\G)OverviewofOSSecurityFeaturesCSEC
HowtoDeployHTTPSCorrectlyEFF.org
2) Videos
DoingDrupalSecurityRightDrupalConLondon
BuildingandSecuringGovernmentDrupalSitesintheCloudDrupalConDenver
SecuringDrupalSitesforGovernmentAgenciesAcquia
DrupalVideosAboutSecurityonArchive.org
SemanticForgeriesinDrupal'sFormAPIGregKnaddison
RetinaNetworkSecurityScannerbeyondtrust.com
NstalkerWebApplicationSecurityScanner
SyhuntWebSecurityAudits
GreensqlDatabaseSecurity
4) Books
CrackingDrupalbyGregKnaddison
O'Reilly.com'sLinuxServerSecuritybyMichaelD.Bauer
HackingLinuxExposedbyBriHatch&JamesLee
AnnouncementofNewCyberSecurityBookspublishedbyscitech
SELinuxSystemAdministrationbySvenVermeulen
ThisisaLivingDocument.Pleasecontributeenhancements
Version0.9.2Page30