Вы находитесь на странице: 1из 87

DEBIAN&UBUNTU SERVERHARDENINGGUIDE

VERSION

1.0 - 11/09/2009

AryKokos

SecureNetworkS.r.l ary[DOT]kokos[AT]securenetwork.it

Specialthanksto: ClaudioCriscione QuentinLampin AntonioGalante StphanePoignant LucaCarettoni fortheirhelpandadvices

HardeningGuide 2/87

Index
Forewords...........................................................................................................................7 ColorConvention...............................................................................................................8 Introduction........................................................................................................................9 Astoryofparadigm,menandmoney...........................................................................9 HardeningLinux..........................................................................................................10 FairyTales....................................................................................................................11 I.Forewordonsecuritymanagement...............................................................................13 I.1Onriskandsecuritymanagement..........................................................................13 I.1.1OnITSecurityManagement............................................................................13 I.1.3Hardening........................................................................................................15 I.2Lessonslearnedfromreallife................................................................................16 II.Hardeningguide:MindMap.......................................................................................17 1.Installation....................................................................................................................18 1.1Partitioningscheme................................................................................................19 1.2MinimalInstallation...............................................................................................21 2.AuthenticationandAccessRestrictions.......................................................................22 2.1Authentication:passwordbased...........................................................................22 2.1.1Onpasswordbasedauthentication.................................................................22 2.1.2Choosinggoodpasswords..............................................................................23 2.1.3Howanattackerwilltrytobreakyourpasswords.........................................24 2.1.4Insightonpasswordqualityparameters.........................................................24 2.1.4.1Length.....................................................................................................24 2.1.4.2Entropypasswordgenerator................................................................26 2.1.4.3Social......................................................................................................27 2.1.4.4Easytoremember...................................................................................28 2.2StrongpasswordpolicyPasswordqualityenforcers...........................................29 2.3Authentication:othermeans.................................................................................30 2.4Accessrestriction:physicallyaccessrestriction...................................................31 2.5Accessrestriction:BiosandBootloader...............................................................32 2.5.1BIOS..............................................................................................................32 2.5.2Bootloader......................................................................................................32 2.6Accessrestriction:systemaccessrestriction,unixuserandgroups.....................33 2.6.1Usersandgroups,filepermission..................................................................33 2.6.1.1Filepermissions......................................................................................34 2.6.1.2Usersandgroups....................................................................................34 2.6.2Elevationscheme,usingsudo........................................................................35 2.7Accessrestriction:aboutadvancedaccessrestriction,SELinux..........................37 2.8Accessrestriction:networkaccessrestriction,FirewallingufwandShorewall...37 2.8.1ufw.................................................................................................................38 2.8.2Shorewall.......................................................................................................39 2.8.2.1OnnetfilterandIPTables........................................................................39
HardeningGuide 3/87

2.8.2.2Shorewallinstallationandconfiguration...............................................40 2.9Remoteaccess,OpenSSH.....................................................................................43 3Reducingtheattacksurface...........................................................................................47 3.1Disablingunneededdaemonsandservices............................................................47 3.2Checkingfilepermissionsandsystemexecutables...............................................48 3.3Deletingordisablinguneededuseraccounts........................................................50 3.4TCP/IPStackhardening.........................................................................................51 3.4Disablingipv6......................................................................................................52 3.5Filesystemmountingoptions.................................................................................52 3.6MiscandKernelHardening..................................................................................53 4.Monitoringanddetectingintrusions............................................................................55 4.1Alerttransportmechanism:Postfix......................................................................55 4.2HostbasedIntrusiondetectionsystems.................................................................58 4.2.1OSSEC...........................................................................................................58 4.2.2OtherHIDS....................................................................................................59 4.2.3Rootkitshunters.............................................................................................59 4.2.3.1Rkhunter.................................................................................................59 4.2.3.2Chkrootkit..............................................................................................61 4.2.3.3Unhide....................................................................................................61 4.3Monitoringlogs.....................................................................................................62 5.2.1Logwatch........................................................................................................62 5.2.2Logcheck........................................................................................................63 4.4Watchdogs.............................................................................................................65 5.Keepinguptodateandinformed.................................................................................66 5.1KeepingUpToDate..............................................................................................66 2.2.1Updatingwithapt...........................................................................................66 2.2.2Automaticnotifications..................................................................................67 5.2Informed................................................................................................................69 Chapter6:MitigationandConfinement.........................................................................70 6.1Intro......................................................................................................................70 6.2Accesscontrol.......................................................................................................71 6.2.1SELinux........................................................................................................71 6.2.2GRSecurity,AppArmor,TOMOYO,SMACKandco..................................74 6.3Virtualization........................................................................................................75 Chapter7AdvancedHardening.......................................................................................77 7.1SSH........................................................................................................................77 7.1.1Invisible..........................................................................................................77 7.1.2Dedicatedconnection.....................................................................................77 7.1.3Portknocking...................................................................................................78 7.1.4Airlock............................................................................................................78 7.1.5Antibruteforcing............................................................................................78 7.1.6Usingkeys......................................................................................................79 7.2Antiscanning.........................................................................................................79 7.3KernelHardening...................................................................................................79 7.4Delusionandobfuscation.......................................................................................81 7.4.1HidingBannerinformations...........................................................................81
HardeningGuide 4/87

7.4.2DeludingScans..............................................................................................82 chapter8:randomlittlethings.........................................................................................83 8.1Bashhistory...........................................................................................................83 8.2Blowfish/etc/shadow............................................................................................83 8.3AbsolutePath.........................................................................................................84 8.4WebApps..............................................................................................................84 8.5AboutBubbles.......................................................................................................84 8.6Aboutdedicatedmanagementnetworks................................................................84 8.7Securedeletion......................................................................................................84 8.8GccSSP.................................................................................................................85 8.9MorelinksonIDS.................................................................................................85 8.10DeceptionNetworks............................................................................................85 8.11Bastille.................................................................................................................85 8.12PSAD...................................................................................................................85 AppendixC:Somesecuritylinks...................................................................................86 Advisories:..................................................................................................................86 ComputersecurityexpertsBlogs:..............................................................................86 Othersourceofinformation:......................................................................................86 References........................................................................................................................87 BooksinFrench...........................................................................................................87 BooksinEnglish.........................................................................................................87 OtherHardeningguides...............................................................................................88

HardeningGuide 5/87

Illustrations
Illustration1:Foreword:MindMap...................................................................................9 Illustration2:Chapter1:MindMap.................................................................................14 Illustration3:Samplepartitioningscheme.......................................................................15 Illustration4:Minimalinstall:nothingselectedinthisscreen........................................17 Illustration5:Chapter2:MindMap.................................................................................18 Illustration6:Passwordattacktype..................................................................................20 Illustration7:Randompasswordgeneration(/dev/urandomandtr)................................23 Illustration8:Passwordqualitycheckercontrol..............................................................26 Illustration9:Privilegeelevationscheme........................................................................32 Illustration10:nmapoutputbeforeandafterfirewalling.................................................38 Illustration11:Chapter3:MindMap...............................................................................42 Illustration12:sysvrcconfdaemonconfiguration.........................................................42 Illustration13:Chapter4:MindMap..............................................................................50 Illustration14:rkhuntercheck.......................................................................................54 Illustration15:Chkrootkitatwork...................................................................................56 Illustration16:Unhidesysatwork...................................................................................57 Illustration17:AnextractofaLogcheckreport...............................................................58 Illustration18:Cronapt...................................................................................................63

HardeningGuide 6/87

FOREWORDS
Thisdocumentismeanttobetwothingsatthesametime. Ononeside,anintroductiontocomputersecurityforallthesystem administratorswhoaremovingtoUbuntuinthelastfewyears,butwhoare findingthemselvesinanewworldwherethere'snoofficialSecurityGuide.We hopetoprovideajumpstarttosecuritybestpracticesintheUbuntuecosystem: ifyouaregoingtoworkwiththesesystems,thenthisisagoodplacetostart. Keepinmind,however,thatthisguideisnotmeanttobeawalkthroughinLinux administration:abasicunderstandingofhowtheOperatingSystemworkis required. Ontheotherside,wethinkthatevenexperiencedandsecuritywisesystem administrators,whohavenotyetdevelopedtheirownstandardforsecure installationandhardeningwillfindthisdocumentusefulasareferenceand guide.Maybetherewillstillbeatrickortwoyoudidn'tknowabout. Anyremark,criticorerrorreportiswarmlywelcomed:feelfreetowritetothe authorary[dot]kokos[at]securenetwork.itortome claudio[dot]criscione[at]securenetwork.it. Ihopeyouwillfindthisguideuseful,andmaybethatyouwillhelptoimproveit! ClaudioCriscione

HardeningGuide

Forewords 7/87

COLORCONVENTION

ThecolorideawastakenfromthewebsiteofBobCromwell[Cromwell]:paragraphsare highlightedindifferentcolorsaccordingtotheirlevel. Thismanualmayalsobeusedasaquickreferenceguide:inthiscasethereadermaygo fromhighlightedparttohighlightedpart.

Green1bar: Green instructions correspond to a basic security level, requiring a minimal time investmentbutonlygrantingasmallimprovementinsecurity.

Orange2bars: Orangeinstructions represent alowmediumsecurity levelwhichmayrequire a highertimeinvestment.

Red2bars(1thin,1large): Redinstructionscorrespondtoahigherlevelofsecurity,buthavetobeadaptedto the reader' system, require good understanding of the technologies and their environmentandprobablyalotoftestingbeforegoinglive.

Blue(2fatbars):Stories,anecdotes. Purple(doubleline): Nonfinishedparts.

HardeningGuide

ColorConvention 8/87

INTRODUCTION
Hardening is a process which aims at securing a system ; absolute security is impossibletoreachbutreducingthesurfaceattackandreachinganequilibriumbetween securityandcostispossible. Hardening a server means, at the practical level, reducing as much as possible the attacksurfaceandmonitoringtheexposedparttodetectintrusions. ThisguidewilldescribeandexplainhowtosecureanUbuntuServer(and,tosome degree,aDebiansystemaswell) uptoreasonablelevelofsecurity:acompromise betweensecurity,usability,timeandcosts. AlltheinstructionspresentinthisguideweredoneandtestedonUbuntuServer8.04 orDebianEtch. Beforereadingthis guide,wewouldlikethereadertokeepinmindtwoimportant points: Everyattack,ifyourenemyisdecidedenough,issuccessful

If an enemy is decided enough, he will break in. It is only a matter of how much resourcesheisabletoinvest;andtime.

Linuxisnotasecureoperatingsystem,andwillneverbeone

Mostofourinformationsystemsarefundamentallyinsecure.Thishappensbecausethey werenevermadewithsecurityasaprimaryaim. PopularOperatingsystemssuchasUnix/LinuxorWindowsarenotanexception.

Astoryofparadigm,menandmoney
Onceuponatime,westartedbuildinginformationsystems.

HardeningGuide

Introduction 9/87

Atthistimetheyweremadetobeusedbyalimitednumberofskilledandtrusted persons.Thesystemswererarelyinterconnectedandwhentheywere,thenetworkwas consideredassecure. Thesystemswererarelystandardandonlyalimitednumberofskilledengineerscould understandandusethem. Thesecuritymechanismsweremostlyconceivedtoavoidhumanmistakesorbuggy programs.Andtheywereeffective. Thentheworldchanged. Nowweliveinaworldweresystems becomemoreandmorecomplex,ubiquitous, standardandinterconnectedwhileusersarelessskilledandoftennottrustworthy. Banks, industries and governments which used to operate mainframes and custom systems,nowtendtousestandardsystems,duetotheeconomicalpressure. Andallthosesystemsareinterconnected. Theproblemisthatnowadaysoursystemscannotonlybeattackedbyalimitednumber ofskilledattackersbutalsobythefirstsheepwhoisabletouseasearchengineanda mouse.Communicationinterceptionandinformationsystemsespionnageanddisruption whichwerereservedtogovernmententitiesorsomepowerfulorganization,becomes nowfeasiblebyasinglenonskilledperson. Andwestillusesystemsbasedontheoldparadigm,thatwejustpatchedtoachievea minimalsecurity.

HardeningLinux
Usingalinuxsystemisnotaprotectionbyitself.Itisasvulnerableasawindowsor solaris operating system, and was never conceived to be a secure operating system. Ofcoursesomeprojectstrytoenchanceitssecurity,someofthembylimitingtheattack surface,otheraimingatthecorrectnessoftheconfigurationortryingtoretrofitthe security monitor concept. But as its conception and development does not aim at producinganhighsecuritysystem,thisisquietuselessagainstadecidedattacker.There isnotevenasecuritykernel,norverifiedcodenormandatoryaccesscontrolbydefault. EvenwithaSELinuxpatch,whichgreatlyimprovesthesecurity,itisnotsufficientasit doesnotworkonasecuritykernel.Hugesflawssuchasthepossibilitytopatchthe kernelvia/dev/kmem,runingnetworkfacingdemonsasrootthusrequiringahugeTCB orsharedresourcesarestillpresentondefaultinstalls.Unixsystemsjustfailtoverify thecompletemediation,tamperproofandverifiabilityproperties.Formoreinformation onsecuresystems,weadvicethereadertorefertoOperatingSystemSecurityofTrent
HardeningGuide Introduction 10/87

Jaegerchapter4part2,MorganandClaypoolPublishers;1edition(October7,2008). Hardeningasystemisliketryingtosecureabuilding.Ofcoursethefirstthingsthatyou shoulddoistocheckthatallthedoorsareclosed,forcethepersontouseoneentry, identify them, ask for their ID card an even put a camera and guards. This system will never stop a trained attacker, he will just find a way to enter the building. Butmaybeitissufficienttostopcertainattackers:thenonskilledone,andmaybethat yourthreatmodelonlyconsidersthemandthatyouaccepttheriskrepresentedbythe trainedone. Allthisdiatribeagainstthecurrentsecuritystateshallnotstopyoufromhardeningit. Hardeningasystem,especiallybasedonlinuxisanhardbutfeasibletask:itconsistsin finding the equilibrium between security and costs (including also usability and innovation). The aim of this guide is not to protect you against very determined or competent attackerswhichrequiresarealsecuritymanagement,verycompetentpersonsandalot ofresourcesbuttoprovideyousomeweaponstodefendyoursystemsagainstthemost commonattacks.Thewholeideaistoraiseupthecostofattackingyoursystemsto discouragemostofthenoncompetantattackers. Competantsordecidedonewilleverfindawaytoenter,ifitisnotusingthecomputers itwillbeusingthehumanweaknesses,butnoncompetantsonewillpasstothenext target. Itislikeputtingalockonyourluggageatthehotelwhenyougoout:itwillneverstopa competantattackerwhowilljustlocpickitnoradecidedonewhowilljusttakethe wholeluggageandbreakthelockathome,butitwillkeepmostofthemadeshonest. And for most cases, it is sufficient. If it is not, find an other way to secure your belongings.

FairyTales
Hereareafewstoriesthathappenedduringouraudits. #1IIS.vbs Duringanaudit,nessusreportedusanopenftpserviceonawindowsserveramong hundredofotherones.Insidetherewereafewfilesandastrangeiis.vbs.Openingitwe foundacoupleofcredentials:Administrator/companyName=000.Aswecouldnot believeitwetrieditandgotfulladminaccessonthismachine. Afterwardwediscoveredthatthiscomputerwasusedtoautomaticallydeploy/updated applicationsonallthedomain.

HardeningGuide

Introduction 11/87

#2Oracleforms Duringapentest,after10daysexploitingSQLinjections,wecasuallydiscoveredthat thedevelopersleftalogin/passwordinthehtmlcommentsoftheoracleformswebpage. Thesecredentialsgivesfullaccesstoallthedatabase. #3Jbossandbackup.tar DuringaVA,wefoundaJbossadmininterfaceleftopen.Loadingashell.war,we startedwalkingaccrossthedirectories.In/tmpwefoundcredentialsforanftpservice,a lotofdeploymentscriptswith5usercredentialsanda6Gobackup.tar. Fromthecredentialswelearnedthepasswordschemeofthecompany: companyNameService,letsaythatthecompanynamewasfoo,the"webservers" accountpasswordonthe"webserver"hostwasfooWeb,theoracleaccountontheoracle serverwasfooOra,thetomcatfooTomandsoon.Wequicklygotaccesstomostofthe companyservers.Ofcourseallthekernelwereold,anvulnerables,especiallytothe vmsplice()localrootexploit. Fromthebackup.tar,wegotaccesstoallthecompagnysofwaresourcecode. Inothercaseswegotaccesstoallthecustomersdatabasebyasingletelnetl"froot"on anoldsolarissystem.Othertimesitwasjustbyusingjohnon/etc/shadowobtainedvia adirectorytrasversal(theadminleftthefileworldreadable). Allthoseattackscouldhavebeenavoidedbyverysimplesecuritymeasures. Thosearetheonedescribedinthisguide.

