WordPress security & hardening, the definitive guide
文章推薦指數: 80 %
Is WordPress secure? Plugins and themes. Run less software; Observe the least privileged principle; Update your WordPress plugins and themes ...
WordPresssecurity&hardening,thedefinitiveguide
LastupdatedonAugust24th,2021byMarkGrima.Filedunder
WordPressSecurity
Home
WordPressSecurityBlog
WordPresssecurity&hardening,thedefinitiveguide
WordPressismassivelypopular.AroundeveryoneinfivesitesontheInternetusesWordPressinsomeform.Bethattorunahumbleblog,oramulti-siteContentManagementSystem(CMS)ore-commercesite.Asaresult,itisnosurprisethatWordPresswebsitesareaverypopulartargetforbothexperiencedhackersandscript-kiddiesalike.
Thelastthinganywebmasterwantsistofindoutthattheirwebsitehasbeenhacked;maybetakenhostageandispartofabotnet,spreadingmalware,orpartakinginDenialofService(DoS)attacks.Inthisarticlewe’llbesharinganumberoftipsandstrategiestohelpyouhardenyourWordPresswebsite.
Tableofcontents
IsWordPresssecure?
Pluginsandthemes
Runlesssoftware
Observetheleastprivilegedprinciple
UpdateyourWordPresspluginsandthemes
Stayawayfrom‘nulled’WordPresspluginsandthemes
KeepWordPressuptodate
WordPressHosting
WordPressdashboard
Disableregistration
Credentials
Two-FactorAuthentication(2FA)
HardeningWordPresscore
Disabledebuglogging
DisableXML-RPC
RestricttheWordPressRESTAPI
PreventWordPressversiondisclosure
PreventWordPressuserenumeration
DisabletheWordPressfileeditor
Disablethemeandpluginmanagement
TLS(SSL)
Conclusionsandnextsteps
IsWordPresssecure?
Thisisaquestionmanysystemadministratorsask,andrightfullyso.WhileWordPressisoverallwell-builtandsecure,ithasareputationforbeingpronetosecurityvulnerabilitiesandnotbeing“enterprise-grade”.Thatreputationisnotexactlyfair.Moreoftenthannot,issueslieinWordPressbeinganincrediblypopularsoftwarepackagewhichiseasytosetupwhiletakingsecurityshortcuts.Whichbringsustoourfirsttopic—pluginsandthemes.
Pluginsandthemes
ThenumberoneissuewhichplaguesWordPresssecurityisalsowhatmakesitincrediblypopular.WordPresspluginsandthemesvaryfarandwideintermsofqualityandsafety.WhilealotofworkhasbeendonebytheWordPressteamtohelpdevelopersbuildmoresecurepluginsandthemes,theystillremainasecuritynightmare.Thiscanbenoticedwhenusingpoorlymaintainedplugins,orpluginsobtainedfromasketchysource.
BeforewecontinuediscussingWordPresspluginsandthemes,let’sfirstunderstandwhataWordPresspluginactuallyis.PluginsaresimplycustomPHPcodethatWordPressrunsinordertoextendWordPress’sfunctionality.ForamoredetailedandtechnicalexplanationrefertoWhatareWordPressplugins.
Similarly,WordPressthemesallowforthecustomizationofthevisualaspectsofyourWordPresssite.Fromanattacker’sperspective,thereisverylittledifferencebetweenthetwosincebothcanbeabusedtorunmaliciouscode.
Runlesssoftware
Sohowcanyoutellifapluginismaliciousornot?That’sacomplicatedquestion,butfortunatelywehaveananswerforyou.WehavewrittenaboutthisindetailinhowtochoosethebestWordPresspluginforyourWordPresswebsite.
Eventhoughyoumakeallthenecessaryresearch,therearealsochancesthatthepluginmightstillbeasecuritythreat.Sooneofthewaystoreduceyourriskistoonlyrunthesoftwareyouabsolutelyneedandtrust.BeforeinstallinganewWordPresspluginaskyourselfifyoureallyneedtoinstallthatplugin.Canasmallcodesnippetinasite-specificplugindothetrick,ordoyoulegitimatelyneedafullyblownplugin?
Important—beveryvigilantwithcodesnippetsyoufindontheInternet.Neveruseapieceofcodeunlessyoufullyunderstandwhatit’sdoing—justbecauseit’sonStackOverflow,itdoesn’tmeanit’ssafetouse.
Ifyouhaveagenuineneedtorunaplugin,makesureit’sactivelymaintainedandregularlyupdatedasweexplaininourguide.Asaruleofthumb,themoredownloadsandrecentupdatesthepluginorthemehasindicatesthatitisinwideuseandthatitisbeingactivelymaintainedbyitsauthors.Thisdoesnotmeanthatthepluginwillneverhaveavulnerability.However,ifavulnerabilityisfound,thedeveloperwillactquicklyandissueafixquickly.
Trytoavoidpluginswhichdon’thavemanydownloadsandcritically,donothaveanactivecommunityandregularupdates.Ifsomethinghasn’treceivedanupdatewithinayear,it’sgenerallyaredflag.
Observetheleastprivilegedprinciple
WordPressdoesnotneedtousetheMySQLrootusertoconnecttoitsdatabase.NordoeseveryWordPressuserneedtohavetheroleofanadministrator.Similarly,it’snotagoodideatorunmostprogramsasaprivilegeduser,unlessthereisaspecificreasontodoso.
Securitybestpracticealwaysdictatesforapplicationstoalwaysbegiventheleastprivilegespossiblethatallowittoworkproperly,withanyadditionalprivilegesdisabled.Thispracticeiscommonlyreferredtoastheprincipleofleastprivilege.
Let’shypotheticallyassumeWordPressisconnectingtoadatabasewithaprivilegeduseraccount.IntheeventofaWordPressplugincontaininganSQLinjectionvulnerability,anattackermaybeabletonotonlyrunSQLqueriesasanadministrator,butinsomecasestheymayevenbeabletoexecuteoperatingsystemcommands.Ifanattackerissuccessfulinexecutingoperatingsystemcommands,theymaybeabletocarryoutreconnaissanceandescalateanattackfurthertoothersystems.
Runningsoftwarewithadministrativeprivileges,orprovidinguserswithmoreaccessthannecessaryisaskingfortrouble.Itgoesagainstatried-and-testedleastprivilegeprinciple,sinceitallowsanattackertoinflictmoredamageintheeventofasecuritybreach.
ThegoodthingwithWordPressisthatishasanumberofbuilt-inroles,whichyoucanusetoassigndifferentprivilegestodifferentusers,dependingontheirrequirements.WehavewrittenextensivelyaboutthisinhowtouseWordPressuserrolesforimprovedWordPresssecurity.
UpdateyourWordPresspluginsandthemes
WordPresspluginandthemesupdatesareimportantnotjusttobenefitfromnewfunctionalityandbugfixes,butalsotopatchsecurityvulnerabilities.BothpluginsandthemesareeasytoupdatewithintheWordPressinterface.
Somecommercialpluginswilllikelyhavetheirownmechanismstokeeppluginsuptodate,however,inmostcasesthisistransparenttotheusers.Nonetheless,justmakesurethatwhateverupdatesystemisbeingused,youkeepyourpluginsandthemesuptodate.
Donotuse‘nulled’WordPresspluginsandthemes
WordPressmakesuseoftheGPL1.Withoutgoingintomuchdetail,theGPLlicenseallowsforanyonetofreelydistributeGPL-licensedsoftware.Thisincludescommercial/premiumGPL-licensedWordPressthemesandplugins.Assuchitmaynotbeillegaltodownloadamodified,usuallyreferredtoasnulled,premiumthemeorpluginanduseitforfree.
However,asyoumayhavealreadyguessed,asidefromnotsupportingtheplugindeveloper,youareveryunlikelytoreceiveupdatesfornulledplugins.What’smore,youhavenowayofknowingifthesourcetothispluginhasbeenmodifiedtodosomethingnefarious.
KeepWordPressuptodate
Justlikeyoushouldkeepyourpluginsandthemesuptodate,youshouldalsomakeitapointtokeeptheversionofWordPressyou’rerunninguptodate.Fortunatelythisisnowmucheasierthanitwasinthepast,withcriticalsecurityupdatesoccurringautomatically.Ofcourse,unlessyouexplicitlydisablethisfunctionality.
Asidefromnewfeatures,improvementsandbugfixes,WordPresscoreupdatesalsocontainsecurityfixeswhichmayprotectyoufromattackersexploitingyourWordPresswebsiteandusingitforill-gottengains.
WordPressHosting
WhereandhowyouchoosetohostyourWordPresssitewillhighlydependonyourrequirements.WhilethereisnothingwrongwithhostingandmanagingWordPressyourself,ifyouareeithernotastechnicallysavvy,oryouwanttomakesuretomeetmostoftheWordPresssecuritybasicswithoutdoingalotofheavylifting,youmaywanttooptforamanagedWordPresshostingprovidersuchasKinstaorWPEngine.
Sincewehavehadwebsiteshostedwithbothhosts,wehavewrittenaboutthem.Inourcustomerstorieswehighlightourexperiencewiththem.TolearnmoreaboutyourexperiencereadourWPEngineandKinstacustomerstory. ManagedWordPresshostingabstractsawayalotofsecuritydecisionsandconfigurationyouneedtootherwiseworryaboutyourself.
Naturally,managedWordPresshostingmayalsonotbeforyou.YoumayopttohostWordPressyourself,especiallyifyou’rebudgetconstrained.SelfhostingWordPressalsogivesyougreatercontroloveryourWordPressinstallation.TolearnmoreaboutallthedifferentWordPresshostingoptionsandwhatworksbestforyourefertotheguidetochoosingWordPresshosting.
WordPressdashboard
Yoursite’sWordPressdashboardisaplaceyoudon’twantanyoneunauthorizedtobelurking.WhiletherearesomesitesthathavelegitimatereasonstoallowpublicuserstologinusingtheWordPressdashboard,thisisahugesecurityriskandmustbeverycarefullyconsidered.
Fortunately,mostWordPresswebsitesdonothavethisrequirementandassuchshouldpreventaccesstotheWordPressdashboard.Thereareseveralwaystodothisandyoushouldpickwhatworksbestforyou.
AcommonpracticeistorestrictaccessbypasswordprotectingtheWordPressAdmin(wp-admin)pages.Anothersolutionwouldbetoonlyallowaccessto/wp-admintoanumberofselectedIPaddresses.
Disableregistration
Bydefault,WordPressdoesnotallowpublicuserstoregistertoyourWordPresswebsite.Toconfirmthatuserregistrationisdisabled:
headovertoSettings>GeneralpageinyourWordPressdashboardarea
navigatetotheMembershipsection
ensurethatthecheckboxnexttoAnyonecanregisterisnotselected.
Credentials
Likeanyotherwebsite,accesstoyourWordPressdashboardisonlyasstrongasyourcredentialsare.EnforcingstrongWordPresspasswordsecurityiscrucialsecuritycontrolofanysystem,andWordPressisnoexception.
WhileWordPressdoesnothaveanywaytosetapasswordpolicyoutofthebox,apluginsuchasWPasswordisanabsoluteessentialtoenforcepasswordstrengthrequirementsacrossallofyouruserswhohaveaccesstotheWordPressdashboard.
OnceyouenforcestrongpasswordsecurityonyourwebsiteuseWPScantotestforweakWordPresscredentials,tomakesurenoaccountisstillusingweakpasswords.
Two-FactorAuthentication(2FA)
AnotheressentialsecuritycontrolforyourWordPressdashboardistorequiretwo-factorauthentication.Two-factorauthentication(2FA)makesitsignificantlyharderforanattackertogainaccesstoyourWordPressdashboardshouldanattackermanagetouncoverauser’spassword(e.g.anattackermaydiscoverauser’spasswordfromadatabreach).
Luckily,itisveryeasytosetuptwo-factorauthenticationonWordPress.Thereareanumberofhighqualitypluginsyoucanusetoaddthisfunctionality.Readthebesttwo-factorauthenticationpluginsforWordPressforahighlightofthetop2FApluginsavailableforWordPress.
HardeningWordPresscore
EventhoughWordPress’scoreisasecurepieceofsoftware,itdoesn’tmeanthatwecan’thardenitfurther.ThefollowingareanumberofhardeningstrategiesspecifictotheWordPresscore.
Makesuredebugloggingisdisabled
WordPressallowsdeveloperstologdebugmessagestoafile(thisbeing/wp-content/debug.logbydefault).Whilethisisperfectlyacceptableinadevelopmentenvironment,keepinmindthatthisfilecanalsobeeasilyaccessedbyanattackerifthesamefileand/orsettingsmaketheirwaytoproduction.
WordPressdebugisdisabledbydefault.Thoughitisalwaysbettertodoublecheckitis—ensureyoudonothavetheWP_DEBUGconstantdefinedinyourwp-config.phpfile,orexplicitlysetittofalse. RefertotheWordPressdebugguideforalistofallthedebuggingoptions.
IfforsomereasonyouneedtheWordPressdebuglogsonyourlifewebsite,logtoafileoutsideofyourwebserverroot(e.g./var/log/wordpress/debug.log).Tochangethepa
define('WP_DEBUG_LOG','/path/outside/of/webserver/root/debug.log');
DisableXML-RPC
TheWordPress’sXML-RPCspecificationwasdesignedtoallowcommunicationbetweendifferentsystems.ThismeansthatvirtuallyanyapplicationcouldinteractwithWordPress.TheWordPressXML-RPCspecificationhashistoricallybeenimportantforWordPress.Itallowsittointeractandintegratewithothersystemsandsoftware.
ThegoodthingisthatXML-RPChasbeensupersededbytheWordPressRESTAPI.TohighlightsomeofthesecurityconcernsaroundXML-RPC;it’sinterfacehasbeenthesourceofnumeroussecurityvulnerabilitiesovertheyears.Italsocanbeusedbyattackersforusernameenumeration,passwordbruteforcing.ordenialofservice(DoS)attacksviaXML-RPCpingbacks.
ThereforeunlessyouareactivelyusingXML-RPCandhaveappropriatesecuritycontrolsinplace,youshoulddisableit.Sincethisissomethingeasilyachievablewithoutinstallingathird-partyplugin,we’llcoverhowtodosobelow.
Whileyoumaysimplyconfigureyourwebservertoblockaccessto/xmlrpc.php,apreferredmethodofdoingthisistoexplicitlydisableXML-RPCusingabuilt-inWordPressfilter.Simplyaddthefollowingtoapluginfileandactivateitonyoursite.
add_filter('xmlrpc_enabled','__return_false');
Headsup
It’sagoodideatomakeuseofaWordPressmustusepluginforthisandothersimilarcodesnippets.
RestricttheWordPressRESTAPI
InthesameveinasXML-RPC,theWordPressAPIisthemodernwayforthird-partyapplicationstocommunicatewithWordPress.Whileitissafetouse,itisadvisabletorestrictsomefunctionswithinittopreventuserenumerationandotherpotentialvulnerabilities.UnlikeXML-RPC,WordPressdoesnotprovideasimple,nativewaytodisabletheRESTAPIentirely(itusedto2,butthisgotdeprecated,soit’swisenottodosoanylonger),however,youcanrestrictit.
AsistypicalwithWordPress,youmayeitheruseaplugintoachievethis,oryoucanaddthefollowingfiltertoapluginfileandactivateitonyoursite.ThefollowingcodewilldisabletheWordPressRESTAPIforanyonewhoisnotloggedinbyreturninganunauthorizedHTTPstatuscode(statuscode401)usingtherest_authentication_errorsWordPresshook.
add_filter('rest_authentication_errors',function($result){
if(!empty($result)){
return$result;
}
if(!is_user_logged_in()){
returnnewWP_Error('rest_not_logged_in','Youarenotcurrentlyloggedin.',array('status'=>401));
}
return$result;
});
Additionally,theWordPressRESTAPIenablesJSONPbydefault.JSONPisanoldtechniqueforbypassingthebrowser’ssameoriginpolicybeforemodernbrowserssupportedCORS(Cross-originResourceSharing).Sincethiscouldpotentiallybeusedasastepinanattackbyanattacker,thereisnorealreasonforthistobeenabled.Itisrecommendedtodisableitusingtherest_jsonp_enabledWordPressfilterusingthefollowingPHPsnippet.
add_filter('rest_enabled','__return_false');
Refertothefilter’sdocumentationformoreinformationaboutit.
PreventWordPressversiondisclosure
Likemanyotherwebapplications,bydefault,WordPressdisclosesitsversioninanumberofplaces.Versiondisclosureisn’texactlyasecurityvulnerability,howeverthisinformationisveryusefulforanattackerwhenplanninganattack.Asaresult,disablingWordPress’sversiondisclosurefeaturesmaymakeanattackjustalittlebitmoredifficult.
WordPressleaksalotofversioninformation.Luckily,thisGitHubgistoffersacomprehensivelistofWordPressfilterstodisableintheformofaWordPressplugin.Ofcourseyoucanincorporatethiscodeintoanyexistingsite-specificormust-usepluginsyoualreadyhave.
PreventWordPressuserenumeration
WordPressisvulnerabletoanumberofuserenumerationattacks.Suchattacksallowanattackertofigureoutwhatusersexistwhetherauserexistsornot.Whilethismayseemharmless,bearinmindthatattackersmayusethisinformationaspartofalargerattack. Formoreinformationaboutthistopic,readhowtoenumerateWordPressuserswithWPScan.
InordertopreventWordPressuserenumeration,you’llneedtoensurethatthefollowingWordPressfeaturesaredisabledorrestricted.
RestricttheWordPressRESTAPItounauthenticatedusers
DisableWordPressXML-RPC
Don’texpose/wp-adminand/wp-login.phpdirectlytothepublicInternet
Additionally,youwillalsoneedtoconfigureyourwebservertopreventaccessto/?author=
延伸文章資訊
- 1An Overview of Basic WordPress Hardening - Sucuri Blog
Our website security analyst gives a brief overview of basic WordPress hardening tips and tricks ...
- 2The Ultimate WordPress Security Guide - Step by Step (2022)
Another way to harden your WordPress security is by disabling PHP file execution in directories w...
- 3WordPress Hardening: 18 Ways to Harden Security of Your ...
WordPress hardening is a catch-all term used to describe settings and configurations that increas...
- 4WordPress Hardening: A Complete Guide - Astra Security
Steps to WordPress hardening ; Sign into WordPress account and go to WordPress general settings; ...
- 515 Ways To Harden The Security Of Your WordPress Site
15 WordPress Security Tips · Keep WordPress core, themes, and plugins up to date · Only install t...