Vous êtes sur la page 1sur 19

Home

Categories

Archives

About

Contact
Search:type,hitenter

RootUsers

Guides,tutorials,reviewsandnewsforSystemAdministrators.

23HardeningTipstoSecureyourLinuxServer
PostedbyJarrodonSeptember1,2015

Gotocomments

Leaveacomment(1)

ItisimportanttosecureaLinuxsystemasmuchaspossibleinordertoreducethelikelihoodof
compromise.
Hereare23securitytipstoguideyouthroughhardeningyourLinuxoperatingsystem.

Index
1. PatchtheOperatingSystem
2. PatchThirdPartyApplications
3. DisableRemoteRootAccess
4. DisableRootConsoleAccess
5. RestrictRootPrivileges
6. EnableandConfigureFirewall
7. EncryptNetworkTransmissions
8. TwoFactorAuthentication
9. SecurityEnhancedLinux(SELinux)
10. ReduceAttackSurface
11. LogReview
12. LimitSSHAccess
13. PhysicalSecurity
14. SecuringtheBIOS
15. SecuringtheBootLoader
16. EncryptData
17. CentralizedAuthentication
18. EnforceStrongPasswords
19. PasswordAging
20. AccountLockout
21. UsingSSHKeys
22. HostBasedIntrusionDetectionSystem(HIDS)
23. Virus/MalwareScanning
Note:ThisguidereferstoaLinuxsystemasaserver,computer,orclient.Thesetermsshouldberead
interchangeablyasalltipsapplytoanysystemrunningLinux.

LinuxServerSecurityHardeningTips
1.PatchtheOperatingSystem
Itisextremelyimportantthattheoperatingsystemandvariouspackagesinstalledbekeptuptodateasitis
thecoreoftheenvironment.Withoutastableandsecureoperatingsystemmostofthefollowingsecurity
hardeningtipswillbemuchlesseffective.Toperformanupdateofallpackagesinstalledyoucanmakeuse
ofthesecommandswhichwilllistallavailableupdatesforinstallationandpromptyoutoproceed.
RHELBasedOS:
yumupdate

DebianBasedOS:
aptgetupgrade

Thesecommandswillinstallallavailablepackageupdatesfromtherepository,whichmayincludetheLinux
kernel.Checkthelistofupdatestobeinstalledtoseeifthereisakernelupdateasthiswillrequireareboot
toapply.
InLinuxthekernelisthecorecomponentoftheoperatingsystem,itmanagescomponentssuchas
memory,theCPU,processschedulingandmore.Duetothiscentralrolethekernelcannotberestarted
withoutarebootofthewholeoperatingsystem,sotocompleteakernelupdatethesystemwillneedtobe
rebooted.Therearethirdpartyoptionsavailabletoavoidsystemreboot,suchasthoseofferedbyKsplice
orKernelCare.
Otherpackagesthatruninuserspacecansimplyberestartedtomakeuseoftheupdatedversionwithout
systemreboot.
Itisadvisablethatsecurityupdatesbeinstalledassoonaspossible,thiscaneitherbedonemanuallyor
automaticallyviacrontab.Itisalsosuggestedthatyousubscribetothemailinglistforyouroperating
systemasthesewillkeepyouupdatedonanysecurityupdatestothekernelandothercommonpackages
astheybecomeavailable.

2.PatchThirdPartyApplications
Anyothercustomapplicationsthatyouhaveinstalledthatarenotmaintainedbyapackagemanagermust
alsobepatchedfrequentlysothatthelatestsecurityupdatescanbeapplied.Someexamplesofsuch
applicationsincludepopularwebapplicationslikeWordPress,JoomlaorDrupal.Thesetypesof
applicationsareinstalledoutsideofthepackagemanager,soayumupdateoraptgetupgradewillnot
updatethem.

SomeapplicationsmayupdateautomaticallysuchasWordPress,whileothersmayrequireamanual
processtoupdatesuchasWordPressplugins.Theupdateprocessfortheparticularapplicationwilldiffer
onacasebycasebasis,soifyouareunsurechecktheofficialdocumentationfromthevendorand
scheduleregularupdates.Itisrecommendedthatyousubscribetoanymailinglistsoralertsprovidedby
theapplicationvendortokeepuptodatewithanyvulnerabilitiesthatbecomedisclosedsothatyoucan
updateinatimelymanner.

3.DisableRemoteRootAccess
InLinuxtherootuserhasfullunrestrictedaccesstothesystem,bydisablingloggingindirectlyastheroot
userwecanimprovesecurityasattackerstypicallyattempttocompromisetherootaccount.Thiscanbe
donebyeditingthe/etc/passwdfileandchangingtherootshellfrom/bin/bashto/sbin/nologin
Default/etc/passwdforroot
root:x:0:0:root:/root:/bin/bash

Afterdisablingrootlogin
root:x:0:0:root:/root:/sbin/nologin

ThiswillpreventrootaccessthroughtheGUI,SSH,SCP,SFTPandwithsu.Itwillnotdisablesudoor
consoleaccesshowever.
Servicescanalsobeexplicitlyconfiguredtodisallowrootlogin.RemoteaccessthroughSSHforinstance
canbedisabledfortherootuserbymodifyingthe/etc/ssh/sshd_configfileasbelow.Aftereditingthefile,
restarttheservicetoapplythechange.
PermitRootLoginno