HardeningGuide

Introduction 12/87

I.FOREWORDONSECURITYMANAGEMENT

GOAL: THISCHAPTERWILLPROVIDEASHORTINTRODUCTIONTOITSECURITYMANAGEMENT, PRESENTINGSOMEIMPORTANTNOTIONS,MOSTLYUSEFULTOASYSTEM ADMINISTRATORINORDERTOUNDERSTANDTHENEXTPARTS.INASECONDPART, SOMEREALLIFESTORIES.EXPERIENCEDSECURITYSPECIALISTSMIGHTWISHTOSKIP THISPART.

Illustration1:Foreword:MindMap

I.1Onriskandsecuritymanagement I.1.1OnITSecurityManagement
HardeningisapartofITsecurityManagementwhichisitself,inmostmodels,apartof riskmanagement. InthelastyearsITsecurityevolvedfromatechnicalscience,involvingmostlytheIT department,toamanagementactivitydrivenbythetopmanagement:fromcomputer securitytoinformationsecurity. Afewyearsago,threatsrarelycamefromthenetworkandwheremostlycomingfrom the inside. Securing the system was a matter off controlling access and preventing physicaldisasters.Nowadaysthemajorpartoftheinformationisdigitalizedoncomplex interoperableubiquitoussystems: systemsneedtobeinterconnectedandinteroperable theinformationisstoredanywhere,fromamainframetoaPDAandweexpecttoeasily accesseveryinformationfromeverywhere
HardeningGuide I.Forewordonsecuritymanagement 13/87

systems

become more and more complex and hence harder to secure.

Duetothechallengesposedtothelastthreepoints,whichcompletelychangethescale bothinnumbersandinsizeoftheinvolvedtechnologies,,securityisinafirstplacea matterofmanagement,andthenatechnicalmatter. TheclassicalcycleofITgovernanceisverysimilartoaDeming'swheel,oraPlanDo CheckActcycle:: 1Identifyingrisksandobjectives Identifywhicharetherisks,whichisusuallydoneregardingto: Confidentiality Integrity Availability Traceability Wewillnotgointomoredetailsonwhatariskisandhowitshouldbeidentifiedinthis introduction,butwewillusethetermRiskintherestoftheguideasasynonymof Threat,evenifweknowthataThreatisonlyapartofaRisk. Oncetherisksareidentified,foreachofthem,youwillusuallyneedtoevaluate: Theoccurrence:whatistheprobabilityofthisriskhappening Theimportance(orimpact):whataretheconsequencesregardingthisrisk(direct andindirectlossesintermsofproductivity,reputation,confidentialinformations, etc.)

Onceidentified,anactionshouldbetakentodealwitheachrisk,fromthefollowinglist. Aswewillsoonsee,theseactionsaremergedintoaglobalPlan. Avoidance(eliminate) Reduction(mitigate) Transfer(outsourceorinsure) Retention(acceptandbudget) from[Wriskmana] 2Planning Thispartconsistinstudyingandchoosingthebestsolutionforeachrisk,whichwill consistbothintechnicalandhumansolutions. Thispartresultsinanorganization(orbusinessunit)plan. 3Deployment Realizingtheplan,bysettingrulesandregulations,whichshallbeenforcedasany
HardeningGuide I.Forewordonsecuritymanagement 14/87

otherexistingcompanypolicy:whenitcomestoinformationsecurity,however,traning fortheusershastobeconsideredasacorepartofthesolution,sincesecurityalways requires atradeoff withusabilityandusersarenotalways happytobepartof the process! Once policies and training is in place, technical means to enforce them should be devised and applied: every security system and technical procedures falls in this category. 4Use Governanceofusageincludestwodifferentkindofoperations:everydaytask,thatis updating,processinglogs,backups,keepingadministratorsandusersinformedonnew trendsanduptodate,addingnewusersandsoon;andexceptionaltasks,whichinclude reactingtoanintrusion,checkingananomalyandsoon. 5Check Thisstephastobeperformedinordertoevaluatetheoverallefficiencyofthesystem. Thisisusuallyachievedthroughtwodifferentmeans,thatisbyleveragingactivechecks andpassivechecks.Auditarethemostwellknownoftheactivechecks,andcanbeboth internalandexternal.Eachtypeofaudithashisownprosandcons,externalauditbeing oftenlesspervasivebutfarmoreobjectiveandtrustableandinternalauditbeingableto reachgreateardetails(duetotheknowledgeoftheauditedinfrastructure)butbeing subject to greater biases from the context. Passivechecksencompasseverycontrolwhichisroutinelyperformedbymanual or automatedmeans,likelogcheckingorautomaticdetectionofattacks. Forfurtherreading,weadvicethereadertorefertothepointersinthereferencepartand to well designed methods for risk assessment and management such as EBIOS, MEHARI,CRAMMorOCTAVE.[Mehari]

I.1.3Hardening
Hardeningisaprocesswhichaimsatsecuringasystem;absolutesecurityisimpossible toreachbutreducingthesurfaceattackandreachinganequilibriumbetweensecurity andcost(wherewithcostwerefertobothimplementation,manteinanceandusability costs)ispossible. Hardeningaservermeans,atthepracticallevel,reducingasmuchaspossibletheattack surface,andmonitoringwhatisexposedtodetectintrusion.

HardeningGuide

I.Forewordonsecuritymanagement 15/87

II.HARDENINGGUIDE:MINDMAP

HardeningGuide

II.Hardeningguide:MindMap 16/87

1.INSTALLATION

IN THIS FIRST CHAPTER WE WILL FOCUS ON THE SYSTEM'S INSTALLATION,AIMING AT AMINIMALINSTALL.

Illustration2:Chapter1:MindMap Hardeningasystemismucheasierifyoustartfromaminimalisticsystemandthenadd onlytheneededservices.Hardeningacomplexsystemispossiblebuthasahighercost andismuchmorecomplicated,sinceitiseasytoforgetsome(apparently)harmfulness piece of software somewhere in the machine. Even with modern packet managers, handlinginstalledpackagesisn'taneasytask. Importantnote: Averyimportantpointistoonlyperformatomicoperationswhich canbeeasilyrevertedincaseofamistake.Thismeansthatifyouareeditingyour OpenSSHServerconfigurationfilesyoushouldnotmodify5parametersatthesame time:incaseofamistakeyouwon'tbeabletoindividuatewhichoneisresponsibleof thefailure.Insteadchangethefirstoneandtest,thenproceedtomodifythesecondone andsoon. Virtual machines: If possible, and relevant regarding your requirements, use virtualizationtoyouradvantage:

fortestingpurpose:revertingtoapreviousconsistentstateusingsnapshotsisvery simple copying,makingabackup,moving,deployingvirtualmachinesisdoneinavery shortamountoftime

Therearealotofdifferentsolutionsonthemarket,formoreinformationweinvitethe readertoreadthecorrespondingWikipediaarticle [Virt].Forinformationalpurposes, theauthorusedVMwareServer[VMware]whiletestingthesetupinthisguide.

HardeningGuide

1.Installation 17/87

Ubuntu server installation is straightforward and well documented [Ubuntu Server Install],andthereareonly2pointstowhichyoumaytakecareof:partitioningand packageselection. ForDebianinstallation,thereaderisadvisedtorefertothisdocument[DebianInstall]

1.1Partitioningscheme
Duringtheinstallation,youwillbeaskedforapartitioningscheme;apartitionisa logicalpartofyourharddiskonwhichyouwillputafilesystem,whichinturnwill containyourfiles. Theeasiestsolutionistoputallinasinglepartition,butitdoesn'tprovideasmuch granularcontrolashavingdifferentpartitions.

Illustration3:Samplepartitioningscheme Differentpartitionscanbeusedfordifferentmeans,letseeitthroughsomeexamples:
Performance :ifyourserveractsasavirtualmachinehost,having/var ona

secondpartition(orbetteraseconddisk)withthe noatime option(notwritingthe lastaccesstimeofthefiles)improvesperformancesnoticeably.(nbputtingnoatime onthewholesystemisverybadforaccountability,sinceanext3filesystemwiththe noatimeoptionwillnotrecordaccesstimetofiles.).

HardeningGuide

1.Installation 18/87

Security:someattacksrelyonbeingabletoexecutebinariesin/tmp,mounting

tmpwiththenoexecoptionwillpreventthisfamilyofattacks
DOSdefense :ifforsomereasonadaemonstartstogeneratealotoflogsand

completelyfillyourdrive,therewillnotbeenoughplacefornormaloperations:this will most likely result in a DOS for your system, which is generally named StarvationDOS.Hereasolutionistoput/var/loginadifferentpartition. Tochooseapartitioningscheme,thefirststepistoidentifythefunctionoftheserver andwhataretherequirementsofthesoftwareswhichwillrunonit. Forexampleamailorawebserverwillrequireabig/varbutnotabig/home. A VMwarehostwillrequireabig/var/lib/vmware. Makingthischoicesisnoteasy,butwecanidentify2approaches: basedoncalculus basedonexperiment Buildingatestmachineandmonitoringactual,realworlddiskusagemaybeagood optionifenoughtimeisavailable,aswouldbeanalyzinganexistingmachinecoveringa similarrole. Asaruleofthumb,mostnetworkdeamonsleverageasubdirectoryof/varastheirmain storageinUbuntu. Someexamplesofpartitioningschemesfollow;mountoptionswillbedescribedlater. Exampleforamailorwebserver(alotofdatain/var): / swap /tmp /home /var /var/log ExampleforaVMwarehost(itisbettertohaveadedicatedpartitionforVM):

/ swap /tmp /home /var /var/lib/vmware

HardeningGuide

1.Installation 19/87

1.2MinimalInstallation
Choosetheminimalinstall,justthebasicsystem,nothingmore:inthisway,evenifyou willhavetoinstallmorepackagesatalaterstage,youwillretainfullcontrolofwhatis installedinyoursystem.Hardeningisalsoaboutcontrol,sinceattackersdon'treally whetheryouareusingavulnerablesoftwareinstalledonyourmachineornot.

Illustration4:Minimalinstall:nothingselectedinthisscreen

HardeningGuide

1.Installation 20/87

2.AUTHENTICATIONANDACCESSRESTRICTIONS

IN THIS PART WE WILL PRESENT SOME AUTHENTICATION PARADIGMS,WITH A SPECIAL INSIGHT ON PASSWORD QUALITY.THEN WE WILL CONTINUE ON ACCESS RESTRICTION ATSYSTEMANDNETWORKSLEVELS.

Illustration5:Chapter2:MindMap

2.1Authentication:passwordbased
Oneofthekeytosecuritycanbesummarizedasfollows: Choosegoodpasswords. Itisthatsimple.Choosegoodpasswords,foranyuserofanyservice,andyouwill noticeablyimprovethesecurityofyoursystem. From all the possible authentication schemes, password based ones are the most commononeastheyarethedefaultmechanismforalargemajorityofsystemsandare verylowcost,sincetheymostlikelyonlyrequireakeyboardtobeused. Goodpasswordsareoftremendousimportanceastheyareusedtogainaccessoruse privileges. Weakpasswordsarestilloneofthemostwidelypresentandexploitedvulnerabilityofa system.

2.1.1Onpasswordbasedauthentication
Beforedescribingthedifferentparameterswhichmakegoodpasswords,itisimportant
HardeningGuide 2.AuthenticationandAccessRestrictions 21/87

tounderstandwhatagoodpasswordactuallymeans: Agoodpasswordisapasswordwhichisnoteasilyguessablenoreasilyforced. Not easilyforced meansthatifanattackertriesalotofpasswords,withoutanyother knowledge,itwillrequirehimalongenoughtimetofindtherightone. Herethequalityofthepasswordisnotheonlyparameter,thesystemwhichwillcheckit isasimportantasthepassword. If thereisany flawintheauthenticationmechanism,thequalityofthepassword becomesuseless.Herewewilltakeanexampleofanexploitfoundonmilw0rm:
==================================================== 3Com OfficeConnect Wireless Cable/DSL Router Authentication Bypass Original Advisory: http://www.ikkisoft.com/stuff/LC-2008-05.txt luca.carettoni[at]ikkisoft[dot]com ==================================================== An unauthenticated user may directly invoke the "SaveCfgFile" CGI program and easily download the system configuration containing configuration information, users, passwords, wifi keys and other sensitive information. http://<IP>/SaveCfgFile.cgi

Thiskindoferrorscanalsobefoundattheoperatingsystemlevel,forexamplethe telnetlfrootcommandwhich,onsomeversionsoftheSolarisoperatingsystem, leadtoaremoterootshell.1 Thetimerequiredtocheckthepasswordisalsoimportant: Asystemwith6charpasswordwhichrequiresalmost20secondstocheckapassword forcorrectnessismuchsaferthanasystemwith8charswherecheckingonepassword will require 1/10000s (time to check all the keyspace 26^6*20 =6e9 vs 26^8/10000=2e7). Obviously, speed check can be tremendously influenced if the authenticationisperformedoveranetwork. Lastbutnotleasthavingacomplexpassword,buteasilyguessable,isuseless. DuringaVulnerabilityAssessment,forinstance,wesawsystemadministratorsusing theircompanynamewritteninpseudoleetasrootpasswords.Ifthecompanyname wasArtichaud,thepasswordwas4rt1ch4ud,whichtechnicallyisnotabadpassword, butisdefinitelyeasilyguessablebyanattacker.

1 http://milw0rm.com/exploits/3293
HardeningGuide 2.AuthenticationandAccessRestrictions 22/87

2.1.2Choosinggoodpasswords
Do Don't

At least 8 characters containing Generic passwords such as admin, special char such as ,.:_&/ is a Password0,root,password,etc minimum 10to12isadvisedorpassphrases Choose passwords which will be Passwords related to publicly available accepted by your users and easy to informationsuchas company'sname,server remember. function,personalinformation Use password quality enforcers to Words present in any dictionary of any checkthequalityofthepasswords. language

2.1.3Howanattackerwilltrytobreakyourpasswords
Whenanattackertriestobreakapassword,hewill:
1:trygenericpasswordslikeadmin/admin,Administrator/Passwordordefaultones.

Anicelistofgenericpasswordsisavailablehere:[DefPAssList] Evensomewormswilltrytoleveragedefaultortrivialpasswordsinordertogainaccess toremotesystems.


2:identifyandgeneratealistofpasswordsrelatedtoyouoryourcompany,ortothe

functionoftheserver. Database isneveragoodpassword. Thisisgenerallycalleda targetedattack.

3 : leverage a dictionary, submitting any and all words in it, or even multiple dictionariesindifferentlanguages. 4 : if everything else fails, perform a bruteforce, that is trying all passwords, coveringallthesocalledkeyspace,thatisthesumofallthepossiblecombinations which can be generated using all the characters supported by the system up to the maximumpasswordlenght.Thiswillrequiretime,dependingonthespeedthecheckis performedandthesizeofthekeyspace.

2.1.4Insightonpasswordqualityparameters
Thequalityofapasswordcanbejudgedbymanydifferentparameters.Inthissection wewilldiscusssomeofthemandhowtheyinteracttocreateastrongpassword.
HardeningGuide 2.AuthenticationandAccessRestrictions 23/87

2.1.4.1Length

One of the most important parameter is the keyspace : the quantity of possible passwords.Abiggerkeyspacemeansabiggernumberofpasswordstotest,andsoa longertime:ifcrackingitrequires10daysforanadminpassword,thereisnosecurity; insteadifitrequires200yearsitissafeforanormaluse. Thekeyspacesizedependsonthelengthofthepasswordsandthedifferentcharacters whichcanbeused. Herearesomenumbersjusttoillustratetheprinciple. Type Numbers,4 Char,8 Char,num,8 Char,maj,num,8 Char,maj,num,special(mostused),8 Char,8 Char,12 Char,maj,num,special(mostused),12 Char,17 3251 fkjduhad g5su96po kL89klI9 Jla@K:5& fkjduhad jatnpkcfslzk d=dLt@9p:kS7 Password Keyspace 10^4=1000 26^8=2.1e11 36^8=2.8e12 62^8=2.2e14 92^8=5.1e15 26^8=2.1e11 26^12=9.5e16 92^12=3.7e23

urjanhdpemkjtqplm 26^17=1.2e24

Longstoryshort:ifyoudon'tusespecialchar,usealongerpasswordtocompensate. RainbowTables:Insomecaseshavingalongpasswordisnotsufficient. Normallyapasswordisneverstoredincleartext:thereisnoneedforthat,sinceevery checkandcomparisoncanbeperformedbytheoperatingsystembyonlyleveragingits hash.Ahashisamathematicaloperationwhichcanassociateanydatatoafixedsize chunkofinformation:agoodhashshouldberesistanttocollisions(i.e.itshouldbevery difficulttoidentifyaninputwhichwillproduceagivenoutput)andthisisthemost importantrequirementinthesecurityframework. Hereisanexamplewithawellknownhashingalgorithm,sha1: a:~a$echo"hello"|opensslsha1 f572d396fae9206628714fb2ce00f72e94f2258f a:~a$echo"hella"|opensslsha1 1519ca327399f9d699afb0f8a3b7e1ea9d1edd0c a:~a$echo"Thisisalongphrase"|opensslsha1 18cfab92cf66ef9f2ae4c5302ba3d500d307377e Noticehowthehashof hella isquitedifferentfromtheoneof hello.Sinceitisnot possibletoinvertthefunction,foranygoodhashingfunction(wherecollisionsarenot
HardeningGuide 2.AuthenticationandAccessRestrictions 24/87

easilyachievable)anattackerneedstocalculatethehashforeverypasswordhetriesand thencompareit.Thiscalculusisverytimeconsumingwhenperformedonsuchahuge amountofdata.However,everytimeagivenstring,forinstancehello,ishashedwiththe samealgorithmtheoutputisthesame:f572d396fae9206628714fb2ce00f72e94f2258f. Anattackercouldjustbuildadatabaseofallpossiblepasswords,thesocalledRainbow Tables, dramaticallyreducing calculustimefromahashtoaresearchinadatabase. That'swhymodernsystemsusesomethingcalledsalt,arandominputaddedtothe calculus.Thisisjustadummyexampletoillustratetheconcept: passwordishello;salt=12;hash(pass,salt)= 8f28e3ba39c87dacc148385e58ffe3a772b624b2 passwordishello;salt=18;hash(pass,salt)= 9e720243cd309b471faad1259cfe14ca4c4190ab SomenonLinuxoperatingsystems(mostnotablyWindows)arevulnerabletoRainbow Table attacks, and tools/rainbow tables are available such as ophcrack2 or the Free RainbowTablesproject.
2.1.4.2Entropypasswordgenerator

Havingabigkeyspaceisnotsufficient:thesecurityofthepasswordalsodependsonthe probabilitythatyouchoosearandompassword.Let'stakeanexampleofasysadmin whousedtochoosehispasswordslikethis(pippohereishisowncompanyname): Pippo1927? Pippo5672! Pippo9232. Pippo1532; Pippo3427: Hispasswordswerequietcomplex,butwerealwaysdoneonthesamescheme:10chars, startingwithPippo,4numbersand1specialchar:theentropyofthepasswordsisvery low. Sohereyouhavetwosolutions:eitheruselongpasswordsorgetthemfromagood sourceofrandomness,forex/dev/urandom. #SCRIPT:Generationofarandompasswordinbash password="$(trdc"[:alnum:]"</dev/urandom|headc10)"; echo"Passwordis:${password}" (usepassword="$(trdc"[:print:]"</dev/urandom|headc10)";forabiggerkeyspace (:print:includesmorecharsthan:alnum:),seemantrfordetails)

2 http://ophcrack.sourceforge.net/
HardeningGuide 2.AuthenticationandAccessRestrictions 25/87

Someoutputs:

Illustration6:Randompasswordgeneration(/dev/urandomandtr) For further informations, the reader can refer to a NIST document3 or the SANS passwordpolicy4

2.1.4.3Social

As we said before while describing the targeted attack type, an aggressor will try passwords related to the server context, such as name of the company or personal informationrelatedtotheadministrationstaff.Asfordictionaryattacks,therearehuge wordlistsavailableontheInternet,forexampletheoneprovidedbyopenwall5 .:::::;):::::. Arethosepasswordsstrong? balderdash/Quatsch windowgardening SieistfranzoesischerHerkunft! !@#$%^&* LegenSieetwasfuerschlechteZeitenzurueck! maxtrix4x uranium235 SPSPARC&CACHE 3http://csrc.nist.gov/publications/nistpubs/80063/SP80063V1_0_2.pdf
4 www.sans.org/resources/policies/Password_Policy.pdf

5ftp://ftp.openwall.com/pub/wordlists/all.gz
HardeningGuide 2.AuthenticationandAccessRestrictions 26/87

Solution:noIgotthemfromtheall.gzwordlist
2.1.4.4Easytoremember

Strong,complexpasswordsarenotsuitableforallsituations:iftheyaretoocomplexto remembertheuserwillwritethemdownonapaper,undertheirkeyboardor simply forget them. 3B9d31c6e3d10ebf is a good password, but a very difficult one to remember.

ALWAYSCONSIDERTHEPSYCHOLOGICALASPECTOF

SECURITY.IFSECURITYISNOTACCEPTEDBYYOURUSERS, THEYWILLTRYTOFINDAWAYTOBYPASSIT.

ANEXAMPLE:SOMECOMPANIESHAVETHEIRUSERSCHANGINGTHEIRPASSWORDEVERY MONTHWERETHEREISNONEEDTODOIT.THISALWAYSRESULTSINTODUMBPASSWORDS, SUCHASAUGUST2008,SEPTEMBER2008(MORETHAN8CHARS,1CAP+NUMBERS).

ADMIN PASSWORDS Importantpasswords(root/admin/encryption): Agoodpasswordshouldbeaminimumof 12chars long,withnumbers,upcase, lettersandspecialchars,oralongpassphrase(morethan24chars). Aswesaidbefore,youcancompensatelackofentropybylength Toremember,asolutionmaybetouseashortstory: passphrase:marrygavemethreedollarsandarose password:marry3$&1ROSEormarry3$ROSE Commonpasswords: 12charsshouldbeusedtoo,butifyourusersarenotabletorememberthem,8to10 charsmaybeused. USER PASSWORDS Outside an high security context, it is very difficult to make users choose good passwords. The best solution would be a 8 to 10 characters long password which includes both alphanumeric and special characters, but as they are difficult to remember,agoodsolutionistheuseofpassphrases. Anempiricalstudyisavailablehere:[RossAndersonSHB2008]
HardeningGuide 2.AuthenticationandAccessRestrictions 27/87

2.2StrongpasswordpolicyPasswordqualityenforcers
Agoodpasswordpolicythatis,awrittenrulerequiringuserstohavestrongpasswords isnecessary,butitwillneverforceanusertousegoodpasswords. Toenforcepasswordquality,wesuggest2simplesolutions: retroactive:regularlyauditthepasswords proactive:forbideveryweakpasswordwhentheuserstrytosetone ProactivepasswordenforcingcanbedoneeasilyviaapackageincludedinUbuntu, libpampasswdqc,whichwillcheckthequalityoftheproposedpasswordandrefuseit ifitistooweakaccordingtoitsconfiguration. #aptgetinstalllibpampasswdqc #nano/etc/pam.d/commonpassword add: Forahighsecuritysystem: "password required pam_passwdqc.so max=72 similar=deny enforce=everyone retry=2ask_oldauthtok=updatecheck_oldauthtok" Thisisadefaultbehaviour,abitparanoidandsometimesabitannoyingforsystems whichdonotrequireanhighsecurity,soyoushouldlowertherequirements.

USEPASSWORDQUALITYCHECKERSTOLIMITTHE

USEOFWEAKPASSWORDS

Illustration7:Passwordqualitycheckercontrol
HardeningGuide 2.AuthenticationandAccessRestrictions 28/87

Foramultiusersystem,mediumsecurity Example:passwordrequiredpam_passwdqc.somin=disabled,12,8,6,5max=40 From the manpage http://linux.die.net/man/8/pam_passwdqc : min=N0,N1,N2,N3,N4 (min=disabled,24,12,8,7)Theminimumallowedpasswordlengthsfordifferentkinds ofpasswords/passphrases.Thekeyworddisabledcanbeusedtodisallowpasswords ofagivenkindregardlessoftheirlength.Eachsubsequentnumberisrequiredtobe nolargerthantheprecedingone. N0isusedforpasswordsconsistingofcharactersfromonecharacterclassonly.The character classes are: digits, lowercase letters, uppercase letters, and other characters.ThereisalsoaspecialclassfornonASCIIcharacterswhichcouldnotbe classified,butareassumedtobenondigits. N1isusedforpasswordsconsistingofcharactersfromtwocharacterclasseswhichdo notmeettherequirementsforapassphrase. N2 isusedforpassphrases.Apassphrasemustconsistofsufficientwords(seethe passphraseoptionbelow). N3 and N4 are used for passwords consisting of characters from three and four characterclasses,respectively. Forfurtherreading,checkhttp://www.openwall.com/passwdqc/.

2.3Authentication:othermeans
Insomesituationspasswordbasedauthenticationisnotappropriated: Inenvironmentrequiringaveryhighlevelofsecurity,policiesmayrequiremultiple factorauthentication. Whenusersuseweakpasswords,writethemdownorpassthem,andthereisno nontechnicalmeantoavoidthisbehaviour. Generallyspeaking,authenticationcanbeperformedthroughthreedifferentmeas Whatyouknow Examplesofthiskindofauthenticationarepasswordbasedauthentications,butother examplesinclude,forinstance,asetofquestionswhichtheuseristheonlyoneableto answer.

HardeningGuide

2.AuthenticationandAccessRestrictions 29/87

Whatyouhave This authentication schema is performed by showing the system the user owns something:itcanbeaphysicaltoken,asmartcardoradigitalcertificateitself. Whatyouare While this is mostly used for identification purposes, what you are, biometric authenticationmeansarebecomingincreasinglycommoninmanyscenarios. Withstrongauthenticationinmostofthecaseswemeanmultiplefactorauthentication, i.e.leveragingmultipleauthenticationmeansatthesametime.Forexampleasmartcard (oratoken,orsomethingyouhave)whichwillrequireaPIN(somethingyouknow) inordertobeunlockedandbeabletoperformauthentication. Thefollowingtablepresentsashort,bynomeanexhaustivelistingsofauthentication means:
Technology FreeSolution Commercial Solution Pros Cons Maninthemiddle Socialengineering

Onetimepassword Listofpasswords onapapersheet Aonetime passwordis OPIEorS/Key generated,theuser basedwith hastoenteritto softwareon authenticate cellphone OTPoverSMS Biometrics

Usingatokensuch Lowcost asRSASecurID, Entrustidentity Easytouse guard,etc

Canbetricked, sinceit'soften undertraineddueto overfittingissues. Openssl WithPINon smartcard,very strongauth Costs Complextosetup

Publickey cryptography Certificates

2.4Accessrestriction:physicallyaccessrestriction
Physicalsecurityshouldbeconsideredwithgreatcare,ifanattackerhasphysicalaccess totheservers,heownsthem:somanyattacksareavailablewithlocalaccesstothe systemthatitisalmostimpossibletovoidthemall,withoutimposingagreatburdenon theserverperformance.

HardeningGuide

2.AuthenticationandAccessRestrictions 30/87


2.5.1BIOS

NOPHYSICALSECURITY=NOSECURITY

2.5Accessrestriction:BiosandBootloader

Bydefault,BIOSaccessisnotrestrictedinmostcomputers,whichmaybeanissuein certaincases:
Iftheattackerhasaphysicalaccesstothemachine,hecanbootonalivecdandaccess

allthediskcontentinbothreadwritemodeswithoutbeingstoppedbyfilepermissions, accesscontrolsorbeingsubjecttoanyrestriction.Itisthustrivialtoinjectrookitsor malwareinthesystem.


Hecanalsosetanadminpasswordwhichisrequiredatboottimeandthusimpacton

theserveravailability.

SetanadminpasswordonyourBIOS,andonlyallowmodificationifthepasswordis given. Set HDD as the first boot device, ensuring boot order cannot be manipulated. If possibledeactivateNetworkBoot Theprocedureisvendorspecific,sochecktheBIOSmanualfordetailedinstructions. Ifthesituationrequiresit,insomerarecasesyoumaysetabootpasswordwhichwillbe requiredateveryboot.Ifthisusageisabsolutelylogicforalaptop,itmayimpactthe availabilityofyourserverastherealwaysshouldbesomeonetoenterthispassword.

2.5.2Bootloader
Forsimilarreasons,yourbootloadershouldbepasswordprotectedagainstanychange: tipicallyanattackerwilltrytobootinsinglemodeinordertogetfulladministrative access,bootonanotherkerneloranotherdevice. Passwordprotectingthebootloarder(whichismostlikelyGrubonanynewinstallation) isthusofprimaryimportance:atrivialinit=/bin/bashattheendoftherootbootlineis enoughtobypassanypasswordangainrootaccesstothesystem.Usingapasswordwill preventtheattackerfromtamperingtheGrubconfiguration.

HardeningGuide

2.AuthenticationandAccessRestrictions 31/87

Passwordprotectinggrub: Firstweshallcalculateasaltedhashofthepassword:it'snotagoodideatousea plaintestpassword,sinceshouldanattackermanagetoread/boot/grub/menu.lsthe wouldeasilyretrievethepassword. arik@montmiraille:~$grub grub>md5crypt md5crypt Password:password1234 password1234 Encrypted:$1$dNSZt$c/k5TILRxiWsclSxOrfnJ/ Now,editingthe/boot/grub/menu.lstfile,wewilladdthefollowingline,inthefirst section,asthefirstline: passwordmd5$1$dNSZt$c/k5TILRxiWsclSxOrfnJ/ Thiswilldisableanyinteractiveeditingcontrolandentriesprotectedbythekeyword lock:foralltheentrieswhichdonohavetobeactivatedbyanunauthorizeduseradd thelockspecifierasfollows: title Boot dos lock rootnoverify (hd0,1) makeactive chainloader +1 Ifyouusethekeywordpasswordinsteadoflock,thengrubwillaskforthepassword atboottime. Lastasmenu.lstisbydefaultworldreadable,makeitreadableonlybyroot: #chmod600/boot/grub/menu.lst

2.6 Access restriction : system access restriction, unix user and groups 2.6.1Usersandgroups,filepermission
OnanyUnixsystem,usersareidentifiedwithinthekernelbyauniquenumbercalled UID(UserIdentifier),whichisthenlinkedtoausername.Anyusercanbelongtoany numberofgroups,withaminimumofone.Thecombinationoftheusernameandtheset
HardeningGuide 2.AuthenticationandAccessRestrictions 32/87

ofgroupstheuserisamemberofisleveragedtoallowordenyactions(i.e.fileaccess) totheuser.
2.6.1.1Filepermissions

Onatraditionalun*xlikesystemafilewillhaveasetofpermissionsconfiguredforthe owneruser,fortheownergroupandforeveryoneelseinthesystem.Privilegesare expressedusing9bits,whichcanbeeasilyretrievedusingasimplelslcommand. Forexamplealslontextowillgive: rwxrxr1user1wheel802009012819:05texto :thefirstdashissignalingthelistedfileisindeedafileandnotadirectory,which wouldresultinad. rwx:thefirst3charsarefortheuseruser1,ownerofthefile:hemayread,writeor executethisfile rx:appliestothegroup,herewheel:usersmemberofthegroupmayexecuteor readthefile rappliestoalltheotherusersofthesystem:theymayonlyreadthefile Onlytheownerofafilemaychangeitsrights:thisactionisperformedthroughthe chmodcommand. Chmodcanbeused: Usingthepeculiarx+yway toallowothertoexecutethefile:chmodo+xfile toremovetheright:chmodoxfile forthefirstparameterugocanbeusedandrwxforthesecond one withtheXXXwaycalculatedaccordingto: r w x r w x r w x 400 200 100 40 20 10 4 2 1