Rootprivilegescanbedelegatedouttootheruseraccountsasrequired.Asabestpracticeyoudonotwant
toprovidetherootpasswordtomultipleusersasitmakesauditingandtrackingwhoisdoingwhatwiththe
accountmoredifficult.Toproviderootaccesstootherusers,theuseraccountcanbeaddedtothesudoers
filewhichwillgrantthemrootprivileges.Thisfilecanbemodifiedwiththevisudocommand.
[root@centos~]#visudo
...
rootALL=(ALL)ALL
bobALL=(ALL)ALL
...

Therootaccountwillbetherebydefault,otheraccountscanalsobespecified.Inthisinstancethebob
accounthasbeenaddedtoalsohavefullsudoprivilegesandcanrunallcommandsasrootbyprefixing

themwithsudoandcorrectlyenteringtheirpassword.

4.DisableRootConsoleAccess
Thepreviousstepdisablesremoteaccessfortherootaccount,howeveritwillstillbepossibleforroottolog
inthroughanyconsoledevice.Dependingonthesecurityofyourconsoleaccessyoumaywishtoleave
rootaccessinplace,otherwiseitcanberemovedbyclearingthe/etc/securettyfileasshownbelow.
echo>/etc/securetty

Thisfilelistsalldevicesthatrootisallowedtologinto,thefilemustexistotherwiserootwillbeallowed
accessthroughanycommunicationdeviceavailablewhetherthatbeconsoleorother.
Withnodeviceslistedinthisfilerootaccesshasbeendisabled.Itisimportanttonotethatthisdoesnot
preventrootfromlogginginremotelywithSSHforinstance,thatmustbedisabledasoutlinedinpoint3
Disableremoterootaccessabove.
Accesstotheconsoleitselfshouldalsobesecured,aphysicalconsolecanbeprotectedbytheinformation
coveredinpoint13Physicalsecurity.

5.RestrictRootPrivileges
Asmentionedaboveusersthatrequirerootprivilegescanbeaddedtothesudoersfile,howeverwecan
furtherrestrictwhattheuserscanrunasrootratherthansimplyprovidingfullaccessbyexplicitlyspecifying
thecommandsinthesudoersfile.Forinstancewithbobremovedfromthesudoersfile,heisnotableto
reboottheserver.
[bob@centos~]$sudoreboot
[sudo]passwordforbob:
bobisnotinthesudoersfile.Thisincidentwillbereported.

Howeverafterrunningvisudoandeditingthesudoersfileasbelow,thisbecomespossible.
bobALL=/usr/sbin/reboot

Afterthischangebobisnowabletoperformtherebootasrootbutnothingelse.

6.EnableandConfigureFirewall
Afirewallsuchasiptablesorfirewalldshouldbeusedtorestrictinboundandoutboundtraffictoandfrom
yourLinuxserver.Whileitisidealtorestrictbothinboundandoutboundtraffic,itismorecommonfora
servertoallowanyoutboundtrafficandonlyrestrictincomingtraffic.Thisisgenerallybecauseattacks
initiateexternallyespeciallyfromtheInternet,theseexternalnetworksarethereforelesstrustworthythan

theserveritself.Ifaserviceontheserveriscompromisedandtheserveriscapableofconnectingouttothe
Internetwithoutrestrictionthenitcouldcausefurthercompromiseofthesystem.
ThefirewallshouldbeusedtospecifysourceanddestinationIPaddressesandportsifpossible.For
example,wecanallowSSHaccesstoTCPport22toonlycomeinfromtrustedIPaddress1.2.3.4which
willpreventanyoneelsefromattemptingtoconnecttotheserverviaSSH.Destinationaddressescanalso
belimited,forinstancewemayonlywantourservertoconnectouttoaparticulartrustedrepositoryfor
packageupdatesoverTCPport443.Byallowingthisoutboundaccessandnootherexternalconnections
totheInternetwecanpreventtheserverfromdownloadingotherfiles,oratleastrestrictwhatisavailable.
RestrictingbasedonsourceanddestinationIPaddresseswithportsismuchbetterthansimplychanging
theportthataserviceislisteningon.ForinstanceyoucouldchangetheSSHportto4567ratherthanthe
defaultof22.Whilethismaystopsomeautomatedattacksitwillbetrivialforaportscannersuchasnmap
todetectasitsonlysimplesecuritythroughobscurity,assoonasthesecrecyhasbeenlostsohasthe
security.Oncefirewallrulesareinplacenmapcanalsobeusedtoscanasystemforopenports,allowing
youtoconfirmtherulesareworkingasintended.

7.EncryptNetworkTransmissions
Whileafirewallwilldeterminetheallowedinboundandoutboundtrafficitisimportantthatyouencryptall
inboundandoutbounddatacommunicationstokeepthemsecure.Thisinvolvesusingtoolsthatsupport
encryptionsuchasSSL/TLS.ForexampleifyourLinuxserverisrunningawebserversuchasApacheand
thewebsitehasaloginpagewhereusersenterausernameandpassword,ratherthanconfiguringthisto
useplaintextHTTPitshouldbesettouseHTTPSwhichwillensurethecommunicationbetweentheserver
andtheclientisencrypted.Thiswillpreventdatatransferoverthewirefrombeingseenbyanyoneelse,
assumingtheprivatekeyonthewebserverissecureofcourse.
Toachievethisessentiallyyouneedtoactivelymakethechoicetousetoolsandprotocolsthatsupport
encryptionwhencommunicatingoverthenetwork,forinstanceusingSSHratherthantelnet,usingSFTP
ratherthanFTP,orusingIMAPSratherthanIMAP.OthertoolssuchasVPNcanbeusedtoestablish
secureandencryptedtunnelsbetweentwohosts.

8.TwoFactorAuthentication
TwofactorauthenticationcanbeimplementedforSSHaccessorotherapplicationlogin,itwillimprove
loginsecuritybyaddingasecondfactorofauthentication,thatisthepasswordistypicallyknownas
somethingyouknow,whilethesecondfactormaybeaphysicalsecuritytokenormobiledevicewhichacts
assomethingyouhave.Thecombinationofsomethingyouknowandsomethingyouhaveensuresthatyou
aremorelikelywhoyousayyouare.
TherearecustomapplicationsavailableforthissuchasDuoSecurityandGoogleAuthenticatoraswellas
manyothers.Thesetypicallyinvolveinstallinganapplicationonasmartphoneandthenenteringthe
generatedcodealongsideyourusernameandpasswordwhenyouauthenticate.

GoogleAuthenticatorcanbeusedformanyotherapplicationsthanjustSSH,suchasforWordPresslogin
withthirdpartypluginsupport.

9.SecurityEnhancedLinux(SELinux)
SELinuxwasoriginallydevelopedbytheNSAasasetofpatchestotheLinuxkernel.SELinuxreduces
vulnerabilitytoprivilegeescalation,providesfinegrainaccesscontrolandseparatesprocessesfromeach
other.Processesrunintheirowndomainwhichpreventsthemfromaccessingfilesusedbyother
processes.
ForexampletheApache(httpd)webserverrunswiththecontextsystem_u:system_r:httpd_t:s0,ifthis
processiscompromisedbyanattackertheiraccesstofurtherresourcesandcausingpotentialdamageis
limitedbySELinuxpolicy.BydefaultApachecanaccessfileslabelledwiththehttpd_sys_content_ttype,
filescreatedwithin/var/www/htmlwillbelabelledwiththisbydefaultsothatApachecanservewebfiles.
OtherfilesanddirectorieselsewhereinthefilesystemwillnothavethisbydefaultsoApachewillnotbe
abletoaccessnonwebfilesstoredelsewhereduetoSELinuxpolicyrestrictions.YoucanviewtheSELinux
typeofafileordirectorywithlsz.
SELinuxcomesenabledwithRHELbasedoperatingsystemssuchasCentOSbydefaultanditis
recommendedtouse.OvertimeIhaveseenlotsofLinuxbasedguidessimplyadvisethatSELinuxbe
disabledanddiscardedratherthanconfiguredcorrectly.Thisisnotideal,SELinuxshouldalwaysbe
enabledpreferablyinenforcingmodehoweveryoucaninsteadsetittopermissivemodewhichwillnot
enforceanythingbutinsteadloganythingthatwouldhaveotherwisebeenblockedinenforcingmode,which
isbetterthanhavingitdisabledentirely.
TogetdetailedlogsinplainEnglishthatwillgiveyousuggestedcommandsonhowtoresolveSELinux
problems,installthesetroubleshootandsetroubleshootserverpackages.Thiswillprovidethesealert
command,whichcanberunagainsttheaudit.logfileandwillprovideadviceonfixinganyproblemsthat
havebeenlogged.
SELinuxcanbequiteintimidatingatfirsthoweveritsdefinitelyworthlearningtotakeadvantageofthe
increasedsecuritythatitcanoffer,IhavefoundtheofficialRedHatdocumentationSELinuxUsersand
AdministratorsGuidetobeanexcellentresource.

10.ReduceAttackSurface
EverytimeyouinstallanotherpackageorstartanadditionalserviceonyourLinuxserveryouareeffectively
increasingtheattacksurface.Bydoingthistherearemorethingsavailableforanattackertoattemptto
targetasthereismorecodeandmovingpartsavailable,increasingthelikelihoodofavulnerability.
WheninstallingLinuxbydefaultagraphicaluserinterface(GUI)isusuallyinstalled,inaserverenvironment
itishighlyrecommendedthatyoudonotinstallthistohelpreducetheattacksurfaceandresourceusage.If
theGUIisalreadyinstalleditispossibletouninstallit.

AnothergoodoptionwheninstallingLinuxistoselectaminimalinstallation,thiswillinstallabasesetof
importantpackagesthatarerequiredwithnotmuchextrabloat.Thisispreferableasyouwillhavefewer
packagesinstalled,youcaneasilyinstallanythingthatyourequireafterinstallationfromtherepository
ratherthanhavingabunchofpackagespreinstalledthatmayneverevenbeused.
Yourattacksurfacecanbereducedbydisablingservicesthatarenotneededandbyuninstallingor
removingpackagesandsoftwarethatarenotrequired.Thefollowingcommandscanbeusedtoviewthe
statusofinstalledservices,theywilllistservicesthatareconfiguredtostartuponboot.
CentOS6andearlier
chkconfiglist

CentOS7
systemctllistunitfilestype=service