Forexample,toputfileinrwxrxrxchmod755file Directoriescanalsobechmoded,andrecursivlytoobychmodRXXXdirectory
2.6.1.2Usersandgroups

Ownershipofafilecanbechangedbychownandchgrp,respectivelymanagingthe owneruserandgroup. Withrightsandgroups,wecanallowonlycertainentitiestodocertainactions. ForexampleifIwanttoallowonlyJohn,JackandWillietorebootmySMSserver: addjohn,jackandWillietoasmsAdmingroup makesmsmanager.shbelongtomeanddefinehisgrouptosmsAdmin chmoditrwxx FortmoreinformationonSUIDseeappendixonchroot


HardeningGuide 2.AuthenticationandAccessRestrictions 33/87

2.6.2Elevationscheme,usingsudo
Toperformimportantoperation,youneedtoactasanadministrator: Onmost linux distributionswehaveaclassicaluser/rootmodel:usershavelimited privilegesandshallsutorootforprivilegedoperations. Theelevationschemeis: loginasrootandexecutecommandsORloginanormaluser,su,executecommands Ubuntu's developers adopted a different model, based on sudo : for administration purposes,oneshallconnectasanusermemberoftheadmingroupandthenperform privilegedoperationswithsudo. Theelevationschemeis: loginasaprivilegeduser,thansudocommand. Thisschemeissuitableforalaptop/workingcomputerbutmaypresentsomerisksfora server: Whathappensiftheadmin(orroot)passwordiscompromised(keylogger,shoulder surfing,etc)?Anyonecandirectlylogin. What if the log in mechanism is flawed or if there is a possible attack on the authenticationmechanism.(Thisdohappened,thinkoftheOpenSSLDebianissue6) Thefirstthingtoassumeisthattheadminpasswordisalwayscompromised:directroot loginoutoftheconsoleshouldnotbepossible(forexampleviaSSH).Ofcourseyou willneedtologinasadministratortomanageyourserver,butweneedtoaddanextra layerofauthenticationtodoso. HereweproposeamodelsimilartotheBSDoneandintegratedwiththesudowayof Ubuntu:usesudoasitpermitsafinergrainedcontrolandloggingfacilitieswhileusing awheelgroup:onlymembersofthewheelgroupcanusesudo. With this model we have 2 kind of users : normal users and administrators. Only administratorscanusesudo(sutorootdoesn'tworkonastandardUbuntuinstallation), but,outofthelocalconsole,logingasadministratorisnotallowed. Soausershallfirstlogasanormaluser,thensutoadministratorandthenusesudo.If theadministratorpasswordiscompromised,theattackerwillneedtocompromisean otheraccounttobeabletousethepassword.Ifhecompromisesanormalaccount,he 6 DebiandevelopperpatchedOpenSSHwhichreducedtheentropyofthekeysto16 bitandsopermittobruteforcethemquickly.Moreinformationhere: http://www.metasploit.com/users/hdm/tools/debianopenssl/
HardeningGuide 2.AuthenticationandAccessRestrictions 34/87

won'thaveanyspecialrights.

Illustration8:Privilegeelevationscheme

Here,wewillsetupamodelwhere: usersshallfirstloginasnormalusers thensutoaprivilegedaccountiftheyneedtoexecutesensiblecommands. Firstaddanewuser: $sudoaddusermyuser Nowwecreateawheelgroup(here,groupofusersallowedtousesu) $sudogroupaddwheel Thenaddtheuserswhomneedtosu,inthiscase: $sudoaddusersecadminwheel $sudoaddusermyuserwheel Checkthatyourusersbelongstothecorrectgroups: $groupsuser Now,restricttheuseofsutowheelmembers: $sudochgrpwheel/bin/su $sudochmod4750/bin/su Hereusermyusercanusesubutnotsudoashe'snotintheadmingroup.Toexecutea sensiblecommandhefirstneedstosu(switchuser)tosecadmin,andthenusesudo.

HardeningGuide

2.AuthenticationandAccessRestrictions 35/87

Privilegeelevationschema: sshmyuser@host;susecadmin;sudocommand

For tighter control, you can configure the sudoers file more granularly : itispossibletoconfigurerightsusingvisudo,forexampleifyouwanttodelegate theapacheadministrationparttoanotheradministratorwithoutgivinghimfull administration rights or if you want to log actions. Adetailedhowtoisavailableonubuntuwebsite7

2.7Accessrestriction:aboutadvancedaccessrestriction,SELinux

Seeappendix:MACSELinux

2.8Accessrestriction:networkaccessrestriction,Firewallingufw andShorewall
Afirewallisjustasoftwarewhichallows/deniestrafficaccordingtoapolicy.Itcanhave a lot of different uses, but we won't explore the ins and outs of firewalls in this document.HerewewillonlyuseittorestrictTCP/IPtraffic,inordertoshrinktheattack surfaceanUbuntuserverpresentstoattackers. Afirewallisnotalwaysnecessary,butitcanprovideagoodsecurityenhancement:if yourwebserveralsorunsasshserver,inordertoavoidanyconnectiontobemadeon ssh,youcanconfigureyourfirewallittoactlike: Denyallbydefault allowtraffictoWebserveronports80and443 allowtraffictosshonport22onlyfromtheITstaffroomIP Someoneperformingascanonthismachinewillonlyseeport80openandsowillnot beabletoattackthesshdaemon.Whilethisisaverybasicsecurityruleandcommon senseconfiguration,anhighnumberofserversontheinternetarecurrentlyexposing criticalservicestoeveryone. Thereare2policiestype:allowallthenrestrictORdenyallandallowcertainthings.
7 https://help.ubuntu.com/community/Sudoers
HardeningGuide 2.AuthenticationandAccessRestrictions 36/87

Asitgoesforblacklistingingeneral,it'snotagoodideatotrytoidentifyallsortof attacksandpossibleconnections.It'sfareasiertoidentifyeverythingwhichshouldbe allowedstartingfromadenyallperspectiveinthebeginning. Ifyouallowallthenremovecertainpermissions,anattackermayeasilyfindawayto circumventthepolicy.

2.8.1ufw
Forastandard,basicusewerecommendufwasyourfirewallconfigurator:itispresent bydefaultonthesystemandveryeasytoconfigure.Underthehood,ufwwillconfigure theiptablesfirewallyourUbuntusystemisalreadyrunning. //Firstenableufw: #ufwenable Firewallstartedandenabledonsystemstartup //Specifydefaultpolicy,herewilldenyallincomingtrafficandallowalloutgoing #ufwdefaultdeny Defaultpolicychangedto'deny' (besuretoupdateyourrulesaccordingly //Nowletseetheusage,fromma: //ufw[dryrun]enable|disable //ufw[dryrun]defaultallow|deny //ufw[dryrun]loggingon|off //ufw[dryrun]status //ufw[dryrun][delete]allow|denyPORT[/protocol] //ufw[dryrun][delete]allow|deny[protoprotocol][fromADDRESS[portPORT][to ADDRESS[portPORT]] //Oklet'senablesshonport22andapacheonport80 #ufwallow22 Ruleadded #ufwallow80 Ruleadded //Nowletseethestatus root@ubuntu:/home/ary#ufwstatus Firewallloaded ToActionFrom
HardeningGuide 2.AuthenticationandAccessRestrictions 37/87

22:tcpALLOWAnywhere 22:udpALLOWAnywhere 80:tcpALLOWAnywhere 80:udpALLOWAnywhere #ufwallow22:toallowenteringconnectionsonport22 #ufwallowssh:equivalentifyouusestandardportscf/etc/services #ufwallow22/tcp:toallowonlytcp #ufwallowprototcpfrom192.168.229.100to192.168.229.78port80:toallowaccess onlyfrom192.168.229.100 #ufwdeleteallowprototcpfrom192.168.229.100to192.168.229.78port80:todelete thepreviousrule (addresscanalsobesomethinglikew.x.y.z/24) #ufwallowprototcpfrom192.168.229.100toanyport22:toallowsshaccessonly from192.168.229.100 Youcan alsomodify /etc/ufw/before.rules (andafter.rules)(ex:bydefault it leaves icmp,multicastandsomeotherstuf,itmaynotberelevantinyourcase)

2.8.2Shorewall
UfwisperfectforverybasicfilteringonanUbuntusystem,evenifitispossibleto installitonadebiansystem,asfornowitisstillnotpackagedfordebianandsowe ratheradvicetomakeyourownscriptsoruseshorewall. Makingafinegrainedcontrolhomemadescriptsisanexcellentsolution,thisone8isa goodexample,butwillrequireanonnegligibletimeinvestment. Inmostofthecases,aspeciallyforabastionhostwhichisalreadybehindafirewall, usingspecialconfigurationtoolsfornetfilterwillbeasefficientashomemadescripts whilereducingthetimeinvestment. Herewewilluseasoftwarecalledshorewall(shorelinefirewall):ahighleveltoolfor configuringNetfilter.
2.8.2.1OnnetfilterandIPTables

Netfilter is a framework that provides a set of hooks within the Linux kernel for interceptingandmanipulatingnetworkspackets[NFwi]. 8http://www.devarticles.com/c/a/JavaScript/DetectingandCounteringServer Intrusions/
HardeningGuide 2.AuthenticationandAccessRestrictions 38/87

Netfiltercanbeusedasafirewallingfacility,butnotonly(asforexampleitcanbeused forOSfingerprintingdisruption). Iptablesistheuserspacetoolusedtocreatetherules.Iptablessyntaxisverylogicbut quietobscureifyouarenotusedtoit.Forexampletoallowinboundpacketswhich initiatesaHTTPconnection,theruleis: iptablesAINPUTptcpjACCEPTdport80mstatestateNEW


2.8.2.2Shorewallinstallationandconfiguration

Firstinstallshorewall: #aptgetinstallshorewallshorewalldoc Theshorewallteamprovidesasetofstandardrulesregardingparticularcases.Here wewanttobuildabastionhost #cp/usr/share/doc/shorewallcommon/examples/oneinterfaces/*/etc/shorewall/ #cd/etc/shorewall #gzipd*.gz Shorewallisconfiguredwithasetoffiles: zones:Firstyoudefineyourzones(doesmakemuchmoresenseifyouconsiderthe caseafirewallwith3or4interfaceswhereyouhavethenet,FW,localand DMZzones). Herewehaveonlytwozones:fw:thefirewall(seeitasyourcomputer)andnet: theinternet(theoutsideworld). Herenothingtochange

policy:whereyoudefinethedefaultpolicy.Bydefault: fromtheinsidetotheoutside:ACCEPT fromtheoutsidetotheinside:DONOTACCEPT Thedefaultpolicyshouldalwaysbeadefaultdenyone Herenothingtochange rules:whereyouspecifyspecificrules interfaces:whereyoudefineinterfacesrelatedparameters.(ifshorewallcomplains aboutrfc1918,takeoftheparameterintheinterfacesfile) shorewall.conf:generalsettings IMPORTANT:ifyouareusingaprivateclassA,BorCnetwork(10.0...,172.16... and192.168...)takeofthenorfc1918in/etc/shorewall/interfaces Aasallinboundtrafficisnotallowedbydefault,configuringshorewallconsist in

HardeningGuide

2.AuthenticationandAccessRestrictions 39/87

authorizingtheentriesregardingtotheservicesyouwanttoallowtheconnectionto: Hereyouhave2solutions:usemacroswhichareprebuiltinstructionsprovidedbythe shorewallteamorspecifybyhandtherules. Herewewilltaketheexampleofawebserver: edit/etc/shorewall/rulesandaddatthebottom: #Action SOURCE DESTINATION PROTO $FW $FW DESTPORT(S)

Web/ACCEPT net IMAP/ACCEPT net

ACCEPT ACCEPT

net net

$FW $FW

tcp tcp

80 143

HardeningGuide

2.AuthenticationandAccessRestrictions 40/87

Here the 2 first lines are equivalent to the two seconds : in the first cases the specificationsdoneviamacrosandinthesecondcasebyhand. Tolisttheavailablemacros:#shorewallshowmacros (someexamples:FTP,SSH,DNS,POP3,SMB,BitTorrent) Lastedityour/etc/default/shorewallandchangestartup=0tostartup=1 andstartshorewall: #/etc/init.d/shorewallstart Totestyourrules,youcanusenmap

Inthisconfigurationoutboundtrafficisnotstrictlyrestricted,forahighersecurity, outboundconnectionscanbefilteredinatighterway. Formoredetailsonfirewallingandshorewallconfiguration,thereadermayreferto: [Shorewallbastion]

HardeningGuide

2.AuthenticationandAccessRestrictions 41/87

[Shorewallstart] [NetfilterHowto]

Illustration9:nmapoutputbeforeandafterfirewalling

2.9Remoteaccess,OpenSSH
OpenSSHpermitsyoutoremotelylogininasafeway:allthetrafficiscipheredwhich avoidssniffingattacks. EvenifOpenSSHiswrittenwithsecurityasmainobjective,havinganSSHdaemon runningisonemorepossibleopendoorforanattacker.Soinstallitonlyifyouneed remoteadministration.

HardeningGuide

2.AuthenticationandAccessRestrictions 42/87

Installation: #aptgetinstallopensshclient #aptgetinstallopensshserver Nowwewillrestrictdirectaccesstoprivilegedusersviaopenssh: edit:/etc/ssh/sshd_configchange: #vim/etc/ssh/sshd_config "PermitRootLoginyes"to"PermitRootLoginno"(withoutthe"") andadd "DenyGroupsadmin" andrestartsshdaemon: #/etc/init.d/sshrestart ChangeOpenSSHdefaultport(toavoidsomeautomaticattacksandforceanattackerto performascan) #vim/etc/ssh/sshd_config >Port22toPort21021 #/etc/init.d/sshrestart

.::;)::. Shortstory:passwordstealinginauniversity9: Ateacherfoundsstrangethatsomestudentshadamarkof04/20atthefirstexamand 16/20inthesecond.Hethinksthatthosestudentshadaccesstotheexam'ssubjectbut hedoesn'tunderstandhow. Afterinquiry(logs,askstudent,etc)itappearsthatthestudentsusedtheirnotebook's webcamtofilmtheteacherenteringhispassword. Thisdoesn'tnotonlyhappenedinfilms. .::;)::. Inanotheruniversity:computerinselfserviceroom.Thecomputerislockeddown: passwordonthebios,bootonlyonharddisk,passwordongrub,computephysically lockedanduptodate. ButthesysadminusedtoinstallsomecomputersoverPXEandforgottodisableit. Andonedayastudentseeingpxeonthescreenwhenrebootingthecomputerused ittobootonalivecdonanothercomputerandcat/boot/grub/menu.lst. Thepasswordwasinclear.Itwasthesameasthebiospassword...androotpassword.
9 http://zythom.blogspot.com/2008/09/slaphappy.html (InFrench)
HardeningGuide 2.AuthenticationandAccessRestrictions 43/87

Ofcourseonecanrestrictmoretheaccessconditions: allowingorbanningusersvia: AllowUsers DenyUsers AllowGroups DenyGroups. Thesyntaxisthesameastheaboveexample:todenyanuntrustedusersgroup,add DenyGroupsuntrustedinyoursshd_config. Example:allowuserstotoandtata edit/etc/ssh/sshd_configandadd: AllowUserstototata

Ifthecomputerdoesn'tneedtobecontactedfromeverywhere,limitsshaccesstoa limitedsubsetofIP Thiscanbedoneat3levels: 1PacketfiltringSeeIptablespart TCPWrapper/etc/hosts.allow/etc/hosts.deny PAM The simpliest way to limit access from certain IP is via the server's firewall, for examplewithufw: #ufwallowprototcpfrom192.168.229.100toanyport22:toallowsshaccessonly from192.168.229.100 Formoredetails,seepart4onaccesrestriction.

IftheriskofbeingattackedviaSSHisveryhigh,don'tallowdirectSSHaccessfrom theinternet.Ifanattackercan'tseeanopenport,he'snotabletoattackit.Forthisyou canuse: portknocking(seepart7):bydefaultthefirewallblocksall,andifaclientsendsa predefinedtypeofmessages,thefirewalldynamicallyopenstheportforthespecified IP. a second channel : this is for very high security purpose ; you can connect a cellphoneto yourcomputeranduseitasasecondchanneltosendorderstoyour server.