Shouldyoufindaservicethatyouknowisnotrequireditcanbedisabledsothatitdoesnotstartonboot,
onlydothisifyouaresurethattheserviceisnotrequiredassomemaybeneededbytheoperatingsystem
orotherservicesthatyoumakeuseof.
CentOS6andearlier
chkconfigoffservicename

CentOS7
systemctldisableservicename

Toviewafulllistofinstalledpackagesyoucanrunyumlistinstalled,shouldyoudeterminethatthereare
packagesthatarenolongerrequiredyoucanremovethemwithyumremovepackagename.
Withthenetstatcommandyoucanlisttheportsthataprocessontheserverisactivelylisteningfor
connectionson.Thiscanhelpidentifysomethingmaliciousthatisrunningwaitingtoacceptanexternal
connection,ormayshowanalreadyestablishedconnectionthatshouldnotbeallowed.Thisiswhyyou
wouldwanttorestricttheconnectivityinthefirewallasoutlinedinpoint6Enableandconfigurefirewall.If
youfindsomethingmaliciousyoucantrytostoptheserviceorkillthelistedPID,thoughthislikelywillnot
stopitfromstartingupagain.

[root@centos~]#netstatantup
ActiveInternetconnections(serversandestablished)
ProtoRecvQSendQLocalAddressForeignAddressStatePID/Programnam
tcp000.0.0.0:220.0.0.0:*LISTEN1218/sshd

tcp00127.0.0.1:250.0.0.0:*LISTEN1736/master
tcp064192.168.0.100:221.2.3.4:29667ESTABLISHED2716/sshd:root@pts
tcp600:::80:::*LISTEN2859/httpd
tcp600:::22:::*LISTEN1218/sshd
tcp600::1:25:::*LISTEN1736/master
tcp600:::443:::*LISTEN2859/httpd
tcp600:::8443:::*LISTEN2859/httpd
udp000.0.0.0:1230.0.0.0:*701/chronyd
udp00127.0.0.1:3230.0.0.0:*701/chronyd
udp600:::123:::*701/chronyd
udp600::1:323:::*701/chronyd

InthisexamplesshdislisteningonTCPport22forSSHconnectionsandthereisoneestablished
connectionfrom1.2.3.4.Therearemanyotherserviceslisteningonvariousportssuchashttpdlisteningfor
port80and443connectionstoserveHTTPandHTTPSrequests.
Anothergoodmethodofreducingtheattacksurfaceistosegregateimportantrolesbetweendifferent
servers.Ratherthanhavingoneserverdoingeverythingitispreferabletosplitimportantrolesupinto
differentinstances.Forexampleyoumayhaveoneserverthatactsasthewebserver,anotherthatactsas
thedatabaseserver,anotherthatactsastheemailserverandanotherthatactsastheDNSserver.
Withtheincreaseinvirtualizationtechnologiesovertherecentyearsthisisbecomingcheaperandeasierto
takeadvantageof.Bysplittingthedifferentrolesintodifferentserversyourereducingtheattacksurface,if
oneoftheservicesisvulnerabletocompromisethenyouonlyhavetoworryaboutthatserverrunningthat
particularvulnerableserviceatleastinitiallyuntiltheyworktheirwayindeeper!

11.LogReview
WhilenotdirectlyhardeningyourLinuxserver,byreviewingthelogsyoucanidentifypossibleproblemsthat
shouldberesolved,suchasunauthorizeduseraccess.Securityeventsandothermessagesarestoredin
thelogfilesforareasonandshouldbereviewed.Itcanbedifficultandtimeconsumingtomanuallyreview
thelogfilesoneachserver,soyoucouldinsteadlookatimplementingasystemsuchaslogstashora
syslogservertocentrallycollectalllogs.
Accesslogsshouldbemonitoredsothatunauthorizedaccessattemptsaremadeawareanddealtwithas
required.Evensuccessfulaccessattemptsshouldbeloggedasthatwillprovidevisibilityoverwhatuser
accountsaredoinginthecaseofanattackerthathasgainedaccess,oralegitimateuserthatis
misbehaving.Logwatchcanalsobeinstalledandconfiguredtoemailperiodicsummariesofeventsthatare
loggedsuchaspackagesinstalledorusersthathaveloggedin.Beingawareofwhatishappeningonyour
systemswillhelpyoudetectanypotentialattacks.

12.LimitSSHAccess
BydefaultanyuserthatyoucreateonaLinuxserverwiththedefault/bin/bashshelliscapableofloggingin
remotelybySSHonceithashadapasswordset.SSHaccesscanberestrictedtoadefinedsetofusersor

groupsbyusingAllowUsersorAllowGroupsin/etc/ssh/sshd_configrespectively.Notallusersonaserver
willtypicallyneedSSHaccesssothiscanberestrictedtoonlythosethatneedaccesstomanagethe
server.
Forexample,thebelowconfigurationin/etc/ssh/sshd_configwillonlyallowusersrootandbobSSH
access,anyotheruserwillbedeniedaccesswhentheyattempttologinviaSSH.
AllowUsersrootbob

UsersthatshareacommonattributecanbegroupedtogetherandallowedinsteadwithAllowGroupswhich
ismorescalablewithalargernumberofusers.Besuretorestartthesshdservicetoapplyanychanges
madehere.

13.PhysicalSecurity
Physicalaccesstoyourservercaneasilyundoalotofthestepsoutlinedhere,soitisequallyimportantto
ensurethatyourserverisphysicallysecuresothatitcantbeaccessedbyanunauthorizeduser.
Ifyourserverishostedwithinadatacenterenvironmenttheywilllikelyalreadyrestrictphysicalaccessand
havevarioussecuritymeasuresinplace,itisrecommendedthatyoudiscusstheprotectionmeasuresin
placeforyourserverandensurethatthesemeetyourrequirements.
Alternativelyifyouhostyourserveronpremisesathomeorinanofficeitshouldbelockedsecurelyina
dedicatedserverroomifpossibleinacentrallocationofthebuilding,withaccessonlygrantedtothosethat
needtophysicallymaintaintheserver.Keepinganyserverracksorcaseslockedisalsorecommended.

14.SecuringtheBIOS
PasswordprotectingtheBIOScanhelpslowdownanattackerwithphysicalaccessfromchangingBIOS
settingsorbootingthesystemfromCDorUSBdrive.AstheBIOSwilldifferbetweenmanufacturersyou
shouldrefertoyourspecificdocumentationregardingsettingthis.
Itisimportanttonotethatthisdoesnotprotectthesystemverywelliffullphysicalaccessispossible,asthe
BIOSpasswordcanusuallybeeasilyresetwithjumpersonthemotherboardorbyremovingtheCMOS
battery.Youwouldthereforebebetteroffprotectingsystemdatawithencryptionascoveredinpoint16
Encryptdata.Thisalsofurtherenforcestheimportanceofpoint13Physicalsecurity.
WhiletherearebettermethodsofsecuringaLinuxsystemassuggested,BIOSpasswordscanstillbe
usefulforpubliccomputerssuchasinapubliclibraryforexample.InthisinstanceaBIOSpasswordwill
stoprandompeoplefrominsertingaCDorUSBdriveandtryingtobootintoadifferentoperatingsystem,
yestheycouldgetaroundthisprotectionbyopeningthecomputerandresettingtheBIOSpassword
howevertheyareprobablylesslikelytostartdoingthisinapublicplaceasitsmoredifficulttodo
undetectedcomparedtosimplyinsertingaCDorUSBdrive.

15.SecuringtheBootLoader
Bysecuringthebootloaderwecanpreventaccesstosingleusermodewhichlogsinautomaticallyasroot.
ThisisdonewithGRUB2bysettingapasswordwhichisstoredinplaintextbydefault,itisrecommended
thatyousetanencryptedpasswordinsteadsothatthegrubpasswordcannotbeeasilyretrievedoffthe
disk.

16.EncryptData
SensitivedatastoredontheLinuxservershouldbeencrypted.Ifphysicalaccesstotheserverissomehow
obtainedandtheunencryptedharddrivesarestolenitwillbepossibleforalldatatobereadbyanattacker.
Althoughphysicalsecuritycanhelpprotectagainstthisscenarioyoushouldplanfortheworstandencrypt
thedata.Physicalsecuritymaybemoredifficulttoimplementforportabledevicessuchasalaptopsand
tablets,strongencryptioncanhelpprotectdataonstolendevices.
Thisproblemalsoexistswithvirtualmachineshoweverpossiblytoalesserextent,ifthevirtualharddiskfile
iscopiedthenitispossibletoaccessthedatacontainedwithin.Topreventthisandsecurethedatait
needstobeencryptedatrestandnotstoredondiskincleartext.Therearemanywaystohandle
encryption,LinuxUnifiedKeySetupondiskformat(LUKS)isoneofthemandworksquitewell.Oncedata
hasbeenencryptedifyoulosethepasswordorkeytoaccessthatdatayouwillnolongerbeabletoaccess
thedata.

17.CentralizedAuthentication
Usingacentraldirectorytomaintainuseraccountsistypicallymoresecureandmuchmorescalableasyou
increasetheamountofclients/serversthatyouneedtoaccess.Examplesofsuchadirectoryinclude
MicrosoftsActiveDirectoryandRedHatsIdentityManagement,eithercanbeusedforauthentication
withinaLinuxenvironment.
Acentraldirectoryprovidesseveralsecurityadvantages.Bystoringalluseraccountsinthedirectory,
shouldauseraccountbelockedoutitwillbelockedoutregardlessoftheclientcomputertryingtologin.
Withoutadirectoryserverlocalaccountswouldbedefinedonaperserverbasis,soanattackerperforming
abruteforceattackcouldsimplylockouttheaccountononecomputerandthenstarttheattackupagain
onanother.
Thiscentralizedmanagementalsoensuresthattheuserspasswordmeetsadefinedglobalpasswordpolicy
suchaslengthandcomplexityrequirementswhichwouldotherwisebemanuallydefinedonindividual
servers.Definingthingslikepasswordpolicyonindividualserverslocallyhasthepotentialtoreduce
securityiftheyareallnotconfiguredtothesamelevelasitbecomespossibleforsometobeincorrectly
configuredtohaveweakersecuritysettingsovertime.
Itcanalsobemuchmoredifficulttocompromisethepasswordhashesofanaccountastheyarestored
withinthecentraldirectoryserver,ratherthanoneachindividualserver.Althoughaccesstothe/etc/shadow
filerequiresrootaccesstoreaditmaybepossiblethatanattackerhascompromisedoneofyourservers