HardeningGuide

2.AuthenticationandAccessRestrictions 44/87

Part3:Reducingtheattack surface

HardeningGuide

2.AuthenticationandAccessRestrictions 45/87

3REDUCINGTHEATTACKSURFACE

IN THIS CHAPTER WE WILL SEE HOW TO REDUCE AN ATTACKER ATTACK SURFACE. MOSTLY BY DISABLING UNNEEDED DAEMONS, MODULES, SETTING TIGHT MOUNT OPTIONS,TCP/IPSTACKANDKERNELHARDENING.

Illustration10:Chapter3:MindMap

3.1Disablingunneededdaemonsandservices
Standardinstallationprovidesonlyafewdaemons,howeverastheymaybeusedasan entrypointforanattacker,wewilldisabletheonewhicharenotneeded. Disablingdaemonscanbedonebyhand,butitismuchmoreeasierviasysvrcconf,a tooldoneforthispurpose

Illustration11:sysvrcconfdaemonconfiguration

HardeningGuide

3Reducingtheattacksurface 46/87

Toinstall: #aptgetinstallsysvrcconf Tolaunch: #sysvrcconf Lookatrunlevel2column Onastandardinstall(ubuntuserver8.04): atd>"runjobsqueuedforlaterexecution":Maybeuseful,leave cron>daemontoexecutescheduledcommands:Maybeuseful,leave klogd>KernelLogDaemon:leave rc.local>Leave rmnologin>leave rsync>no ssh>ifneeded sysklogd>leave (configurationforDebianisverysimilar)

3.2Checkingfilepermissionsandsystemexecutables
On modern linux systems, passwords are not stored any more in clear text in /etc/password,butyoucanfindahashin/etc/shadow.Ifanattackcanread/etc/shadow, hecantrytoattackyourpasswordusingpasswordcrackingtoolslikejohntheripper. Thatiswhywewillcheckthatonlyrootandshadowgroupmemberscanreadit.

Check/etc/shadowpermissions(onafreshinstallpermissionsshouldberight,checkit ifyouhardenanalreadyinstalledsystem): #lsl/etc/shadow rwr1rootshadow7362008092212:53/etc/shadow

CheckforunauthorizedSUID/SGIDSystemExecutables #find/\(perm4000operm2000\)typefprint toremovethesetID:chmodsfile This section is in orange : by default there are not a lot of SUID/SGID System executablesbutdeactivatingthemdependsonthecases,whichhastobedonespecify

HardeningGuide

3Reducingtheattacksurface 47/87

foryoursystem. Onmydefaultinstalledsystem,Ihave: /bin/fusermount /bin/su /bin/umount /bin/ping6>ifnoipv6needed /bin/mount /bin/ping /var/local /var/lib/libuuid /var/log/news /var/mail /var/cache/man /usr/src /usr/local/lib/python2.5 /usr/local/lib/python2.5/sitepackages /usr/bin/expiry /usr/bin/wall>notreallyusednowadays /usr/bin/traceroute6.iputils /usr/bin/sudoedit /usr/bin/passwd /usr/bin/mtr /usr/bin/chsh /usr/bin/chage /usr/bin/sshagent /usr/bin/newgrp /usr/bin/sudo /usr/bin/gpasswd /usr/bin/at /usr/bin/crontab /usr/bin/mlocate /usr/bin/chfn /usr/bin/arping /usr/bin/bsdwrite /usr/lib/openssh/sshkeysign /usr/lib/pt_chown /usr/lib/eject/dmcryptgetdevice /usr/sbin/pppd>Isitneeded /usr/sbin/uuidd /lib/dhcp3client/calldhclientscript /etc/ppp/peers /etc/chatscripts /sbin/unix_chkpwd

HardeningGuide

3Reducingtheattacksurface 48/87

Findfileswithoutanyowner: #find/\(nouseronogroup\)print Normallyyoushouldnotfindsomething,ifitisthecaseyou'llneedtoinvestigateit.

Checkthatrandomize_va_spaceis1(defaultok): root@gamon:/proc/sys/kernel#sysctlkernel.randomize_va_space kernel.randomize_va_space=1 checkifExecuteDisable(XD)orNoExecute(NX)issupported(x86systems) $cat/proc/cpuinfoandsearchforpaeornxflags (bydefaulttheubuntukernelsupportspae)

3.3Deletingordisablinguneededuseraccounts
This stepis notreallymandatoryonafreshlyinstalledsystem,butisusefulif you hardenanexistingone.Firstcheckthatonlylegitimateaccountsarepresent:userwho can'tloghasa*afterthefirst: Ifthereistext,thatmeansthattheycanlogin(usuallywithapassword),socheckthem carefully.Havingmyuseronastandardinstallisok.Checkiftherearenotoldaccounts ortesting/devaccounts(whichmayhaveaweekpassword).

USEONLYWHATISNECESSARY,ADDFEATURES

ONLYWHENTHEYARENEEDED.IFPOSSIBLEAVOID

WEBINTERFACES.
Lookin/etc/shadow,foreverylinewitha*afterthefirst:(*or!Meansthatthe usercannotloginwithhispassword),modifyyour/etc/passwdlikethis: Inshadow: syslog:*:14148:0:99999:7::: Inpasswdmodifytohave: syslog:x:102:103::/home/syslog:/bin/false

HardeningGuide

3Reducingtheattacksurface 49/87

Bydefaultallnonusersaccountareblockedwith*,butitisbettertolockpasswdtoo. Forfurtherreadings,refertothislink.10

3.4TCP/IPStackhardening
DetailedexplicationsareavailableonCromwell'swebsite11 Ubuntuhasbydefaultalotofsecurityoptionsconfiguredinasafeway

Youneedtoedityoursysctl.conf,andmakethefollowingchanges: #vim/etc/sysctl.conf addthefollowinglines: #ICMPredirectshouldnotbeusedasitmaypermittoinjectroutes;disablethem net.ipv4.conf.all.accept_redirects=0 net.ipv6.conf.all.accept_redirects=0 net.ipv4.conf.all.send_redirects=0 net.ipv6.conf.all.send_redirects=0 #Logstrangepacketswithsource/destinationinvalid;thisshouldalsologrejected #sourceroutedpacketsandspoofedpackets net.ipv4.conf.all.log_martians=1 #Lastenablesyncookiestoprotectagainstsynflooding net.ipv4.tcp_syncookies=1

Note:someusersreportedthatthesysctl.confwaydidn'tworkondebian,thesolutionis toputascriptin/etc/network/ifup.d/with #!/bin/sh echo0>/proc/sys/net/ipv4/conf/all/accept_redirects andsoon.(thepreviouslinecorrespondstonet.ipv4.conf.all.accept_redirects=0) 10http://ferry.eof.eu.org/lesjournaux/ll/public_html/ch16s03.html 11http://www.cromwellintl.com/security/securitystackhardening.html


HardeningGuide 3Reducingtheattacksurface 50/87

3.4Disablingipv6
Ifyouarenotusingipv6(mostofthecasesnowday)disableitasitmaybeapotential vectorforattacks. #vim/etc/modprobe.d/aliasesandcomentthisline aliasnetpf10off #aliasnetpf10ipv6 addin/etc/modprobe.d/blacklist blacklistipv6 check: lsmod|grepipv6

3.5Filesystemmountingoptions
Mountoptionscanbeusedtoreducethewayanattackercanuseincasethesystemis compromised.Insomecaseitwillpreventtheattack,inotherno;herehegoalisjust toreducetheattacksways. Nodev:afilecannotbeusedasadevice.In/tmp,/varand/home,itshouldnot happenonanormalsystem. noexec:donotexecutebinaries.Forastandarduse,binariesshouldnotbeexecutedin /tmpand/var nosuid:donotexecutesuidbinaries.Forastandarduse,SUIDbinariesshouldnotbe esecutedin/tmpand/varor/home Edit/etc/fstab: #vim/etc/fstab anaddforeachpartition: /tmpnosuid,nodev,noexec /var nosuid,nodev,noexec

HardeningGuide

3Reducingtheattacksurface 51/87

/home /usr

nosuid,nodev nodev

nosuid,nodev,noexecon/var,mayleaveyouunabletousesomeapplicationssuchasapt orVMware.Settingnosuid,nodev,noexecon/varshouldbedoneonlyafterproper testing.

3.6MiscandKernelHardening
Checkcoredumparedisabled:sysctlfs.suid_dumpable 0bydefault:ok

FormoreinformationonkernelhardeningseeAppendixG:KernelHardeningwith GRSecurity/PaX

HardeningGuide

3Reducingtheattacksurface 52/87

Part4:Monitoringanddetecting intrusions

HardeningGuide

3Reducingtheattacksurface 53/87

4.MONITORINGANDDETECTINGINTRUSIONS

ONCE THE ATTACK SURFACE REDUCED TO IT'S MINIMUM, WE SHALL MONITOR THE EXPOSED ONE. IN A FIRST TIME WE WILL INSTALL AN ALERT MECHANISM THEN INSTALLSOMEHOSTBASEINTRUSIONDETECTIONSYSTEMS.

Illustration12:Chapter4:MindMap

Notethatthispartfocusesonaverybasicconfiguration,abareminimumandneed tobeadaptedtoyourneeds

4.1Alerttransportmechanism:Postfix
Somesoftwareswillneedtosendreportsoralerts,whichareusuallysentbymail.As thedefaultinstalldonotprovideaMTA,wewillinstallpostfix.Wechosepostfixforhis easyconfigurationandhisgoodsecurityrecords. Asweonlyneedtosendmailandnotreceiveanymessage,wewillconfigureittolisten onlyontheloopbackinterface.Thisisdoneforsecurityreasons:leavingadaemon listeningonport25whichisnotneededmayprovideapotentialentrypointforan attacker.
HardeningGuide 4.Monitoringanddetectingintrusions 54/87

First,installpostfix #aptgetinstallpostfix Aconfigurationscreenwillappear,selectnone #aptgetinstallmailx //Nowcreateafile/etc/postfix/main.cfwithrightsrwrrrootroot $sudotouch/etc/postfix/main.cf $sudochmod611/etc/postfix/main.cf //Copypastthisin/etc/postfix/main.cf ##################################################################### # #See/usr/share/postfix/main.cf.distforacommented,morecompleteversion #Debianspecific:Specifyingafilenamewillcausethefirst #lineofthatfiletobeusedasthename.TheDebiandefault #is/etc/mailname. #myorigin=/etc/mailname smtpd_banner=$myhostnameESMTP$mail_name(Ubuntu) biff=no #appending.domainistheMUA'sjob. append_dot_mydomain=no #Uncommentthenextlinetogenerate"delayedmail"warnings #delay_warning_time=4h readme_directory=no #TLSparameters smtpd_tls_cert_file=/etc/ssl/certs/sslcertsnakeoil.pem smtpd_tls_key_file=/etc/ssl/private/sslcertsnakeoil.key smtpd_use_tls=yes smtpd_tls_session_cache_database=btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database=btree:${data_directory}/smtp_scache #See/usr/share/doc/postfix/TLS_README.gzinthepostfixdocpackagefor #informationonenablingSSLinthesmtpclient. myhostname=ubuntu alias_maps=hash:/etc/aliases
HardeningGuide 4.Monitoringanddetectingintrusions 55/87

alias_database=hash:/etc/aliases mydestination=ubuntu,localhost.localdomain,localhost relayhost= mynetworks=127.0.0.0/8[::ffff:127.0.0.0]/104[::1]/128 mailbox_size_limit=0 recipient_delimiter=+ inet_interfaces=loopbackonly default_transport=smtp relay_transport=smtp inet_protocols=ipv4 ##################################################################### Hereinfactitisalocalsetupwithpossibilitytosendmails: default_transport=smtp relay_transport=smtp Withpostfixonlylisteningonlocalinterface: inet_interfaces=loopbackonly Youcanchangechangethehostname: myhostname=ubuntu Note:whenaptgetinstallpostfix,itwillalsoinstall: opensslopensslblacklistpostfixsslcert Restartpostfix #/etc/init.d/postfixrestart Asfornowmailssenttorootwillbelocalydelivered,whichmaynotnesoconvenient. We will instruct the system to send them to user@yourdomain.com by editing /etc/aliasesandadd postmaster:root root:user@yourdomain.com #sudonewaliases Nowtestitby: $mailsTestyou@yourdomain.com TEST! . $

HardeningGuide

4.Monitoringanddetectingintrusions 56/87

4.2HostbasedIntrusiondetectionsystems 4.2.1OSSEC
OSSECisanhostbasedintrusiondetectionsystemwhichperformsloganalysis,file integritychecking,rootkitdetectionandactiveresponse.

ANHOSTBASEDINTRUSIONDETECTIONSYSTEMIS

WARMLYADVISEDBUTDONOTCONFIGUREITTOTHROWTO MUCHALARMS:DOREMEMBERTHATTHEPSYCHOLOGICAL ASPECTOFSECURITYISOFFIRSTIMPORTANCE,TOOMANY WARNINGSWILLFINISHINTHESPAMFOLDER.

OSSECrunsonGNU/Linux(Ubuntu,Debian,Redhat,Gentoo,etc)Open/Free/NetBSD, solaris,aix,hpux,MacOSX,VmwareESXandWindows(2000,XP,2003,Vistaand 2008) which represent a big advantage when managing a heterogeneous parc of machines. OSSECcanworkinagent/servermodeorinlocalmode. OSSECdoesthesamethingsasacombinationoftoolssuchaslogcheck,chkrootkit,etc but all integrated in one and has active response capacities. This last point if well configuredcanbeuseful:itpermitstoexecutecertaincommandswhencertaintriggers areactivated.Oneonesideitpermitsyoutoreactassoonastheattackhappens,thus limitingthedamages;butontheotherafalsepositivenayblockyoursystemandan attackercanuseittoDOSyoursystem. #aptgetinstallbuildessential Getthelastversiononhttp://www.ossec.net/main/downloads #wgethttp://www.ossec.net/files/ossechids1.6.1.tar.gz #tarzxvfossechids1.6.1.tar.gz #cdossechids1.6.1 #./install.sh Followinstallinstructions,hereareoneforasinglehost: en|local|acceptdefaultoptions,donotenableactiveresponse(thisoptionneedtobe tested) startossec: #/etc/init.d/ossecstart

HardeningGuide

4.Monitoringanddetectingintrusions 57/87

Uninstallbuildessential: #aptgetremovepurgebuildessential Nowyoushouldhavethisprocessrunning: ossecm/var/ossec/bin/ossecmaild root/var/ossec/bin/ossecexecd ossec/var/ossec/bin/ossecanalysisd root/var/ossec/bin/osseclogcollector root/var/ossec/bin/ossecsyscheckd ossec/var/ossec/bin/ossecmonitord

4.2.2OtherHIDS
ThereadermayconsiderotherHIDSsuchassamhain,TripwireorAIDE. Formoreinformation,thereaderisinvitedtoconsulttheappendixMoreHIDS

4.2.3Rootkitshunters
4.2.3.1Rkhunter

Rkhunterwillcheckforthepresenceofrootkitsandbackdoorsviamd5signaturesand triggers(anormalities,exinterfaceinpromiscuousmode).

Illustration13:rkhuntercheck
HardeningGuide 4.Monitoringanddetectingintrusions 58/87

#aptgetinstallrkhunter Cronjob: Edit/etc/rkhunter.conf Uncomment: MAILONWARNING=you@yourdomain.com USE_SYSLOG=authpriv.notice #rkhunterupdate #rkhunterccreatelogfile Now lauchit with cronjob reportwarningsonlyoptions :no interactive, only warnings.BydefaultonUbuntuServer8.04youhavethiswarnings: root@ubuntu:/etc/postfix#rkhunterccronjobreportwarningsonly Warning:Hiddendirectoryfound:/dev/.static Warning:Hiddendirectoryfound:/dev/.udev Warning:Hiddendirectoryfound:/dev/.initramfs Oneormorewarningshavebeenfoundwhilecheckingthesystem. Pleasecheckthelogfile(/var/log/rkhunter.log) root@ubuntu:/etc/postfix# We'llhavetowhitelistthem: #vim/etc/rkhunter.conf Searchforthoseanduncomment: #ALLOWHIDDENDIR=/etc/.java #ALLOWHIDDENDIR=/dev/.udev #ALLOWHIDDENDIR=/dev/.udevdb #ALLOWHIDDENDIR=/dev/.udev.tdb #ALLOWHIDDENDIR=/dev/.static #ALLOWHIDDENDIR=/dev/.initramfs #ALLOWHIDDENDIR=/dev/.SRCunix (If you use unhide, /usr/sbin/unhide and /usr/sbin/unhidelinux26, will generate warnings #rkhunterpropupdtofixthisonlyinacleansystem) Nowyouhaveachoicebetween: Heartbeatlikereport:eachdayamail,evenwhennoabnormalitiesaredetected.A goodsolutionifyoumanageafewmachines,butimpossibletouseiftherearemore thanafewmachines.