anddoesindeedhaverootaccesstothelocalserver.Theattackerwouldthenbeabletoviewthe
passwordhashesforallusersontheserverandperformanofflinebruteforceattackwhichcouldresultin
themgainingfurtherusercredentialsthatmayberequiredtoaccessadditionalsystems.

18.EnforceStrongPasswords
Byenforcingstrongpasswordswecanimprovethesecurityofanaccountasbruteforceattackbecomes
moredifficult,strongerpasswordsrequiremoretimeandcomputingpowertodiscover.Thisisgenerally
donethroughpolicyonthedirectoryserverwheretheaccountsexist,butcanalsobeconfiguredlocallyon
aperserverbasis.InCentOS7strongpasswordsareenforcedbythepwqualityPAMmoduleratherthan
thecracklibmodule,howeverbothusethesamebackend.
pwqualitychecksthestrengthofapasswordagainstasetofrules,firstitchecksifthepasswordisa
dictionarywordandthenifnotitchecksthecustomsetofrulesdefinedwithin/etc/security/pwquality.conf.
Toenablethepwqualitymoduleaddthefollowinglineintothe/etc/pam.d/passwdfile.
passwordrequiredpam_pwquality.soretry=3

The/etc/security/pwquality.conffileisthenusedtoconfigurethecheckssuchasminimumlength,thisfile
documentsallavailablevariableswell,belowisanexampleconfiguration.
minlen=8
minclass=4
maxsequence=3
maxrepeat=3

Inthiscasetheminimumacceptablesizeforthenewpasswordislength8,theminimumnumberof
requiredclassesofcharactersis4(digits,uppercase,lowercase,andsymbols),themaximumsequenceis
3(suchasabcor123),andthemaximumnumberofallowedconsecutivesamecharactersis3(suchas
aaaor111)
Itsalsoimportanttonotethatarootuserisabletosetanypasswordforthemselforanyotheruser
accountregardlessofthis,theywillbewarnediftheyareusingaweakpasswordhowevertheycanavoid
thepasswordenforcement.

19.PasswordAging
Passwordagingdefendsagainstbadpasswordsbeingdiscoveredandreusedbyanattacker,evenifa
passwordiscompromiseditwillonlybeusableforasetperiodoftime.Accountswhicharenolonger
requiredbuthavenotbeenlockedoutwillbecomeinaccessiblewhenthepasswordexpires.Thisneedsto
beconfiguredasbydefaultapasswordchangewillnotberequiredfor99999days.
Passwordagingcaneitherbemanagedlocallyonaperserverbasis,orasmentionedabovewithina

centraldirectorysuchasActiveDirectoryorIdentityManagement.Ideallyyoureusingacentraldirectoryto
makethesepolicychangesmucheasier,youwouldsettheminoneplaceandtheywouldapplyforall
usersthatloginoveramultitudeofservers.
Itispossibletomanagepasswordagingonaperserverbasislocally,itwilljustrequiremoreadministration
timeandincreasesthelikelihoodofaconfigurationmistakewhichcanresultinlesssecureaccounts.Below
aresomeexamplecommandstoapplypasswordaging.
Showaccountaginginformation,thesevaluescanbemodifiedfurtherwiththechagecommand.
[root@centos~]#chagelbob
Lastpasswordchange:Aug19,2015
Passwordexpires:never
Passwordinactive:never
Accountexpires:never
Minimumnumberofdaysbetweenpasswordchange:0
Maximumnumberofdaysbetweenpasswordchange:99999
Numberofdaysofwarningbeforepasswordexpires:7

Torunchageinteractivelytosetthesevaluesonauseraccountrunchageusername.

20.AccountLockout
Whilehavingstrongpasswordsinplaceforuseraccountscanhelpthwartbruteforceattacksasmentioned
previouslyinpoint18Enforcestrongpasswords,thisisonlyonewayofslowingdownthistypeofattack.
Agoodindicationofbruteforceattackisauseraccountthathasfailedtologinsuccessfullymultipletimes
withinashortperiodoftime,thesesortsofactionsshouldbeblockedandreported.Wecanblockthese
attacksbyautomaticallylockingouttheaccount,eitheratthedirectoryifinuseorlocally.
Thepam_tally2.soPAMmodulecanbeusedtolockoutlocalaccountsafterasetnumberoffailures.To
getthisworkingIhaveaddedthebelowlinetothe/etc/pam.d/passwordauthfile.

authrequiredpam_tally2.sofile=/var/log/tallylogdeny=3even_deny_rootunlock_time=

Thiswilllogallfailurestothe/var/log/tallylogfileandlockoutanaccountafter3consecutivefailures.By
defaultitwillnotdenytherootaccounthoweverwecanalsolockoutrootbyspecifyingeven_deny_root
(thoughthismaynotberequiredifyouhavedisabledrootaccessasperpoint3Disableremoteroot
accessandpoint4Disablerootconsoleaccess).Theunlocktimeistheamountofsecondsafterafailed
loginattemptthatanaccountwillautomaticallyunlockandbecomeavailableagain.
Failedloginscanbeviewedasbelow,toviewallfailuressimplyremovetheuserflag.
[root@centos~]#pam_tally2user=bob
LoginFailuresLatestfailureFrom
bob408/21/1519:38:23localhost

Thefailurecountcanbemanuallyresetbyappendingresetontothiscommand.
pam_tally2user=bobreset

Ifaloginissuccessfulbeforethelimithasbeenreachedthefailurecountwillresetto0.Formoredetails
seethepam_tally2manualpagebytypingmanpam_tally2.
Itsworthnotingthatthemanualpageadvisestoconfigurethiswiththe/etc/pam.d/loginfile,howeverI
foundthatunderCentOS7thisdidnotworkandneededtousethe/etc/pam.d/passwordauthfileinstead.I
alsotriedusing/etc/pam.d/systemauthwhichIfounddocumentedelsewherebutthisalsofailed,sothis
maydifferbasedonyouroperatingsystem.
Youcanalsomanuallylockandunlocklocaluseraccountsratherthanwaitingforthefailurelimittobe
reached.
Locktheuseraccountbob.
[root@centos~]#passwdlbob
Lockingpasswordforuserbob.
passwd:Success

Unlocktheuseraccountbob.
[root@centos~]#passwdubob
Unlockingpasswordforuserbob.
passwd:Success

Becarefulwhenenablingaccountlockout,asautomaticlocksonaccountsusedbyvariousservicescould
possiblyleadtooutages.
OthertoolssuchasFail2BancanalsobeusedtoblockthesourceIPaddressesthefailedloginsinitiate
frominthefirewall.Thishastheadvantageofblockingtheattackwithoutlockingtheaccountand
preventinglegitimateuseraccess.

21.UsingSSHKeys
SSHkeyscanbeusedtoincreasethelevelofsecurityforauserremotelyauthenticatingtoaLinuxserver
throughSSH.SSHkeysaretypicallypreferableintermsofsecuritywhencomparedtoapasswordasthey
arefarlessvulnerabletobruteforceattack,thereissimplyalotmoreentropyinakeythanpassword.
SSHkeysarebaseduponpublickeycryptography,wherebyyouwillgenerateakeypairwhichincludesa
publickeyandaprivatekey.Thepublickeyisstoredonthedestinationserverthatyouwishtoaccessand

willallowonlythecorrespondingprivatekeyaccess.
Itisthereforeextremelyimportantthatyouprotectyourprivatekey,ifanattackerisabletoaccessthiskey
thentheywillbeabletologinasyouruser.Bestpracticesdictatethatyourprivatekeybeencryptedwitha
passphrasewhichcanbeconfiguredwhenyoucreatethekeypair.Itsalsoimportantthattheprivatekey
filebereadableandwritableonlybytheuserthatownsthekey,thiswouldbepermissions0600andisset
asdefaultoncreation.
Createthekeypairwiththesshkeygencommand,thetspecifiesthetypeofkeytocreate,hereweare
usingrsaversion2.
[bob@centosroot]$sshkeygentrsa
Generatingpublic/privatersakeypair.
Enterfileinwhichtosavethekey(/home/bob/.ssh/id_rsa):
Createddirectory'/home/bob/.ssh'.
Enterpassphrase(emptyfornopassphrase):
Entersamepassphraseagain:
Youridentificationhasbeensavedin/home/bob/.ssh/id_rsa.
Yourpublickeyhasbeensavedin/home/bob/.ssh/id_rsa.pub.
Thekeyfingerprintis:
8e:dc:08:bb:8d:0e:12:04:22:ae:5e:f5:0a:21:3e:b0bob@centos
Thekey'srandomartimageis:
+[RSA2048]+
|+|
|=|
|.+..|
|=..o.|
|Eoo..S|
|..o.+.=|
|.....+o|
|..+|
|.+.|
++
[bob@centos~]$lsla/home/bob/.ssh/
rw.1bobbob1766Aug1916:41id_rsa
rwrr.1bobbob398Aug1916:41id_rsa.pub

Intheaboveexamplewecreatedtheid_rsaprivatekeyfileandcorrespondingid_rsa.pubpublickeyfile.
Nextuploadthepublickeytotheremoteserverthatyouwishtoaccess,thiscanbedonemanuallyorwith
thesshcopyidcommandasshownbelow.

[bob@centos.ssh]$sshcopyidbob@1.2.3.4
Theauthenticityofhost'1.2.3.4'can'tbeestablished.
ECDSAkeyfingerprintis97:b6:fc:11:49:20:3c:10:ac:16:49:46:e5:56:03:30.
Areyousureyouwanttocontinueconnecting(yes/no)?yes
/usr/bin/sshcopyid:INFO:attemptingtologinwiththenewkey(s),tofilteroutanythatar
/usr/bin/sshcopyid:INFO:1key(s)remaintobeinstalledifyouarepromptednowitisto
bob@1.2.3.4'spassword:
Numberofkey(s)added:1

Nowtryloggingintothemachine,with:"ssh'bob@1.2.3.4'"
andchecktomakesurethatonlythekey(s)youwantedwereadded.

Thiswillplacetheid_rsa.pubpublickeyfileonthedestinationserver,inthiscase1.2.3.4withinthe
~/.ssh/authorized_keysfile,youcanthenSSHtothedestinationbysimplyrunningsshbob@1.2.3.4and
youshouldbepromptedforthepassphraseforyourprivatekey.
OnceanaccounthasbeensetuptomakeuseofSSHkeysratherthanapasswordyoucanoptionally
disablepasswordauthenticationthrough/etc/ssh/sshd_configtoincreasesecurityasshownbelow.
PasswordAuthenticationno
PubkeyAuthenticationyes

Reloadsshdtoapplythesechanges.