HardeningGuide

4.Monitoringanddetectingintrusions 59/87

Anomalyreport:getamailonlywhenthereisaproblemdetected...fine,butwhen anattackerownsyourmachine,hewillcertainlydisableyourHIDSandrootkit hunters. Edit /etc/cron.daily/rkhunter, and replace the content by : #!/bin/sh /usr/bin/nice10/usr/bin/rkhuntercronjobreportwarningsonly

4.2.3.2Chkrootkit

Chkrootkitisanotherrootkithunterwhichiscomplementarytorkhunter.

Illustration14:Chkrootkitatwork

#aptgetinstallchkrootkit tomakeatest: #chkrootkitq


4.2.3.3Unhide

unhideisaforensictooltofindprocesseshiddenbyrootkits,Linuxkernelmodulesor byothertechniques.Itdetectshiddenprocessesusingthreetechniques: Theproctechniqueconsistsofcomparing/procwiththeoutputof/bin/ps. Thesystechnique consists of comparing information gathered from/bin/pswith informationgatheredfromsystemcalls. ThebrutetechniqueconsistsofbruteforcingtheallprocessIDs.Thistechniqueisonly availableonLinux2.6kernels. unhidetcpisaforensictoolthatidentifiesTCP/UDPportsthatarelisteningbutare
HardeningGuide 4.Monitoringanddetectingintrusions 60/87

notlistedin/bin/netstatthroughbruteforcingofallTCP/UDPportsavailable Fromthemanpageofunhideandunhidetcp

Illustration15:Unhidesysatwork

#aptgetinstallunhide An interesting feature of unhide is that it can work with rkhunter : remove hidden_procsfromDISABLE_TESTin/etc/rkhunter.confXXXXXTEST #!/bin/bash unhidebrute unhideproc unhidesys unhidetcp

4.3Monitoringlogs
Aservergeneratesalargequantityoflogs,whichcannotbewellprocessedbyahuman being. Log watcher are software which will parse system logs and alert the administrator accordingtopresetrules;wewillseehowtoinstallandconfigure3ofthem:logwatch, logcheck(andOSSEC).

HardeningGuide

4.Monitoringanddetectingintrusions 61/87

5.2.1Logwatch
Firstwewillinstall,ifrelevantregauardingthesituation,logwatch.Logwatchwillmake areportatgivenintervalsoftime,bydefaultitwillreportastatuson: Cron iptables pam postfix ssh Diskspace

Illustration16:AnextractofaLogcheckreport

Logwatchinstallation(optionnal): #aptgetinstalllogwatch

5.2.2Logcheck
Logcheckparseslogsandraisesalarmsifananomalyisdiscovered,itisaveryuseful tool. Toinstall: aptgetinstalllogcheck Then edit /etc/logcheck/logcheck.conf if you want to change some configuration options,defaultsettingsareok.(ifyoucorrectlysetthemailaliasforroot) ChangeSENDMAILTO="you@yourdomain.com" Logcheckwillraisealotofalarms,andmostofallalotofregularalarm.Toavoid this,youmayaddapersonnalfilein/etc/logcheck/ignore.d.server/

HardeningGuide

4.Monitoringanddetectingintrusions 62/87

Inthisfileyoucanspecifyexceptionsbasedonregularexpressions: HereisaquickanddirtyhackIusedonthetestmachine: ^.*ntpd\[[09]+\]:.*$ ^.*pam_unix.*cron:session.*$ ^.*UFWBLOCKINPUT.*$ ^.*/usr/sbin/fcheck&&if!/usr/sbin/fcheckasxrf/etc/fcheck.*$ ^.*.*postfix/smtp.*to=<me@gmail.com>.*$ ^.*/USR/SBIN/CRON.*$ ^.*MARK.*$ ^.*/usr/local/rtm/bin/rtm20>/dev/null2.*$ ^.*IPv6addrconf:prefixwithwronglength5.*$ ^.*Readingincludedconfigurationfile:/etc/xinetd.d/.*$ ^.*postfix/smtp.*$ ^.*/dev/vmmon.*$ ^.*/dev/vmci.*$ ^.*perl:warning:.*$ ^.*kspostfix/pickup.*$ ^.*kspostfix/cleanup.*$ ^.*kspostfix/qmgr.*$ ^.*kspostfix/local.*$ AdvancedHIDS: ForadvancedHIDS,youmyrightyourownscriptswhichwillbemuchmoredifficultto findandstopbeforetheysentthealarm. Sometricks: sendit'slogtoaremoteserverforremotechecking 12 Hideit,asabackupscript,asa[pdflushprocess],etc
12 Howto change a UNIX process and child process name by modifying argv[0] http://www.uofr.net/~greg/processname.html int argv0size = strlen(argv[0]); //Take note of how many chars have been allocated ... strncpy(argv[0],"main-thread-name",argv0size); //replace argv[0] [0..argv0size] ...
HardeningGuide 4.Monitoringanddetectingintrusions 63/87

4.4Watchdogs
Forspecificpurposes,youcansetwatchdogs,specialalarmraisers.Someexamples:

IPwatchdog:watchesafteraserverandregularlypingsit,willraiseanalarmifhe cannotpingit defacementwatchdog:awatchdogcanregularlymonitorawebpagelookingfora defacement

fork(); //make child process ... strncpy(argv[0],"child-thread-name",argv0size); [0..argv0size]

//replace

argv[0]

HardeningGuide

4.Monitoringanddetectingintrusions 64/87

5.KEEPINGUPTODATEANDINFORMED

KEEPING A SYSTEM UP TO DATE IS OF TREMENDOUS IMPORTANCE, AN OUTDATED SYSTEM IS PRONE TO BE ATTACKED USING KNOWN VULNERABILITIES WHICH ENLARGES THEATTACKPERIMETER. UPDATING IS PART OF THE MANAGEMENT PROCESS, BUT STANDS ON TECHNICAL MEANS.INTHISCHAPTERWEWILLSEESOMEBASISONHOWTOKEEPUPTODATEAND HOWTOKEEPINFORMEDONNEWATTACKS.

5.1KeepingUpToDate 2.2.1Updatingwithapt
Installing,removingandkeepingthesystemuptodateisdoneviatheaptoraptitude commands.Hereisashortoverviewofsomeusefulcommands: Firstyouneedtogetthelastversionofthepackageslist: $sudoaptgetupdate Toupgradeyoursystem: $sudoaptgetupgrade Toupgradeyoursystemandinstalllastversionsofthedependencies: $sudoaptgetdistupgrade Toinstallanewpacket,herevlc: $sudoaptgetinstallvlc Toremoveapacket: $sudoaptgetremovevlc Toremoveitandremovetheconfigurationfiles: $sudoaptgetremovepurgevlc Tosearchforapakage: $sudoaptcachesearchvlc

HardeningGuide

5.Keepinguptodateandinformed 65/87

2.2.2Automaticnotifications
Tohaveautomaticnotificationoftheneedtoupdateasystem,acronjobcanbesetor thereadercanusecronaptdependingonthenumberofserveryouhavetomanage. Thecronaptsolutionisperfectforafewservers(upto10),formorethan10servers anautomatedoramanagedsolutionshouldbeused. Whichmaybe: managementsolution:decidetoupdateregularlyalltheserversatthesameperiod ofthemonth/week.Withthissolutionallserversshouldbeonthesamestate. Technicalsolution:useadedicatedsolutionormakeyourown(cronjobs+mails)

AMEDIUMHARDENEDSYSTEMREGULARLYUPDATED

ISMUCHBETTERTHANANEXTREMEHARDENEDONE UPDATEDEACH3YEARS.

cronapt will regularly update packages list and download new packages without installing them, so logging in to the system and performing an aptget upgrade is required. Iflogcheckisinstalledyouwillreceiveamailwith:

HardeningGuide

5.Keepinguptodateandinformed 66/87

Illustration17:Cronapt

Toinstallcronapt: aptgetinstallcronapt Defaultsettingareshouldsufficeforastandarduse

Ifyoudon'twanttousecronapt,youcanuseaverysimplescriptlike: #!/bin/bash # #CronScriptrunfrom/etc/crontabor/etc/cron.daily # #Checksifupdateareavailablebysimulatinganaptgetupgrade if[n"`aptgetsimulateupgrade|grepInst`"] then echo "Hello, I need updates" | mail s "Updates availbale : `uname n`" yourname@yourdomain.com fi andaddtoyour/etc/crontabthefollowinglinetocheckforupdateeverydayat18h30 3018***/pathToScript

HardeningGuide

5.Keepinguptodateandinformed 67/87

5.2Informed
Thereadermayconsidertosubscribetosomemailinglistsonwhichnewvulnerabilities areannounced: ForDebianhttp://lists.debian.org/debiansecurityannounce/ ForUbuntuhttps://lists.ubuntu.com/mailman/listinfo/ubuntusecurityannounce

Bugtraq,Fulldisclosurearerecommendedtooforgeneralannounce.(highvolumeof exchangedmessages) OtherMailinglistsshallbeofsomeinterestforthereader: DailyDave http://sikurezza.org/lists(InItalian) http://www.ossir.org/listes/index.shtmllists(InFrench)

SomewebsitesandBlogsarelistedinappendixF.

HardeningGuide

5.Keepinguptodateandinformed 68/87

CHAPTER6:MITIGATIONANDCONFINEMENT

UP TO NOW WE FOCUSED ON CONTROLLING ACCESS AND REDUCING THE ATTACK SURFACE, MAKING IT HARDER FOR AN ATTACKER TO ENTER OUR INFORMATION SYSTEM.AFTERWARDS, WE SET UP A MONITORING SYSTEM WHICH AIMS AT ALERTING THE ADMINISTRATORS WHEN IT DETECTSABREAKIN. INTHISCHAPTERWEWILLFOCUSONMITIGATIONASAPARTOFAGLOBALDEFENSEINDEPHT STRATEGY. THE MAIN IDEA IS,CONSIDERING THE ATTACKER MANAGED TO BREAK IN,TO MITIGATE HIS ACTIONANDTOLIMITTHEDAMAGESHECANDO.

6.1Intro
Letusconsiderthesimpleexampleofacompromisedcorporatemailserver.Thankstoa misconfiguration,asoftwareflaworahumanerror,anattackermanagedtohavefull adminrightsonacorporatemailserver.Ofcourseiftheintrusiondetectionsystemis correctlyconfigured,theadministratorswillquicklybealertedandwillhandlethe situation.Butwhatifittakes3hourstomakeaquickfix?Itmeansthattheintruderhad accesstoallthemailsfromtheCEOstrategicplanstosometechnicaldetailsonanew product. Nowifthiscompanyhadencryptedallofthemailtraffic,eveninthecaseofa successfulbreakin,theinformationleakagewouldbestronglymitigated. Therearealotofmitigationtechniquesforalotofdifferentpurposes.Herewewill focusonserviceisolation(mostlydaemons),bothattheconfidentialityandavailability levels,whichrepresentsanimportantissue. Ofcoursethesimpliestwaytodosoistouseadedicatedphysicalmachineforeach serviceonadedicatednetwork.Forhighsecurityenvironmentsthisislikelythebest solution,butformostofthesituationsthisissimplytooexpensive. Furthermore,usingstrictisolationonallservicescanimprovesecurityevenonsingle purposeservers,sincewecanstillisolatethedaemonfromtheoperatingsystemitself. Wewillfocusontwotypesofsolutions:AccessControllike(exSELinux)and virtualizationlike.

HardeningGuide

Chapter6:MitigationandConfinement 69/87

Noteonchroot: Chrootisjustasyscallwhichchangestherootdirectoryofaprocess:atthebeginningit waswrittenfortestingpurposes,notsecuritypurposes. Chrootisnotasecuritytoolandshouldnotbeconsideredasone.Insomecases, however,whenthesoftwareisreallywellwrittenwithsecurityinmind(exopenssh)it canbeusedforsecuritypurposes.Formoreinformationonthematter,seetheappendix onchroot. Noteonsystrace: Systracecanbeusedasasyscallfirewalltosandboxuntrustedsoftwaresornetwork daemons. Systracewillinterceptsyscallsmadebyasoftwareandallowordenythemaccordingto apolicy.Whilesettingitupunderstrictrequirementsisnotdifficult,ittakesagood knowledgetoconfigureitwell. Itcanstillbeusefultoboxnetworkdeamons,forexampleIusedittorestrictApache allowingittoonlytoaccessinreadmodeafewdirectories. Anhowtoonusingsystracecanbefoundattheaddressinthenote.1

6.2Accesscontrol
InthissectionwewillfocusonMandatoryAccessControlandRoledBasedAccess Control,anddescribesomesolutions. Whilethiskindofsolutionsarematureandusedsinceyearsinthemilitaryand governmentcontext,theyarenotlargelydeployedonthecivilianmarket,apartfrom someselected,highsecuritycompanies. Evenifthosesolutionshaveimprovedalotinthelastyears,configuringthemisstill difficultandrequiresexperiencedadministrators. Ofcoursealotofpoliciesarealreadyavailableforstandardsoftwares,forexamplethe SELinuxtargetedpoliciesofSELinuxforapache.Butwhenyouwanttousespecific softwareoruseMLS,thetaskbecomesmuchharderandrequiressomeconsiderable experience. Maintenanceisalsohardertoperformasitrequiresatleastsometrainingandgood documentation,apointwhichbecomesofcriticalimportanceinthecaseofturnoverin thesysadminteams. Herewewillconsiderafewsolutions,theiradvantagesanddisadvantages13.

6.2.1SELinux
SELinuxisasetofmodificationproposedbytheNSAtoprovideMandatoryAccess ControlontheLinuxplatform.
13 Seehttps://wiki.ubuntu.com/AppArmoronMACproblems
HardeningGuide Chapter6:MitigationandConfinement 70/87

SELinux adds to the linux kernel a Mandatory Access Control which provides information separation and threats tempering. Its most interesting features is containment : with well defined policies, it can contain a lot of attacks. A policy is a set of rules describing what a given user or process can actually do on the system. These rules supercede any permission or properties at the file system level, being even able to somehow restrict the superuser (i.e. root). For instance, if the MySQL user is not explicitely allowed to do so, it won't be able to write on the /tmp directory, which is usually world writable. As a result, even if an attacker takes control of a daemon, his actions will be restricted to what the policy allows him to do. If used in strict mode, even if the attacker manages to attaint root privileges, he will be restricted to a specific role. If the security policies are well configured, he can not do any damage. If you want to test such a case, Russel Coker provides a SELinux Debian based play machine where you can connect as root14 SELinuxrespondstoproblemssuchas"Ineedtorunourlegacyapplicationasroot, butonlyaccessto/var/customer_datawithreadrightsandnootherpartofthesystem suchas/var/mail". Thebigproblemisthat,ifitisnotconfiguredwellenough,thiskindofcontrolcan provideafalsesenseofsecuritywherethereisnone. Forexampleduringthe2009FrenchSymposiumonsecurity(SSTIC09),aspeaker presentedasolutionforasecurecomputerforhomeusers(projectSEC&SI).Asfor anexampleheshownusthatevenifanuserhadtheclassicalunixrightson"test.sh" whichallowedhimtoexecuteit,hecouldnot.Hetested./test.shandnothing happened.Attheendofthetalkoneoftheattendeeaskedtotry"shtest.sh",which worked. Ofcoursethiswasanexampleforatalk,butthiskindofissuecanalsohappeninreal life,onproductionsystem. Also,don'tforgetthatwhileSELinuxisabletoblocksomerootexploits15itwillnot stopallofthem.Theplaymachinewasownedshortlyafterthepublicationofthe vmspliceexploit16,butasaverygoodexampleofdefenseindepthitwascontainedby theunderlyingxen.