22.HostBasedIntrusionDetectionSystem(HIDS)
Evenafterimplementingadditionalsecuritymeasuresitisstillpossiblethatyourservermaybecome
compromised,noservershouldeverbeconsidered100%secure.Shouldthishappenyouwouldwanttobe
alertedsothatyoucaninvestigatefurther.Thiscanbedonebyusingahostbasedintrusiondetection
systemwhichistypicallyinstalledontheserverasanagentwhichmonitorstheinternalsofthesystemand
canalertifanattemptedorsuccessfulintrusionisdetected.Whilethisdefinitelywillnotdetectandalertfor
everypossibleintrusionitisagoodprotectionmeasuretoputinplace.
OSSECisacrossplatformopensourceHIDSthatiscapableofperformingloganalysis,fileintegrity
checking,policymonitoring,rootkitdetectionandrealtimealertingandresponse.

23.Virus/MalwareScanning
Inadditiontodetectingintrusionitisalsoimportanttofrequentlyscanthefilesystem,memoryandrunning
processesforknownvirusesormalwarethreatsthatmayhavemadeitontoyourLinuxserver.Thescan
shouldbeabletoactivelyquarantineknownbadfilesthataredetectedandsendoutanotificationalertfor
furtherinvestigation.
Itisagoodideatorunsuchscansduringperiodsoflowresourceusagesothatthescandoesnotconflict
withnormalservice.Thiswilldependontheworkloadofyourserver,howeverscanningovernightoron
theweekendusuallyworkswellandmosttoolsallowyoutospecifyaloadlevelthresholdtopauseatand
continueafteritdropsbackdown.
ClamAVisapopularopensourceantivirusavailableforLinuxtodetectviruses,trojans,malwareandother
maliciousthreatsandworksquitewell.AlotofothertoolsalsoincorporateClamAVsuchasMaldetwhichis
anothergreattool.OtheroptionssuchasConfigeXploitScanner(CXS)alsomakesuseofClamAVandwill
activelyscanfilesastheyareuploadedormodified,forinstanceifanattackerisabletomodifyafilewith

knownmaliciouscodeitwillbedetectedandquarantinedwithinseconds.

Conclusion
AlthoughitisimpossibletoperfectlyfullysecureaLinuxsystem,wecansignificantlyreducetheamountof
vulnerabilitieswithinasystemandbyextensionthechanceofacompromisebybeingsecurityconscious
andimplementingthesehardeningtips.Thereisalwaysgoingtobeatradeoffbetweensecurityand
usability,wherethatlineisdrawninyourenvironmentisuptoyou.
DoyouhaveanyothersecuritytipsthatyouuseinyourLinuxenvironment?Letmeknowinthecomments
andIllbehappytoupdatethepostsothatwecanimproveuponitandhaveausefulanduptodate
communityresource.

Sharethis:

Related

HowToConfigureKey
BasedAuthenticationfor
SSH
September8,2015
In"HowTo"

Linux,Security

HowToInstallandConfigure
MariaDB
September3,2015
In"HowTo"

LinuxServerMaintenance
Checklist
January7,2015
In"Linux"

Linux,Security

HowtoCreateaWebsiteorBlogwithWordPress

Leaveacomment?

HowToInstallandConfigureMariaDB

1Comments.

HowToConfigureKeyBasedAuthenticationforSSH|RootUserspingbackonNovember21,2015at10:26
pm

LeaveaComment

NOTEYoucanusetheseHTMLtagsandattributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote
cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s>
<strike> <strong>
NAME
EMAIL
WebsiteURL

SUBMIT
Notifymeoffollowupcommentsbyemail.
Notifymeofnewpostsbyemail.

TrackbacksandPingbacks:
HowToConfigureKeyBasedAuthenticationforSSH|RootUsersPingbackon2015/11/21/22:26

LikeRootUsersonFacebook

RootUsers
69likes

LikePage

Bethefirstofyourfriendstolikethis

Subscribe

Share

Subscribetoreceivenotificationsofnewpostsbyemail.

EmailAddress
Subscribe

SupportUs
Youcanhelpsupportthissitebyleavingatip.

Donate
BitcoinAddress:
13HwADqUucxk7LYR57iqPXXabhQJMkuFD8

FollowRootUsersonTwitter
Tweets

Follow

RootUsers
@RootUsers_

10h

LearnHowToSetGNOMEDisplayManager
BannerMessagesinCentOS7#Linux
rootusers.com/howtosetgno
pic.twitter.com/weegEdhXFh

Tweetto@RootUsers_

RecentPosts
HowToSetGNOMEDisplayManagerBanner
Message
OverviewofKiwicon2015
HowToViewBitlockerDiskStatus
ConfigureSquidProxyToForwardToAParent
Proxy
HowToDisableUSBStorageDevicesInLinux

RecentComments
JarrodonHowtoconvertanOVAvirtualmachineto
VHD
breadmasteronHowtoconvertanOVAvirtual
machinetoVHD
JarrodonGzipvsBzip2vsXZPerformance
Comparison
grokonGzipvsBzip2vsXZPerformance
Comparison
JarrodonHowtoIncreasethesizeofaLinuxLVMby
expandingthevirtualmachinedisk

Categories

ExamGuides
HowTo
Linux
Security
Technology
Uncategorized
Windows
XenServer

Copyright2015RootUsers

Vous aimerez peut-être aussi