14 http://www.coker.com.au/selinux/play.html 15 http://doc.coker.com.au/computers/selinuxsaves/ 16http://etbe.coker.com.au/2008/04/03/trustandplaymachine/


HardeningGuide Chapter6:MitigationandConfinement 71/87

SELinuxsupports4differentkindofpolicies17: Strict:Whereeverythingisdeniedbydefaultandwhereyouneedtospecifyrules foreachaction.Anexcellentchoiceatastrictsecurityconsideration,butdifficultto configureandmanage.Duetoitslonganddifficultconfiguration,mostpeople choosenottouseit,andwetendtoagree. Targeted:Inthiscase,theideaistolockdownonlyafewspecificdomains,and leavetheuserspaceunconfined.Thesepolicies,aslongasyousticktoastandarduse, areeasytosetup,especiallyfornetworkdaemonssuchasapache. MLS:Whichallowstheuseofsecuritylevels.Forhighsecuritypurpose,hardto configureandmaintain. Minimum:liketargeted,butoptimizedforlowmemorysystems LastbutnotleastSELinuxispresentbydefaultonallUbuntuserverkernels,not requiringanyrecompilationandthusbeingsuitableformassdeployment. NotethatwhileSELinuxisverywellsupportedunderRedHatlikeoperating systems,andatalowerlevelonDebian,itisnotexactlymatureonUbuntuserver. HereweshalltaketheexampleofconfiningapacheonaDebiansystem:18 Part1:SELinuxInstallRemoveapparmor: aptgetremoveapparmor #aptgetinstallselinux edityour/boot/grub/menu.lstandaddselinux=1attheendofthekernelline Rebootyoursystem(neededforrelabeling,thatishavingthekerneladdthelabels SELinuxleveragestoimplementitssecurityrestrictions) Ifyouplantowriteyouownpolicies,edit/etc/selinux/configandset SELINUX=enforcing SELINUXTYPE=refpolicytargeted SELinux'statuscanthenbecheckedoutbyrunning #sestatusv InordertoretrievealltheinstalledSELinuxpolicymodules /usr/share/selinux/refpolicy#semodulel authlogin1.9.1 cups1.9.0 getty1.5.0 inetd1.6.0 17 http://fedoraproject.org/wiki/SELinux/Policies 18 Formoredetailsseehttps://help.ubuntu.com/community/SELinux https://wiki.ubuntu.com/HardySELinux
HardeningGuide Chapter6:MitigationandConfinement 72/87

init1.9.0 libraries2.0.0 locallogin1.6.0 logging1.9.0 lpd1.8.0 modutils1.6.0 mount1.9.0 mta1.9.0 selinuxutil1.8.1 ssh1.9.0 stunnel1.5.0 sysnetwork1.5.0 unconfined2.1.0 userdomain2.5.0 xserver1.7.0 Afterinstallingrefpolicytargeted(aptgetinstallselinuxpolicydefault),wewilltry toloadtheApachepolicy: #semodulei/usr/share/selinux/refpolicytargeted/apache.pp)forDebian #semodulei/usr/share/selinux/default/apache.ppforUbuntu Relabelthefilesrelatedtothenewpolicy: #restoreconRv/etc/usr/sbin/var/run/var/log RestartApacheandcheckwithpsaxZthatapacheisconfined NotethathereSELinuxisrunningintargetedmode,notstrictmodeandisnot providingcontainementagaisntanattackwhichleadstoarootshell.

6.2.2GRSecurity,AppArmor,TOMOYO,SMACKandco
BesideSELinux,thereareothersolutionswhichprovideAccessControl,eachhavingits peculiarstrengthsandweaknesses. WechosetofocusonSELinuxbecauseofitspresencebydefaultintheUbuntuserver kernelanditslargeuse.ButthereareotherverygoodsolutionssuchasGRSecurity, whichhoweverrequiresarecompilationofthekernel. ItmustbenotedthatAppArmoris,atleastfornow,thedefaultMAConUbuntu systems.WhiletheinnerworkingsofAppArmorandSELinuxarequitedifferent,from anuserperspectivetheyarenotsodifferent,withsetsofpoliciesdefiningwhateach user/processcanactuallydoonthesystem. GRSecurity:Averycompletesolutionwhichontopofprovidingarathereasyto configureRBACsystemechancestheglobalsecurityofthesystem.Formore informationseechapter7.A
HardeningGuide Chapter6:MitigationandConfinement 73/87

AppArmor:AnalternativesolutiontoSELinux,whichaimsatbeingeasierto configureandmaintain.ItisthedefaultMACpresentonUbuntuserver,anditspolicies canbefoundunderitsselfnameddirectoryinside/etc TOMOYO19:AMACimplementationbyNTT,itispathnamebased(whereSELinux islabelbased)andpresentbydefaultonlinuxkernel(from2.6.3020).Notethepresence ofaninterestinglearningmode.Thisis,indeed,apromisingproject,butnotyetready forproduction. SMACK21:AMACsystemwhichaimsatsimplicity,integratedbydefaultintheLinux kernel. RSBAC22:AnotherACcontrolmechanism. AppArmorisnolongerreallysupportedbyNovellnorincludedbydefaultinthekernel, whichraisesinterrogationsonhiscontinuity.MandrivaswitchedfromAppArmorto Tomoyo(inMandrivaLinux2010). Summingup,RedHatandFedoraleverageSELinux,SuseLinuxandUbuntuuse AppArmorandMandrivaTomoyo.

6.3Virtualization
Aspresentedinpart6.2AccessControlmechanismhasitsadvantagesanddrawbacks. WhilevirtualizationisabroadtechnologywithmultipleimpactsatmanylevelofIT,it canbesomehowusedtorestrictandcontrolaccessandexecutionofsoftware. Insomesituations,virtualizationisaveryeffectiveandconvenientwaytoachieve privilegeseparationandisolation. IncomparisontoACmechanismithassomeadvantages: Itiseasiertoconfigureandmaintaintheconfinedparts.Outoftheinitial configuration,maintenanceoftheconfinedpartsisidenticaltoaclassicalsystemwhich alargemajorityofyoursysadminsareabletodo(incomparisontoasystemrunning SELinuxorGRSecuritywhichrequiresexperiencedadmins).Formationandteam switchingaremucheasiertoperform. MostMACreliesonawelldoneconfigurationandonatrustablekernel.Agood configurationisdifficulttoachieveandrequiresexperiencedadmins.Sometimesthe kernelcannotbetrustedbecauseofaprocedureerrororinthecaseofsomeexploits (seepart6.2.1onSELinux).VirtualizationtechniqueswhichallowseachVMtorunits ownkernel(soweexcludeOperatingSystemlevelVirtualization)permitstoavoidsuch problems.Ofabsoluteisolationisnoteasillyachievable,someattacksmaypermitto
19 http://tomoyo.sourceforge.jp/ 20 http://kernelnewbies.org/Linux_2_6_30 21 http://schauflerca.com/ 22 http://www.rsbac.org/
HardeningGuide Chapter6:MitigationandConfinement 74/87

executecodeonotherVMoronthehost,suchasCloudBurstforVMware23.Butisadds onemorelayerofsecurity:theattackerneedsatfirsttocontroltheguestandthento piercethevirtualizationsystem.

Theclassicaladvantagesofvirtualization:serverconsolidation,easiermanagement, optimizedhardwareusage,etc.Formoreinformationsontheadvantagesof 242526 virtualizationseethispointers.

Therearemainly2kindsoftechnologies.

Fullvirtualization,whichemulatescompletelyorpartiallyhardware.Itallowstorun anykindofguestOS(Linux,Windows,BSD,Plan9).Itprovidesverygood isolationbutrequiresmuchmoreressourcestorun(VTinstructionsandmulticore OSareadvised).VMware,VirtualBoxorQEMUaresomeexamplesofthiskindof technology. OperatingSystemLevelVirtualizationisalightweightapproach,similartoafat BSDjailorachrootonsteroids:onekernelandninstancesofthesameOS.It providesthebestperformancesbutprovideslessisolationandrequirethesameOS toruninthecontainers. OpenVZorLinuxVServeraresomeexamples NotethatOpenVZandVServerareeasytoinstall:asimpleaptgetissufficient VServeriscompatiblewithGRSecurity

Paravirtualizationisaparticularkindofhardwarevirtualization,wheretheguestOSis modifiedtoperformsomeofthetasksoftheVMM,thusprovidingbetterperformances butrequiringaspeciallymodifiedGuestOS.XEN,UMLorKVMaresomeexamplesof Hypervisors(VirtualizationSoftwares)supportingparavirtualizationnatively.

Example
Atypicalexampleofisolationbyvirtualization,consideringaLAMP/Asterixinstall wouldbe: aVMactingasafirewall/QOSrunninganOpenBSD(oraPfSense) aVMforApache/PHP aVMforMySQL aVMforasterix The3applicativeVMarenotdirectlyconnectedtothenetworkbutplacedonspecific hostonlyvirtualnetworks.AllthecommunicationsshallpassviathefirewallVM whichcanfilterthefluxandmanagetheQOS. 23http://cve.mitre.org/cgibin/cvename.cgi?name=CVE2009124 24 http://software.intel.com/enus/articles/theadvantagesofusingvirtualization technologyintheenterprise/ 25 http://www.networkworld.com/community/node/34082 26 http://www.btquarterly.com/?mc=prosconsvirtualization&page=virt viewresearch
HardeningGuide Chapter6:MitigationandConfinement 75/87

CHAPTER7ADVANCEDHARDENING

THE LAST2CHAPTERS OF THIS GUIDE ARE A LITTLE MORE THAN A COLLECTION OF NOTES. WHILE ARE NOT AIMING AT PROVIDING A COMPREHENSIVE STEPBYSTEP GUIDE TO ADVANCED HARDENING, WE HOPE TO PROVIDE SOME USEFUL INSIGHTS TO THEREADERNONETHELESS.

7.1SSH
Inthissectionwewillconsiderthattheattackermayhavea0dayexploitforSSH,and seesomeworkaroundstomitigatetheimpactofitsattack.Besidemitigatinga0day attack, these workarounds may apply to SSH access to appliances which are rarely updatedortootherkindofauthenticationservices.

7.1.1Invisible
To avoid being attacked via the SSH vector, the simpliest solution is to make it unreachable. ObviouslythefirstquestionisdoIreallyneedanOpenSSHdaemonrunning?,ifit isjustbyconvenienceorbecauseitisrunningdefault,getitdown. ThenextquestioniswhydoIneedandOpenSSHrunning?,isitpossibletoperform thesametaskwithoutit.Irememberasysadminwhowasgettinghisserversstatistics (diskoccupation,averageload,somelogsfromasoftware)withascriptgettingthemvia OpenSSH.Hecouldhavegotthembymail,withouthavinganotherdaemonrunning. FromwheredoIneedtoaccessit?andWhichkindofuse?.Ifyouconnectto theserveronlyfromalimitednumberofIP,youshouldallowconnectiononlyfrom thoseIP,whichwillreducetheattackIPspace. Ifyouneedanaccessfromeverywhereyouwillneedtohideit,useasecurityairlockor adedicatedconnection.

7.1.2Dedicatedconnection
AdedicatedconnectionoveraRTC/GSM/Radiolinkisarobustbutcostlysolution.Itis alsopossibletofiltertheincomingcommunications.Ingeneral,thiskindofsolutionis ratherusedasabackuplineratherthanforpuresecuritypurposes.Themainadvantage isthatthenetworkisnottheinternetbutanoperatorsnetworkwhichis(hopefullyto
HardeningGuide Chapter7AdvancedHardening 76/87

somedegree)bettercontrolledandeasiertorestrict(exbruteforcing,MITM).

7.1.3Portknocking
Portknockingworkslikethesecretknockonthecloseddoor,identifyingyouas a friend. The basic idea is to close all the ports ofa given service, soif an attacker performsascanhewillseeaclosedbox.Whenyouwanttoconnecttoyourbox,you firstknockonport3000then4000and6000.Thedaemonunderstandsthatyouarea friendandopensthedesiredportonlyforyourIPandforadeterminedamountoftime. Thissolutioncanbeimplementedforexamplewithportknockd. Howeverthesesolutionspresentsomedrawbacks:itisreplayable,doesnotauthenticate theuseranddoesnotworkwithNAT. Anotherideaissinglepacketauthorization:theclientsendsauniqueencryptedpacket whichispassivelymonitoredbytheserver.Thissolutionismuchmorediscrete(itwon't makeyourIDSyield)andnonreplayable. Animplementationisfwknop27.

7.1.4Airlock
Iftheserviceneedstobeexposedandtheprevioustechniquescan'tbeused,youcanstill setupanairlock:adedicatedorvirtualmachineactingasaproxy.Itcanbeathin, lightweightmachineoravirtualmachine,actingonlyforonemachineorforanentire network. Themachineneedstobeparticularlywellhardenedandmonitored.Agoodsolutionmay betouseSSHtoconnecttoitand,anotherwaytoconnecttotheserver(exSSHtothe proxythenconnecttoaVMwareadminconsoleoverthetunnelwhichgivesyouaccess totheVM).

7.1.5Antibruteforcing
Softwares such as fail2ban or OSSEC can blacklist IPs from which are coming bruteforceattacks. Thosekindofsoftwareareeffectiveagainstbruteforceattackscommingfromalimited numberofIPsbutwillnotworkagainstadistributedbruteforceattack. Securingasysteminsuchawayisalwaysatradeoffbetweensecuringitagainstone typeofattackandopeningnewDOSvectors. Anicehowtoforfail2banmaybefoundhere28 Thereisalsotheiptablessolution29:
27 http://cipherdyne.org/fwknop/ 28 http://www.howtoforge.com/fail2ban_debian_etch 29 http://kevin.vanzonneveld.net/techblog/article/block_brute_force_attacks_with_iptables/
HardeningGuide Chapter7AdvancedHardening 77/87

sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 8 --rttl --name SSH -j DROP

PamTallycanalsobeusedforthispurpose30

7.1.6Usingkeys
To avoid password bruteforcing an easy and efficient solution is to use Public Key authentication31.Anhowtocanbefoundhere32.Ofcoursedoremembertodisablethe passwordbasedauthentification. Asthisisintheory,thebestsolutionsthereareusuallytwoproblems: strongPRNGarerarelyused,whicharemandatoryforhighsecurityenvironement. AlotofcompanieswouldnothavesomanyproblemsaftertheDebianOpenSSL debacleiftheyhadusedanhardwarePRNG. Keydistributionisahugeproblem.Usuallyusersarenottolikelytosendtheir passwordsviamail(ofcoursesomeofthemdoit)butitwon'tbotherthemtosenda simplefile.Inothercasestheywillleavetheirprivatekeyunprotectedandworld readable.Andtooftentheywillleavebothkeyandpasswordauthentication,incase theyloosetheirkey,withweakpasswords. IwarmlyadviseyoutousePublicKeyauthentication,butonlyifyouaresuretobeable tocorrectlymanagethekeys.

7.2Antiscanning
Softwaressuchasportsentry33canblockcertainkindofportscanning3435.

7.3KernelHardening
Grsecurity/PaXworksat2levels: anhardenedkernel(alotofpatchwhichwillclosealotofpossibleattackvectors) AnACLsystem,lesspowerfulthanSELinuxbuteasiertouse. Grsecurity/PaXcontainsattacksatapplicationlevel,attackswhichleadstoarootshell, andwillpreventsomeattackswhichleadstoarbitrarycodeexecutioninkernelspace. Forexamplethevmsplice()exploitdoesn'tworkonaboxrunningagrsecurity/PaX
30 31 32 33 34 35 http://www.kernel.org/pub/linux/libs/pam/LinuxPAMhtml/sagpam_tally.html http://www.openbsd.org/cgibin/man.cgi?query=sshkeygen http://sial.org/howto/openssh/publickeyauth/ http://sourceforge.net/projects/sentrytools/ http://linux.cudeso.be/linuxdoc/portsentry.php http://aide.sivit.fr/index.php?2006/01/20/96portsentry (infrench,buteasytounderstand)
Chapter7AdvancedHardening 78/87

HardeningGuide

kernelwiththeUDEREFoptionactivated Fromthewebsiteoftheproject: grsecurity is an innovative approach to security utilizing a multilayered detection, prevention,andcontainmentmodel.ItislicensedundertheGPL. Itoffersamongmanyotherfeatures: *AnintelligentandrobustRoleBasedAccessControl(RBAC)systemthatcan generateleastprivilegepoliciesforyourentiresystemwithnoconfiguration *Changeroot(chroot)hardening */tmpraceprevention *Extensiveauditing *Preventionofarbitrarycodeexecution,regardlessofthetechniqueused(stack smashing,heapcorruption,etc) *Preventionofarbitrarycodeexecutioninthekernel *Randomizationofthestack,library,andheapbases *Kernelstackbaserandomization *Protectionagainstexploitablenullpointerdereferencebugsinthekernel *Reductionoftheriskofsensitiveinformationbeingleakedbyarbitraryreadkernel bugs *Arestrictionthatallowsausertoonlyviewhis/herprocesses *SecurityalertsandauditsthatcontaintheIPaddressofthepersoncausingthe alert36 Becarefulatsomeoptions,especiallyifyouwanttorunitinavirtualmachine. EmulateTrampolinesNO fromthehelpinmenuconfig:enablingthisfeature*may*openupaloopholeinthe protectionprovidedbynonexecutablepagesthatanattackercouldabuse. Restrictmprotect YESiyyouarerunningaphysicalserver NOifitisavirtualone Preventinvaliduserlandpointerdereference IfyouarerunningonaphysicalmachineYES IfitisavirtualMachineitwillslowitdownalotNO Note:UDEREFmakessurethat(data)segmentsforuserlandandthekernelare properlylimited,eitherupwards(userland)ordownwards(kernel)37 UDEREFandKERNEXEConwouldhavepreventedforexamplethevmsplice()local rootexploit38
36 http://www.grsecurity.net/ 37 http://grsecurity.net/~spender/uderef.txt 38 MISC39,p8,Linux/vmsplice:lafaille3en1,MatthieuLoriol,inFrench
HardeningGuide Chapter7AdvancedHardening 79/87

7.4Delusionandobfuscation
Uptonowwefocusedonsecuringandmonitoringourserver,butthere'sstillsomething wecandotovoidattacks:deludetheattacker. Fromanattacker'sperspective,thefirststeptoattackasystemistostudyit:whichports areopen,whichservicesarerunning,whatOS,whichversion,andsoon. Withsuchaknowledge,anattackerwillbeabletoperformaimedattackswhichhavethe maximumofchancestosucceed. The general aim of this section is to explain how to complicate this information gatheringstep,hidingortamperinginformation. Themainadvantagesofsuchanapproachare: itwillstopalotofdumbattackers/automatedattacks(ex:bots)whichrelyonbanner grabbing Itmayslowdownanattacker,andbuyyoualittletimetoreact Itwilllikelymaketheattacknoisier

7.4.1HidingBannerinformations
A lot ofsoftwares suchas SSH, Apache orPostfix give a lot ofinformation to an attacker.ForexampleifItelnetafreshlyinstalledUbuntuserveronport22Iget: "SSH2.0OpenSSH_4.7p1Debian8ubuntu1.2" WeknowthatthemachineisrunningOpenSSHv4.7andthatitisanUbuntu:free informationforanattackertoget.Hidingatleastpartoftheinformation(theversionis neededforsomeRFC,butnottheubuntuforinstance)tomakelifealittleharderfor theattackers. Ifwetakearandomwebsiterunningapachewemayhavesomethinglike: Server:Apache/2.0.55(Debian)PHP/5.1.21+b1mod_ssl/2.0.55OpenSSL/0.9.8b Forsomeapplications(likePostfix)modyifingthebannerisaneasytask,amatterof trivialreconfiguration;forotherapplications,likeOpenSSH,you'llneedtorecompile thesoftwarefromsourceafterapplyingaproperpatch. Someexamples: Apache: To avoid Server: Apache/2.0.55 (Debian) PHP/5.1.21+b1 mod_ssl/2.0.55 OpenSSL/0.9.8b,inyourhttpd.confadd/(oruncomment) ServerTokensProductOnly ServerSignatureOff
HardeningGuide Chapter7AdvancedHardening 80/87

(andexpose_php=Offinyourphp.iniifyouusephp) RegardingApache,anelegantandcleanalternativeisleveragingmod_securitywith #Servermaskingisoptional #SecServerSignatureMicrosoftIIS/0.0 seehere:http://techgurulive.com/2008/08/15/secureyourapache2withmodsecurity/ Postfix: inmain.cfmodifysmtpd_banner=$myhostnameESMTP$mail_nametosmtpd_banner =$myhostnameESMTP AsforSSH,itsversioncanbehiddenbypatchingthesourcecode39itself:inservconf.c replace snprintf(buf,sizeofbuf,"SSH%d.%d%.100s\n",major,minor,SSH_VERSION); with snprintf(buf,sizeofbuf,"SSH%d.%dHIDDEN\n",major,minor); However,itshouldbenotedthatiftheoperatingsystemversionordistributionisgiven outbysomeotherdeamon,theburdenofpatchingandkeepingthepackageupdatedis easilynotworthit.

7.4.2DeludingScans
Deluding scans is a difficult matter, meddling with lowlevel TCP details: having a firewallorbeingbehindaNATcanchangeTCPbehaviourcompletely. Generallyspeakingthebestsolutionistorelyonanapplicativeproxyinfrontofthereal service,forexampleanOpenBSDbasedproxy(pfallowstosetfingerprints40). Shouldyouwanttotrydecoymethodsinaproductionenvironment,whichisnotreallya bestpractice,thesethreetoolsareamongthemostwellknownsoftware: PortSentrycanbeusedtoblocksomekindofscans,othertoolstrytohideor faketheOStypeandothertoslowdownthescans. IPMorphisatoolwhichaimsatthiskindofdelusion,infactitworksagainst Nmap,Xprobe2,Ring2,SinFPandp0f ChaosTables(nowinxtables)aimsatdeludingnmapscans41.

39Seehttp://www.kramse.dk/projects/unix/opensshhideversion_en.html
40 Seesetfingerprintsinhttp://www.openbsd.org/cgibin/man.cgi? query=pf.conf&sektion=5&arch=i386&apr

41http://jengelh.medozas.de/documents/Chaostables.pdf http://jengelh.medozas.de/projects/chaostables/ http://xtablesaddons.sourceforge.net/ http://nfws.inl.fr/en/?p=104


HardeningGuide Chapter7AdvancedHardening 81/87

CHAPTER8:RANDOMLITTLETHINGS

8.1Bashhistory
Anattackercanlearnalotofinformationsfromthe.bash_historyfile:addressesof otherservers,installedsoftwareorevenpasswords. Youcanaddtoyour.bashrcand.bash_profileor/etc/profileanordertodeletehistoryat login: rm~/.bash_history or shred~/.bash_history Theparanoidwayconsistsindirectlylinkingyourbash_historyon/dev/null lns/dev/null~/.bash_history Rememberthatthismayimpactusabilityofyoursystemasyouwillnotbeableto accessthehistoryofthecommandsyouentered.

8.2Blowfish/etc/shadow
BydefaultUbuntuandDebianusesamd5basedfunctiontostorehashesofpasswords in/etc/shadow.Ifanattackerisabletoread/etc/shadow,hewilltrytoforcethe passwords. Thetimeitwillrequiredependsmostlyontwoparameters:thequalityofthepassword andthewayitisstored.Bothofthemcontributetothequantityofcalculustoperform, andthusthetimeanattackerwillneedtocrackthepasswords. TheOpenBSDteamimplemented42apasswordhashingmethodbasedonblowfish, whichduetothewayblowfishworks,requiresmorecalculusandsomoretimetocrack thepasswords. Youcanuseblowfishbasedpasswordstoragebyinstallinglibpamunix2.Anhowto maybefoundhere43.

42 CftheUSENIXpaperhttp://www.openbsd.org/papers/bcryptpaper.ps 43 http://digitalconsumption.com/forum/615BlowfishshadowfilesonDebian
HardeningGuide chapter8:randomlittlethings 82/87

8.3AbsolutePath
Itisadvisedtouseimportantcommandssuchassuorsudobycallingthemwiththeir absolutepath:ex/bin/su. Ifyoudon'tknowanabsolutepathusewhichCOMMANDtogetit. Thisisadefenceagainstaverytrivialattack:ifanattackermodifiesyourPATH variabletoinclude.andputsacustommadesuorsudocommandhecanstealyour passwordorexecutearbitrarycode. Checkthat$PATHdoesnotcontain.oranemptystring.Checkitbyecho$PATH

8.4WebApps
Webapplicationsaretoooftenoneoftheweakestpartofasystem.Ifyoucanavoidtheir use,doit.IfnotyoucanhidethembyrestrictingtheiraccesstosomeIPoronlyovera SSHtunnelorwithportknocking,orevenatrivialHTTPBasicAuthentication.There'sa hugedifferencebetweenexposingawebapplicationtotheinternetandprotectingiteven withtheeasisestofthepasswords.

8.5AboutBubbles
Bubbles aremoreamanagementissuethanatechnicalone:itconsists ofcreating securitybubblesforafewveryimportantcomputers.Thosefewareplaced in a separateddedicatednetworkwhichisaccessibleonlyoveraVPNandmaintainedbyan alphateam(trainedadminswhichonlymaintainsaverysmallnumberofcomputers) andregularlyaudited.

8.6Aboutdedicatedmanagementnetworks
Asageneralrule,aseparated,isolatednetworkisaverygoodidea.Most implementations,however,arejustflatnetworkconnectingeveryserveronthenetwork, regardlessoffirewallsandIDS.That'saverybadideafromasecurityperspective!

8.7Securedeletion
If your server contains sensitive information, we need to prevent an attacker from recoveringthemiftheyaredeleted.Thisisespeciallythecaseiftheserverismoved fromoneplacetoanother,ifit'sharddrivesaresenttoanotherlocationorifitisstolen. Forthiswecanuseshredwhichwilloverwritethefilealotoftimebeforecancelingit, makingverydifficultitsrecovery. Tosecurelydeleteafilenamedtoto2: #shredremovetoto2

HardeningGuide

chapter8:randomlittlethings 83/87

Scenario:youneedtomoveafileserverfromyouritalianofficetoyourfrenchdata center. The server contains corporate critical informations (client informations, projectsdetails,strategicplans).Evenifyoubackupedyourdataanddeleteditonthe harddrive,ifthetransportingservicesislostitorifitisstolen,anattackercanuse forensicstoolstogetthedeleteddata.Asfilesystemsencryptionisnotalwaysan optiononservers,youneedtosecurlydeletetheinformation,forexampleusingshred.

8.8GccSSP
GCCSSPshouldbebydefaultfromedgy44

8.9MorelinksonIDS
Tiger:http://www.nongnu.org/tiger/ Diffmon:http://linux.about.com/cs/linux101/g/diffmon.htm swatch:forlogwatching Scandetection:portsentry,scanlogd OSIRIS:http://osiris.shmoo.com/ ModuleHunter: http://exitthematrix.dod.net/matrixmirror/misc/kernel_auditor/module_hunter.c

8.10DeceptionNetworks
Somecompaniesuseslargedeceptionnetworks,asubnetofhoneypotstoslowdown(ex withlabrea)anddetectautomatedattacks

8.11Bastille
BastilleUnix45isaninteractivescriptwhichhelpsatsecuringanunixsystem. Howtohere46

8.12PSAD
psadisacollectionofthreelightweightsystemdaemons(twomaindaemonsandone helperdaemon)thatrunonLinuxmachinesandanalyzeiptableslogmessagestodetect portscans andothersuspicious traffic.Atypicaldeploymentistorun psad on the iptablesfirewallwhereithasthefastestaccesstologdata.47

44 45 46 47

https://wiki.ubuntu.com/GccSsp http://www.bastilleunix.org/ https://help.ubuntu.com/community/BastilleLinux http://cipherdyne.org/psad/


chapter8:randomlittlethings 84/87

HardeningGuide

APPENDIXC:SOMESECURITYLINKS
Anonexhaustivelistoflinksaroundsecuritywhichmaybeofsomeinterestforthe reader.

Advisories:
CERTAANNOUNCES(InFrench):http://www.certa.ssi.gouv.fr/ SecuniaAdvisories:http://secunia.com/ PacketStormSecurityHeadlines:http://packetstormsecurity.org/ http://milw0rm.com/ TheOpenSourceVulnerabilityDatabasehttp://osvdb.org/

ComputersecurityexpertsBlogs:
(notanexhaustivelist) RobertGraham'sBlog:http://erratasec.blogspot.com/ StefanoZanero'sBlog:http://raistlin.soup.io/ BruceSchneierBlog:http://www.schneier.com/blog/ RichardBejtlich'sBlog:http://taosecurity.blogspot.com/ ClaudioCriscione'sBlog:http://oversighting.com/ AntonChuvakin'sBlog:http://chuvakin.blogspot.com/ SecurityResearch,ComputerLaboratory,UniversityofCambridge http://www.lightbluetouchpaper.org/ Doxpara:http://www.doxpara.com/

Othersourceofinformation:
Theregister:http://www.theregister.co.uk/security/ GNUCitizen:http://www.gnucitizen.org/ SecurityFocus:http://www.securityfocus.com/ Heisesecurity:http://www.honline.com/security/news/

HardeningGuide

AppendixC:Somesecuritylinks 85/87

REFERENCES
References
[Cromwell]BobCromwellhttp://www.cromwellintl.com [Wriskmana]http://en.wikipedia.org/wiki/Risk_management [Mehari]https://www.clusif.asso.fr/en/production/mehari/ [Virt]http://en.wikipedia.org/wiki/Platform_virtualization [VMware]www.vmware.com [UbuntuServerInstall]https://help.ubuntu.com/8.04/installationguide/ [DebianInstall]http://www.debian.org/releases/stable/installmanual [DefPAssList]Defaultpasswordlisthttp://www.phenoelitus.org/dpl/dpl.html [RossAndersonSHB2008]http://www.cl.cam.ac.uk/TechReports/UCAMCLTR 500.pdf [NFwi]http://en.wikipedia.org/wiki/Netfilter [Shorewallbastion]http://www.shorewall.net/standalone.htm [Shorewallstart]http://www.shorewall.net/GettingStarted.html [NetfilterHowto]http://www.netfilter.org/documentation/HOWTO//networking conceptsHOWTO.html Formoreconveniencewhenreadingthepdfversion,allotherreferencesaremadeas footnotes.

BooksinFrench
ManagerlascuritduSIMatthieuBennasar,AlainChampenois,PatrickArnould, ThierryRivatDUNOD2007 Comprendreetgrerlesrisques FranckMoreau&al. Editionsd'Organisation 2002

BooksinEnglish
BuildingsecureserverswithLinuxMichaelD.BauerO'Reilly2003 HardeningLinuxJamesTurnbullApress2005 HackProofingLinuxJamesStranger,PatrickLane,EdgardDanielyanSyngress 2001
HardeningGuide References 86/87

LinuxsecuritycookbookBarett&Al.O'Reilly2003 PracticalUnix&InternetSecurityGarfinkel&Al.O'Reilly2003 LinuxBibleChristopherNegusWiley2007 LinuxFirewalls:AttackDetectionandResponsewithiptables,psadandfwsnort MichaelRashNoStarchPress2007

OtherHardeningguides
UNIXandLinuxSecurityChecklist,AustralianComputerEmergencyResponseTeam (AusCERT)http://www.auscert.org.au/5816 Cromwell's Hardening Ressources, hardening.html http://www.cromwellintl.com/security/linux

SecuringandOptimizingLinux,http://www.faqs.org/docs/securing/index.html GentooLinuxSecurity,http://www.gentoo.org/security/en/ NSA Hardening Tips Pamphlet for the Red Hat Enterprise Linux 5, http://tuxtraining.com/wpcontent/uploads/2008/04/rhel5pamphleti731.pdf NSA Guide to the Secure Configuration of Red Hat Enterprise Linux 5, http://tuxtraining.com/wpcontent/uploads/2008/04/rhel5guidei731.pdf

HardeningGuide

References 87/87

Вам также может понравиться