Upload
alskjdf
View
396
Download
146
Embed Size (px)
Citation preview
PraiseforotherbooksbyMichaelWLucasAbsoluteOpenBSD,2ndEdition"MichaelLucashasdoneitagain."–cryptednets.org"After13yearsofusingOpenBSD,Ilearnedsomethingnewanduseful!"–PeterHessler,OpenBSDJournal"Thisistrulyanexcellentbook.It'sfullofessentialmaterialonOpenBSDpresentedwithasenseofhumorandanobviousdeepknowledgeofhowthisOSworks.Ifyou'recomingtothisbookfromaUnixbackgroundofanykind,you'regoingtofindwhatyouneedtoquicklybecomefluentinOpenBSD–bothhowitworksandhowtomanageitwithexpertise.IdoubtthatabetterbookonOpenBSDcouldbewritten."—SandraHenry-Stocker,ITWorld.com"Doyouneedthisbook?IfyouuseOpenBSD,andhavenotyetachievedgurustatus,yes,thisbookisjustforyou.Evenguruswillfindvaluablethingsinthisbookthattheydidnotknow…ButbeyondtheOpenBSDaspect,therearegreatsectionsoncross-platformapplicationslikesudothatarealmostenoughontheirowntojustifygettingthisbook.Andthereareseveralofthosechapters.So:evenifyoudon’tuseOpenBSDdirectly,wouldyoulikeaquickreferenceonsudo,IPv6networking,andNFSsetup?Oh,andalsotftpd,PXE,anddisklessBSDsystems?Butwait,whatifItoldyouthesereferencescamewithafreebookonOpenBSDinstallationandconfiguration?"–WarrenBlock,wonkity.com"ItquicklybecomesclearthatMichaelactuallyusesOpenBSDandisnotahiredgunwithasetwordcounttosatisfy...Inshort,thisisnotadrive-bybookandyouwillnotfindanyhandwaving."–MichaelDexter,callfortesting.org
DNSSECMastery"WhenMichaeldescendsonatopicandproducesabook,youcanexpecttheresulttocontainloadsofusefulinformation,presentedalongwithhumorandreal-lifeanecdotessoyouwillwanttoexplorethetopicindepthonyourownsystems."—PeterHansteen,authorofTheBookofPF"PickupthisbookifyouwantaneasywaytodiveintoDNSSEC."—psybermonkey.net
SSHMastery"…oneofthosetechnicalbooksthatyouwouldn’tkeeponyourbookshelf.It’soneofthebooksthatwillhaveitsbindingsbent,andmanypagesbookmarkedsittingnearthekeyboard."—TheExceptionCatcher“…SSHMasteryisatitlethatUnixusersandsystemadministratorslikemyselfwillwanttokeepwithinreach…”—PeterHansteen,authorofTheBookofPF"Thisstripping-downoftheusualtech-bookexplanationsgivesittheimmediacyofextendeddocumentationontheInternet.Notthemultipagehow-toarticlesusedasvehiclesforadvertising,butanin-depthpresentationfromsomeonewhousedOpenSSHtodoanumberofthings,andpaidattention
whiledoingit."—DragonFlyBSDDigestNetworkFlowAnalysis"Combiningagreatwritingstylewithlotsoftechnicalinfo,thisbookprovidesalearningexperiencethat'sbothfunandinteresting.Nottoomanytechnicalbookscanclaimthat."—;login:Magazine,October2010"Thisbookisworthitsweightingold,especiallyifyouhavetodealwithashoddyISPwhoalwaysblamesthingsonyournetwork."—Utahcon.com"Thebookisacomparativelyquickreadandwillcomeinhandywhentroubleshootingandanalyzingnetworkproblems."—Dr.Dobbs"NetworkFlowAnalysisisapickforanylibrarystronginnetworkadministrationanddatamanagement.It'sthefirsttoshowsystemadministratorshowtoassess,analyzeanddebutanetworkusingflowanalysis,andcomesfromoneofthebesttechnicalwritersinthenetworkingandsecurityenvironments."—MidwestBookReviewAbsoluteFreeBSD,2ndEdition"IamhappytosaythatMichaelLucasisprobablythebestsystemadministrationauthorI’veread.Iamamazedthathecancommunicatetop-notchcontentwithasenseofhumor,whilenotoffendingthereaderorsoundingstupid.Whenwasthelasttimeyoucouldphysicallyfeelyourselfgettingsmarterwhilereadingabook?IfyouareabeginningtoaverageFreeBSDuser,AbsoluteFreeBSD2ndEd(AF2E)willdeliverthatsensationinspades.Evenmoreadvanceduserswillfindplentytoenjoy.”—RichardBejtlich,CSO,MANDIANT,andTaoSecurityblogger“MasterpractitionerLucasorganizesfeaturesandfunctionstomakesenseinthedevelopmentenvironment,andsoprovidesaidandcomforttonewusers,novices,andthosewithsignificantexperiencealike.”—SciTechBookNews“…readswellastheauthorhasaveryconversationaltone,whilegivingyoumorethanenoughinformationonthetopicathand.Hedropsinjokesandhonesttruths,asifyouweretalkingtohiminabar.”—TechnologyandMeBlogCiscoRoutersfortheDesperate,2ndEdition“IfonlyCiscoRoutersfortheDesperatehadbeenonmybookshelfafewyearsago!ItwouldhavedefinitelysavedmemanyhoursofsearchingforconfigurationhelponmyCiscorouters....IwouldstronglyrecommendthisbookforbothITProfessionalslookingtogetstartedwithCiscorouters,aswellasanyonewhohastodealwithaCiscorouterfromtimetotimebutdoesn’thavethetimeortechnologicalknow-howtotackleamorein-depthbookonthesubject.”—BlogcriticsMagazine"Forme,readingthisbookwaslikehavingoneoftheguysinmycompanywholivesandbreathesCisco
sittingdownwithmeforadayandexplainingeverythingIneedtoknowtohandleproblemsorissueslikelytocomemyway.TheremaybemanyadditionalthingsIcouldpotentiallylearnaboutmyCiscoswitches,butlikelyfewI'mlikelytoencounterinmyenvironment."—ITWorld"ThisreallyoughttobethebookinsideeveryCiscoRouterboxfortheveryslimchancethingsgogoofyandhelpisneeded'rightnow.'"—MacCompanionAbsoluteOpenBSD"MycurrentfavoriteisAbsoluteOpenBSD:UnixforthePracticalParanoidbyMichaelW.LucasfromNoStarchPress.Anyoneshouldbeabletoreadthisbook,downloadOpenBSD,andgetitrunningasquicklyaspossible."—Infoworld"IrecommendAbsoluteOpenBSDtoallprogrammersandadministratorsworkingwiththeOpenBSDoperatingsystem(OS),orconsideringit."—UnixReview“AbsoluteOpenBSDbyMichaelLucasisabroadandmostlygentleintroductionintotheworldoftheOpenBSDoperatingsystem.ItissufficientlycompleteanddeeptogivesomeonenewtoOpenBSDasolidfootingfordoingrealworkandthementaltoolsforfurtherexploration…ThepotentiallyboringtopicofsystemsadministrationismadeveryreadableandevenfunbythelighttonethatLucasuses.”—ChrisPalmer,President,SanFranciscoOpenBSDUsersGroupPGP&GPG"...TheWorld'sfirstuser-friendlybookonemailprivacy...unlessyou'reacryptographer,orneveruseemail,youshouldreadthisbook."—LenSassaman,CodeConFounder“Anexcellentbookthatshowstheend-userinaneasytoreadandoftenentertainingstylejustabouteverythingtheyneedtoknowtoeffectivelyandproperlyusePGPandOpenPGP.”—Slashdot“PGP&GPGisanotherexcellentbookbyMichaelLucas.Ithoroughlyenjoyedhisotherbooksduetotheircontentandstyle.PGP&GPGcontinuesinthisfinetradition.IfyouaretryingtolearnhowtousePGPorGPG,oratleastwanttoensureyouareusingthemproperly,readPGP&GPG.”—TaoSecurity
SudoMastery:UserAccessControlforRealPeoplecopyright2013byMichaelWLucas(http://www.michaelwlucas.com/)Allrightsreserved.AmazonEdition.Author:MichaelWLucasCoverdesign:BradleyKMcDevittCopyediting:AidanJulianna"AJ"PowellCoverPhoto:ElizabethLucas(concertinawireatabandonedfactory,Detroit)published2013byTiltedWindmillPresswww.tiltedwindmillpress.comAllrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyany
means,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.Forinformationonbookdistribution,translations,orotherrights,pleasecontactTiltedWindmillPress([email protected]).
Theinformationinthisbookisprovidedonan"AsIs"basis,withoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthiswork,neithertheauthornorTiltedWindmillPressshallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.
AcknowledgementsIwanttothankthefolkswhoreviewedthemanuscriptforSudoMasterybeforepublication:BryanIrvine,JRAquino,HughBrown,andAvigdorFinkelstein.SpecialthanksareduetoToddMiller,thecurrentprimarydeveloperofsudo,whowasverypatientandhelpfulwhenansweringmydaftquestions.
WhileIappreciatemytechnicalreviewers,noerrorsinthisbookaretheirfault.Allerrorsaremy
responsibility.Mine,doyouhearme?Youreviewerswantblameforerrors?Gomakeyourown.XKCDfansshouldnotethattheauthordoesnotparticularlyenjoysandwiches.However,MiodVallat,
currentlyexiledtoFrance,wouldreallylikeasandwichwithnicefreshbread,reallygoodmustard,andlow-carbgroundglassandrustynails.AndBryanIrvinewouldlikearueben.
ThisbookwaswrittenwhilelisteningobsessivelytoAssemblage23.
ContentsChapter1:IntroducingsudoChapter2:sudoandsudoersChapter3:EditingandTestingSudoersChapter4:ListsandAliasesChapter5:OptionsandDefaultsChapter6:ShellEscapes,Editors,andSudoersPoliciesChapter7:ConfiguringsudoChapter8:UserEnvironmentsversusSudoChapter9:SudoforIntrusionDetectionChapter10:SudoersDistributionandComplexPoliciesChapter11:SecurityPoliciesinLDAPChapter12:SudoLogging&DebuggingChapter13:AuthenticationAfterword
Chapter1:IntroducingsudoResolved:controllinguseraccesstoacomputer'sprivilegedprogramsandfilesisarightpain.Noneofthesystemsthatevolvedtocopewithmappingreal-worldprivilegesontodigitalschemesareverygood.Thebestaccesscontrolsystemsmerelyhurtlessthanothers.
Unix-likesystemscontrolprogramsandfileaccessthroughusersandgroups.Eachindividualuserhasauniqueidentifier,giveneitherasausernameorauserIDnumber(UID).Usersarearrangedinuniquelyidentifiedgroups,giveneitherasagroupnameoragroupIDnumber(GID).Specificusersandgroupshavepermissiontoaccessspecificfilesandprograms.
ThisschemesufficedduringUNIX'schildhood.AlargeuniversitymighthaveacoupleofUNIXservers.Hundredsofusersloggedontoeachserverformail,news,andcomputation-intensiveapplications.Studentswentinonegroup,gradstudentsinanother,thenprofessors,staff,andsoon.Individualclassesanddepartmentsmighthavetheirowngroups.
Thesystemownershadaspecialaccount,root.Therootaccounthasultimatesystemcontrol.Asasecurityandstabilityprecaution,Unix-likesystemsrestrictcertainoperationssothatonlyrootcanperformthem.Onlyrootcanreconfigurethenetwork,mountnewfilesystems,andrestartprogramsthatattachtoprivilegednetworkports.Thismadesensewhenyouhadtwoserversforanentirecampus–reconfiguringthenetworkoraddinganewdiskdriveisaserioustaskinthatenvironment.Thejobofmanagingmultimillion-dollarsystemsshouldremainintrusted,highlyskilledhands.
Inthe21stcentury,Unix-likesystemsarecheapandplentiful.Teamsofpeoplemightsharesystemsadministrationtasks,oronepersonmighthavecompletecontroloverasystem,oranythinginbetween.Eithersituationcompletelychangesyoursecurityrequirementsfromthoseofthepreviouscentury.
Largeorganizationsoftendividesystemsadministrationresponsibilitiesbetweenskilledindividuals.Onepersonmightberesponsibleforcareandfeedingoftheoperatingsystem,whileasecondpersonhandlestheapplicationrunningontheserver.Theserversupportstheapplication,andtheapplicationiswhytheserverexists,butbothpeopleneedtoperformtasksthatrequireroot-levelprivileges.Butroot-levelprivilegeisanall-or-nothingaffair.There'snodivisionbetween"accesstochangethekernel"and"accesstorunprivilegedapplications."Iftheapplicationadministratorhasroot-levelaccess,hecanchangethekernel.Youcanalwaysrelyongentleman'sagreementstoonlytouchthepartsofthesystemyou'reresponsiblefor,butwhenyourorganizationemploysateamofsystemsadministratorsandateamofdatabaseadministratorstosupportdozensorhundredsofservers,thesegentleman'sagreementsquicklydecomposeintofinger-pointingbloodbaths–evenwithoutvendor-providedapplicationsetupscriptsthathelpfullycustomizethekernelwithouttellinganyone.Theseorganizationsneedafiner-grainedaccesscontrolsystemthanrootprovides.
Theall-or-nothingmodelbreaksdownevenmorewheneveryonehasaUnix-likesystem.Settingasidetheinnumerablephonesandtabletswhichhaveextrasoftwaretomakethemuser-friendly,manyfolksrun
Unix-likeoperatingsystemsonadesktoporlaptop.EverytimetheyaccessaUSBdriveoruseacoffeeshopwirelessnetwork,somethingonthesystemneedsroot-levelprivileges.Usingrootprivilegesisn'tterriblyonerous–loginwithyourregularaccount,usethesucommandtoswitchusers,entertherootpassword,runthecommandsthatneedrootaccess,andexittherootaccount.ButwhenyoumustusetherootaccountanytimeyouputinaUSBdrive,bouncethenetwork,add,reconfigure,orrestartsoftware,itquicklybecomesdownrightannoying.Whilesoftwarecanmanagemuchofthisforyou,sometimesyoumusttriggerrootprivilegesforroutinetasks.
ThecomputingindustryisfullofreallysmartpeoplethathaveexpandedtheclassicUNIXprivilegecontrolmodels.Onemethodisthroughsetuidandsetgidprograms.Whileprogramsnormallyworkwiththeprivilegesoftheuserwhorunsthem,setuidandsetgidprogramschangetheireffectiveUIDandGIDtosomeothervalue.Youcanhaveasetuidprogramthatrunsasroot.Changingyourpasswordrequireseditingsecuredfilesin/etc/,sothepasswdcommandissetuid.Butintrudersreallylikesetuidandsetgidprograms.Flawsintheseprogramsmightbeexploitedintofullrootaccess.Andmostoperatingsystemsdon'tletyoumakeshellscriptssetuid,onlyprograms.
Thenthereareseveralvarietiesofaccesscontrollists(ACLs)whichmorebroadlyexpandtheuser-group-othersownershipmodel.ACLsallowyoutodeclaresomethinglike"Thispersonownsthefile,butthesegroupsandpeoplecanmodifyit,withtheseexclusions,andthesegroupsandpeople(withsomeexclusions,ofcourse!)canexecuteit,whiletheseotherpeoplecanreaddatafromit,exceptfor…"Atthispointthesystemsadministratorgetsaheadacheandstartscontemplatingacareercleaninguprealsewageinsteadofthemetaphoricalkind.Andofcourse,allthedifferentACLimplementationsareeversoslightlyincompatible.VeryfewpeoplecancorrectlyimplementACLsonasingleplatform,andthatexpertisedoesn'treallyextendtootherplatforms.ACLshaveaplaceinsystemsadministration,andifyoureallyneedthem,they'reinvaluable.Butmostofusdon'tneedthem.
Andsadly,accesscontrollistsareaboutasgoodasitgets.Exceptforsudo.
WhatIsSudo?Sudoisaprogramthatcontrolsaccesstorunningcommandsasrootorotherusers.Thesystemownercreatesalistofprivilegedcommandsthateachusercanperform.Whentheuserneedstorunacommandthatrequiresroot-levelprivilege,heaskssudotorunthecommandforhim.Sudoconsultsitspermissionslist.Iftheuserhaspermissiontorunthatcommand,itrunsthecommand.Iftheuserdoesnothavepermissiontorunthecommand,sudotellshimso.Runningsudodoesnotrequiretherootpassword,butrathertheuser'sownpassword(orsomeotherauthentication).
Thesystemadministratorcandelegateroot-levelprivilegestospecificpeopleforveryspecifictaskswithoutgivingouttherootpassword.Shecantellsudotorequireauthenticationforsomeusersorcommandsandnotforothers.Shecanpermitusersaccessonsomemachinesandnotothers,allwithasinglesharedconfigurationfile.
Someapplications,notablybigenterprisedatabasesoftware,rununderaspecificdedicatedaccount.Usersmustswitchtothisaccountbeforemanagingthesoftware.Youcanconfiguresudotopermituserstorunspecificcommandsasthisaccount.Maybeyourjuniordatabaseadministratorsonlyneedtorunbackups,whiletheleadDBAneedsafull-onshellpromptasthedatabaseaccount.Sudoletsyoudothat.
Finally,sudologseverythingeverybodyasksittodo.Itcanevenreplaythecontentsofindividualsudosessions,toshowyouexactlywhobrokewhat.
What'sWrongwithSudo?Ifsudoissoawesome,whydoesn'teverybodyuseit?
Sudoaddsanotherlayerofsystemsadministration.Addingthatlayerrequirestime,energy,andattention.Itrequireslearningyetanotherdangedprogramwhenyoualreadyhavetoomuchtodo.Ifyou'reresponsibleforrunninganenterprisesystemwithseveralgroupsofadministrators,investinginsudoreducesyourworkload.Butyoumustlearnhowtouseitfirst.
SomecommercialUNIXesdon'tincludesudobecausetheyalreadyincludetheirownproprietaryescalatedprivilegemanagementsystem.OpenSolaris-basedsystemshavepfexecandrole-basedaccesscontrol(RBAC).HPhaspbrun.IfyouwereacommercialUNIXvendorwhospentlotsofmoneyandenergydevelopinganACL-basedprivilegemanagementsystem,wouldyouincludeandencourageuseofasimpler,easiertoolinstead?Imight,butthat'swhyI'mnotabigcommercialUNIXvendor.
Manyopen-sourceUnix-likeoperatingsystemsdoincludesudointheirbasesystem.Some,suchasUbuntuandOSX,completelydisabletherootaccountandonlypermitprivilegedaccessviasudo.Thisisalurchintherightdirection,butmostpeoplewhohavesudouseitincorrectly.
What'sthewrongwaytousesudo?Sudoisnotareplacementforsu.Sudoisnotawaytocompletelyavoidrequiringauthenticationforprivilegedaccess.Sudoisnotatooltoforcesomeonetomakeyouasandwich.Apropersudosetupsimplifiessystemmanagement.Animpropersudosetupletsintrudersandunauthorizeduserscorruptordestroyyoursystemfasterandeasier.
"Properuseofsudo"doesn'tmeancomplicated,orevenextensivepolicies.I'veseensystemadministratorsspendhourswritingcomplicatedsudopolicies,onlytowatchuserswaltzrightpasttheirrestrictions.Sometimestheusersdidn'tevenrealizethattherestrictionswereinplace.Sudohaslimits.Onceyouunderstandthoselimits,youcanmakerealisticdecisionsabouthowandwhereyourorganizationdeployssudo.
TheproblemIseemostoftenwithsudohasnothingtodowiththesoftwareitself.Apropersudodeploymentinacomplicatedorganizationrequiresthesystemadministrationteamtoagreewhoisresponsibleforwhat.Sudoenforcesjobdutiesandresponsibilitiesinaconfigurationfile.Theconfigurationfileisflexible,butpeoplecannotexceedtheprivilegesspecifiedtherein.
Whataretheboundariesofyourresponsibilities?Whatpermissionsdoyouneedtodoyourrealjob,andwhichtasksshouldsomeoneelsedo?Beingforcedtositdownandthinkaboutthesethingscanbeuncomfortable,andcantemporarilyincreaseconflictswithinanorganization.Oncetheargumentssettle,however,conflictsdecrease.There'snobickeringoverwhodidwhat,when,orhow.Everybodyknowsthatthedatabaseteamcan'tformatfilesystems,thewebteamcan'trestartthedatabase,andthesudologsclearlyshowwhotookanyprivilegedactions.Andhavinganaudittrailimprovessystemstability.Whenpeopleknowthatthesystemlogstheirprivilegedactions,andthattheycanandwillbeheldresponsibleforbreakingthings,theystopbreakingthingssooften.Weird.
WhoDoesSudoProtectYouFrom?Sudoprotectsthesystemfromharmbyintrudersorsystemsadministrators,anditprotectssystemsadministratorsfrommanymanagementproblems.
Givingauseraccesstoonlyalimitedsetofprivilegedcommandslimitsthedamagethatusercaninflictonthesystem.Theuserwhoonlyhasaccesstomanagethewebserverordatabasecannotmanglediskpartitions.Ifanintrudercompromisesthatuser'saccount,theintruderislikewiseslowedorcontained.
Similarly,lackofaccessprotectsthesystemadministratorwhensomethinggoeswrong.Evenwithoutsudologs,auserwithlimitedadministrativeaccesscansay"Hey,Ididn'treconfigurethewebserver.Idon'thavethataccess,remember?"Accountabilityworksbothways.Useittoyouradvantage.
SudoSupportSudoisfreely-availableopensourcesoftware.Youarewelcometodownloaditfromthemainwebsite(http://sudo.ws)oramirroranduseitthroughoutyourorganizationatnocharge.Thelicensepermitsyoutousesudoasthebasisofyourownproducts,resellittoclients,orincorporateitintosoftwareyouthenredistributeorresell.Youcanusesudoforanythingyoulike.
Whatyoudon'tgetissophisticatedsupport.Sudoisnotcreatedbyacommercialcompany.It'sdevelopedandsupportedbytheuserswhoneedit,
andcoordinatedforthelastseveralyearsbyToddMiller.Youcancontributetosudobysubmittingpatchesandbugreports.Youcanfindpeopleandcompanieswhowillsupportyoursudoinstall,andwhowillevenwritecustomcodeforyou.Butthere'snobodyforyoutoyellatifyoursudoinstalldoesn'tworkthewayyouexpect.There'snotoll-freenumber,nominimum-wagesupportminionwithaquestionablegraspofyourlanguagewaitingtotakeabuseandinvectiveinexchangeforcash.
Havingsaidthat,thepeopleonthesudomailinglistsarebothextremelyhelpfulandveryinterestedinrealproblemreports.Theyrespondwelltorequestsforhelpandpoorlytodemands.Ifyouwanttodemandhelp–ifyouwanttoscreamandrantandraveandturnblueinthefaceuntilyourproblemgoesaway–anynumberofcompanieswillsellyouthat.
Thesoftwareisfree.Sudo's"officialsupport"isagiftthatevaporatesassoonasyoustoptreatingitlikeone.
WhoShouldReadThisBook?EveryonewhoworksonaUnix-likesystemshouldunderstandsudo.
Ifyouareasystemadministratorresponsibleformaintainingacomplicatedsystem,youprobablywanttoassignyourapplicationadministratorsexactlytheprivilegesneededtodotheirjobs,nomoreandnoless.Correctsudoconfigurationfreesupyourtimeandprotectsthesystemfromwell-intentioneddisasters.
Ifyouareanapplicationadministrator,youneedtodoyourjob.Thismeansyouneedtheaccesstoperformprivilegedtasks.Workingviasudomeanschangingyourprocessesslightly–notinanymajorway,butyoucangocompletelybonkerstryingtofigureoutwhysudocddoesn'tworkuntilyouunderstandwhat'sreallyhappening.Anunderstandingofsudoletsyoudraftthesudorulesyouneedandgivethemtothesystemadministrator.Evenifthesystemadministratordisagrees,negotiatinginsudopolicylanguagemeansthatyoubothunderstandexactlywhatyou'rerequesting.Youcanhavespecificdiscussionsaboutwhoisresponsibleforwhat.Nosystemadministratorwilltellanapplicationadministratorthathedoesn'tneedtheaccesstomanagehisapplication–shecertainlydoesn'twantthatjob!Theonlyquestionis:howcanthataccessbebestaccomplished?
Ifadisagreementbetweenteamsisbroadenough,thisiswhereyouinvokemanagementtomakeaveryspecificdecisionandsetclearlinesofauthorityandresponsibility.Insomeenvironments,gettingthatmanagertotakethatstepisamiracleinitself.Butamandatetoimplementsudoletsyoucornerhim.Andifyouhaveacrankysystemadministratorwhoclaimsthatgrantingyounecessaryaccesswithoutgivingyourootisimpossible,thisbookwillletyoucategoricallyrefutethat.Which,admittedly,isitsownvindictivepleasure.
Ifyoumaintainonlyyourpersonalsystem,whywouldyoucareaboutsudo?Evenonapersonallaptop,somecommandsmeritmorethoughtandconsiderationthanothers.Icanunderstandwantingtotriviallyreconfigurethelaptop'snetwork,tweakremovablemedia,orkillthatberserkwebbrowser.Youprobablydothesetaskssooftenthatyouunderstandthemwell–myfingerscanconfigureanetworkcardwithoutdisturbingmybrain.Buttasksyouperformlessoften,suchasinstallingsoftwareorformattingdisks,requirealittlemoreattention.Itmakessensetopermitsudotorunroutinetaskswithoutapassword,buttorequireauthenticationbeforeupgrading.
ServerPrerequisitesThisbookassumesyou'rerunningsudoonaUnix-likeoperatingsystem.SudoisavailableforBSDandSolarisderivatives,Linux,andeverycommercialUNIX.WhilemyreferenceplatformisFreeBSD,sudoworksonallofthesesystemsandmore.
Myreferenceimplementationissudo1.8.8.Ifyou'rerunninganolderversion,somefeaturesmightbeabsent.Asurprisingnumberofoperatingsystemvendorsincludewildlyobsoletesudopackages.Checktheversionofsudoonyoursystembyrunningsudo–V.Ifyourversionismucholderthan1.8.8,upgrade.Youcanalwaysgetthelatestsourcecodeandaselectionofprecompiledpackagesatthemainsudowebsite,http://sudo.ws.
Thesudodocumentationandthisbookassumethatyouroperatingsystemconformsfairlycloselytothetraditionalfilesystemlayout.Theexamplesinthisbookshowcommandsinstandarddirectoriessuchas/bin,/usr/bin,/sbin,andsoon.Ifyouroperatingsystemusesitsowndirectorylayout,you'llneedtoadjusttheexamplestomatch.
SysadminBackgroundWheremanyimportantprogramsrequireanextensivebackgroundinrelatedsoftwarebeforeyoucanusethem,sudoisniceinthatit'sfairlyself-contained.Youcanmastersudowithoutunderstandingalltheprogramsthatuserscanaccessthroughsudo.Sudoisasystemmanagementtool,however;themoreyouunderstandyoursystem,thebetteryoucanleveragesudoandthemoreconfidenceyou'llhaveinyourconfiguration.Iassumeyoucaninstallsudo,eitherfromanoperatingsystempackageorfromsourcecode.
ConfiguringsudorequiresrootaccessonaUnix-likesystemandfamiliaritywithaterminal-modetexteditor.Sudodefaultstousingvi,butyoucanuseEmacsoranyothereditor.
That'severything.Really.Alltheotherknowledgeyou'llpickupaswego.
LearningSudoThegoalofthisbookistoletyoureplaceaccesstoprivilegedcommandsviathesucommandandtherootpasswordwiththesudocommandandtheuser'spersonalauthenticationcredentials.Onceyou'recomfortablewithsudo,youcanusethesystem'sauthenticationmechanismtoeliminateauser'sabilitytobecomerootviasu.Therootpasswordwillbecomesomethingonlyusedinadisaster,orperhapswhenyou'reatthephysicalconsole.Eliminatingroot'sgenericauthenticationimprovessystemsadministratoraccountabilitywithinanorganization.Butoneofthebestwaystomakethisprojectfailistodeploysudotooquickly.
Configuringsudohasitsownpitfalls.You'llneedtolearnhowsudofitsintoyourenvironment.Nothingcausesquiteasmuchagonized,frustratedself-recriminationaslockingyourselfoutofyourownserver.Don'tbetooquicktodisablerootaccessviasu,asyoucanusethataccesstorepairabrokensudoconfiguration.Yes,sudohasfeaturesandtoolstoverifythatyoursudopolicyissyntacticallycorrect.Asudopolicythatsays"nobodycandoanything"issyntacticallycorrect,however.Leaveyouroldrootaccessinplaceuntilyou'reabsolutelyconfidentinthenewsudoarrangements,orbecomecomfortablewithbootingyoursystemintosingle-usermodetorepaireithersuorsudo.Avirtualmachineorjailcanbeausefultoolfordestructivelearning.
Someoperatingsystems(notablyUbuntuandOSX)providerootaccesswithsudoratherthansu.Ifyou'reexperimentingwithsudo,andsudoisyourmainmethodofaccessingprivilegedcommands,you'reinariskysituation.Beforemuckingwithsudo,enablerootaccessandputarootpasswordonyourlearningmachine.Makesureitworksandthatyoucangetrootaccesswithoutsudo.Youcanthenfreelyexploresudowithoutblockingprivilegedaccess.Onceyou'recomfortablewithsudo,youcanfullydeployitwithoutworry.
TheofficialsudodocumentationdescribesvarioussudofeaturesinExtendedBackus-NaurForm(EBNF),aformalgrammarforprogramconfiguration.WhilefamiliaritywithEBNFisausefulskillforanysysadmin,I'mchoosingtonottakeyouthroughtheformaldefinitions.Instead,thisbookdemonstratesthemostimportantsudofeaturesthroughsnippetsofactualconfigurationpolicies.
Alsonotethatthisbookdoesnotcoverallpossiblesudoconfigurations,nordoesitcovereveryavailablesudofeature.Icoverwhatthevastmajorityofsystemsadministratorsneed,butifyou'rerunninganolderoperatingsystem,usinganoldversionofsudo,oradministeraUnix-likesystemthatveerswildlyfromthecommonstandards,you'llneedtodiveintothedocumentationtoidentifythesharpedgesofyoursituation.Butafterreadingthisbookyou'llhaveasolidgroundinginsudotechniquesandagoodideaofexactlywhatinformationyou'relookingforandhowtouseit.
AvoidingsudoManysystemadministratorsconfiguretheirsystemstorequirerootprivilegesforroutinetaskswhentheyshouldusethegroupprivilegessupportedbythebaseoperatingsystem.Wetendtolookatpermissionsfortheuserandothers,butpaylessattentiontogrouppermissions.Beforerunningtosudotosolveanaccessproblem,seeifyoucansolveyourproblemwithgroupsinstead.Requiringrootprivilegestopermitaccesstofilesorprogramsislikerequiringuseofasledgehammertohangapicture.
Usegrouppermissionsforprogramsorfilesthatneedtobeaccessedbyseveralpeople,andonlythosepeople.Asatrivialexample,assumeseveralpeoplemaintainthefilesforaWebsite.Youcancreateagroupcalled,say,webadmins,andassignthatgroupastheownerofthewebsitedirectoryandallfilesinit.Takealookatourwebsite'stop-leveldirectory.#ls-ltotal94drwxrwxr-x2mikewebadmins512Jul122013content-rw-rw-r--1theawebadmins16584Oct202013logo.jpg-rw-rw-r--1petewebadmins767Oct202013errata.html-rw-rw-r--1mikewebadmins2736Jul122013index.html-rw-rw-r--1petewebadmins167Jul122011index2.html-rw-rw-r--1theawebadmins66959Oct202006banner.jpg
Theindividualfilesareownedbyasingleperson–mike,thea,orpete.Butthefilesarealsoreadableandwritablebythegroupwebadmins.Anyoneinthisgroupcanreadandeditthesefiles,andanythinginthedirectorybeneaththisone.
Thespecificsofaddinggroupsvariesamongoperatingsystems.Iwouldtellyoutoedit/etc/groups,butsomeoperatingsystemshavespecialtoolsspecificallyforovercomplicating–er,managing–groups.Usethetoolrecommendedinyouroperatingsystemmanual.
WhatGroupsamIIn?
Toidentifywhichgroupsyouareamemberof,runid(1).#iduid=1001(mike)gid=1001(mike)groups=1001(mike),10020(webadmins)
Myuseraccountisinthegroupsmikeandwebadmins.Icouldeditthefilesintheexampleabovebasedonmygroupmembership.IcouldalsoeditacoupleofthosefilesbecauseIownthemandthepermissionslettheownereditthefiles.
ProgramsversusGroups
Grouppermissionswon'tsolveallaccessproblemsforprograms.Someprogramsperformprivilegedfunctions,andlettingagroupruntheprogramwon'tgivetheprogramtherightstoperformthetask.Remember,aprogramrunswiththeprivilegesofthepersonrunningtheprogram.
Tocontinuethesagaofourwebmanagementteam,webserversrunonTCPports80and/or443.Onlyrootcanattachtonetworkportsbelow1024.Ifauserrunsthewebserverprogramwithoutanyextra
privileges,theprogramwillrunasthatuseraccount.Itwon'thavethenecessaryprivilegestoattachtothosenetworkports,andsothewebservercannotstartproperly.Settingtheprogrampermissionssothatausercanruntheprogramdoesn'tmeanthattheprogramwillwork.Ifyouwantyourwebadminsgrouptogetrootprivilegesspecificallyforstarting,stopping,andotherwisemanagingthewebserversoftware,youneedtogivetheusersinthatgrouprootprivileges.That'swheresudocomesin–youcanassignthemembersofthewebmanagementteamcontrolofthewebserverwithoutgivingthemanythingelse.
BookOverviewSudoisasuiteofinterrelatedprograms.You'llgetbetterresultsconfiguringsudoifyouunderstandhowthesedifferentpartsfittogether.
Traditionalsudohastwocomponents:thesudoprogramandthesudoerspolicyengine.Chapter2givesyouanelementarygroundinginboth.
Thesudoerspolicyfilecanonlybeeditedwithrootprivileges.Anerrorinthesudoersfilepreventsanyonefromgettingrootprivilegeswithsudo.Ifyou'vedisabledrootaccessthroughothermeans,asudoerserrorlocksyououtofthesystem.Thesudosuiteincludesaspecialtool,visudo,justforeditingandvalidatingthesudoersfile.Usingvisudoreducestheoddsyou'llgetreallyangrywithyourself.IcovervisudoinChapter3.
Sudopoliciesquicklybecomeverycomplicated.Reducethiscomplexitythroughusinglistsandaliases,asdiscussedinChapter4.
Youcannotadjustallpartsofsudo'sbehaviorthroughpolicyrules,however.Thesudoerspolicyenginealsoincludesvariousdefaultsettingsandoptionstochangethem,whichIdetailinChapter5.
Someprogramsofferwaystobreakoutofsudo'srestrictionsthroughshellescapes–notbecausetheywerewrittendeliberatelytoavoidsudo,butbecauseoftheirverynature.Chapter6coverswaystopreventgettinganunrestrictedrootshellfromtexteditorsandsimilarprograms.
Mostofthisbookisaboutthesudoerssecuritypolicyengine,butthesudoprogramitselfcanalsobetweaked.Chapter7discussessudo.conf.
Auser'senvironmentcancauseallkindsoftroublewhenusedbyprivilegedprograms.Chapter8coverscleaningtheshellenvironmentandeitherblockingorpermittingenvironmentvariablesinasudocontext.
Sudocanperformbasicintegritycheckingonprogramsbeforerunningthem.You'llseehowinChapter9.
Ratherthanmaintainingaseparatesecuritypolicyoneachofdozensorhundredsofmachines,youcanuseonecentralpolicyandpushitouttoallyourhosts.Chapter10coversrealisticlyusingasinglepolicyacrossyournetwork.
SudocanalsogetitssecuritypolicyfromyourLDAPauthenticationserver,ratherthanthroughthesudoersfile.IcoverLDAPandsudoinChapter11.
Onceyoucontrolauser'saccesstoprivilegedcommands,thenextquestionbecomes"whatdidtheuserdo?"Sudoincludesthreedifferentloggingsystems,eachwithadifferentusecase.Chapter12discussesallthree.
Finally,sudocantreatusercredentialsinavarietyofways,andifyouwanttoadjusthowyoursudoinstallhandlespasswordsandotherauthenticationdata,youwillwanttoreadchapter13.
Butbeforewegettothatadvancedstuff,let'sstartwiththebasicsaboutsudo.
Chapter2:sudoandsudoersThetwokeycomponentsofthesudosuitearethesudoprogramand/etc/sudoers.Usethesudocommandtorunaprogramwithescalatedprivilege.Thesudoersfiledefinesthepolicytellingsudowhichcommandsausercanrun,andwithwhichprivileges.
sudo101Youwanttorunacommandundersudo?Runsudofollowedbythecommand.HereIaskforanNFSmount.$sudomountfileserver:/home/mike/mntPassword:mount_nfs:fileserver:hostnamenorservnameprovided,ornotknown$
Sudoasksforapassword.Thisismypassword,nottherootpassword.IfIentermypasswordcorrectly,andifIhavepermissiontorunthiscommandviasudo,I'llgettheprogram'snormaloutput.AndaboutnowiswhenIrememberthattheofficesupportteamrenamedthatmachine.
Thegoodnewsis,sudoremembersthatIauthenticated,andwon'taskformypasswordforthenextfiveminutes.Someoperatingsystemschangethistime,soyou'llwanttocheckthesudomanpagefordetails.(Youcanchangethistime,oruseentirelydifferentauthentication,asdiscussedinChapter13.)Ifyoumakeamistake,youcanreenteracorrectedcommandimmediatelyafterwardsandnothavetoretypethepassword.
Thefirsttimeyourunsudoonanysystem,sudoprintsafewlinesabouttheimportanceofthinkingbeforeyourunprivilegedcommands.Takethislecturetoheart.Privilegedcommandsareprivilegedbecausetheycanreconfigure,deconfigure,damage,demolish,ordestroyasystem.
RunningCommandsasAnotherUser
Runningcommandsasrootisn'talwaysdesirable.Somesoftware,notablydatabasesandapplicationservers,mighthaveadedicateduserjustforthemselves.Theapplicationexpectstorunasthatuser,andthatuser'senvironmentisconfiguredtomanagetheapplication.ApplicationsrangingfrombigJava
programstotinytoolssuchasAnsible[1]
usethismodel.Youcanrunacommandasaspecificuserbyaddingthe–uflag.#sudo–uoraclesqlplus
Thisstartsupthetargetuser'senvironmentandrunsthespecifiedcommand,muchlikesu-.
RunningCommandsasAnotherGroup
Everyuserhasaprimarygroup,listedwiththeiraccountin/etc/passwdoritsequivalent.Groupsfromadditionalsources,suchas/etc/group,areconsideredsecondarygroups.Someprogramsonlyworkiftheuser'sprimarygroupisitspreferredgroup.Thisgetsreally,reallyannoying,asyouwouldprobablyprefertousegroupsfortheirintendedpurposeratherthanbabysittingonepieceofpickysoftware.Dependingonhowyouroperatingsystemhandlesgroupsandhowyoursoftwareisinstalled,youmightneedtochangeyourprimarygrouptorunacommand.Usethe–gflagandagroupname.#sudo–goperatorstupidpickycommand
Sudoliestotheprogramandtellsitthatyourprimarygroupisoperator.YoucouldalsouseagroupIDnumber,byputtingahashmarkbeforetheGID.Yourshellmight
demandyouescapethehashmarkonthecommandline.Wetcshusersdon'thavethatrequirement.#sudo–g#100stupidpickycommand
SudorunsthecommandasifyourprimarygroupIDis100.Thisisasmuchas90%ofusersknowaboutsudo.Everythingelseyoulearnwillmakeyoumoreofan
expert.
sudoers101Ifrunningsudoseemssimple,it'sbecausetherealworktakesplaceinthesudoersfile,oftencalledjust"sudoers."Thesudoersfilecontainstherulesdefiningwhichuserscanrunwhichprivilegedcommands.Myexamplesassumethatsudoersis/etc/sudoers,butwhereveryourpackageputsitisfine.Nevereditthesudoersfilebyhand;alwaysusevisudoascoveredinChapter3.
SomeoperatingsystempackagesincludeOS-specificexamplesintheirsudoersfileforspecialfeaturesthattheoperatingsystemsupports.Beforemakinganychangestothedefaultsudoersfile,copytheoriginaltoasafelocationsoyoucanrefertoitlater.
Thesudoersfilecontainsaseriesofrules,oneruleperline.Everyruleusesthisgeneralformat.Mostoftherestofourdiscussiononsudoerscoversextending,stretching,andgenerallyabusingthisformat.usernamehost=command
Usernameistheusernamethatthisruleappliesto.Theusernamemightalsobeasystemgroup,oranaliasdefinedwithinsudoers.Hostisthehostnameofthesystemthisruleappliesto.Wewillshare/etc/sudoersacrossmultiple
systemsinChapter10.Theequalsignseparatesthemachinefromcommands.Finally,commandliststhefullpathtoeachcommandthisruleappliesto.Sudoconfigurationrequires
fullpathstocommands.Thesudoersfilerecognizesavarietyofspecialkeywords.OneofthemostcommonlyseenisALL,
whichmatcheseverypossibleoption.Toallowalluserstorunanycommandoneveryhost,youcouldwriteasudoersfilelikethis:ALLALL=ALL
Thisisroughlyequivalenttogivingeveryonerootaccess,butusingtheirownpasswordinsteadoftherootpassword.Don'tdothis.Ataminimum,restrictaccessbyusername.mikeALL=ALL
Theusermikecanrunanycommandonallservers.Youcanalsorestrictsudoaccessbyhost.Mostcommonlyyou'llseetheserverlimitationasALL
becausemostsystemsadministratorsconfiguresudoonaper-hostbasis.Ifyouseparatelymanageeveryserver,definingtheserverasALLreallymeans"thisserver."Asabestpractice,however,puttheservernamehere.(Runhostnametogettheserver'sname.)Chapter10coversindetailassigningsudoprivilegesbyhost.mikewww=ALL
Theusermikecanrunanycommandonthehostwww.Torestrictausertorunningasinglecommand,givethefullpathtothecommandinthelastfield.
mikewww=/sbin/reboot
Theusermikecanrunthecommand/sbin/rebootontheserverwww.Easyenough,right?Nowlet'scomplicateit.
MultipleEntries
Eachuniquecombinationofaccessrulesneedsitsownlineinsudoers.It'sperfectlylegaltousemultipleentrieslikethis:mikewww=/sbin/rebootmikewww=/sbin/dump
Thisquicklygetscumbersome,though.Ifyouhavemultiplesimilarrules,separateindividualpartswithcommas.mike,petewww=/sbin/reboot,/sbin/dump
Theusersmikeandpetecanruntherebootanddumpcommandsonthehostwww.Whileyoucanlistmultiplecommandsandusersinasinglerule,youmustusedifferentrulesfor
differentaccesslevels.theaALL=ALLmike,petewww=/sbin/reboot,/sbin/dump
Thefirstruledeclaresthatsystemownertheacanrunanycommandonanyhost.Shehasgraciouslyallowedminionsmikeandpetetoruntwocommandsonthehostwww.
PermittingCommandsasOtherUsers
Someapplications,usuallydatabasesorcommercialJavaprograms,mustberunbyspecificuserstoworkcorrectly.Sudoletsyouruncommandsasauserotherthanroot,ifthesudoerspolicypermitsit.Listtheusernameinparenthesesbeforethecommand.katebeefy=(oracle)ALL
Theuserkatecanrunanycommandsontheserverbeefy,butonlyastheuseroracle.Shecanfullymanagethedatabase,buthasnospecialprivilegesotherwise.
Userswithaccesstospecificuseraccountscanalsohaveseparateaccesstoroot-levelprivileges.mikebeefy=(oracle)ALLmikebeefy=/sbin/mount,/sbin/umount
mikecanmountandunmountdisks,aswellasmanagetheOracledatabase.
LongRules
Onceyoulistmultiplecommandsbyfullpath,multipleusers,andmultiplemachinesinasinglerule,individualsudoerslinescangetreallylong.Endalinewithabackslashtoindicatethattherulecontinuesonthenextline.kent,mike,petebeefy,www,dns,mail=/sbin/mount,/sbin/umount,\
/sbin/reboot,/sbin/fsck
Whitespaceandadditionallinesmakeruleseasiertomanage.Usethemliberally.
Edges
Hereareacouplelastpointsaboutsudoers.Sudoprocessesrulesinorder,andthelastmatchingrulewins.Iftworulesconflict,thelastmatching
rulewins.We'llseehowthiscomesintoplayaswebuildcomplexsudoersrules.Theexclamationpoint(!)isthenegationoperator.It'susedtoexcludeoneitemfromalist.Youcould
saythataruleappliestoeverythingexceptaspecificuser,host,orcommand.Italsoturnsoffoptions.Rememberthattheexclamationpointmeans"not."Therestofthisbookhasmanyexamples.
Finally,asudoersfilemustalwaysendinablankline.Ifvisudoindicatesanerroronthelastline,butthesyntaxalllookscorrect,verifythatyouhaveablanklineattheendofyourpolicy.
Nowthatyouhaveabasicgraspofsudoandsudoers,let'screateourownsudoersfileandtestitwithsudo.
Chapter3:EditingandTestingSudoersIfsudocannotparse/etc/sudoers,itwillnotrun.Ifyourelyonsudotogetrootprivilegesonyourserverandyoubreaksudo,youlockyourselfoutoftheserver'sprivilegedcommands.Fixingsudoersisaprivilegedcommand.Thisisabadsituation.Don'tputyourselfhere.Sudoersmustcontainvalidsyntax.Sudoincludesatoolspecificallyforeditingsudoers,visudo.
Visudoprotectsyoufromobvioussudoersproblems.Itlocks/etc/sudoerssothatonlyonepersonatatimecaneditit.Itopensacopyofthefileinyourtexteditor.Whenyousavethefile,visudoparsesitandchecksthesudogrammar.Ifyournewsudoersfileissyntacticallyvalid,visudocopiesthenewfileto/etc/sudoers.
Rememberthat"syntacticallyvalid"isnotthesameas"doeswhatyouwant."
Visudodefaultstousingthevieditor.Whileallsysadminsmusthaveapassingfamiliaritywithvi[2]
,thatdoesn'tmeanyouneedtodoeverythingwithit.Visudorespectsthe$EDITORenvironmentvariable,soyoucanuseyourpreferredtexteditor.
Setyourpreferrededitor,andwe'llgoontoeditingsudoers.
Creating/etc/sudoersWhilemostoperatingsystemsincludeasampleordefaultsudoersfilewithlotsofexamples,you'reheretolearn.Learningmeansmakingyoursudoerspolicyfromscratch,justlikeacakebutnotasdelicious.Movethedefaultsudoersfilesomewheresoyoucanuseitasareference.Whenyourunvisudo,itcreatesanewfile.#visudo
Createaverysimplesudoersfile,givingyouraccountfullprivilegestotheserver.HereTheagivesherselfunlimitedaccessviasudo.theaALL=ALL
Savethefileandexit.Withasimplerulelikethis,permittingoneuserfullaccesstothemachine,yourtexteditorshouldexitcleanlyandvisudoshouldinstalltherules.
Now,asalearningexercise,breaksudoers.(UbuntuandAppleusers,youdohavearootpassword,right?)Runvisudoandpoundkeystocreatealineofgarbageonthebottomofthefile.Saveandexit.You'llsee:#visudo>>>/usr/local/etc/sudoers:syntaxerrornearline3<<<Whatnow?
Ifyoupresse,visudoreturnsyoutothetexteditortofixyourproblem.Gotothelinespecifiedandseewhat'sgoingon.Removethegarbage,andvisudowillletyouexitthetexteditorandinstallthepolicy.
Tothrowawayyourchangesandretaintheoldsudoerspolicy,pressx.Anoldworkingsudoersisbetterthanthenewbrokenone.Ididthismorethanoncewhilelearningsudo,sodon'tletitworryyouatthisstage.
IfyoupressQ,youinstallthebrokenfileas/etc/sudoers.Whensudocannotparse/etc/sudoers,itimmediatelyexits.PressingQtellsvisudotobreaksudountilyouloginasrootandfixit.Donotpressthisbutton.Youwon'tlikeit.
Ifyouforgetthesekeys,enteringaquestionmarkpromptsvisudotoprintoutyouroptions.Rememberthatavalidsudoersfileisnotthesameasausefulsudoersfile.Ablanksudoers,denying
allprivilegestoeveryone,isperfectlyvalidandveryquicktoparse.Visudoalsoacceptsasudoersfilewhereeveryrulespecifiesusersandcommandsnotonthesystem,oraserverotherthanthelocalsystem.
Whenyou'recreatingthesudoersfileforyournetwork,Istronglyrecommendthatthelastrulegivesyouraccounttherighttorunvisudo.Ifeverythingelsefails,youcanfixtherules.theaALL=/usr/sbin/visudo
Rememberthatsudoprocessesrulesinorder,andthelastmatchingrulewins.Putyouremergencyrescueruleattheveryendofthefile.
TestingsudoersYou'vewrittenyourfirstsudoerssecuritypolicy.Atthemoment,youcanreaditprettyeasily–itonlyhastwolines:yourfullaccessentryandyouremergencyvisudoentry.Butwhenyourpolicygetsmorecomplicated,howcanyoutellwhatausercanaccess?
Userscanusesudo's–lflagtolisttheirprivileges.$sudo-lPassword:Usertheamayrunthefollowingcommandsonthishost:
(root)ALL(root)/usr/sbin/visudo
$
WhenTheaentersherpassword,sheseeswhatcommandsshecanrun.Thisoutputmightlookalittleodd,butitshouldalsolookalittlefamiliar.It'saprettystandardsudoersentry,withtheuserandhostremoved.Remember,ifyoudon'tspecifyauserinsudoers,sudorunsthecommandasroot.Thismightbealittlemoreobviouswithaslightlymorecomplicatedexample:$sudo-lUsertheamayrunthefollowingcommandsonthishost:
(root)ALL(oracle)ALL(root)/usr/sbin/visudo
Theacanrunallcommandsasroot,allcommandsastheuseroracle,andvisudoasroot.That'sfineforausertochecktheirprivileges,butwhataboutthesystemadministrator?Howcanyou
besurethatyoursudoerspolicyworksthewayyouthinkitshould?Usethe–Uflagalongwith–ltospecifyauser.#sudo-Umike-lUsermikeisnotallowedtorunsudoonwww.
OnlyrootandusersthatcanrunALLcommandsonthecurrenthostcanuse–U.Withmyunprivilegeduseraccount,Icanonlycheckmyownaccess.SudoseesthatTheahasthemagicALLattachedtohersecuritypolicy,soshecanviewmyaccess.Otherwiseshe'dhavetorunsudo–umikesudo-l,whichiskindofdaft.
We'llusesudo–lthroughoutthisbooktoseehowcomplicatedsudoerspoliciesexpandintouser-visiblerules.Irecommendusing-Uafterachangetoverifytheuser'saccessbeforetellinghimthattheaccessherequestedisavailable.
Chapter4:ListsandAliasesWritingasudoerspolicyissimple.Youjustwritedownwhocanrunwhatonwhichmachine.Whatcouldbeeasier?Nowrepeatthatforfivehundredusers.Makesureuserswithacommonfunctionhaveidenticalsecurityrules.AndthoseOracledatabaseadministrators?Youmustincludeeverysinglecommandeachadministratorneedstorunasaseparateuserforeachandeveryoneofthem.
Ifyouhadtowriteallthisoutinsudoers,you'djustspray-painttherootpasswordonthewallofthebreakroominstead.
Tomakethingsmorecomplicated,Unix-likesystemsgetinformationfromawholebunchofsources.Someofthemaren'tevenvaguelyUnixy.IfaserverisattachedtoanActiveDirectoryorNISdomain,youmightneedtousethatinformationinyoursecuritypolicy.Perhapsyouwantarulethat"allusersintheDomainAdminsgroupcanmountCIFSshares."Youneedtoknowhowtodrawthisinformationintoyoursudoerspolicy.
Sudoersoffersaliasestocondenseandsimplifysecuritypolicies.Analiasisapredefinedlistofitemsthatyoucanuseinsudoersrules.Youcanusealiasesanywhereyouuseausername,host,orcommand.Changinganaliasisasimple,effective,andguaranteedconsistentwaytomakechangesincomplexsudoersfiles.
Butbeforewegetintoanyofthat,let'slookatwildcards.
WildcardsAwildcardisaspecialsymbolthatcanmatchdifferenttypesofcharacters.Sudoersletsyouusewildcardstomatchhosts,filesystempaths,andcommand-linearguments.SudoerswildcardslookalotlikeshellorPerlregularexpressions,butaren't.Wildcardsarebuiltontheoperatingsystem'sglobandfnmatchfunctions.Ifyouroperatingsystem'sglobandfnmatchfunctionssupportcharacterclasses,youcanuseclassesinwildcards.Ifyoudon'tknowwhatcharacterclassesare,don'tworryaboutit.
MatchingNumbersandCharacters
SupposeyournetworkhasseveralDomainNameServiceservers,allwithhostnameslikedns1,dns2,dns3,andsoon.Youprobablywouldn'tgiveanon-DNSserveranamestartingwiththosecharacters.YourDNSadministratorneedsfullaccesstotheseservers,soyoucoulduseawildcardinthehostdefinition.freddns?=ALL
Thequestionmark(?)matchesanysinglecharacter.Thissudoersruleappliestoanyhostdns0throughdns9.ItalsomatchesdnsAthroughdnsz.MaybeyouonlyhaveDNSservers1through4,don'tforeseeanyexpansion,anddon'twanttoautomaticallygiveprivilegedaccesstoyourregularDNSadminsonanynewDNSserversthatappear.freddns[1-4]=ALL
Byspecifyingarangeofcharactersinbrackets,yourestrictthematch.Youcanusearangeoflettersinbrackets.
petewww[a-z]=ALL
Petecanrunanycommandontheserverswwwathroughwwwz.Notmanypeopleuselettersthisway,butit'sanoption.Youcanalsousecapitalletters,andtherangeA-zmatchesallcapitalandlowercaseletters.petewww[A-z]=ALL
Ifyouwanttomatchmultiplecharactersofatype,appendanasterisk.freddns[0-9]*=ALL
Ifyoueventuallyhavetheserverdns9183,Fredcanmanageit.Hewillbeverytiredbythen,I'msure,sohopefullyyou'lluseauseraliastogethimsomehelp.
MatchingEverything
Theasteriskcharacter,moregenerally,matchesanynumberofcharactersornoneatall.Itmatcheseverything,withsomedeliberateexceptions.IfTheaneedsPetetomanageaserver'scorefunctions,shecouldgivehimarulelikethis:peteALL=/sbin/*,/usr/sbin/*,/usr/local/sbin/*
Petecanrunanycommandinanyofthecommonsbindirectories.Visudoisprobablyinoneofthosedirectories,soPetecanchangehisownprivileges.Theaneedstolearnthefinepointsofaccesscontrol,ormaybemovevisudotoaprivatedirectory.
Whenusedforcommands,theasteriskdoesnotmatchtheslashcharacterusedtoseparatedirectories.
Ifyouwantausertohaveaccesstoalltheprogramsinasubdirectory,youmustexplicitlyspecifythatsubdirectory.peteALL=/usr/bin/*,/usr/bin/X11/*
Whenusedforcommand-linearguments,however,theasteriskdoesmatchtheslash.Commandsmightincludeslashesinarguments,afterall.Theymightincludewhitespace,anytextstrings,orwhoknows
what.[3]
Thismeanssysadminsneedtotakecareusingwildcardsforcommand-linearguments.It'shardtobeatthetextbookexampleofadangerouswildcardrule:peteALL=/bin/cat/var/log/messages*
Petecanseethecontentsof/var/log/messages,aswellastherotatedlogssuchas/var/log/messages.1.Thatseemsharmlessenough.Butwildcardsmatchanynumberofcharacters,soPetecouldrunacommandlikethis:$sudocat/var/log/messages/etc/shadow
Thissurelyisn'twhatthesystemownermeant.It'sprettyeasytoworkaroundthis.Thequestionmarkmatchesasinglecharacter.
peteALL=/bin/cat/var/log/messages,\/bin/cat/var/log/messages??
OrTheacouldusearangeofnumbers.peteALL=/bin/cat/var/log/messages,\
/bin/cat/var/log/messages.[0-9]
Narrowernumberrangeswork,ofcourse.
MatchingSpecificCharacters
Sometimesyoumustmatchselectcharacters,ratherthanarange.YoumightneedtomatchanyofthecharactersA,c,orq.There'snowaytoexpresstheseasarange,butyoucanmatchspecificcharactersinsquarebrackets.peteALL=/opt/bin/program–[Acq]
Thispatternmatchesasinglecharacterspecifiedwithinthebrackets,allowingyoutosafelypermitauseraccesstospecificcommand-linearguments.
Thecharacters*,?,[,and]havespecificmeaningsinsudoers.Ifyouneedtomatchoneofthesecharacters,putabackslashbeforeit.Hereweallowthearguments[and].carlALL=/opt/bin/program–[\[\]]
Youcannowpermitanycombinationofargumentsyoudesire.
BlockingEverything
Maybeyouspecificallywanttoforbidusinganyargumentsatall.Twodoublequoteswithnospacebetweenthemtellsudoerstoonlymatchtheemptystring.dirkALL=/opt/program""
Dirkcanruntheprogramspecifiedonlyifhedoesn'tgiveanyarguments.
AliasesAnaliasisanamedlistofsimilaritems.Youcanusealiasestorefertotheuserrunningthecommand,thehostssudoisrunon,theuserthecommandisrunas,orthecommandsbeingrun.Asasimpleexample,let'smakeanaliasthatincludesthecommandsforbackingupandrestoringUnix-likesystemsusingtraditionaldump.Cmnd_AliasBACKUP=/sbin/dump,/sbin/restore,/usr/bin/mt
Auserwhocanrunthesecommandscancreateanddeploybackups.Whohasthisthanklessjob?mikeALL=BACKUP
Luckyme.Foroneuser,analiasmightnotseemlikemuchofanadvantage.Ifyouhaveseveralbackupoperators,
however,youcancreateaaliasfortheirusernames.HereIcreatetheTAPEMONKEYSaliasforthepeoplewhomanagebackups.User_AliasTAPEMONKEYS=mike,pete,hank
Whenyoucombinethesealiases,youcanwriteasudoersrulelikethis:TAPEMONKEYSALL=BACKUP
Twoaliasdeclarationsandonerulereplaceamuchlongerrule.Youcouldwritetheexactsamerulewithoutaliases.mike,pete,hankALL=/sbin/dump,/sbin/restore,/usr/bin/mt
Thisislongerandmoredifficulttoread.Whenyouaddcommandsorusers,itgrowslongerstill.Andsuccessfultapemonkeyswillpickupmoreduties,lengtheningthecommandlist.
Usingaliasesmakespersonnelandtaskchangesinstantlypercolatethroughoutsudoers.There'snoriskofdozensofcut-and-pastechangesnumbingyourbrain.
Aliasnamescanonlyincludecapitalletters,numbers,andunderscores.Thenamemustbeginwithacapitalletter.CUSTOMERSisavalidaliasname,but_CUSTOMERSand2CUSTOMERSarenot.Youmustdefinealiasesbeforeusingthem,sopeoplenormallyputallaliasesatthetopofsudoers.
Nowlet'slookatthefourtypesofdatafoundinsudoers,howtoextendthem,andhowtousetheminaliases.
UserListsandAliasesRememberinChapter1whenItoldyouthateverysudoersrulestartedwithausername?Yeah,well…that'snotexactlycorrect.Strictlyspeaking,eachrulestartswithalistofusers.Ausernameisthemostcommontypeofentryonthislist,buttherearemore.Therearemanymore.
Theusernamessudoersrecognizesaren'tnecessarilyusernamesfrom/etc/passwd.MyorganizationmanagesuseraccountsviaLDAP,andsudoersrecognizesLDAPusernamesexactlylikelocalusernames.ButmyparticularLDAPconfigurationrestrictsusernamessotheylooklikelocalones.YoumightneedtopullininformationfromMicrosoftActiveDirectory,or/etc/group,orauseralias,orsomeobtusedirectorysystemonlyusedbythreeNewGuineatribesmenandyourcutting-edgeorganization.
Sudoersrecognizesseventypesofuserlists.
OperatingSystemGroups
Sudoersacceptsgroupsfromtheoperatingsystem.Givethegroupnamewithapercentsign(%)infrontofit.Icouldcreatethe/etc/groupsentrydba,addmydatabaseadministratorstoit,andreferenceitinsudoers.%dbadb1=(oracle)/opt/oracle/bin/*
Everyoneinthedbagroupcanrunallthecommandsinthedirectory/opt/oracle/bin,asoracle,ontheserverdb1.
Someoperatingsystemshaveasystemgroupforuserswhocanbecomeroot(adminonUbuntu)orwhomayusetherootpassword(wheelonBSD-basedsystems).Thedefaultsudoerspolicyhasanexampleofgivingtheseusersunlimitedsystemaccess.%wheelALL=(ALL)ALL
Thepeopleinthisgroupdon'tgetanyadditionalaccessthroughthisrule–membersofwheelcanalreadyusesutobecomeroot.Butthisletspeopleacclimatetousingsudointheirday-to-daywork.
Remember,usetheidcommandtoseewhichgroupsyouraccountisamemberof.
UserID
YoucanuseuserIDnumbersinsudoersbyputtingahashmark(#)beforethem.#10000ALL=/sbin/reboot
AnyaccountwiththeUID10000canrebootanymachineviasudo.Idon'tknowwhyyouwouldwantthisusertorunaroundrebootingeverything,butI'veseenconfigurationsmorebizarrethanthis.
IfyouhavemultipleuseraccountswithidenticaluserIDs,thisruleappliestoallofthoseuseraccounts.
GroupID
Ifyoudon'twanttousegroupnames,usegroupIDnumbersprefacedby%#.OnatraditionalBSDsystem,wheelisgroup0.%#0ALL=ALL
Ifyourusernameserviceisflaky,youmightwanttogothisroute.Irecommendyoufixthenameserviceinstead,butyoumightnotcontrolthat.
AswithuserIDs,ifyouhavemultiplegroupswiththesameGID,thisruleappliestobothequally.
Netgroup
Ifyou'remanagingyoursystemsviaNIS,yournextstepshouldbetostopusingNIS.Butuntilyougettothatpoint,youcanreferencenetgroupsinsudoersrulesbystartingthemwithaplussign(+).+webmastersALL=/opt/apache22/bin/*,/opt/apache22/sbin/*
YourwebmasterteamcanrunanyoftheprogramsinthetwospecifiedApachedirectories.
Non-Unixgroup
IfyourversionofsudohasthenecessarypluginsoradditionalcodetosupportcheckinggroupsagainstinformationsourcesbeyondthenormsofUnix-likesystems,youcanreferencethoseinsudoers.Prefacethemwith%:.%:AdminsALL=ALL
Manynon-Unixdirectoryservicesusespacesornon-ASCIIcharactersingroupnames.Thesecharactersmustbeescapedsomehow.Escapingspecialcharactersisapain,soenclosetheentiregroupname(includingtheleading%:)indoublequotes."%:DomainAdmins"ALL=ALL
Whenindoubtaboutnon-Unixgroups,usedoublequotes.Whenyourunidtoseewhichgroupsyouraccountbelongsto,non-Unixgroupsappearintheoutput
afterthestandardUnixgroups.
Non-UnixGroupID
Soyou'veattachedyoursystemtoanon-Unixdirectoryandyouwanttousethenumberofthoseforeigngroupsratherthanthenames?Noproblem.Put%:#beforethegroupnumber.Yes,that'sapercentsign,acolon,andahashmark.%:#87119301ALL=ALL
Ifyoufindyourselfneedingtodothis,however,Isuggestthatyoustepbackandreconsiderhowyou'reusingyourdirectoryservice.
UserAliases
Yourlistofusernamescanincludeauseralias,sowe'dbetterdiscussthose.Auseraliasisalistofsystemusers.AlluseraliasdefinitionsstartwiththestringUser_Alias.User_AliasSYSADMINS=theaUser_AliasMINIONS=mike,pete,hank,dirk
Here,theuseraliasSYSADMINScontainsoneuser,thea.Intheeventthattheorganizationgetsanotherfullsystemsadministrator,addingtheirusernametothealiaswillgivethenewpersonthesamerightsasThea.
TheuseraliasMINIONScontainsfourusers.WhenTheausesthisaliasinasudoersrule,itaffectsallfourminionsidentically.Otherrulesmightalteranindividualminion'saccess,ofcourse.
Youcanuseanytypeofusernamesinauseralias.User_AliasWHINERS="%:DomainUsers",%operator,MINIONS
Remember,aliasnamescanonlyhavecapitalletters,numbers,andunderscores.Thealiasnamemuststartwithacapitalletter.
HostListsandAliasesThehostsentriesinsudoersacceptsvaluesotherthanpurehostnames.Butlet'stalkaboutthosepurehostnamesfirst.
Sudodeterminesthenameofthelocalhostbyrunninghostname.ItdoesnotrelyonDNS,/etc/hosts,LDAP,oranyothernamedirectory.Thetraditionalhostnamelocalhostdoesn'tworkinaruleunlessthat'swhathostnamereturns.(Youcanchangethisbehaviorwiththefqdnoption,whichwe'llexamineinChapter10.)Thismeansthatyourhostnamesinsudoersmustmatchthehostnamesetonthelocalmachine.Changethehostnameandsudobreaks.Ifhostnamereturnsafullyqualifieddomainname(e.g.,www.michaelwlucas.cominsteadofwww),thensudoersonlyneedsthemachinename,notthefulldomainname.
Inadditiontousingthelocalhostname,sudoerscanacceptavarietyofIPaddressesandnetgroups.
IPAddresses
SudocandifferentiatebetweenhostnamesandIPaddresses,soyoudon'tneedtoputanyspecialmarkersinfrontofanIPaddress.mike192.0.2.1=ALL
Sudochecksallofthemachine'srealnetworkinterfacesforIPaddresses.Italsochecksinterfacesattachedtorealinterfaces,suchasVLANinterfacesandbridges.Itignoreslogicalinterfacessuchastheloopback.
Youcanalsousenetworksinsudoers,specifyingnetmaskseitherindotted-quad(192.0.2.0/255.255.255.128)orClasslessInter-DomainRouting(CIDR)format(192.0.2.0/24).Ifanyinterfaceonthemachineisinthatnetwork,thesudoersruleapplies.pete192.0.2.0/24=ALLmike198.51.100.0/255.255.255.0=/etc/rc.d/named*
Formachineswithmultipleinterfacesondifferentnetworks,rememberthatsudousesthelastmatchingrule.Iftherulesfortwonetworksconflict,thelastrulewins.
Netgroups
YP/NISsitescanrefertonetgroupsinsudoersbyputtinga+infrontofthename.carl+db=ALL
Formostofus,however,thewaytorefertogroupsofhostswillbewithhostaliases.
HostAliases
Ahostaliasisanamedlistofhosts.IndicateahostaliaswiththestringHost_Alias.Ahostaliascanincludeanyvariationofhostnamerecognizedbysudo.Host_AliasWWW=www[1-3]
Youcanincludeonehostaliasinanother.Host_AliasDMZ=192.0.2.0/24,198.51.100.0/255.255.255.0,WWW
Likeuseraliases,hostaliasnamesmustcontainonlycapitalletters,numbers,andunderscores,and
muststartwithacapitalletter.Youcanthenusethisaliasinasudoersrule.mikeDMZ=all
NowIhavefullprivilegesonthehostsintheDMZgroup.
RunAsListsandAliasesYoucangrantauserpermissiontorunacommandasanotheruserbyputtingthetargetusernameinparenthesesbeforethecommand.Wesawhowtodothisearlier:chrisbeefy=(oracle)ALL
Chriscanrunanycommandsonthehostbeefyastheuseroracle.ThesearecalledRunAsprivileges.
RunAsLists
Likeusernames,RunAsusersarelists.Supposeyouhavemultipledatabaseplatforms–Oracle,MySQL,andPostgres.Yourdatabaseteamneedsaccesstoruncommandsonanyhostasthedatabaseuser.Anytypeofusernamethat'svalidinalistofusersisvalidinaRunAsstatement.carlALL=(oracle,postgres,mysql)ALL
DatabaseadministratorCarlcanrunanycommandonanyserver,solongasherunsitasoneofthedatabaseuserprograms.
Ifyouhavenon-Unix-styleuserswhocanruncommands,youcanwritesudoersrulesthatincludethem.peteALL=("%:DomainUsers",%operator,lpd)ALL
Youcanalsoletauserrunacommandasamemberofagroup,ratherthanasaspecificuser.StandardUnixconventionistospecifyfileownershipwithausername,acolon,andagroupname.Towritearulethatpermitsrunningacommandasagroupmember,skiptheusername.Youmighthavelogfilesthatareonlyvisibletomembersofthegroupstaff.%helpdeskALL=(:staff)cat/var/log/secure
Helpdeskstaffcanrunthiscommandasiftheywereinthegroupstaff.
RunAsAliases
You'reprobablygettingthehangofthisbynow,buttobecompletelet'stalkaboutRunAsAliases.ARunAsaliasletsyougroupusersneededtoruncommands.ThenameofaRunAsaliascanonlyincludecapitalletters,numbers,andunderscores,andmustbeginwithacapitalletter.Runas_AliasDB_USERS=oracle,postgres,mysql
YoucanusethestringDB_USERSanywhereyou'dwanttousealistofusernames.carlDB=(DB_USERS)ALL
Wenowhaveasingle,readablerulethatletsCarlrunanythingasadatabaseuser,onanyserverintheDBalias.IfCarlgetsanyhelpindatabaseadministration,thesystemownercanreplaceCarl'snamewith,say,aDB_ADMINSalias.
CommandListsandAliasesInsomeways,listsofcommandsarethesimplestlists.Acommandcaneitherbeapathwithawildcard(/sbin/*)orafullcommandname(/sbin/dump).Youcanputthesecommandsinlists,aswe'vealreadyseen.mikeALL=/sbin/dump,/sbin/restore,/usr/bin/mt
There'snowaytopullinnon-Unixcommands.What'sonthefilesystemiswhatyouhavetoworkwith.
CommandAliases
Commandaliasesarelistsofcommandsassignedaname,labeledwithCmnd_Alias.Therulesforcommandaliasnamesareexactlythesameasotheraliases.Commandaliasescanincludeothercommandaliases.Cmnd_AliasHELPDESK=/usr/bin/passwd,BACKUP
Youcanuseacommandaliasanywhereyou'duseacommand.
CommandTags
Youcanusetagsbeforeacommandlistorcommandalias.Atagisaflagthatchangeshowthecommandruns.I'llshowexactlywhatthetentagsdoinmoreappropriatesectionsofthebook,butyoushouldrecognizeatagwhenyouseeit.Atagappearsbeforethecommandlist,separatedfromthecommandsbyacolon.mikeALL=NOEXEC:ALL
Tagnamesareallcapitals,withoutanynumbersorsymbols.Atagaffectsallthecommandsinthelistfollowingthetag.We'llusetheNOEXECtaginChapter6,sodon'tworryaboutwhatitmeansrightnow.
ExcessRulesSomerulesaremoregenerousthantheyneedtobe.Let'sreconsiderCarl'sdatabaseaccess.carlALL=(oracle,postgres,mysql)ALL
Carlcanruncommandsasthethreedatabaseusersonallcomputersintheorganization.Hedoesn'tneedthisaccessonallthemachines,however.Mostmachineshaveonlyonedatabaseserverorclientinstalledonthem.YouseeveryfewsystemsrunningbothMySQLandPostgres.
Inmanyenvironments,thisextraaccessprobablydoesn'tmatter.IfCarltriestorunacommandasoracleonasystemrunningPostgreSQL,thecommandwillfail.
$sudo-uoraclesqlplussudo:unknownuser:oraclesudo:unabletoinitializepolicyplugin
Iftheuserexists,thankstothewondersofLDAP,butthere'snosoftware,thecommandwillfail.Ifthesoftwareexists,butisn'tconfigured,thecommandwillfail.Ifthesoftwareisconfiguredandthecommandfails,thedatabaseprobablyisn'trunning.AndifCarltriestoconfigureOracleonthePostgreSQLserver,seniorsysadminTheaneedstohavesharpwordswithhim.Probablyinvolvingatireiron.
Whenyouwritecomplicatedpolicies,youwillneedtodecidehowmuchworkyou'rewillingtodotoeliminatethisexcessaccess.IsCarl'sabilitytoconfigurePostgreSQLontheOracleserverarisk?Ifitis,eliminateit.
NegationinListsRememberthe!characterIbroughtupbackinChapter2?Wecanusethenegationcharactertoexcludeitemsfromalist.User_AliasNOTSCUM=%wheel,!mikeNOTSCUMALL=ALL
Themembersofgroupwheel,withoneexception,getfullaccesstothesystem.TheasaysthatwhenI
tellherwhatIdidwithhercomfychair,Imightgetmyaccessback.[4]
Negationisverypowerfulforhost,user,andRunAsaliases.Itisnotonlynotusefulforcommandaliases,itisactivelyharmful.Listsofcommandsincludeeitherthefullpathtospecificcommands,oradirectorywithawildcard.
You'dthinknegationwouldbeeffectiveforcommandlists.Butuserscancopyfiles.Theycancreatelinkstofiles.Theycanfindawaytoaccessafilethroughavarietyofpaths.Toseewhythisisaproblem,here'sanaliasforthecommandsusefultobecomeroot.Cmnd_AliasBECOME_ROOT=/bin/sh,/bin/bash,/bin/tcsh,/usr/bin/su
Here'sasudoersrulethatexcludesthosecommands.%wheelALL=ALL,!BECOME_ROOT
Thisseemstowork.IfItrytorunaforbiddencommand,sudotellsmeI'mnotallowedandlogstheerror.Beinganannoyinglycleveruser,though,Itrythefollowing:$cp/bin/sh/tmp/mycommand$sudo/tmp/mycommand#iduid=0(root)gid=0(wheel)groups=0(wheel),5(operator)
Oops.Thesysadminexcluded/bin/sh,butnotthecopyof/bin/shinstalledas/tmp/mycommand.AndcertainlynotthecopyofzshthatIcompiledmyselfandinstalledinmyhomedirectory.
Youcannotuseexclusionstoremovecommandsfromalist.Thereisnowaytoexcludecommandssecurelyorsafely.Thesudoauthorshavedocumentedthisextensively,havebeggedpeoplenottodoit,andstillsysadminsallovertheworldinsistondoingthis.Nothingscreams"Idon'treadtheinstructions!"likeusingexclusionsinsudoercommandlists.Excludeusers.Excludemachines.EvenexcludeRunAsaliases.Butdon'texcludecommands.
AliasesinSudoAuserwhocheckshisprivilegeswithsudo–lwillseetheexpandedaliases,notthealiasenamesortheirdefinitions.$sudo-lPassword:Usermikemayrunthefollowingcommandsonthishost:
(root)ALL,!/bin/sh,/bin/bash,/bin/tcsh,/usr/bin/su
Idon'tseetheBECOME_ROOTalias,soIdon'tknowhowTheawrotethispolicy.Idoseehowtogetrootonthismachine,withoutTheabeinganywiser.Becauseasysadminwhodoesn'tconfiguresudocorrectlycertainlyisn'treviewingthelogseither(seeChapter12).
Aliasesareasimplewaytorationalizeandsimplifyyoursudoerpolicy.Nowlet'sseehowtochangethecoreofhowsudobehavesthroughoptionsanddefaults.
Chapter5:OptionsandDefaultsSudo'sstandardbehaviorsaccommodatethemostcommonusecases.Theinterestingthingaboutthemostcommonusecase,however,ishowuncommonitis.Youcanchangemostofsudo'scorebehaviorbysettingvariousoptionsinsudoers.Theseoptionscanbesetasglobaldefaultsorattachedtospecificrules,hosts,users,orcommands.
SetdefaultswithDefaultsstatements.AsudoerspolicycanhavemultipleDefaultsstatements.IfmultipleDefaultsstatementsconflict,thelastmatchingoneapplies.We'llseelotsofsampleDefaultsstatementsthroughoutthischapter.
Mostoptionsthataffectspecificsudofunctionshavetheirownchapter,andarediscussedinthatchapter.Thatis,wecoverenvironment-affectingoptionsinChapter8andloggingoptionsinChapter12.Thischaptercovershowtouseoptionsingeneral,bothforspecificgroupsandasdefaults.We'llstartbyusingoptionsinDefaultsstatements.
OptionTypesOptionscanbeeitherboolean,integers,integersorlistsusableinbooleancontext,orstrings.
BooleanOptions
Someoptionsaffectsudowiththeirmerepresence.They'retoggleswitches,turningbehaviorsonandoff.Somebooleanoptionsareonbydefault,evenwhentheydon'tappearinsudoers.Deactivatethembyputtinganexclamationpointbeforethem.
Formanyyears,whenausertypedthewrongpassword,sudorespondedbyinsultingthem.Thesudodeveloperschangedthisawhileback,apparentlyinanefforttomakesudoseemmoreprofessionalorenterprise-friendly.Insultingusersisasysadmin'sprerogative,however,andautomatinginsultsdemonstratessysadmincompetence.Puttheinsultsoptioninsudoerstomakesudoinsultuserswhocan'ttypetheirpassword.Defaultsinsults
Whentheusertypesthewrongpassword,he'llreceivemotivationalcommentaryinadditiontoapasswordprompt.$sudo-lPassword:Sorryaboutthis,Iknowit'sabitsilly.Password:stty:unknownmode:doofusPassword:Harmcancometoayoungladlikethat!sudo:3incorrectpasswordattempts
Ifyoursudoinstallationinsultsusersbydefault,youcandisabletheinsultsbydisablingtheoption.Defaults!insults
Usersnowgettheboring"Sorry,tryagain"message.Someoperatingsystempackagersdeliberatelyremovethisoptionfromtheirversionofsudo.Ifyours
doesthis,Irecommendcomplainingbitterlyuntiltheyseetheerroroftheirways.
IntegerOptions
Someoptionstakeanumberasanargument.Useanequalsigntoseparatetheargumentfromtheoptionname.Theseoptionssetalimitforthissudooption.
Commonwisdomonpasswordsisthattheyshouldincludemixed-caseletters,numbers,andassortedsymbols.Oh,andtheyshouldbelong.Thiscombinestomakethemhardtotype,especiallywhenthepasswordisn'tvisibleasyoutypeit.Yourusersmightneedmorethanthreetriestotypetheirpasswordcorrectly.Here,Thealetsuserstrytotypetheirpasswordfivetimesbeforekickingthemoutofsudoandlogginganerror.Defaultsinsults,passwd_tries=5
HerewecombinetwooptionsinoneDefaultsstatement,separatedbyacomma.Youcanuseasmany
optionsonalineasyouwant,butIrecommendgroupingthembyfunction.
IntegersusableinBooleanContext
Ifanintegeroptionsetsalimitonsudo'sbehavior,theseoptionsletyoudisableafeaturebysettingthelimittozero.Doyourememberthatsudocachesthefactthatyouhaveauthenticatedforfiveminutes?Youcanchangethenumberofminutesitremembers.Defaultsinsults,timestamp_timeout=10
Thelongersudocachestheauthentication,however,thegreatertheriskthattheuserwillwalkawayfromaprivilegedterminalsession.Manyusersdon'tlocktheirworkstationswhentheyleavetheirdesk.Usingalongertimeoutincreasestheoddsofasecurityproblem.
Thewayaroundthis,ofcourse,istocompletelydisabletheauthenticationtimeout.Requiretheusertoenterapasswordeverytimetheyrunsudo.Bysettingthetimeouttozero,youentirelydisableauthenticationcaching.Defaultsinsults,timestamp_timeout=0
Dependingonyourenvironment,andwhatcommandspeopleuseforsudo,disablingtheauthenticationtimermightbetooharsh.Butthismakessenseifyou'reusingstrongauthenticationmethods,aswe'llseeinChapter13.
StringOptions
Someoptionsneedargumentsliketextorapathtoafile.Whenausermistypeshispassword,there'samiddlegroundbetweeninsultingtheuserandofferinga
bland"Sorry,tryagain."Youcanuseacustommessagebysettingthebadpass_messageoption.Defaultsbadpass_message="Wrongpassword.Ihavenotedyourincompetence.Tryagain!"
Whentheusermistypeshispassword,sudodisplaysthecustommessage.Iputthemessageinquotesbecauseithasspecialcharacters,likespacesandtheexclamationpoint.Optionsthattakeafilepathasanargumentdon'tneedthequotes.
SettingOptionsforSpecificUsesOptionsaren'tjustglobaldefaults.Youcansetoptionsonanindividualbasis,sothattheyonlyaffectcertainusers,commands,orspecificmachines.
Per-UserDefaults
Certainusersshouldgetdifferentdefaultsettingsthanothers.Perhapsyouneedtosetdifferentauthenticationtimeoutsforsomeusers,oradifferentpasswordprompt,orsomewhinercomplainedthatthesysteminsultedhim.Youcanchangethedefaultsforspecificusers.UsethekeywordDefaults,acolon,theuseroralistofusers,andtheoption.
Thefirsttimeyourunsudoonanymachine,itprintsashortlectureremindingyoutobecareful.Mostusersneedthereminder.Butsystemadministratorsarecontinuouslymindfuloftheirresponsibilitiesand
arepainfullyawareofthedamagetheycandowithamisplacedkeystroke.[5]
Theydon'tneedreminding,andonceyou'veseenthelecturehundredsoftimes,itonlyannoysyou.HereTheadisablesthelectureoptionforherself.Defaults:thea!lecture
Shecouldalsodisablethelectureforeveryoneallowedtousetherootpassword.Defaults:%wheel!lecture
Thepeoplewhohaverootprivilegeswillnowbeveryslightlylessannoyed.Whichcanonlybegood.
Per-HostDefaults
Tooverridesudoersdefaultsonaper-hostbasis,useDefaults,anatsymbol(@),thelistofhostsorhostalias,thentheoption.Anythingthatcanbeinahostsaliascanappearhere.DefaultslectureDefaults@TESTHOSTS!lectureDefaults@PRODUCTIONlecture=always
Herewehavetwohostaliases.Inthetestenvironment,usersarenotlectured.Inproduction,however,everytimesudoasksfortheirpassworditalsolecturesthem.Irecommendreservingthislastfeaturefortrulytroublesomeusers.
Per-CommandDefaults
Tosetper-commandorcommandaliasdefaults,useDefaultsandanexclamationpoint.Perhapssomeuserscanbetrusted,mostofthetime.Butmaybeaspecificuserhasdifficultywitha
certaincommand.Ormaybeacertainproblemhashappenedoncetoooften.Defaults!lectureDefaults!/sbin/fdisklecture=always,\
lecture_file=/etc/disklabel-lecture
Thelecture_fileoptionletsthesysadminwriteacustomlecturemessage.Inthiscase,/etc/disklabel-lecturecontainsatextmessagetoreplacethestandardlecture.
Ifyourelabelavitaldiskagain,Theawillleavethetattersofyourstill-livingbodyinthebreakroomasawarningtoothers.
Thelectureappearsonlyiftheusermustentertheirpassword,butthat'sbetterthannothing.Tomakethelectureappeareverytimeheusesthiscommand,requiretheusertoenterapasswordeverytime.Defaults!/sbin/fdisklecture=always,\
lecture_file=/etc/disklabel-lecture,\timestamp_timeout=0
Bysettingtimestamp_timeouttozeroforthisspecificcommand,Thearemovesthetimeoutonauthentication.Wheneverauserrunsfdisk,sudodisplaysthethreat–er,lecture–anddemandsapassword.
Tagscanbedefaults.Defaults!ALLnoexec
ThisdefaultsetstheNOEXECtagsetonallcommands.
PerRunAsDefaults
Lastly,tosetadefaultforaRunAsrule,usearightanglebracketbetweenDefaultsandtheuserlist.Defaults>operatorlecture
Anyonewhorunscommandsasoperator(normally,thebackupteam)getslectured.
ConflictingDefaults
Considerthefollowingsudoerspolicy.Defaults:mikeinsultsDefaults!/usr/bin/su!insultsmikeALL=/usr/bin/su
ThefirstlinesaystoinsultmewheneverIrunsudo.Thesecondlinesaysthatwheneversomeonerunssuviasudo,don'tinsultthem.Thethirdlinegivesmetherighttorunsu.Thedefaultsconflict.Whathappens?$sudosuPassword:Sorry,tryagain.
Sudodoesnotinsultme.Remember,sudoerspoliciesworkonalastmatchbasis.ThelastmatchingDefaultstatementsays
"don'tinsultsuusers."Toinsultme,reversetheorderofthetwoDefaultsstatements.Nowthatyouknowhowtouseoptions,we'llseetheminplaythroughtherestofthisbook.
Chapter6:ShellEscapes,Editors,andSudoersPoliciesUnix-likeoperatingsystemsandtheirsoftwaregrownewfeatureslikemossgrowsontheOregonCoast.They'reeverywhere.Manyolderbutpopularprograms,suchasthepagersmoreandlessandtheeditorvi,letusersrunshellcommandsfromwithinthem.Tryityourself–viewafilewithmore.Whileyou'restilllookingatthefile,enteranexclamationpointandthenashellcommandsuchaslsorifconfig.Thecommandwillrun.You'llseetheoutput,thenmorereturnstothetextitoriginallydisplayed.
SystemsadministratorswhoworkedondumbterminalsoroverSLIPconnectionsdesperatelyneededtheabilitytoescapetoashell.Youdidn'twanttoleaveafilejusttoverifyiftheIPaddressonyourmachinematchedsomethinginthefile.NowthatwecanhaveumpteenSSHsessionsopentoasinglemachine,shellescapesaren'tusedsomuch.
Unlessyouusesudo.Thenshellescapesbecomereallyawesome,inabadway.Considerthefollowingsudoerspolicy:mikeALL=/usr/bin/more
Icanusemoretoviewfilesonanysystem.That'scool.Icanlookat,say,/var/log/auth.logtoseewhyauser'sSSHconnectionsfail.ButI'mrunningmoreasroot.ThatmeansanycommandsthatIcangetmoretorun,willrunwithrootprivileges.Irunsudomoreonafile,thenenter:!visudo
I'minvisudo,thesudoerseditor!Icaneditthepolicytoaddarulepermittingmetorunallcommandsonallmachines,save,andexit.ThenIquitmoreandcheckmyprivileges.$sudo-lUsermikemayrunthefollowingcommandsonthishost:
(root)/usr/bin/more(root)ALL
Iftheseniorsysadmindiscoversthis,she'llhavemyheadonaplatter.Again.Ifauserhasaccesstoalimitedsubsetofprivilegedcommands,youmustensurethathecannot
bootstraphimselfintogreateraccess.Dothiseitherthroughrestrictingthecommands,orbyprohibitingcommandsfromrunningothercommands.
CommandRestrictionsOnewaytoeliminateshellescapesistoverifythatnopermittedprogramincludesshellescapes.Thisishard–manyprogramshaveshellescapes,notjustpagersandtexteditors.Youcouldeliminatethepagerissuebyonlyallowingtheusersprivilegedaccesstocat(1),requiringthemtodumptheoutputtoapager.$sudocatauth.log|less
Thiseliminatesonlyshellescapesfrompagers,however.Tofollowthismethod,youmustcarefullycheckthedocumentationofeverypermittedcommandforshellescapes.Andnotalldocumentationiscomplete.
ForbiddingCommandsfromExecutingCommandsShellescapesaren'ttheonlywaytobreakoutofaprogram.Manyprogramsrunotherprograms.We'vealreadylookedatvisudo,whichrunsatexteditorforyou.OnmodernUnix-likeoperatingsystems,sudocanstopprogramsfromexecutingotherprograms.SudousestheLD_LIBRARY_PRELOADenvironmentvariabletodisableprogramexecution.EverymodernBSD,Linux,andUnix-likeoperatingsystemsupportsthisvariable,butcheckyoursystem'sdocumentationifyou'reuncertain.
TheEXECandNOEXECtagscontrolwhetheracommandmayexecutefurthercommands.EXEC,theunwrittendefault,permitsexecutionofcommandsbyothercommands.NOEXECforbidsexecution.Putthetagbeforethecommandinyoursudoersrule.mikeALL=NOEXEC:ALL
Whatdoesthisdo?Usesudomoretoexamineafile,andtryashellescapeintovisudo.Insteadofgettingintothevisudoeditor,morejustprintsamessagelike"done"or"execfailed."Whyisitdone?Ittriedtorunthecommandandfailed.
TheNOEXECtagevendisablesrunningvisudoviasudo.$sudovisudovisudo:unabletorun/usr/bin/vi:Permissiondeniedvisudo:/usr/local/etc/sudoers.tmpunchanged
Thevisudocommandtriestorunatexteditor.Visudocannotrunadditionalcommands,soitfails.AglobalNOEXECtagiskindofharsh,though.Somecommandslegitimatelyspawnotherprocessesto
dotasksforthem.Forexample,thenewaliasescommandlegitimatelyrunssendmail.Irecommendusingaglobalblock,andthenwhitelistingspecificcommands.mikeALL=NOEXEC:ALL,EXEC:/usr/bin/newaliases
Thenewaliasescommandispermittedtospawnnewprocesses.Averysavvyintrudercouldperhapsgetnewaliasestospawnaprivilegedshell,butthatattackconsiderablyraisestheskillneededtopenetrateyoursystem.
Awhitelistofpermittedcommandsisaperfectapplicationforacommandalias.Defaults!ALLnoexecCmnd_AliasMAYEXEC=/usr/bin/newaliases,/usr/local/sbin/visudomikeALL=ALL,EXEC:MAYEXEC
Ausercouldrunsudo/bin/sh,butthatnewshellwon'tbeabletoexecuteanycommandsotherthanthose
builtintotheshell.[6]
Theusercouldstilldamagethesystem,butdoingsodemandsgreaterexpertise.Manythird-partysudotutorialssuggestspecificallyforbiddingspecificprogramsfromexecutingotherprograms,muchastheysuggestexcludingcommandsfromapermittedlist.Bothsolutionshavethesameproblem.Theonlywaytohavetruesecuritythroughsudoistoexplicitlyenumeratethecommandsusersmayuse.
EditingFilesManyeditorsoffershellescapes.Butyouneedaccesstoaneditortochangecertaincriticalfiles.Youmighttryasudoerspolicylikethis.mikeALL=NOEXEC:/usr/bin/vi/etc/ssh/sshd.conf
Wouldthisgivetheabilitytochangethefile,withoutshellescapes?Yes.Butithasmoregeneralproblems.Firstoff,Iamnotusingold-fashionedviforday-to-daywork.IprefereitherEmacsored(ifImustuseaprimitiveeditor,IwantonethatdemonstratesthatI'manalphageek).AndImighthavealegitimateneedforanunprivilegedshellescapewhileeditingthefile.
That'swheresudoeditcomesin.Sudoeditletsausereditaprivilegedfilewithoutrunninganeditorasroot.Whenyourunsudoeditonafile,sudocopiesthetargetfiletoatemporaryfile,setsthepermissionsonthetemporaryfilesoyoucaneditit,andrunsyoureditoronit.Youeditthefilewithanormal,unprivilegedtexteditor.Whenyouexittheeditor,sudoeditinspectsthetemporaryfile.Ifthefilehaschanged,itcopiesthetemporaryfiletothetargetfile.
ConfiguringSudoedit
Toconfigureeditingpermissions,usethesudoeditkeywordandthefullpathtothetargetfile.%wheelALL=sudoedit/etc/ssh/sshd_config
UsersinthewheelgroupcanedittheSSHserverconfigurationfilethroughsudo.
Usingsudoedit
Toeditafile,usethesudoeditcommandandthefilename.$cd/etc/ssh$sudoeditsshd_config
Atexteditoropens.Theusercanmakechanges,save,andexit.Sudoeditputstheireditedfileinplaceoftheoriginal.
Whateditordoestheuserget?Thatdependsontheuser'senvironment.Iftheeditorhasa$SUDO_EDITORenvironmentvariable,that'sused.Otherwise,sudoeditlooksfor$VISUALor$EDITORvariables.Ifthosedon'texist,sudoeditlooksforaneditoroptioninsudoers.Sudoeditusesviasalastresort.Iencourageyoutosetaneditorinsudoers,asviiskindofboring.Defaultseditor=/bin/ed
Givethefullpathtothedefaulteditor.Ifausercan'tuseyoureditorandcan'tsethisown,heshouldn'tbeeditingthesudoerspolicy.
WritingSudoersPoliciesYounowhaveallthepiecesthatmakeupasudopolicy.Everythingelsebuildsonwhatyou'vealreadylearned.Let'sdiscusshowtousingthesetoolstobuildasudoerspolicy.
InChapter4IdemonstratedhowexcludingcommandsfromALLletspeoplerunarbitrarycommandsasroot.Inthischapter,I'vedemonstratedhowshellescapesgivepeoplerootaccess.Whilesudologsallcommandsbydefault,itdoesn'tautomaticallylogeverythingthathappens.Programslikesudoreplaygivemoredetailedlogsbutneedspecialconfiguration(Chapter12.)Thenaturalquestionis:whatgoodarethesudotoolsifausercanavoidrestrictionssoeasily?
Ifyouruserscanrunarbitrarycommandsasroot,it'snotthefaultofthetool.Theproblemisthatyou'vewrittenyoursudoerspolicybadly.Don'tbetooembarrassed–mostpeoplewritepoorsudoerspolicies.Manyoperatingsystemsshipwithasudoerspolicythatpermitsallusersinanadministrativegroupunlimitedaccess.Thispolicymeansthatyouradministratorscandoanythingwithoutevenbeinglogged.Amaliciousintruderoradministratorcanhideanawfullotofdamagebehindashellescape.
So,whattodo?Theonlywaytowriteasecuresudoerspolicyistodenycommandsbydefault.UseoftheALL
keywordinacommandgivespeopletoomanyeasywaystogainunlimitedprivilegedaccess.Userswillworkfuriouslytogetaroundrestrictionsthattheybelieveareintheirway.Don'tleavethemaholetosquirmthrough.
Consideryoursudoerspolicylikeafirewall.Backinthe10baseTera,peopleranfirewallsthatpermittedallaccessandthenblockedtraffictovulnerableservices.Ontoday'sInternet,that'sasignofincompetence.Treatyoursudoerspoliciesthesameway.Defaultpermitsudoersrulesmakemeproclaim"The90scalled,they'dliketheirsecuritypolicyback."
ThemerepresenceofthewordALLinthecommandportionofasudoersrulemeansthattheusercangetunrestrictedrootaccessregardlessofanyrestrictionsyoumightthinkyou'replacingonhim.Youcannotrealisticallyenumeratebadnessinasudoerspolicyanymorethaninafirewall;theonlysafepracticeistopermitknownnecessaryactivity.
YoucansafelyuseALLforusers,RunAs,andserverlists.Unprivilegeduserscan'tchangetheirusernameoraserver'shostname,buttheycanchangethefullpathtocommandswithouttrouble.
Fromthispointon,IneveruseALLinthecommanddescriptionexceptforspecificexamplesofpoorpractice.Todootherwiseistoinviteabuseandintrusion.It'sonethingtonotbeembarrassedbyerrorswhenyou'restartingout,butnowyouknowbetter.
Chapter7:ConfiguringsudoWaitjustacotton-pickin'minute…isn'tthiswholebookaboutconfiguringsudo?Whathavewebeenreadingabout,anyway?
We'vebeenconfiguringsudosecuritypoliciesinsudoers.Theconfigurationofthesudoprogramitselfdependsonhowsudowasbuilt,andhowthesystemsadministratorchangedthesudoclientconfigurationviasudo.conf.
Sudo'sDefaultConfigurationThesudosoftwaresuiteasdownloadedfromthemasterwebsiteshipswithadefaultconfiguration,butyouroperatingsystempackagerhasprobablychangedsomeofthosesettings.Youcanidentifytheactualdefaultsofyourlocalinstallbyrunningsudo–V.$sudo–VSudoversion1.8.7Sudoerspolicypluginversion1.8.7Sudoersfilegrammarversion43SudoersI/Opluginversion1.8.7
Hereanormaluserhasaskedsudoforitsconfiguration,andgetssudo'sversionnumberandafewbasicfactsabouttheconfiguration.
Toreallyseewhat'sinsideyoursudoinstall,usethe–Vflagasroot.#sudo-VSudoversion1.8.7Configureoptions:--sysconfdir=/usr/local/etc--with-ignore-dot--with-tty-tickets--with-env-editor--with-logincap…Sudoerspolicypluginversion1.8.7Sudoersfilegrammarversion43Sudoerspath:/etc/sudoersnsswitchpath:/etc/nsswitch.confAuthenticationmethods:'pam'Syslogfacilityifsyslogisbeingusedforlogging:local2Syslogprioritytousewhenuserauthenticatessuccessfully:notice…
Thisgoesonforoverahundredlines.You'llseehowthissudobinarywasconfiguredtocompile,whereitlooksforitsfiles,howitauthenticates,whichenvironmentvariablesitautomaticallypurgesandwhichitallowstopassunscathed,andmore.Takealookatthisoutputonyourownsudoinstallation.
Youcanchangesomeofthesesettingswithentriesinsudo.conf.
sudo.confYoucanconfigurethesudoprogramitselfin/etc/sudo.conf.Sudousuallyrunsjustfinewithoutanyconfigurationfile,butifyouneedtodebugaproblemorchangebasicbehavioryouneedtounderstandsudo.conf.Thefilehasfourvalidconfigurationtypes:Plugin,Path,Set,andDebug.Chapter12includesinformationondebuggingsudo,solooktherefordetailsontheDebugflag.ForeachoftheothersI'llgiveonesimpleexampleofhowsudousesthattypeofconfiguration,butI'llrefertothesetypesofsettingsinlaterchapters.
Plugins
Asudopluginchangeshowsudobehavesatafundamentallevelbyreplacingeitherthepolicyengineortheinput/outputsystem.Youcanuseaplugintoreplace/etc/sudoerswithyourownsecuritypolicylanguage–actually,sudolearnsthatsudoersexistsbecauseofthesudoersplugin.Ifyouwanttobuildaspecialloggingsystem,useanI/Oplugin.Pluginsareanewfeatureasofsudo1.8,sotheonlyfreepluginsthatexistasIwritethisarethedefaults.CommercialfirmssuchasQuestOne(http://www.quest.com)havealreadywrittensudoersandloggingplugins,andothersaresuretofollow.
Touseaplugin,givethePluginkeyword,thenameoftheplugin,andthenameofthesharedlibrary.HereIexplicitlyconfigurethesudoerssecuritypolicyandthesudoinput/outputloggingmodule(Chapter12).Pluginsudoers_policysudoers.soPluginsudoers_iosudoers.so
Sudo'ssharedlibrariesinstallin/usr/local/libexec/sudobydefault,butyoucanputanexplicitpathinsudo.conf.Ifyoubuildsudowithanon-standardlocation,thebuildprocesssetstheappropriatedefaultdirectory.Ifyouhaveacustom-builtsudopluginorsomethingfromavendor,however,youmighthavetogivethefullpath.Pluginsudoers_policy/opt/custom/moderninsults.so
Youshouldonlyneedtoexplicitlydefinethefullpathifyou'rewritingsudocodeandwanttopointatyourspeciallybuiltlibrary.
Youcanonlyhaveonesudopolicyengineatatime.IfyouusetheQuestpolicyengine,youcannotalsousesudoers.Thepointofhavinganexternalpolicyengineisthatitcandothingsthatsudoerscan't.Youcanusemultipleloggingsystems.
Paths
Sudocanuseexternalprogramsandlibrariesforselectfunctions.I'musingthenoexectagasanexample,butwe'llrefertothePathsettingthroughoutthisbookasneeded.
TheNOEXECtagusesasharedlibrarytoreplacethesystemcallsthatexecuteprogramswithsystemcallsofthesamenamethatreturnerrors.Thistagreliesonasharedlibrarythatincludesthedummyfunctions.Youshouldneverneedtouseanynoexecsharedlibraryotherthantheoneincludedwithsudo,
buthere'showyouwouldsetit.Pathnoexec/usr/local/libexec/sudo/sudo_noexec.so
You'llnormallyuseapathtodothingslikecallanexternalpasswordprogram(seeChapter8).
Set
SudohasafewfeaturescontrolledthroughSetcommands.Thesearegenerallyswitcheswithpredefinedvaluessuchastrueandfalse.I'llusecoredumpsasanexample.
Sudohandlessensitivesecurityinformation.Itnormallykeepsthatinformationinmemory,anddiscardsitassoonaspossible.Acoredumpfilefromacrashedsudoprocesswouldcontainallofthatsensitivesecurityinformation.Sudothereforedisablescoredumpsbydefault.Ifyouwanttoenablecoredumps,setdisable_coredumptofalse.Setdisable_coredumpfalse
Thissettinghandlesthesudopartofcreatingacorefile,butmostoperatingsystemsdon'tletsetuidprogramsdumpcore.OnFreeBSD,enablecoredumpsfromsetuidprogramsbysettingthesysctlkern.sugid_coredumpto1.OnOpenBSD,setthesysctlkern.nosuidcoredumpto0toallowsetuidprogramstodumpcore.OnLinux,setthesysctlskern.suid_dumpableandfs.suid_dumpableto2.
Fromhereonout,I'llrefertomakingentriesinsudo.confandexpectyoutounderstand.
Chapter8:UserEnvironmentsversusSudoAuser'sshellenvironmentmightnotbeconducivetogoodsystemmanagement.Environmentvariablesexisttoaltersoftwarebehavior.Softwarerunningwithelevatedprivilegesneedstobehavewell,andenvironmentvariableswhichchangethatbehaviorcanthreatenyoursystem.Forthatreason,sudodefaultstoremovingmostoftheuser'senvironmentbeforerunninganycommand.
Ifyou'renotsurewhat'sinyourenvironment,runthecommandenv.Youshouldseesomefamiliaritemsinthere,suchasSHELLandPATH,butyouwillalsoseeabunchoflesswell-knownvariableslikeSHLVLorG_BROKEN_FILENAMESorEDOOFUSorwhatever.Someoftheseareprobablyimportant.Manyofthemaren't.Youmightnotevenknowhoworwherethesevariablesgetset.Purgingtheenvironmenthelpsensurethatprivilegedcommandsrunastheyshould.
DangerousEnvironmentVariablesHowcanenvironmentvariablesbedangerous?Programscheckenvironmentvariablesfortheirsettings–forexample,shellsuse$HOMEtoidentifytheuser'shomedirectory.TheseenvironmentvariablesarepartofwhatmakesasystemUnix-like.
Ontheotherhand,someprogramsusetheenvironmentvariableLD_LIBRARY_PRELOADtoidentifydirectoriesthatcontainadditionalsharedlibraries.Butthatdirectorymightcontainaversionoflibcthatcopiesauthenticationcredentialstoaremoteserver.Andthere'sawholefamilyofLD_variablesusedondifferentoperatingsystems.Shellslikebashuse$IFStogivethecharacterthatseparatescommand-linearguments.ChangingIFStoacarefully-chosenvaluecanmakeprocessesdowildlyunexpectedthings.Ifyouloseyourtermpaperbecauseanincorrectenvironmentvariablemadeyourtexteditoreatyourfiles,that'sannoying.Ifyouusethatsameenvironmentwithaprivilegedcommand,youmightlosemorethanyourownfiles.
Programscanlookforanyenvironmentvariable.Commercialsoftwareoftenuseshundredsofenvironmentvariablestostorearbitraryconfigurationdata,muchasMicrosoftWindowsusestheRegistry.Thereisnomasterlistofdangerousenvironmentvariables,aswhatissafeononesystemcandevastateanother.
Sudoletsyoucarefullycontrolyourshellenvironment.
ExecutionEnvironmentSudodoesn'tjustrunaprivilegedcommandforyou.Itspinsupaninstanceofashell,runsthecommand,exitstheshell,andreturnscontroltotheshellyouransudofrom.Thisiswhycommandslikesudocd/opt/secretdon'tworkthewayyoumightexpect.Sayyourcommandpromptisinyourhomedirectory.Yourunthecdcommand.Sudostartsupashellandchangesintothedesireddirectory.Thenthatshellexits.Yourrunningshellinstanceisstillinyourhomedirectory,whiletheshellinstanceinthedesireddirectorynolongerexists.
Youwanttoseewhat'sinthatsecretdirectory?Trysudols/opt/secret.Youwanttorunamorecomplicatedseriesofshellcommands?Explicitlystartashellinstanceandwriteyourcommandsasaquotedstring.$sudosh–c"cd/home;du–d0|sort–rnk6"
HereIstartashellinstance,gatherthetotalsizeofallthedirectoriesin/home,andsortthembysize,largestfirst.Theexactspecificsofthisshellcommanddon'tmatter;thepointisthatIhadsudorunalistofshellcommandsviash–c.Youstillneedprivilegestorunsh.
Sudobasestheinitialenvironmentofthenewshellinstanceonyourenvironment,unlessyoutellitnotto.Youcantellsudotoestablishthisenvironmentinthreedifferentways:takeyourcurrentenvironmentandpassthroughselectedenvironmentvariables,takeyourenvironmentandstripoutselectenvironmentvariables,orabandonyourenvironmentandusethetargetuser'senvironment.We'llcovereachseparately.
WhitelistingEnvironmentVariables
Bydefault,sudoremovesallenvironmentvariablesexcept$TERM,$PATH,$HOME,$MAIL,$SHELL,$LOGNAME,$USER,and$USERNAME.Thismeanssudorunscommandsinyourpreferredshell,withyourregularpath,anddoesn'tautomaticallydumpcreatedfilesinroot'shomedirectory.Sudoalsoautomaticallyremovesanyenvironmentvariablethatbeginswiththecharacters(),asthesecanbeinterpretedasBashfunctions.Allwellandgood…untilyouneedsomeotherenvironmentvariable.
Thisiswheretheenv_keepsudoersoptioncomesin.env_keepletsthesystemownerdefinealistofenvironmentvariablesthatsudoshouldretain.Forexample,severalenvironmentvariablescontrollanguageandcharactersetdisplayoptions.Ifyou'reanativeRussianspeaker,youprobablywantcommandsthatrunundersudotouseyourpreferredcharacterset.Defaultsenv_keep+="LANGLANGUAGELINGUASLC_*_XKB_CHARSET"
Notethe+=aftertheoptionname.Thismeans"addthefollowingtoanyexistinglist."Ifyouuseaplainequalsign,theoptionwilloverwritethedefaults.You'llgetyourcharacterset,butloseyourpath,shell,andhomedirectory.Youcouldalsouse-=tosubtractanenvironmentvariablefromthelist.
Youcanhaveasmanyenv_keepstatementsasyouneed,andcanmatchthemtospecificuser,machine,command,andRunAslists.PerhapsadministratorscankeeptheirSSHenvironmentvariables,sotheycancopyprivilegedfilesacrossthenetworkviaSFTP.Defaults:%wheelenv_keep+="SSH_CLIENTSSH_CONNECTION\
SSH_TTYSSH_AUTH_SOCK"
Ormaybeyou'restuckbehindaproxyserver,andeverybodyneedstheproxyintheirenvironment.env_keep+="ftp_proxyFTP_PROXYhttp_proxyHTTP_PROXY"
Youcanpassanyneededenvironmentvariableintothesudoenvironment.
BlacklistingEnvironmentVariables
Leavingtheuserenvironmentintactexceptforenvironmentvariablesknowntobedangerousisanotherexampleofenumeratingbadness.Ifyouintendtoshootyourselfinthefoot,however,here'showtoloadthehandgun.
Theenv_resetoptiontellssudotoremoveallenvironmentvariablesexceptatrustedfew.It'ssetbydefault.Toturnthisoff,explicitlydisableitinsudoers.Defaults!env_reset
Evenifyouwanttopassmostenvironmentvariablesunscathed,there'sprobablyafewyouneedtostripfromtheenvironment.Usetheenv_deleteoptiontoremoveanenvironmentvariable.Defaultsenv_delete+="LD_LIBRARY_PRELOAD"
Usersretaintheirentireenvironment,exceptforLD_LIBRARY_PRELOAD.Runningsudoshwouldletthenewshellinstancereadinanewcopyofthesevariablesfroma
configurationfile,andyoucancertainlysetthemyourselfinsidetheshell.Butwhenyourunanindividualcommand,sudowillstripthesevariablesfromtheenvironment.
Justlikeenv_keep,env_deleteletsyouaddenvironmentvariablestothedeletionlistbasedongroups,commands,andsoon.
AllowingUserOverrides
Someusers,runningsomecommands,mightneedtocustomizetheirenvironmentinwaysthesecuritypolicycan'tanticipate.Anapplicationservermightbehavedifferentlydependingonthepresenceorabsenceofenvironmentvariables,andifthesoftwarechangesquicklythosevaluesmightneedconstantupdating.Sudoersletsyouwriteasecuritypolicythatsays"Herearethestandardenvironmentsettings,butletthesespecificuserssettheirownenvironmentvariablesforthesespecificcommands."
UsetheSETENVandNOSETENVtagsoncommandstolettheuserasksudotonotalterhisenvironmentvariables.TheSETENVtagpermitsuserstokeeptheirenvironmentonrequest.Here,Petehasaspecificexceptionpermittinghimtocontrolhisenvironmentoncertaincommands.petedbtest1=(oracle)SETENV:/opt/oracle/bin/*
Onthemachinedbtest1,PetecanusehisownenvironmentwhenrunningOraclecommandsasoracle.Oraclesoftwareishighlysensitivetoenvironmentvariables.Petecanexplorearbitraryconfigurationsonthetestserver,andmakeaformalrequestforanupdatedsudoerspolicyinproductiononceheunderstandswhatheneeds.
Petemustspecificallyasksudotonotchangehisenvironmentbyusingthe–Eflag.$sudo–E–uoracle/opt/oracle/bin/sqlplus
Withoutthe–Eflag,sudowillperformitsstandardenvironmentstrippingdespitethepresenceofNOSETENVinsudoers.
UsethetagNOSETENVtooverrideapreviousSETENV.petedbtest1=(oracle)SETENV:/opt/oracle/bin/*petedbtest1=(oracle)NOSETENV:/opt/oracle/bin/gennttab
PetecancontrolhisenvironmentforallOraclecommands,exceptforgennttab.(Remember,sudorulesarelastmatch.)
InadditiontotheSETENVtag,there'salsoasetenvoption.Useitjustlikeanyotheroption.Defaults:theasetenv
Theacanoverrideherenvironmentanywhere,providedsheusesthe–Eflagwithsudo.Astheseniorsysadminshe'salreadyonthehookforsystemdamage,andsheneedstheflexibilitytotroubleshootanypossibleproblem.Givingherselftheabilitytooverridetheenvironmentondemandisaperfectlylegitimateexception,especiallyasitonlyworksatthosetimesshespecificallyrequestsit.
Onlygivehighlytrusteduserstheabilitytooverrideenvironmentvariables,andthenonlyintestenvironments.Remember,sudopoliciesaren'tjusttocontrolusers–they'realsoforlimitingthedamagemaliciousintruderscaninflictonthesystem.
TargetUserEnvironment
Ioncesatinameetingwhichboileddownto"TheserverrunsfineunlessDaverestartsit."TheadministrativesolutionwastofireDave,butthetechnologicalsolutionwasfixinghowsudomanagedDave'senvironment.(FortunatelyforDave,thetechnologicalsolutionprevailed.)
Insomecasesyoudon'twanttocarryanyenvironmentvariablesintoyourprivilegedenvironment.Youdon'tevenwantyourshellorhomedirectory–instead,youneedtorunthecommandasthetargetuser,inthetargetuser'sshellenvironment.Sudoletsyoudothatwiththe–ioption.
Byusingsudo–iyousimulateanewloginasthetargetuser,readingthetargetuser'sdotfilessuchas.loginand.profile,thenrunningtherequestedcommand.Youroriginaluserenvironmentisnotretainedinanyway.$sudo–i/opt/apps/bin/start-server
Inmyexperiencehavingsudoinitializeanenvironmentasthetargetuseristhebestwaytomanageapplicationservershighlydependentontheirstartupenvironment.ManyJavaserver-sideapplicationstaketheirconfigurationfromenvironmentvariables,andthosevariablesmightnotbecorrectinyourpersonalenvironment.Byconfiguringthatenvironmentinasingleaccount,youeliminateonethreattotheapplication'sstability.
SudoEnvironmentDefaults
Differentreleasesofsudomightbehavedifferentlywithregardstoenvironmentvariables.Idon'texpectanyofthedefaultpassenvironmentvariablestochange,butafuturereleaseofsudomightaddnewones.
Tolearnabouttheenvironment-handlingdefaultsonyourversionofsudo,runsudo–Vasroot.The
outputtellsyouhowthissystem'sparticularsudobinarywasbuiltandhowittreatsdifferentenvironmentvariables.You'llseethreegroupsofvariables:variablestosanity-check,variablestoremove,andvariablestopreserve.
Forsanitychecking,sudochecksthelistedvariablesforthecharacters%and/,removingthemifpresent.Someenvironmentvariablesaffectyourbasicsession–forexample,abadTERMvariablecanscramblecommandsasyoutypethem.It'sbettertorunacommandwithoutTERMsetthanrunacommandwithagarbageterminal.
You'llseealistof"environmentvariablestoremove."Sudodoesexactlythat.Youcannotoverridethislistwithenv_keep;ifyouwantthesevariablesinthesudoenvironment,youmustsetthemwithinthetargetuser'saccount.
Thelistofenvironmentvariablestopreserveisinadditiontothelistgivenearlierthischapter.YoukeepvariablessuchasHOMEandPATH,butalsothoseshownbyyourspecificsudobuild.
Sudo-SpecificVariables
Acommandrunundersudogetsfoursudo-specificenvironmentvariables:SUDO_COMMAND,SUDO_USER,SUDO_UID,andSUDO_GID.TheSUDO_COMMANDvariableissettotheexactcommandyouranundersudotostartthissession.SUDO_USERgivesyouroriginalusername.SUDO_UIDandSUDO_GIDgiveyouroriginaluserIDandprimarygroupID.
Aprogramorscriptcancheckforthepresenceofthesevariablesandbehavedifferentlyifthey'representorusetheminsomeway.YoucoulduseSUDO_USERinlogmessages,forexample."Yes,Iwasrunbyroot,butreally,Iwasrunbymike.Blamehim."
EnvironmentCustomizationAsudopolicycandomorethanjustallowanddisallowenvironmentvariables;itcanexplicitlysetvariables.Sudoerspoliciesletyousettheuser'spath,andyoucanalsosetarbitraryenvironmentvariablesifneeded.
Managing$PATH
Oneenvironmentvariableisalittletrickierthanmost.Manyintruderstrytosabotageauser's$PATH,sothattheuserwillrunabogusversionofcommandsratherthantheproperone.Ifahelpdeskflunkyneedstoresetauser'spassword,butherunstheprogram/tmp/.1234/hacker/passwdratherthan/usr/bin/passwd,badthingswillhappen.Usethesecure_pathoptiontodefineyourtrustedpathforsudocommands.Defaultssecure_path="/bin/usr/bin/sbin/usr/sbin"
Sudotriestorunthecommandusingthesecurepath.Ifthecommandisn'tinthesecurepath,itfails.Thisaffectscommandsrunviasudo,butnotshellinstancesstartedviasudo.Ifyoustartafull
interactiveshell,theshellreadsthetargetuser's.profileandothershellstartupfilesasitinitializestheenvironment.Securepathshelpwhenrunningsudolikethis:$sudopasswdmike
Inthisusecase,secure_pathmakessurethatthepasswdcommandbeingrunisactuallythesystem'spasswdcommandandnotanintruder'scustomizedcopy.Itdoesn'tverifythatthesudocommandtheuserrunistheproperone,however,sousersstillneedtotakecareoftheir$PATH.
AddingEnvironmentVariables
Sometimesyouwanttospecificallysetenvironmentvariablesforaprivilegeduser.Usetheenv_fileoptiontogivethefullpathtoafilecontainingthenewenvironmentvariables.Onecommonsituationiswhenyou'rebehindaproxyserver.Youwantuserstoalwaysaccesstheinternetviayourproxy?Addtheenvironmentvariablestotheirenvironment.Defaultsenv_file="/etc/sudoenv"
Theenvironmentfilecontainsastandardlistofvariableassignments,likeso.FTP_PROXY=http://proxyhost:8080ftp_proxy=http://proxyhost:8080HTTP_PROXY=http://proxyhost:8080http_proxy=http://proxyhost:8080
Sudoaddstheseenvironmentvariablesbeforestrippingouttheenvironment,solistanyaddedvariablesinanenv_keepsudoersruleaswell.Thisalsomeansyouoverridetheuser'sownenvironmentvariables,soifauserhasadifferentsettingyou'vejustreplacedit.
StartingShellswithSudoSomepeopleusesudoasareplacementforsu.Essentially,theybecomerootwithoutusingapassword.$sudosu
Idon'tencouragethis.Sudologswhichcommandspeopleuse,butwithoutadditionalconfigurationsudodoesn'tlogwhathappensinsideashellsession.(We'llcoversudologginginChapter12.)Butsincesomeofyoudoitanyway,let'sdiscussit.
Thesucommandmeans"switchuser."Runningsu–orsu–linitializesanewshelljustlikeusingsudo–i.Yougetthetargetuser'senvironment.Runningplainsuswitchestheuseryou'rerunningasbutretainsmostofyourenvironment.
Ifyouwanttocompletelyreplacesuwithsudo,youcouldenabletheshell_noargsoption.Withthisoptionset,runningsudowithnoargumentsgivesyouarootprompt.Defaults:theashell_noargs
WhenThearunssudowithoutanycommand-linearguments,she'sroot.$sudoPassword:#
Youcansimulateshell_noargsonthecommandlinebyusingthe–sflag.$sudo-sPassword:#
Iftheuserdoesnothavepermissiontorunroot'sshell,sudodeniesaccessevenifshell_noargsispresent.Anotherpopularuseofsudoistorunashell,butretainyourownenvironment.
$sudosu–m#
Thisleavesyourshellunchangedandretainsanyenvironmentvariablesyoursudoerspolicypasses.Whichshouldyouuse?Ideally:none.Ifyoumustletusersbecomeanotheruserviasudo,configure
completesessionloggingasperChapter12.
SudoWithoutTerminalsSometimesyouwanttorunsudowithoutanattachedterminal.Youmightwantaright-clickmenuinyourdesktopmanagerthatrunsaprogramviasudo.Thissudoprogramwon'truninaterminal,however,sosudocan'taskyouforyourpassword.Youneedawaytogetsudoyourpassword.
Sudocanrunanexternalprogramtopromptforthepassword.Usetheaskpasspathinsudo.conftotellsudowheretofindthispasswordprogram.ThegraphicalpasswordpromptsoftwaremostlikelytobefoundonanydesktopsystemwithsudoisOpenSSH'saskpass,openssh-askpass.Pathaskpass/usr/local/bin/openssh-askpass
Whensudoneedsapasswordanddoesn'thaveaterminaltoaskforone,itusestheaskpasssettingfromsudo.conf.
RequiringaTerminalSometimesacommandrunswithoutafullenvironment.ProgramsthatrunaspartofaCGIscriptorprogramsrunbyschedulerslikecrondon'tactuallyhaveaterminaltorunin.YouraverageUnix-likesystemdoesn'tfireupashellsessiontorunthesecommands,butinsteadrunsthemaschildprocesses.Ifyoudon'twantautomatedprocessesrunningarbitrarycommandsviasudo,lookatrequiretty.
Therequirettyoptiontellssudotoonlyworkifthecommandisruninaterminal.Enablingthisoptioninsudoersmeansthatprogramscannotrunwithoutaterminal.Ausercan'twriteaCGIscriptthatcallssudo–well,okay,theycanwriteit,butthesudocallwon'twork.
Youcannowmanagetheenvironmentsudocreates,orwhetheritneedsanenvironmentatall.Nowlet'sseehowsudocanprotectyourusersfromadamagedsystem.
Chapter9:SudoforIntrusionDetectionOneoftheproblemsmentionedinthepreviouschapteristhatoftamperingwiththeuser'spath.Sanitizingthepathhelps,butthenourintrudermightreplacetheactual/usr/bin/passwdcommandwithhisowntreacherousversion.Sudo1.8.7andlatercanverifythecryptographicdigest(orchecksum,orhash)ofacommandbeforerunningit,preventingthesekindsofattacks.
Whyisthisuseful?Acryptographicdigestisamathematicaltransformationthatcreatesafixed-lengthstringforanypieceofdata,suchasafile.Evenminorchangesinthesourcefiledramaticallychangethegenerateddigest.IfsudoknowsthatthecorrectcryptographicdigestforthelegitimatepasswdcommandisX,butthepasswdcommandonthediskhasadigestofY,sudowillrefusetorunthecommand.Formoreaboutcryptographicdigests,checkoutmybookPGP&GPG(NoStarchPress,2006).
Anintruderisnottheonlyonewhomightalterthefilecontainingacommand.Ifyouhavewriteaccesstothedirectorycontainingthecommand,youmightaccidentallyalterityourself.Similarly,digestscan
protectyoufromuserswhochafeattheirrestrictions."Iknowhowtofixthis,Ijustneedroot!"[7]
Digestverificationcanpreventyoufromrunningacopyofddthatsomeoneaccidentlycopiedoverthemvcommand.Wouldrunningthathurtanything?Probablynot,unlessyouintendedtomovesomeveryoddlynamedfiles.Butsucherrorscanbecatastrophic,andthey'rethefirstsignthatthisoperatingsysteminstanceisbadlydamaged.Youwantasmuchearlywarningaspossibleofsystemdamage.
Usingdigestsforcommandintegrityverificationhastwocomponents:generatingthedigest,andwritingasudoersrulethatvalidatesthedigest.
GeneratingDigestsDifferentUnix-likeoperatingsystemshavedifferentcommandsforcomputingcryptographicdigests.(Becausetheycan.)Ratherthansuggestingthesha512commandonlyforyoutodiscoverthatyouneedsha512sumbecauseyou'reusingLinux,Irecommendthemoregenericopenssltoolforgeneratingchecksums.
SudosupportsseveraldifferentvariantsoftheSHAdigestalgorithm:SHA-224,SHA-256,SHA-384,andSHA-512.Highernumbersmeanthatthedigestismoredifficulttoreverse-engineer,butcreatingandvalidatingthedigestalsotakesmorecomputationpower.Also,digestsgetmuchlongerasthestrength
increases.SHA-224providessufficientprotectionagainstallrealisticattackswithtoday'shardware.[8]
$openssldgst-sha224/usr/bin/passwdSHA224(/usr/bin/passwd)=c6eab09e527dc…
The56-characterstringaftertheequalsignistheSHA-224digestofthefile/usr/bin/passwd.Mostprogramswillhaveuniquedigests.Someprogramshavemultiplenames–forexample,thesendmailcommandisalsoknownasnewaliases,mailq,hoststat,purgestat,andprobablyafewothernames.(Ihavemyownpreferrednamesforsendmail,butchildrenmightstumbleacrossthisbook.)Youcanlistallofthosenamesinasudoersalias.Whichtakesustothenexttopic.
DigestsinSudoersUseacryptographicdigestmuchlikeothertags.Aftertheequalsignputthetypeofdigest,acolon,andthedigestitself,thenthecommandlist.Unlessyouhavemultiplecommandswithidenticaldigests,youprobablyneedoneruleperpermittedcommand.AsSHA-224digestsare56characterslong,I'vetruncatedtheactualdigestinalloftheseexamples.mikeALL=sha224:d14a028c…/usr/bin/passwd
WhenIasksudotorunpasswd,sudocomputestheSHA-224digestfor/usr/bin/passwd.Ifthegenerateddigestmatchesthedigestinthesudoersrule,sudowillrunthecommand.Otherwise,you'llgetthegeneric"notallowed"message.Ifsudo–lshowsthatyouhavepermissiontorunacommand,buteveryattempttorunthecommandgetsthe"notallowed"message,thechecksumonthecommanddoesn'tmatchthefile'schecksuminsudoers.
Ifmultiplebinarieshavethesamedigest,youprobablymadeamistakesomewhere.Double-checkyouropensslcommand.Ifmultipleprogramfilesreallydohavethesamedigest,theymightbethesameprogramindisguise–e.g.,sendmailanditsposse.Youcanlistcommandswithidenticaldigeststogetherlikeso:Cmnd_AliasSENDMAIL=sha224:65f81…/usr/sbin/sendmail,\
/usr/bin/mailq,/usr/sbin/hoststat,/usr/bin/newaliases
Ifyouwanttocomputethecryptographicdigestofeverylegitimatebinaryonyoursystem,Irecommendwritingascripttodoso.Ifthescriptletsyoupredefinegroupsofcommandsforcommandaliases,somuchthebetter.
DigestsandMultipleOperatingSystemsOnceyoucentralizeyoursudoerspolicy,youmightfindthatyouneedapolicythatpermitsmultipledigestsforasinglecommand.ThesendmailcommandsonUbuntuwillhavedifferentdigeststhanthesendmailcommandsonFreeBSD,andthoseonFreeBSD9.2willdifferfromFreeBSD9.3.
Howcanyoucopewiththis?Useonecommandaliasperoperatingsystem.Cmnd_AliasFB92_SENDMAIL=sha224:65f81…/usr/sbin/sendmail,\
/usr/bin/mailq,/usr/sbin/hoststat,/usr/bin/newaliasesCmnd_AliasPRECISE_SENDMAIL=sha224:213ff…/usr/sbin/sendmail,\
/usr/bin/mailq,/usr/sbin/hoststat,/usr/bin/newaliasesCmnd_AliasSENDMAIL=FB92_SENDMAIL,PRECISE_SENDMAIL
DidImentionusingascripttogeneratedigestsforyouroperatingsystem?Youwon'twanttorecomputethisoneverymachineonyournetwork.It'smuchbettertodesignthis
policyonceanddistributeittotherestofthenetwork,aswediscussinthenextchapter.
Chapter10:SudoersDistributionandComplexPoliciesSudoisalotoftroubleforasinglemachine.Ifyourunhundredsorthousandsofsystems,however,sudomakesuserprivilegesmanageable.Noteasyorsimple,butmanageable.Thebestwaytohaveaconsistentpolicyacrossyournetworkistowriteasinglesudoersfileandreplicateittoallmachinesonthenetwork.Whileit'sfairlysimpletodothis,hereareafewhintsonwritinganddeployingsafeandsecurepolicies.
BreakingSudoWe'vetouchedonhowtoescapesudo'srestrictionsearlierinthisbook,butlet'sconsiderthemalltogether.Thefollowingisa"greatesthits"ofhowtowritesudoerspolicies.
Donotexcludecommandsfromanalias.UserscaneasilybypasscommandlistslikeALL,!/bin/sh.UsingtheALLcommandlistgivespeopleprivilegedaccess,nomatterhowthesystemownertriestorestrictit.
UsetheNOEXECflagbydefaultinyourcommandlists.Specificallyenumeratecommandsthatmustrunothercommands.You'llhavearoughfewdaysasuserscalltocomplainthattheycan'truncertaincommands,butyou'llquicklyfindthecommandsthatlegitimatelymustrunothercommands.Whenyouautomaticallydistributingasinglesudoersfileacrossthenetwork,thosechangeswillquicklypropagatetoallhosts.
Usealiasesforusers,commands,hosts,andRunAssettings.Usethealiasratherthanthecommandnameinyourrules.Thissimplifieschangesandhelpsensureallyourusershaveidenticalaccesstoothersintheirgroup.
Mostwaystoescaperestrictionscanbeeliminatedwithproperconfiguration."Properconfiguration"usuallymeans"spelloutexactlythepermittedaccess."Don'tjustgivepeopleunlimitedaccesstoallcommands;instead,sortoutwhoshouldbedoingwhatandwhataccesstheyneedtodotheirrealjobs.Yes,thismeansspendingtimeandenergyhavingface-to-faceconversationswithlivinghumanbeingswhohavetheirownopinionsanddesires,ratherthandoingthefuncomputingstuff.
Hesitatetogiveroot-levelprivilegestoshellscriptsviasudo.Whilesudosanitizestheuser'sshellenvironment,ashellscriptcanputthatscarystuffrightbackin.Intoomanycases,runningashellscriptasrootviasudoisequivalenttogivingtheuserroot.Evenifyouusecryptographicdigestverificationtoensurethatthescriptrunsunedited,shellscriptsoftenpullofteninothershellscripts.Usersandintruderscansubvertanynumberofshellscriptswithenvironmentvariables.Don'tthinkyourusersaredifferentandwon'tmessaroundwithyourcarefullywrittenshellscripts.Theyaren'tandtheywill.
Onsomehosts,atightsudoconfigurationisn'trealistic.Desktopmachinesrunlotsofprogramsthatrunotherprograms.Auserwhohasphysicalaccesstothemachineandneedstorunagraphicdesktopcangetroot-levelaccessonthemachinewithoutmuchdifficulty.Yourbestpracticeistoassumethatdesktopmachinesarenottrustworthy,andsecureyourserversagainstrogueworkstationsaswellasexternalintruders.
Ifyou'renotwillingtodotheworkofcreatingarealsudoerspolicy,thendon'twasteyourtimeslappingtogetherahalf-cookedsudoerspolicythatsort,ofmoreorless,kindof,doeswhatyouwant,basically.Instead,giveusersunlimitedaccessanddealwiththefallout.Afterenoughunnecessarydowntime,systemdamage,andlostnightsandweekends,you'lldevelopawillingnesstowritearealsudoerspolicy.Logginguseractivity(seeChapter12)canhelpassessexactlywhathappenedwhenthingsgowrong,andmightbeagoodreplacementforyourorganization.
HostnamesandSudoersWhenmanagingsudoersindividuallyoneachmachine,thehostnamepartofthepolicytendstodisappearfromthesysadmin'sview.It'sstillinthefile,butyourconsciousmindnolongerseesit.It'sjust"that'ALL='thing"thatmustappearinthemiddleofeveryrule.Ihaven'tgivenitmuchattentionsofar,becausewe'veonlyconsideredsingle-systempolicies.Whenyouwanttouseasinglesudoersfileacrossyourentirenetwork,suddenlythehostnamefieldbecomesmuchmoreimportant.
Sudogetsthenameofthelocalmachinebyrunninghostname.Thehostnameinyoursudoerspolicymustexactlymatchwhateverhostnamethelocalmachinethinksitis.Thiscancausedifficultyinheterogenousnetworks.MyLinuxserversusuallyhaveahostnameconsistingofasingleword,suchaswww8orsip2.MyBSDmachineshaveahostnamethatincludesthedomain,suchaswww.michaelwlucas.com.Beforeyoustartwritingacentralizedsudoerspolicy,investigateyournamingschemeasitisactuallydeployedontherealservers.Aretheyconsistent?Ifyou'reusingcentralizedserverprovisioning,you'reprobablyokay.If
you'restillrunningartisan-managedservers,oryouinstallserversbyhand,youhaveinconsistencies.[9]
Addressthoseinconsistenciesbeforeyoubuildyourpolicy.OruseDNSorIPaddresses.
DNSandSudo
TheDomainNameSystemmapshostnamestoIPaddresses.Aservermightthinkitsnameiswww8,buttheDNSrecordsitaswww8.michaelwlucas.com.DNSiscentrallymanaged(mostly;moreonthatlater).HavingsudorefertoDNSformachinenamesremovesanylocalhostnameinconsistencyissues.ItalsoaddsadependencyonDNSformachinemanagement.IfyourDNSserversfail,sudowillnotwork.Ifsudowon'trunbecauseDNSisdown,andyoucan'trestartDNSbecausesudoisdown,congratulations!Youfailedtothinkthroughyourfailuremodes.ExpectyourlocalTheatocomeforyourcarcassshortly.
HostsmightbeconfiguredtoresolveIPaddressesandhostnamesfromavarietyofinformationsources,suchasYPorLDAP.IftheserverprefersoneoftheseinformationsourcestoDNS,thenyouneedtoverifythatyoursudoersrulesmatchthehostnameinthatinformationsource.Themostcommonalternateinformationsourceisthehostsfile,/etc/hosts.ChecktoseeifyourserverprefersthehoststabletoDNS,andconfirmtheserver'snameinthatfileifso.
AmachinecanhavemultiplehostnamesinbothDNSandhosts,butsudoonlyusestheprimaryhostname.Sudoignoresallaliasesoradditionalrecords.Ifyou'reusingthehostsfile,onlythefirsthostnameinanentryisused.Ifyou'reusingDNS,anyCNAMErecordsareignored.SudoonlyusesthehostnameasshowninforwardandreverseDNS.
ToenabletheuseofDNS,usethefqdnoptioninsudoers.Defaultsfqdn
Sudostillchecksthelocalhostname,andifthesudoersrulehappenstomatchthelocalname,therulematches.Ifthenamedoesn'tmatch,sudousesDNSandcompareseachruletotheserver'sfullyqualifieddomainname.Ratherthanusingtheshorthostnamewww8,you'llneedthefullhostname.
%helpdeskwww8.michaelwlucas.com\/usr/bin/passwd[A-z]*,!/usr/bin/passwdroot
Thelinesinyoursudoersfilewillbemuchlonger,butthat'sokay.Also,yoursudocommandswilltakealittlelongerassudoqueriestheDNSforthelocalhostname.
Theobviouswaytobreakhostname-basedprotections,however,isforthesystemadministratortochangethelocalhost'sname.Ifyoursudoerspolicypermitsanotherwiseunprivilegedusertochangethemachinename,thenhecanchangethepolicyappliedtothemachine.
IPAddresses
IfindthatusingIPaddressesinmysudoerspoliciesismorereliablethanusinghostnames,atleastinmyenvironment.Onalargenetwork,wheremachinesexistondifferentsegmentsandhavedifferentnetworkaccessrules,systemadministratorsusuallyhavenoaccesstothenetworkequipment.Aroguesysadminmightchangethenameofawebservertothatofahostonthedatabasetier,buthecannotchangetheIPaddressofthatserverwithoutlosingaccesstothemachine.
Usehostaliasestodefinethesenetworksubnets.Host_AliasWEBSERVERS192.0.2.0/24Host_AliasDBSERVERS203.0.113.0/24
Assignaccessrulestothesehostaliases,andtheonlywayaproblematicusercangetaroundtheaccesscontrolsistomovethemachinetoanothersubnet.Ultimately,howyoudesignyoursudoerspolicytoavoidthesehostnamechangesdependsonyourstaffandusers,yourenvironment,andyourrisktolerance.
IncludingFilesinSudoersAsudoerspolicycanincludeotherfilesbyreference.Thisletsyouhaveageneralizedsudoerspolicyforallyoursystems,andaddotherfilesbymachineroleorfunctions.Youcanaddspecificfiles,filesbyhostname,orfileswithinadirectorybyusingan#includestatement.
Thefileisinsertedintothesudoerspolicyatthespotthatyouusetheincludestatement.Ifyouincludefilesatthetopofsudoers,yourglobalrulesoverrideanythingintheincludedpolicy.Ifyourincludestatementappearslastinsudoers,thentheincludedfileoverridestheglobalpolicy.Whyisthisimportant?Thinkaboutanincludedfilewiththisline:%wheelALL=!ALL
Thewheelgroupistraditionallythoseuserspermittedtousetherootpassword–alsoknownas"theseniorsysadmins."Dependingonyouroperatingsystem,thismightbetheadmingrouporsomethingelse.Theincludedfileforbidsallusersinwheeltorunanycommandsviasudo.Ifthisruleappearslastinthesudoerspolicy,itremovestheseniorsysadmin'saccesstotheservers.Thisisprobablynotwhatyouwant.
IncludeSpecificFiles
Maybeyouhaveabasetemplateofasudoerssecuritypolicythatyoudistributetoallsystems,sothatyourseniorsystemsadministratorscanaccessallservers.Individualmachineshavetheirownsecuritypoliciestailoredtothesystem'sneeds.Inthiscase,youwouldcopy/etc/sudoerstoallmachinesonthenetwork,andtelllocaluserstoputtheirownrulesinadifferentfile,suchas/etc/sudoers.local.Addan#includestatementtoyourglobalsudoers.#include/etc/sudoers.local
Setyourlocaladditionsinthatfile.
Per-HostIncludeFiles
Maybeyouwanttoincludeafilebasedonthelocalhostname.Youcanusethe%hescapecharactertousethelocalhostnameinafile.#include/etc/sudoers.%h
Onthemachinewww8,sudowouldlookforafilecalled/etc/sudoers.www8.
IncludingDirectories
Includingonefileisn'tenoughforyou?Sudoletsyouincludeallthefilesinadirectorybyusingthe#includedirstatement.#includedir/etc/sudoers.d
ManyLinuxdistributionsusethistypeofsyntax.Theideaisthatyoucanhaveacentral,standardsudoerspolicy,andthencopyadditionalpoliciestoamachinebasedonthemachine'sfunction.Thehostisawebserver?Copyyourstandardfile001-sudoers.wwwtotheincludedirectory.Databaseserver?Copythedatabasefile.Both?Thencopyboth.
Thisisaperfectlyvalidwaytomanageasudoerspolicy.Bythetimeyournetworkgrowsthiscomplex,however,you'remuchbetteroffinvestigatinganLDAP-basedsecuritypolicy(Chapter11)insteadofmanagingsudobylocalfiles.
Sudoreadsandprocessesthesefilesinlexicalorder.Inlexicalordernumbersalwayssortbeforeuppercaseletters,anduppercaselettersalwayssortbeforelowercaseletters.Lowercaseletterscomebeforeaccentedcharacters.You'veseenthiskindoforderingeverytimeyourunaplainlsinadirectory.You'llseenumberssortlike1,11,12,2,andthen21.ThewordRatcomesbeforegerbil.Theeasiestwaytocontrolsortingistohaveallofyourincludedfilesstartwithnumbers,andincludetheleadingzeroes.Thatway,policyfile001-sudoers.wwwwillgetprocessedbefore100-sudoers.database.File2-sudoers.wordpressgetsprocessedafterboth,soincludethoseleadingzeroes.
OruseanLDAP-basedpolicytoshowasingleconsistentpolicytoeachmachine.You'llbehappier…eventually.
ErrorsinIncludeFiles
Ifafileincludedin/etc/sudoersissyntacticallyinvalid,sudowillnotrun–preciselyasifyouhadasyntaxerrorin/etc/sudoersitself.Visudoonlycheckstheintegrityofonefile,noteverythingincludedinthesudoersfile.Usethe–fflagtoaimvisudoatadifferentfile.#visudo–f/etc/sudoers.www8
Visudowillopenacopyofthisfile,editthecopy,checkthefile'ssyntax,andeitherreplacetheoriginalfileortellyoutofixyourerrors,exactlyasitdoesfor/etc/sudoers.
SingleSudoersAcrosstheNetworkIfyourunhundredsofmachines,youalreadyhaveawaytodistributefilestoallofthem.ToolssuchasPuppet,Chef,Ansible,orevenrdist,makethisalmosteasy.Configuringsudoonacentralmachineandpushingthesudoersfileouttoallofthehostsinthenetworkdoesnotpreventsomeonefromeditingalocalmachine'ssudoersfile.Butitimprovesdetectionofandrecoveryfromsuchchanges.It'salsoeasierthanusinganincludedirectory–youcanputyourvariousserversingroupsandusethosegroupsforrules.
Ifyou'recentrallymanagingsudo,Istronglyrecommendhavingeachlocalmachinevalidatethatitcanparsethenewsudoersfilebeforeinstallingitas/etc/sudoers.Ifyouinstallasudoersfilethatworksonsudo1.8.9onamachinerunningsudo1.8.7,youmighthaveincludedoptionsorrulesthattheoldersudocannotparse.Ifsudocannotparse/etc/sudoers,sudowillnotrun.Validatingthenewfilewithvisudo–cfbeforecopyingitintoplacewillsaveyoualotoftrouble.IstronglyrecommendreadingJan-PietMens'blogpost"Don'ttrythisathome:/etc/sudoers"(http://jpmens.net/2013/02/06/don-t-try-this-at-the-office-etc-sudoers/)andtherelatedpostsforaverygooddescriptionofexactlyhowmuchpainabadsudoerspolicycausesonalargenetwork.(It'samusingbecauseithappenedtosomeoneelse.)MensalsohasanAnsibleplaybookforsafelydistributing/etc/sudoerssoyoucanlearnfromhissuffering.
Whileconfiguringyoursudopolicyinonelocationandpushingittoallyourhostshasdistinctadvantagesoverconfiguringitseparatelyoneachhost,betterstillishavingsudoreaditspolicyfromLDAP.
Chapter11:SecurityPoliciesinLDAPOneproblemwithsudoisthatit'snormallyconfiguredonthelocalmachine.Anintruder(oracleverbutverynaughtyuser)wholeverageshiswayintoalteringthesudoersfilecanalterhisownpermissions.Thisisbad.Thewaytoeliminatethisriskistoremovethesudoerspolicyfromthemachine.
TheLightweightDirectoryAccessProtocol(LDAP)providescommoninformationacrossanetwork.Whileitusuallystoresusernamesandpasswords,itcansupportanyarbitrarydirectory-styleinformation.AsudosecuritypolicyfitswellintoLDAP.
TheadvantageofhavingyoursudoerspolicyinLDAPisthatauserwhocompromisesamachinecannotalterthesudoerspolicy.Evengainingrootonaserverdoesn'tgivehimaccesstoaread-onlyLDAPserver.Also,changestoanLDAP-basedsecuritypolicyimmediatelypropagatetoallthemachinesonthenetwork.
Typoscannotpreventsudofromrunning,astheycanwithsudoers.AnLDAPserverwillnotacceptimproperlyformatteddata.Youcanmistypemachineandusernames,butanysudoconfigurationyoustuffintoyourLDAPserverissyntacticallyvalid.
ThedisadvantagesofconfiguringsudofromLDAP?First,youmusthaveanLDAPserver.WhenthatLDAPserverfails,yourauthenticationandsudosecuritybothdiewithit,soyouprobablywantmorethanone.YoumusthaveasudoinstallthatsupportsLDAP,whichisn'tusuallyinthedefaultinstallbutiseasilyobtained.
SudoincludesverydetaileddocumentationonusingLDAPasasecuritypolicyproviderinthedocumentsREADME.ldapandthesudoers.ldapmanualpage.Readthosedocumentsbeforeplanningyourdeployment.Thisbookdoesnotreplacetheofficialsudodocumentation,butprovidescontext,guidance,andanoverviewparalleltothatdocumentation.Idon'tcoverdetailslikeAIXusing/etc/netsvc.confinsteadof/etc/nsswitch.conf;forthat,youneedyouroperatingsystemmanualortheofficialsudodocumentation.
SudoersPoliciesversusLDAPPoliciesBuildingasudosecuritypolicyforLDAPisdifferentthancreatingansudoers-basedpolicy.Firstoff,LDAPsudopoliciesdonotsupportaliases.Theuseraliases,commandaliases,andsoforththatwespentachapteronearlierinthisbook?NotapplicabletoLDAP-basedpolicies.Instead,useLDAPgroupsforusersandservers.Thisisn'tnecessarilyanadvantageoradisadvantage,butyouneedtoknowaboutit.ThedesignofLDAPmeansit'sveryeasytoaddanewcommand,user,orhosttoarule,however.
Asudoers-basedpolicyworksona"lastmatch"basis,soyoucanputgenericrulesatthetopofthepolicyandgetmorespecificfurtheron.LDAPdoesn'tautomaticallydeliverqueryresultsinadeterministicorder.YoucanorderyourindividualsudorulesinLDAP,placingonerulebeforeanothersothat"lastmatch"works,butit'sanextrasteptoremember.YoucannotorderattributeswithinasingleLDAPsudorule.
Finally,LDAP-basedpoliciesdon'tusenegationsforhosts,users,orRunAs.Negationsoncommandsworkexactlyaswellasnegationsdoinsudoers–poorly.Rememberthatyoucannotorderattributeswithasinglesudorule,soifthere'saconflict,anycommandnegationtakesprecedence.Saveyourselftheindigestion.Don'tusenegationswithLDAPsudopolicies.
PrerequisitesThisisnotabookonLDAP.Ifyoudon'tknowwhataschemaoranLDIFis,thissectionwillbaffle,annoy,andpossiblyscareyou.That'sbecauseLDAPcanbaffle,annoy,andscaretheuninitiated.SkipaheadtoChapter12.Loggingsudoactivityismuchmoreinterestingandusefulthanitsounds,andyoudon'tneedanyexternalinfrastructuretodoit.ThischapterfocusesonLDAP-basedsudoerspoliciesandattachingthesudoclienttoLDAP.
Siterequirementsvarytoomuchformetotakeyouthrougha"generic"LDAPconfiguration.AsOpenLDAPistheservermostcommonlyusedforsudo,I'lluseitforspecificdetailedexamples,butI'lltouchonothersupportedLDAPservers.
IassumethatyouhaveLDAP-basedauthenticationworking,thatyoursetupissecureandstable,andyouhaveboththeabilitytoimportLDIFfilesandtomakeminorchangesthroughanLDAPbrowser.Iassumethatyou'reusingthesameLDAPserversforsudoasforauthentication.ThesudoerspolicyinLDAPshouldnotbewritablebythesudoclientsitserves–otherwise,onecompromisedmachinecanrewritethesudoerspolicyforallthesystemsonthenetwork.Similarly,Idon'tletmyLDAPclientservershaveanywriteaccesstotheLDAPserver,requiringuserstogotoaspecifichostorinterfacetochangetheirpasswordsandotheraccountinformation.
Ialsoassumethatyouhaveasudoers-basedpolicytostartwith.Itdoesn'tneedtobeabigpolicy–evensomethingsimplelike"herearesomedefaults,andthisgroupgetsfullaccess"willgetyourolling.
Ifyoudon'thaveLDAP-basedauthentication,stoptryingtostuffsudointoLDAP.You'vegottenaheadofyourself.GetyourmachinespullingtheiruserandgroupinformationfromandauthenticatingagainstLDAP.Thenreturnhereandtryagain.
We'llstartwithyoursudoclient,andthenproceedtotheLDAPserver.
LDAP-AwareSudoAnLDAP-awaresudoworkswithoutasudopolicyinLDAP,soinstallingtheLDAP-awaresudoisthesensibleplacetostart.MostoperatingsystemshaveapackageforsudobuiltwithLDAPsupportorallowyoutoeasilyenableit.Debian-basedsystemshaveasudo-ldappackage.CentOS-stylesystemsallowyoutoenableLDAPforsudoin/etc/nsswitch.conf.OnFreeBSDyoumustbuildyourownsudopackagetoenableLDAP,buttheportssystemmakesthatprettyeasy.Checkyouroperatingsystemdocumentation,andfollowtheinstructionstogetanLDAP-capablesudoinstalledonyoursystem.
ThenconfiguretheLDAPservertoserveandrecognizesudodata.
AddSudoSchematoLDAPserverAnLDAPserverthatsupportssudopoliciesmustunderstandthesyntaxandstructureofthosepolicies.AschemadefinesadatastructureforanLDAPserver.Eachvendor'sLDAPserverproducthasitsownschemasystemthatis(ofcourse)subtlyincompatiblewithalltheotherLDAPservers.SudoincludesthreeLDAPschemasforthreeLDAPserversinthefilesschema.OpenLDAP(forOpenLDAPservers),schema.ActiveDirectory(forMicrosoftservers),andschema.iPlanet(forNetscape-derivedservers).SomeoperatingsystempackagersincludethesudoschemaintheirLDAPserver,socheckforitbeforetryingtoinstallyourown.
AfteryouaddtheschematoanyoftheseLDAPservers,indexthesudoUserattribute.Thisgreatlyacceleratessudolookups.
Next,I'llbrieflytouchonaddingtheschemastoallthreeLDAPservers.
AddingSudotoOpenLDAP
ToaddthesudoschematoOpenLDAP,copytheschematoyourschemadirectory(usually/etc/openldap/schema/)asthefilesudo.schema.Thenaddthefollowinglinestoslapd.conf.Youprobablywanttoplacethesestatementsneartheotherschemaandindexstatements:include/etc/openldap/schema/sudo.schemaindexsudoUsereq
Restartslapd,andOpenLDAPwillsupportsudopolicies.
AddingSudotoiPlanet
Copytheschemafiletotheserverschemadirectory.Thisdirectoryvariesbyoperatingsystem,socheckyourserverdocumentation.Giveitthename99sudo.ldif.Restarttheserver.
NowuseyourLDAPbrowsertocreateaServiceSearchDescriptorforsudoers.serviceSearchDescriptor:sudoers:ou=sudoers,dc=example,dc=com
You'reready.
AddingSudotoActiveDirectory
CopytheActiveDirectoryschemafiletoadomaincontroller,andrunthefollowingcommand.
C:>ldifde-i-fschema.ActiveDirectory-cdc=Xdc=example,dc=com
That'sit.
CreatingSudoPolicyinLDAPThesudopolicyneedsacontainerandaninitialpolicy.Here'showtohandleeach.
SudoersContainer
YoursudopolicyneedsanLDAPcontainer.MostLDAPadministratorshaveverydefiniteideasaboutwherenewcontainersforadd-onsoftwarebelong.Obeyherwishesinthematter–LDAPcausesherenoughgrief,shedoesn'tneedanylipfromyou.Forreference,herearethedefaultlocationsforeachmajorserver:
OpenLDAP:ou=SUDOers,dc=example,dc=comActiveDirectory:cn=sudoers,cn=Configuration,dc=example,dc=comiPlanet:ou=sudoers,dc=example,dc=comDespitecallingthecontainer"sudoers,"rememberthatanLDAP-basedpolicydoesn'tworkquitelike
asudoersfile.Here'sanLDIFforasudocontainerfortheOpenLDAPserverformwlucas.org.Forotherserversor
othercontainerlocations,changetheDistinguishedNamepath.dn:ou=SUDOers,dc=mwlucas,dc=orgobjectClass:topobjectClass:organizationalUnitou:SUDOers
Importthisintoyourserver,eitherthroughthecommandlineorthroughyourbrowser.NowyoucancreateyourinitialLDAPsudoerspolicy.
Converting/etc/sudoerstoLDAP
Theconvenientthingaboutswitchingfroman/etc/sudoerspolicytoanLDAP-basedpolicyisthatyoudon'tneedtocreatetheLDAPentriesfromscratch.YoucanconvertanexistingsudoersfiletoanLDAP-friendlyLDIFfilewiththescriptsudoers2ldif,includedinthesudosuite.It'saPerlscript,usuallyinstalledaspartofanLDAP-awaresudopackage.
Beforerunningsudoers2ldif,youneedtosettheSUDOERS_BASEenvironmentvariabletothelocationofthesudopolicycontainer.ThecommandusesthisvariabletoputthecreatedLDIFinthecorrectpartofthedirectorytree.$SUDOERS_BASE=ou=SUDOers,dc=mwlucas,dc=org$exportSUDOERS_BASE
Nowrunsudoers2ldif,givingyoursudoersfileasanargument.$sudoers2ldif/etc/sudoers>/tmp/sudoers.ldif
ThisspitsoutanLDIFversionofyoursudoerspolicy.Onenicefeatureofsudoers2ldifisthatitfillsinthesudoOrderattribute,orderingyourrulessothatthe"lastmatch"rulesprocessingworks.See"SudoersPoliciesversusLDAPPolicies"earlierinthischapterfordetails.
YoucouldjustimportthisfileintoyourLDAPserverandbedonewithit,butthatwouldleaveyou
blindlytrustingthatthescriptworked.Let'sseewhatkindofentriesyoursudoersfilebecomes.
SudoersintoLDIF
Let'sstartwithaverysimple/etc/sudoers.Defaultsenv_keep+="HOMESSH_CLIENTSSH_CONNECTION\SSH_TTYSSH_AUTH_SOCK"%wheel,%sysadminsALL=(ALL)ALL
WeretainseveralenvironmentvariablestoallowSSHagentforwarding,andthenweallowanyoneinthegroupswheelandsysadminstorunallcommandsviasudo.Essentially,thissudopolicyreplacessuwithsudo.
WhatdoesthisbecomeasanLDIF?Wewillgothroughdescriptionsofallthevariousschemafieldslater,butthegeneratedLDIFisprettyeasytounderstand.We'lllookateachentryseparately.dn:cn=defaults,ou=SUDOERS,dc=mwlucas,dc=orgobjectClass:topobjectClass:sudoRolecn:defaultsdescription:DefaultsudoOption'sgoheresudoOption:env_keep+="HOMESSH_CLIENT
SSH_CONNECTIONSSH_TTYSSH_AUTH_SOCK"sudoOrder:1
Thisentryisnamed"defaults,"accordingtothednstatement.TheobjectClassstatementsattachthistothesudopolicy.ThesudoOptionstatementgivestheactualsudorules.Finally,sudoOrderputsthissudorulefirstinthelistofrulestoprocess.
Here'sthesudoerslinegivingtwogroupspermissiontorunallcommandsasroot,writtenasanLDIF.dn:cn=%wheel,ou=SUDOERS,dc=mwlucas,dc=orgobjectClass:topobjectClass:sudoRolecn:%wheelsudoUser:%wheelsudoUser:%sysadminssudoHost:ALLsudoRunAsUser:ALLsudoCommand:ALLsudoOrder:2
ThisrulehastwosudoUserentries,oneforeachgrouptheruleappliesto.There'sasudoHostentrytoshowthisruleappliestoallhosts,andasudoRunAsUserindicatingthatthisruleletstheseusersruncommandsasallotherusers.ThesudoCommandentrylistsallthecommandsthisrulecovers.
Rememberthatentriesappearwithinaniteminnoparticularorder.ThisrulehastwosudoUserentries,oneforwheelandoneforsysadmins.Thewheelgrouphappenstoappearfirstinthislist,butinalivequeryitmightbereversed.Iforderisimportant,youneedtomakeasecondruleandputitinorderusingthesudoOrderattribute.
YoucanimportthisinitialpolicyintoyourLDAPserver,thenconfigurethesudoclienttopull
ActivatingSudoClientLDAPYourLDAP-awaresudoclienthastheabilitytoaskLDAPforsecuritypolicies,butitprobablywon'tdothatbydefault.YoumusttellsudowheretofindtheLDAP-basedpolicy,andthenconfiguresudotousethatpolicy.
FindingtheLDAPPolicy
IsaidearlierthatIassumeyouhaveaworkingLDAPsetup.ThismeansthatyourlocalmachinecanpulluserandgroupinformationandpasswordsfromyourLDAPdirectory.Thissimplifiessudoconfiguration,becauseyouonlyneedtoworryaboutthesudoportionofLDAP.
Startbyrunningsudo–VtoaskyoursudoinstallwhereitexpectstofinditsLDAPconfigurationfile.$sudo-V|grepldap…ldap.confpath:/etc/ldap.confldap.secretpath:/etc/ldap.secret
Thisparticularsudoinstallexpectstofindldap.confandldap.secretin/etc,thedefaultforthisoperatingsystem.
Mostoperatingsystemscanshareasingleldap.confbetweenallapplications.ThisletsyoursudoinstallpiggybackonyourworkingLDAPconfiguration.Someoperatingsystemsusesudo-specificLDAPconfigurations.Fortheseoperatingsystems,youcanusuallycopythebasicLDAPconfigurationfromthemainsystemfiletothesudo-specificfile.Checkyouroperatingsystemmanualifyouhaveanyconcerns.[10]
NowaddthesudoLDAPconfigurationtoyoursudo'sldap.conf.Sudoacceptsthreedifferentldap.confstatements,butonlysudoers_baseismandatory.
sudoers_base:Thisisthemandatorylocationofthesudoerspolicy.Youcanhavemultiplesudoers_baseentries.Sudowillquerythemintheordergiveninldap.conf.
sudoers_search_filter:ThisisanoptionalLDAPsearchfiltertoreducethenumberofresultsreturnedbyanLDAPquery.Sudoworksfinewithoutthisfilter.
sudoers_timed:Thisisayes(ortrue,oron)orno(orfalse,oroff)settingtotellsudotochecktoseeifasudoersrulehasexpired.See"LDAPPolicyExpiration"laterinthischapter.
Thestandardldap.confentryforsudoonmynetworklookslikethis:sudoers_baseou=sudoers,dc=mwlucas,dc=org
Olddocumentationmentionssettingsudoers_debuginldap.conf.Thisisdeprecated,andthesettingwillbeburiedinanunmarkedgravebeforelong,sodon'tstartusingitnow.Tologsudo'sinteractionswithLDAP,usetheLDAPloggingsubsystemdescribedinChapter12.
NowthatyourLDAPclientscanfindthesudopolicy,tellsudotolookatLDAP.
Sudoandnsswitch.conf
Use/etc/nsswitch.conftotellsudotolookatLDAP.Thenameserviceswitchconfigurationfileusuallytellsprogramswheretolookforinformationsuchashostnamesandusernames.Sudogetslumpedinwiththerestofthem.UseanentrylikethistotellsudotocheckLDAP:sudoers:ldapfiles
Sudowillchecktheinformationsourcesintheorderlistedhere–firstLDAP,then/etc/sudoers.Ifyoursudoinstallshouldneverusethelocalsudoersfile,removethefilesstatementfromthisline.Youshouldalsoaddtheignore_local_sudoersoptiontoyourLDAPpolicy,aswe'llseelater.
SudoRulesandRolesAone-linesudopolicyin/etc/sudoersbecomesasingleLDAPentry,calledasudoRole.Bothoftheentrieswelookedatinthe"SudoersintoLDIF"sectionearlieraresudoRoles.
Allsudoattributeshavespecificpermittedvalues,mostcommonlyusernames,groups,orcommands.Youcannotenteraninvaliddatatypeintoanattribute–anattributethatexpectsausernamewon'tacceptanIPaddress,andtheLDAPserverwillrejectitifyoutrytosetitincorrectly.Mindyou,theLDAPservercan'tknowifmikeisahostnameorusername,soyoumustverifythatthesyntactically-validruleyoujustwroteistheruleyouwanttowrite.TheonespecialvalueisALL,whichmatchesallpossibleentriesforthatattribute.
AllsudoRoleshavetheDistinguishedNames(DN)attribute,thesudoRoleobjectClassattribute,andtheCommonName(CN)attribute.LDAPneedsthem,afterall.ButthreeadditionalattributesmustappearineverysudoRole,andafewoptionalattributescanappearwhenuseful.ThethreemandatoryattributesaresudoUser,sudoHost,andsudoCommand.
sudoUser
ThesudoUserattributeisausername,exactlylikethoseusedinasudoerspolicy.Remember,youcannotusealiasesinasudoUserattribute.Youcanuseoperatingsystemgroups,groupIDs,andnetgroups.Ifyouwanttousenon-systemgroupsinLDAPrules,youmustaddapluginforthemtoeachlocalsudoinstall.GroupsstoredinLDAPworkfine,sousethemratherthanjumpingthroughtheseextrahoops.EachusernamemustappearinitsownsudoUserentrywithinasudoRole.sudoUser:%wheelsudoUser:mikesudoUser:kurt
sudoHost
Thisisalistofhosts,withthesamesyntaxandrestrictionsasahostentryinasudoersrule.Youcanusehostnames,IPaddressesandnetworks,andnetgroups.ALLmatchesallhosts.sudoHost:192.0.2.0/24sudoHost:www.michaelwlucas.comsudoHost:+dbservers
sudoCommand
Thisisthefullpathtoacommand,plusanycommand-lineargumentsandwildcards.Thisisexactlylikethecommandlistinsudoers,exceptthatyoucannotusealiases.ALL,justasinsudoers,matchesallcommands.
Youcanusethewordsudoeditfollowedbyafilenameorpathtopermituseofsudoeditonthosefiles.Similarly,puttingadigestalgorithmandadigestbeforeacommandtellssudotoverifythedigestbeforerunningthecommand.
sudoCommand:sudoedit/etc/namedb/named.confsudoCommand:sha224:d14a028c…/usr/bin/passwdsudoCommand:/sbin/dumpsudoCommand:/sbin/restore
InadditiontothesudoRole'sthreemandatoryattributes,LDAP-basedpolicieshavefouroptionalattributesthatletthemfullyemulatesudoerspolicies:sudoRunAsUser,sudoRunAsGroup,sudoOptions,andsudoOrder.
sudoRunAsUser
ThesudoRunAsUserattributegivesalistoftargetusersthatsudouserscanruncommandsas.ThisworksexactlyliketheRunAslist(seeChapter4)forsudoers.ThewordALLmatchesallusers.sudoRunAsUseralsoacceptsuserIDnumbers,groups,ornetgroups.ListeachtargetinitsownsudoRunAsUserentry.sudoRunAsUser:oraclesudoRunAsUser:postgres
sudoRunAsGroup
Thisattributepermitsuserstoruncommandsasamemberofagroup.Thegroupshavethesamevalidnamesasgroupswithinasudoerspolicy.Listeachtargetgrouponitsownline.sudoRunAsUser:operator
sudoOrder
Thisattributeassignsrolenumber.Rolesareprocessedinorder,fromlowesttohighest.SudoOrderletsyouemulatethelastmatchingrulebehaviorfromasudoerspolicy.AsudoRolewithoutasudoOrderhasasudoOrderof0,andsoisprocessedfirst.IfyouhavemultiplesudoRoleswithoutasudoOrder,theyareprocessedintheorderservedupbyLDAP–thatis,randomly.
sudoRoleTimesLDAP-basedpoliciesletyousetactivationandexpirationdatesandtimesforasudoRole,afeatureyouwon'tfindinsudoers-basedpolicies.Sudochecksforactivationandexpirationtimestampsonlyifyouhavethesudoers_timedoptioninldap.conf.Withoutthisoption,sudoignorestimes.
ThesudoRoleattributessudoNotBeforeandsudoNotAftercontrolsudoRoletiming.Theseattributesacceptavalueofafour-digityear,followedbytwodigitseachformonth,day,hour,minute,second,andaone-digittenthofasecond.Or,ifyouprefer,YYYYMMDDHHMMSSZ.ThedateandtimeareinCoordinatedUniversalTime(UTC),notyourlocaltimezone.sudoNotBefore:201401011300000sudoNotAfter:201401312200000
ThesudoRolefortheexampleabovebecomesvalidon1January2014at13:00,andexpireson31January2014at22:00.Thesetimeslookweird,butmysiteisfivehoursaheadofUTC.Therulebecomesvalidat8AMlocaltime,andexpiresat5PMonthelastday.
ThissudoRoleisnotvaliduntilthedateandtimeinthesudoNotBeforeattribute.ItisnolongervalidafterthesudoNotAfterattribute.
IfyouhavemultiplesudoNotBeforeandsudoNotAfterattributes,themostpermissiveentryisused–thatis,theearliestsudoNotBeforeandthelatestsudoNotAfter.Ifyoutrytoputintwoseparatetimeranges,thesudoRolewillpermitaccessfromtheearlieststarttimetothelatestendtime.IfyouputinasudoRolethatsays"Thisruleisvalidforthefirst10daysofSeptember"andanothersudoRolethatsays"ThisruleisvalidforthelasttendaysofOctober,"theuserwillgetaccessfromthefirstofSeptemberto31October.RemoveobsoletesudoNotBeforeandsudoNotAfterattributesfromyourdirectory.
Arolewithuselessdatesnevergetsused.objectClass:sudoRolecn:mwlucassudoUser:mwlucassudoHost:ALLsudoCommand:ALLsudoNotBefore:201402030000000sudoNotAfter:201402301200000
Here,Theahasgrantedmetotalaccesstoallsystemsfortwelvehours.Onthe30thofFebruary.
DisablingsudoersThepointofputtingsecuritypoliciesinLDAPissothatuserswhofinagletheirwayintoediting/etc/sudoerscannotwriterulesthatgivethemselvesmoreaccess.WeconfiguredsudotolookatLDAPfirstforitspolicy,whichisagoodstep.Nowweneedtodecideifwewanttohavealocalsudoersfile.
Ifwehavealocalsudoerspolicyfile,usersmightfigureouthowtoeditit.IfLDAPtellssudotoignorethelocalsudoerspolicy,itdoesn'tmatterifuserseditsudoersornot;theydon'tgetextraaccess.TheriskyougetisthatwhenyourLDAPsystemsfail,you'lllosesudoaccessonyourLDAPclients.See"LDAPCaching"laterthischapterforpossiblesolutions.
Tellsudotocompletelyignore/etc/sudoers.withtheignore_local_sudoersoptioninLDAP.Addignore_local_sudoerstoyourdefaultpolicy.ThestandardlocationforthispolicyontheOpenLDAPserverforadomainwouldbeattheDistinguishedNamecn=defaults,ou=sudoers,dc=example,dc=orgdn:cn=defaults,ou=SUDOERS,dc=example,dc=orgobjectClass:topobjectClass:sudoRolecn:defaultsdescription:DefaultsudoOption'sgoheresudoOption:env_keep+="HOMESSH_CLIENT
SSH_CONNECTIONSSH_TTYSSH_AUTH_SOCK",ignore_local_sudoers
sudoOrder:1
WhensudoseesthisoptioninLDAP,itstopslookingatthelocalsudoersfile.Doyouwanttodisablelocalsudoerspolicies?Probably.AnLDAPclientwithoutLDAPwon't
functionproperlyanyway,soyou'llmanymoreproblems.Theoptionisyours,however.
LearningsudoRolepoliciesIfmanagingLDAPisn'tyourmainjob,butyouwanttosupportsudopoliciesviaLDAP,yougettolearnanewskill.Onceyouunderstandwritingsudoerssecuritypolicies,expressingthesamethinginLDAPisn'tthatmuchharder.
Ifyougetconfused,sudoers2ldifisyournewfriend.YouwanttoknowhowtowriteanLDIFversionofaparticularsudoersrule?Writeaone-linesudoersfilethatcontainsonlyyourdesiredrule,thenrunsudoers2ldiftoseetheresult.ModifyinganexampleLDIFismucheasierthanwritingonefromscratch.Soon,you'llbewritingandeditingsudoRoleLDIFseffortlessly.Don'ttelltheLDAPadministratoryoucanwriteLDIFs,however,orshemighttrytosuckyouintowritingmoreofthemforotherpeople.
IknowpeoplewhouseLDAPtodistributetheirsudopoliciesbutactuallywritethepoliciesinsudoersformatandthenusesudoers2ldiftogeneratetheLDAPconfiguration.ThisautomaticallyhandlesruleorderingwithsudoOrder.Thisisaperfectlyacceptablesolution,andifyou'renotcomfortablewithLDAPitmightevenbeadvisable.
LDAPCachingThebigriskwhenusingLDAPforauthenticationandpolicydistributionisthatyournetworkbecomesdependentontheLDAPservers.HopefullyyouhaveatleasttwoLDAPservers,distributedinsuchawaythattheyresistmostfailurescenarios.AndhopefullyyouhaveenoughLDAPserversthatafailureofasubstantialfractionofthemwon'toverloadthesurvivors.
YoucanchoosetocacheLDAPinformationlocallyoneachmachine,totidetheserversthroughabriefoutage.TheSystemSecurityServicesDaemon(SSSD)providescachingservices.SSSDisafairlynewprogramcreatedaspartoftheFedoraproject,anditssupportfornon-Linuxsystemsismixedbutimproving.
Asofsudo1.8.4,youcanbuildsudowithSSSDsupport.Sudo-sssdletsyouaddSSSDasanadditionalinformationsourcevia/etc/nsswitch.conf.ThisletssudoreferencethecachedsecuritypolicyeveniftheLDAPserversaredown.YoucanconfigureSSSDtoproactivelydownloadthesudopolicyfromtheLDAPserversoit'spreparedforanLDAPfailure.
Mostoperatingsystemsdon'thaveapackageforsudowithSSSDsupport.Ifyou'reusingSSSD,considerusingitforsudoaswell.GivenSSSD'smixedsupportoneveryoperatingsystemexceptLinux,I'mnotgoingtocoveritindetailhere.IfSSSDsupportsyouroperatingsystem,youcanfindausefultutorialonusingsudowithSSSDathttp://jhrozek.livejournal.com/2065.html.
Nowlet'slookatsudologging.It'smoreusefulthanyouthink.
Chapter12:SudoLogging&DebuggingYoucannowcontrolwhataccesspeoplehavetoprivilegedcommands.Everything'sgood,right?Certainly...untilthedayyouwalkinandfindhalfyourservershangingbecausetheir/usrfilesystemshavefledforpartsunknown.Everybodywillwanttoknowwhotheidiotwas.Sudohasthreedifferentloggingmechanisms:asimple"whatsudodid"logviasyslogd,adebugginglog,andafullsessioncapturelog.Sudocanalsonotifythesystemownerwhenuserssucceedorfailtoruncommands.
SudoandSyslogdSudologsuseractivitythroughthestandardsyslogprotocol.OnyouraverageUnix-likesystem,sudologsshowupinafilelike/var/log/messagesor/var/log/syslog.Here'satypicalsudologmessage:Aug2723:34:44www9sudo:mike:TTY=pts/1;PWD=/home/mike;USER=root;COMMAND=/usr/bin/passwdcarl
Wehavethedateandtimesomeoneransudo,andthemachinename(www9).Thenwehavetheuserwhoransudo(mike),theterminalhewason(pts/1),thedirectoryhewasin(/home/mike),whoheranthe
commandas(root),andthecommandheran(/usr/bin/passwdcarl).[11]
Sudoalsologswhenausercan'trunacommand.Aug2723:35:25pestilencesudo:mike:commandnotallowed;TTY=pts/1;PWD=/home/mike;USER=root;COMMAND=/usr/bin/passwdroot
Notethestringcommandnotallowed.Lookslikesomeone'stryingtoescapethecageinhiscubicle.Again.Thebossneedstohaveawordwithhim.Again.
CustomizingSudoSyslog
Thedefaultconfigurationhassomeweaknesses,though:thelogfile'slocationonthelocalsystem,andthelogsevenexistingonthelocalsystematall.
OnmostUnix-likesystems,sudologsgetdumpedintothemainsystemlog,alongwiththelogsfromalltheotherprogramsrunningonthemachine.Thismakesthelogsmorecomplicatedtosearchthantheyneedtobe.Also,successesandfailuresareloggedtogether.Youneedbothsortsoflogmessages,butyoudon'twantthemsimultaneously.Creatingonelogforsuccessesandoneforfailureswillsimplifytroubleshooting.
SudousestheLOCAL2logfacilitybydefault.Successfulsudorunsgetprioritynotice,whileunsuccessfulonesgetthehigherpriorityalert.Thismeansyoucaneasilysplitthetwotypesofsudoresponsesintoseparatelogfiles.Here'showyouwoulddothisonasystemrunningtraditionalsyslogd.local2.=notice/var/log/sudolocal2.=alert/var/log/sudofail
Touchthetwofilesandrestartsyslogd.Logsofsuccessfulsudousegoto/var/log/sudo,whileunsuccessfulsudoattemptsgoto/var/log/sudofail.
Youcanchangethelog'sfacilityandtheprioritiesusingtheoptionssyslog,syslog_badpri,andsyslog_goodpri.Thisletsyouavoidconflictswithothersoftwarethatusessudo'sdefaultprioritiesandadjusttheprioritiestoaccommodateanylogmonitoringsoftwareyoumighthave.Here'sasudoerspolicyforcustomlogging.Defaultssyslog=local6,syslog_badpri=crit,\
syslog_goodpri=info
Mostsyslogdimplementationsletyousplitoutlogsbyprogramnameaswell.Separatingoutthesudologopensupsomeinterestingcustomerservicepossibilities.Repeatedsudo
failuresareevidenceofaproblem.Eitherauseristestingtheirlimits,orthey'retryingtodotheirjobbut
failing,orthey'reflailingaroundhelplessly.Nowyoucanhaveahelpdeskflunkypickupthephoneandsay"Hey,weseeyou'rehavingtrouble."Theenduserwilleitherfeellikeyouarewatchingoutforthem,oryou'rewatchingthemveryclosely.Eitherway,alittlebitofomniscienceneverhurtsyourreputation.
SyslogSecurityProblems
Almostallsyslogimplementationswritelogstothelocalmachinebydefault.Thisisaproblemforsudo,becauseausermightalterthelogfiles.Ifasysadminwantstoseewhatherusersdoonhermachines,sheneedtoautomaticallylogtoremotemachines.Thiscopymusthappeninrealtime.Havesyslogsendalllogmessagestoacentrallogginghost.Thissyslog.confentryforstandardsyslogdsendsallmessagestoahostcalledloghost.*.*@loghost
Ifyoucan'tsendallthesystemlogs,atleastsendthesudologs.local2.=notice/var/log/sudo,@loghostlocal2.=alert/var/log/sudofail,@loghost
Finally,useasyslogdaemonthatsecurelytransmitsmessagestoyourlogginghost.Programssuchassyslog-ngandrsyslogletyoutransmitlogsencryptedviaSSLand/ortransportthelogsviaTCP.
SudoandEmailSudonormallysendsemailtothesystem'srootaccountwheneverausertriestousesudobutfails.Youcanadjustwhensudonotifiesyouofevents,orwhetheritnotifiesyouatall,withtheoptionsmail_always,mail_badpass,mail_no_host,mail_no_perms,andmail_no_user.Thesenotificationscanquicklyalertwhenauserishavingtroublewithsudo.Theycanalsohelpfindintruders–afterall,ifyourwebserveruserstartstryingtousesudo,youwanttoknowassoonaspossible!
Astandardsudoinstallemailsrootwheneverauserhasaproblemwithsudopermissions,eithertryingtorunacommandtheydon'thaverightstooriftheydon'tappearinthesecuritypolicy.Ifnobodyreadsemailsaddressedtorootonthelocalsystem,thoseemailswillpileupandeventuallyfillyourharddisk.Eitherforwardsudoemailstoanaccountwheresomeonewillreadthem,ordisableemailnotifications.
Themail_no_userflagtellssudotosendanemailnotificationwheneverauserwhodoesn'tappearinthesudopolicyattemptstorunsudo.Sudonormallyenablesthisoptionbydefault,andyou'veprobablyseenthisemailbefore.
Themail_no_permsoptionsendsanotificationwheneverausertriestorunacommandthattheyaren'tpermittedaccessto.Ifindthisnotificationusefultoquicklyfinduserswhoarestrugglingtoperformroutinetaskswithsudo.
Doyouwanttoknowwhenusershavepasswordtrouble?Usethemail_badpassoptiontosendemailwheneverauserentersanincorrectpassword.Ifindthisgeneratestoomanymessagesthatdon'trequireanyaction.
Maybeauserislistedinthesudoersfile,butdoesn'thaveaccesstosudoonthisparticularhost.Themail_no_hostoptiontellssudotosendanemailwheneverausertriestousesudobutdoesn'thavesudoaccessonthathost.
Themail_alwaysoptionsendsanemailanytimeanyoneusessudo,successfullyornot.Youmightwantthisfortesting,butcertainlynotinproduction.
SudoDebuggingSometimessudocandriveyoutothebrinkofmadness.Writingapolicyissimpleenough.Runningthesudocommandisprettyeasy.Butthingsdon'talwaysworkasyouexpect.Whileit'sconceivablethatyou'vediscoveredalegitimatesudobug,thetruthisthatyouprobablydon'treallyunderstandhowsudointerpretsyourpolicy.
Debuggingletsyouwatchsudoasitprocessesyourpolicy.Youcanseeexactlyhowsudomakesdecisionsandadjustyoursudoerspolicytoworkthewayyoudesire.Configuresudologgingin/etc/sudo.conf.
SudoSubsystemsandLevels
Ifyou'veconfiguredsyslog,sudologgingshouldlookveryfamiliar.Logmessagesaredividedintolevelsandsubsystems.
Alevelisameasureofseverityorpriority.Thelowestlevel,debug,includeseverytrivialbitofcrudthatpassesthroughsudo.Thehighestlevel,crit,onlyincludesproblemsthatkeepsudofromrunningcorrectly.Inorderfromleasttomostsevere,thelevelsare:debug,trace,info,diag,notice,warn,err,andcrit.Whichleveldoyouneed?Thatdependsonhowmuchdetailyouwant.Ifindthatnoticelevelisenoughtoidentifymostproblems.Thedebugandtracelevelsproducehundredsoflinesofoutputevenforsimplecommandslikesudo–l,butareveryusefulwhenreportingsudoproblemstothemailinglist.Likesyslog,settingasudodebuglevelwilllogeverythingofthestatedpriorityorhigher.Ifyouchoosetolognoticelevelevents,yougetnotice,warn,err,andcritlevels.
Inadditiontoseveritylevels,sudologsviasubsystems.Youcanlogactivityfromeachsubsystemseparately.Ifyouhaveaproblemwithsudoedit,youcanspecificallylogonlysudoeditevents.Ifsudoseemstomatchthewrongper-hostrules,youcanlognetworkinterfacehandlinginbothsudoandthesudoerspolicy.
Thesudocommandlogsfromthefollowingsubsystems:args–commandargumentprocessingconv–userconversationedit–sudoeditexec–commandexecutionmain–sudomainfunctionpcomm–communicationwiththepluginplugin–pluginconfigurationselinux–SELinux-specificeventsutmp–utmphandlingSudoerspolicyprocessinghasthefollowingsubsystems:alias–processingforallaliases
audit–BSMandLinuxauditcodeauth–userauthenticationdefaults–sudoersDefaultssettingsenv–environmenthandlingldap–LDAPhandlinglogging–loggingeventsmatch–matchingusers,groups,hosts,andnetgroupsnss–networkserviceswitchhandlingparser–sudoersfileparsingperms–permissionsprocessingplugin–pluginmainfunctionrbtree–redblacktreeinternalsBothsudoandthesudopolicypluginsharethesefollowingsubsystems:All–logeverythingfromeverywherenetif–networkinterfacehandlingpty–pseudo-ttyrelatedeventsutil–utilityfunctionsNotsurewhatsubsystemtolog?StartwithAllandtrimdownfromthere.
ConfiguringDebugLogging
Configurelogginginsudo.conf.Theentryneedsfourparts:theDebugstatement,theprogramorplugintobedebugged,thelogfilelocation,andthesubsystemsandlevelstobelogged.Debugsudo/var/log/sudo_debugall@notice
TheDebugsudostatementappliestoboththesudoprogramandthesudoerspolicy.Thisexamplelogstothefile/var/log/sudo_debug.Wespecificallylogallsubsystems,atnoticelevelandabove.
Youcanlogdifferentsubsystemsatdifferentlevels.Ifyouareexperimentingwithsudo'sauthenticationsystem,youmightwanttocrankupauthenticationlogging.Debugsudo/var/log/sudo_debugall@notice,auth@debug
YoucanonlyhaveoneDebugstatementperprogramorplugin.Thismeansyouonlygetonelogfileforstandardsudodebugging,asthesudoprogramandthesudoerspolicysharethesudoDebugstatement.Ifyouareusingadifferentpolicyplugin,itcanhaveitsownDebugstatement.
DebuggingLDAP
OneofthecommonusesofthedebugginglogistofigureouthowsudoisinteractingwithLDAP(seeChapter11).OriginallyyouconfiguredLDAPdebugginginldap.conf,butthatputthedebuggingoutputintheuser'swindowwhenevertheyransudo.Thatwasscary.It'snowpartofthesudologgingsystem.
TologbasicLDAPinteractions,logtheldapsubsystem.Basicdebuggingisavailableatinfolevel,
whiledetailedlogginglivesatdebug.Debugsudo/var/log/sudo_debugall@notice,ldap@info
SudowillnowrecorditsLDAP-relatedactivityinthedebuglog.
DebugUsefulness
Sudohasalotofsubsystems.Someofthem,likeLDAPandenvironmentpurging,produceveryusefullogsforsystemsadministratorstryingtounderstandwhatsudoisdoing.Others,likethemainroutine,produceoutputmeaningfulonlytopeoplewhoprogramsudo.Ifyou'retryingtounderstandaweirdsudobehaviorandyoucan'tseeanythingusefulinthelog,increasethenumberofsubsystemsyou'reloggingand/ortheloglevel.Worstcase,loggingeverythingatthedebuglevelwillgetyoualltheinformationsudoproduces.Afterthat,you'llhavetofallbacktoprogramsliketrussorstraceandthesudo-usersmailinglist.
SudoreplaySudousessyslogtorecorduseractivity.Wecandebugsudoandcreateasudoprogramlogfile.Butwhataboutdetailonwhatpeopledidwithincomplicatedprivilegedsessions?Whatiftheyfiredupaninteractivesystemadministrationtoollikesadmorplainold/bin/sh?Entersudoreplay.
Thesudoprocessistheparentofanycommandrunundersudo.Thismeansthatthesudoprocesscanseeanyinputoroutputofthatcommand.Sudocanlogtheinputandoutput,giveitatimestamp,anddisplayitexactlyasithappened.
Enableoutputloggingwiththelog_outputoption.Donotlogtheoutputfromsudoreplayitself,asyou'llquicklyfillyourdiskwithlogmessages.Andloggingoutputfromtherebootandshutdowncommandscandelaythesystem'sshutdownandrecovery,assudoreplaytriestologanyshutdownmessagesondiskthat'sjustbeenunmountedaspartoftherebootprocess.Defaultslog_outputDefaults!/usr/bin/sudoreplay!log_outputDefaults!/sbin/reboot!log_output
Thedefaultdirectoryforsudologgingis/var/log/sudo-io,butyoucanchangethiswiththeiologoption.Youcanalsoenableinputloggingwiththelog_inputoption.Thisismoreproblematicasinputmight
containpasswordsorothersensitiveinformation.Thelog_inputoptiononlylogswhat'sechoedbacktotheuser,butsomeprogramsprintsensitiveinformation.Iftheuser'sinputdoesnotappearintheterminalwindow,thensudo'sinputlogwon'tstoreit.Defaultslog_input
Mostofthetime,outputloggingsufficestoseeexactlywhatauserdid.Ifyouneedinputlogging,it'savailable.
Youcanenableanddisableinputandoutputloggingonaper-commandbasiswiththeLOG_INPUT,NOLOG_INPUT,LOG_OUTPUT,ANDNOLOG_OUTPUTtags.Ifyouwanttologhowusersapplycertaincommands,usethesetagsinthecommand-specificrules.
ListingLoggedSudoSessions
EnableI/Ologgingonyourtestmachineandrunafewcommandsundersudotocreatesomelogs.Usethesudoreplaylistmode(–l)asroottoviewthelistofloggedsessions.#sudoreplay-lSep119:53:422013:mike:TTY=/dev/pts/1;CWD=/usr/home/thea;USER=root;TSID=000001;COMMAND=/usr/bin/passwdSep120:04:422013:thea:TTY=/dev/pts/2;CWD=/usr/home/thea;USER=root;TSID=000002;COMMAND=/usr/local/bin/emacs/etc/rc.conf…
Eachlogentryincludesseveralfields,delimitedbyeithercolonsorsemicolons.Westartwiththefulldate,inlocaltime.Ourfirstlogentrywasrecordedat19:53:42,or7:53PM,on1September2013.
Thenextfieldistheuserwhoranthecommand–inthefirstentrymike,andinthesecond,thea.Thenthere'stheterminal.Sudorunsloggedsessionsinanewpseudoterminal,soitcancaptureall
inputand/oroutput.Theworkingdirectoryisnext.Editingthecopyof/etc/fstabinyourhomedirectoryisverydifferentfrom
editingtheactual/etc/fstab,andthisfieldletsyoudifferentiatebetweenthose.TheUSERfieldgivestheuserthecommandwasrunas.Here,bothTheaandIranacommandasroot.TheTSIDisthenameofsudo'slogentry.Ifyouwanttoviewtheactualsession,you'llneedthis
number.WhensudoI/Ologgingisenabled,sudoalsoaddstheTSIDtothesyslogmessage.Finally,theCOMMANDistheactualcommandrun.Forthefirstcommand,Iranpasswd,whileinthe
secondTheaedited/etc/rc.conf.Sudologsthefullpathtoallcommandsitruns.
ViewingSessions
Toviewanactualsession,givesudoreplaytheTSIDofthesessioninquestion.Inthatfirstsession,didIreallyrunpasswdtochangetherootpassword?#sudoreplay000001Replayingsudosession:/usr/bin/passwdChanginglocalpasswordforrootNewPassword:RetypeNewPassword:#
Yep,Ichangedtherootpassword.Sudoreplayshowssessionsinrealtime,exactlyastheyhappened.IfIwaitedafewsecondstotypea
password,thereplaysessionpausesexactlythere.ThereplayalsoappearstopausewhileItypedthepassword–there'snovisiblechangebecausetheterminaldidn'tdisplayanyoutputasItypedthenewpassword.
AlteringPlayback
Theabilitytoplaybacksessionsisuseful,butsometimesasessionrunstooquicklytomakesenseortooslowlytowatchcomfortably.
Tointeractivelychangethereplayspeedonlongersessions,youmightwanttosuspend,slowdown,oraccelerateplaybackspeed.Usethespacebartopauseareplay,andanykeytoresume.Alessthansymbol(<)reducesreplayspeedbyhalf,whileagreaterthansymbol(>)doublesit.
Ifyouknowbeforestartingthereplaythatyouwanttoadjustthereplayspeed,preemptivelyadjustthereplayspeedwiththe–mand–scommand-linearguments.
The–mflagsetsamaximumnumberofsecondstopausebetweenchanges,eitherkeypressesorscreenoutput.Maybeyou'veloggedtheoutputofacomplicatedinstallprocessthattookalongtimetorun,andyouwanttoreviewitwithtwosecondsbetweeneachscreenupdate.OrmaybeTheaknewfromthefirsttimeshesawthereplaythatIspentalotoftimesittingatthepasswordpromptwhenIchangedtherootpasswordwithoutauthorization,andshewantstospeedupthedisplayduringyetanotherHuman
Resources[12]
meeting.
$sudoreplay–m1
Usethe–sflagtochangethespeedoftheentirereplay.Thereplayspeedisdividedbywhatevervalueyougive.Ifyouuse-s4,thereplayrunsfourtimesasfast.Ifyouuse–s0.25,thereplayrunsatone-quarterspeed.$sudoreplay–s2
Between–sand-m,andwiththeinteractivecontrols,youcanadjustthereplayspeedasneededforanysituation.
SearchingSudoreplayLogs
Traditionally,youfiguredoutwhodidwhatbyusinggreponthedefaultsystemlog.Sudoreplay'slistmodealsoletsyousearchbycommand,user,RunAs,terminal,andmore.
Thecommandkeywordsearchesforacommandthatmatchesyoursearchterm.IfyouroperatingsystemsupportsPOSIXregularexpressions,yoursearchtermistreatedasaregularexpression.Otherwise,it'sasubstringmatch.HereIsearchforthepasswdcommandinthesudoreplaylogs:#sudoreplay-lcommandpasswd
Thecwdkeywordtellssudoreplaytolookforcommandsruninthegivendirectory.HereIsearchforallsudorunsinthe/etcdirectory:#sudoreplay-lcwd/etc
Don'tincludeatrailingslashonthedirectoryname.Also,thedirectorynamemustmatchexactly–searchingfor/etcwillnotmatch/etc/ssh.Rememberthatusersdon'thavetoruncommandsfromadirectorytoaffectfilesinthatdirectory–youcanrunvi/var/log/messagesfromtheirhomedirectoryratherthangoingintothe/var/log/directoryandrunningvimessages.
Tosearchforallsudosessionsrunbyaspecificuser,usetheaccountnameandtheuserkeyword.#sudoreplay–lusermike
Thegroupkeywordsearchesforcommandsrunasaparticulargroup.Theusermusthaveexplicitlyrequestedtorunacommandasthisgroup(i.e.,withsudo–g)forthisfiltertomatch.#sudoreplay–lgroupoperator
Tosearchforcommandsrunasaspecificuser,usetherunaskeyword.Sudorunscommandsasrootbydefault,sosearchingforrootwouldprobablygetyoualotofresults.#sudoreplay–lrunaspostgres
Youcanevensearchbyterminaldevicenamewiththettykeyword.Wanttoknowwhoransudoontheconsole?Usethettykeyword,butdon'tuse/dev/infrontofthedevicename.#sudoreplay–lttyconsole
Onepopularwaytosearchlogsisbydateandtime.Sudoreplayhasmanywaystofilterlogsearchesbytime,andIcoverthemostcommonlyusedhere.Ifyou'reinterestedinthefulldetails,checkthesudoreplaymanualpage,butanyprogramthatletsyousearchbyfortnightcontainsmoresearchoptionsthananysanepersonneeds.Itsupportsmanyvernaculartimeexpressionssuchas"lastweek,""today,""4hoursago,"aswellasdatesandtimes.
Tosearchforallsudousageonorafteragivendate,usethefromdatekeyword.#sudoreplay-lfromdate"lastweek"
Youmustquotemulti-worddatesearchterms.Toviewallsudousagebeforebutnotincludingagivendate,usethetodatekeyword.
#sudoreplay–ltodatetoday
Forsearchwordsliketoday,lastweek,afortnightago,andsoon,sudoreplayassumesthatthedaystartsatmidnight.
OtherpopulartimeformatsincludeexactdatesandtimeswithAMorPM.Herewesearchforwhathappenedbetween8PMand11:59PMonthefirstofSeptember,2013.#sudoreplay-lfromdate"8pm1Sep2013"todate"11:59pm1sep2013"
Whenyouusewordsformonths,thedayandmonthcanappearinanyorder.Ifyouusenumericalmonths,themonthmustappearfirst.Ifyoudroptheyear,sudoreplayassumesthatit'sthecurrentyear.Thisnextexamplesearchesforanyentriesafter4September.#sudoreplay-lfromdate"9/4"
Use"4/9"instead,andyou'llgetmatchesfrom9April.Iavoidconfusionbynamingmonths.Youcancombinesearchkeywordsbeyondjustdates.Theexamplebelowsearchesformyaccount
runningsudoafterthefirstofSeptember.#sudoreplay-lfromdate"9/1"usermike
Combinesearcheswiththeoroperator.#sudoreplay-lcommand/bin/shorcommand/bin/bash
Ifyouneedtogroupdifferentsearchterms,parenthesescanhelp.#sudoreplay–l(command/bin/shorcommand/bin/bash)usermike
FortunatelyIusetcsh,sothiswon'tcatchme.ThisshouldgetyouwellonyourwaytosearchingyourI/Ologs.Irecommendnotdrinkinganything
whenyoufirstperusewhatyourusersactuallyrunthroughsudo,asaspit-takewastesgoodcaffeine.
SudoreplayRisks
Sudoreplayisapowerfuladditiontoasystemadministrator'stoolkit,butitdoeshaveproblems.Ifyoulogsessioninput,youmightcapturesensitivedatasuchaspasswordsinthesudologs.Thoselogsareunencrypted,andatroublesomeuserwhocanweaselhimselfintoroot-levelaccesscouldfindthatinformation.
Thesudoreplaylogsthemselvesarestoredonthelocalsystem.Anunauthorizedusercoulddamage,alter,ordeletethoselogs.AsIwritethissudocannotstoreitsI/Ologsonaremotesystem,butsessionloggingisafairlynewfeature.Iexpectthatsomeonewillcreateasolutionforoff-serversessionlogstoragebeforelong.Thegoodnewsisthatsudoreplaylogsaremuchhardertoeditthanatextlogfile.WhiletheI/Ologcertainlyisn'ttamper-proof,unskilledtamperingwillbequiteobvious.
Chapter13:AuthenticationSudo'sauthenticationsystemlooksprettystraightforward:enteryourpasswordandrunaprivilegedcommand.Butsudowillletyouchangehowithandlesyourpassword,howoftenyoumustenteryourpassword,andifittakesapasswordatall.Youcantellsudotodemandstrongerauthenticationthanapasswordbyrequiring,say,anSSHagentorahardwaretokenorsomeotherauthenticationmethodI'veneverevenheardof,andhowithandlestoauthenticationmethods.
We'llstartwiththesimplestcase,passwordmanagement.
SudoPasswordConfigurationYoucancontrolhowsudorequestspasswords,howmanytimessudoletstheusertrytoenterapassword,andhowsudosharesauthenticationbetweenterminalsessions.
PasswordAttemptsandTimeouts
Sudogivesusersthreechancestoentertheirpassword.Maybeyouruserscan'tsuccessfullytypetheirpasswordsonthefirst,second,orthirdtry.Usethepassword_triesoptiontogivethemafewextraattempts.
Sudogivesauserfiveminutestotypetheirpasswordbeforetimingthemout.I,forone,findthisexcessive.Ifausercan'ttypetheirpasswordinsixtyseconds,Idon'twantthemonmyserver.Sadly,Theaisamoreaccommodatingsoulthanmyself.Usethepasswd_timeoutoptiontosetatimeoutinminutes.Defaultspasswd_tries=5,passwd_timeout=2
Usershavefivetriestoentertheirpassword,buttheirpasswordprompttimesoutintwominutes.Sudonormallydoesn’tgiveanyfeedbackwhenauserentersapassword.Ifyouwanttheusertosee
somethingwhentheytype,usethepwfeedbackoption.$sudo-lPassword:*********
Mostsecuritypeoplediscourageusingthepwfeedbackoption.Anyonewatchingtheusertypelearnsthelengthoftheuser'spassword.
TargetPassword
Oneofsudo'sfeaturesisthatitdemandstheuser'spasswordtoperformprivilegedactions,ratherthantherootpassword.Incertainenvironmentsthesystemownermightwanttheusertoenterthetargetuser'spasswordratherthantheirown–usuallyforauditcompliancereasons,inmyexperience.Usetherootpw,targetpw,andrunaspwoptionsforthis.
Therootpwoptiontellssudotorequiretherootpasswordratherthantheuser'spassword.Here,usersinthewheelgroupmustusetherootpasswordforsudo.Defaults:%wheelrootpw
Thetargetpwoptiontellssudotorequirethetargetuser'spasswordratherthantheuser'spassword.Iftheuserusesthe–ucommand-lineargumenttorunacommandasanotheruser,heneedstoenterthatuser'spassword.Defaultstargetpw
Finally,therunaspwoptiontellssudotorequirethepasswordofthedefaultRunAsuserinsteadoftheuser'spassword.YoumightwantuserswhorunanyprogramsintheOracledirectorytousetheoracleaccount'spasswordratherthantheirown.Defaults>oraclerunaspw
Betweenallofthese,youcancustomizethenecessarypasswordhoweveryouwant.Youdoriskconfusingtheuser,however.Ifonlytherewassomewaytotelltheuserwhichpasswordtheyneededtoenter…
CustomizingthePasswordPrompt
Sudo'spasswordpromptiskindofboring.Password:doesthejob,butthepasspromptoptionletsyoudomoreinterestingthings.Defaultspassprompt"Yourwussypasswordis:"
Thisismildlyamusingatbest.Butusingescapecharactersinthepasswordpromptstringmakesthecustompromptuseful.
Tousethemachine'shostnameinthepasswordprompt,use%Hor%h.%histheshorthostname,while%Histhefullyqualifiedhostname.Sudocanonlygetthefullyqualifiedhostnameifthefqdnoptionissetorthehostnamecommandreturnsthefullyqualifiedhostname.Defaultspassprompt="Yourpasswordon%his:"
Tonametheuserwhosepasswordsudoexpects,use%p.Thisremindsuserswhatpasswordtoenterwhenyou'reusingtherootpw,runaspw,andtargetpwoptions.Defaultspassprompt="Enter%p'spassword:"
Tonametheuserwhothecommandwillrunas,use%U.Ifyourusersfrequentlyruncommandsasusersotherthanroot,thiscanhelpthemkeepthingsstraight.Heck,ithelpsmekeepthingsstraight.Defaultspassprompt="Enter%p'spasswordtoruncommandas%U:"
Tonametheuserrunningsudo,use%u.Ifyouhavemultipleuseraccounts,thismightalsohelpyoukeepthemstraight.Defaultspassprompt="%u:enter%p'spasswordtoruncommandas%U:"
Ifyouneedapercentsigninyourprompt,usetwoconsecutivepercentsigns(%%).Thepasspromptoptionexpectsthatthesystem'sauthenticationsystem(PAMorsimilar)usesapassword
promptofPassword:.Ifyoursystemusessomethingelseasapasswordprompt,usetheoptionpassprompt_overridetostopthatcheckandinsistthatsudouseyourcustomprompt.
AuthenticationCachingandTimeout
Sudodoesn'tcacheyourpasswordorotherauthenticationcredentials.Itdoesrememberthedateandtimethatyoulastsuccessfullyauthenticatedinagiventerminalsession,however.Thisletsyourunsudoagainwithinthenextfewminuteswithoutusingapassword.Youcancontrolhowsudotreatsthiscacheandhowlongsudowillruncommandsforyouwithoutre-enteringyourpassword.Ifyourunsudo–Vasrootandsearchforthestringtimestamp,you'llseesudo'sauthenticationtimingsettings.#sudo-V|greptimestampAuthenticationtimestamptimeout:5.0minutesPathtoauthenticationtimestampdir:/var/db/sudo
Onceyouenteryourpassword,youwon'tneedtoenteritagainforfiveminutesinthatterminalwindow.Changethiswiththetimestamp_timeoutoptionandanumberofminutesforthetimeout.Usea0todisablethetimestamp.Defaultstimestamp_timeout=0
Ifyouuseanegativevalue,thetimestampwillneverexpire.Don'tdothat.
Accordingtosudo–V,thetimestampsareinthe/var/db/sudodirectory.Changethedirectorywiththetimestamp_diroption.Whilerootnormallyownsthedirectoryandthetimestampsinit,youcouldchangethiswiththetimestamp_owneroption.Istronglyrecommendthatyouleavethesesettingsatyouroperatingsystemdefaultsunlessyouroperatingsystemvendororthesudodeveloperstellyoutochangethem.
UserUpdatingAuthenticationTimeouts
Userscaninteractwiththeauthenticationcachebyeitherupdatingthetimetheylastauthenticatedorbyeradicatingthecachedcredentials.
Ifyouwanttoauthenticatetosudowithoutrunninganycommands,runsudo–v.Sudowillpromptyouforyourpassword,verifyit,andupdatethetimestamp.Usethiswhenyou'reabouttorunawholebunchofcommandsviasudoanddon'twanttogetstoppedbyapasswordprompthalfwaythrough.
Ifyouwantsudotoignoreyourauthenticationtimestampcacheforthisterminalwindow,usethe–koption.Usedonitsown,itinvalidatestheauthenticationtimestamp.Ifyouspecificallywantsudotorequestauthenticationthenexttimeyourunacommand,add–ktothecommandline.#sudo–kifconfig
Evenifyouhavetimeleftinyourauthenticationtimestamp,sudowillnowaskyoutoauthenticate.Tototallyremovetheauthenticationtimestampfromallofyoursudosessions,runsudo–K.Thisentirely
removesyourtimestamps,orifitcan'tremovethem,resetsthemto31December1969.Usesudo–Kbeforewalkingawayfromyourcomputer,evenifyourunascreenlockingprogram.Remember,asystemadministratorcanovercomemostscreenlocks.Youdon'twantacretinlikemeunlockingyourworkstationandusingyoursudoaccess.
DisablingAuthenticationSometimesyouwantausertohavetheabilitytorunacommandwithoutenteringapassword.Ifyou'realwaysreconfiguringyourlaptoptoconnecttodifferentnetworks,itmightmakesensetonotbotherwithapasswordfordhclient,ifconfig,andrelatedcommands.Youmightevenwanttheabilitytoalwaysrunsudowithoutapasswordonyourdesktop.Andrunningsudowithoutapasswordisveryreasonableforautomatedtasks.
Broadlydisablingauthenticationforsudoisunwise.Yes,it'smostconvenient.Also,anyapplicationthatgainscontrolofyourusersessionwillhavetotalaccesstoallofyoursudoprivileges.Ifyou'rerunninganoperatingsystemlikeUbuntu,whichgivestheinitialuserfullrootaccessviasudo,thentherogueprocesswillcompletelyownyourmachine.Disablingsudoauthenticationisequivalentto
deliberatelyimplementingtheWindows95securitysystem.[13]
Ifyoudon'twanttobotherenteringapasswordwhenyouneedsudo,lookatanalternateauthenticationmechanismsuchasanSSHagent(seeSudoandPAMlaterthischapter).
Myexamplesassumeyouselectivelydisableauthentication.Youcanextrapolatethemtogloballydisableauthenticationorlookinthedefaultsudoersfileshippedwithmostoperatingsystems.
TheauthenticateOption
OnewaytocontrolauthenticationistheauthenticateoptiononDefaultsstatements.Theauthenticateoptiondoesn'tappearinmostsudoersfiles,becauseit'saninvisibleglobaldefault.Negateittodisableauthentication.HereIdisableauthenticationforifconfiganddhclient:Defaults!/sbin/ifconfig,/sbin/dhclient!authenticate
Icannowsetupmylaptopatthecoffeeshopwithoutbotheringwithmypassword.
AuthenticationTags
Ifyouwanttoverypreciselycontrolauthenticationinyoursudoerspolicy,usethetagsPASSWDandNOPASSWDonspecificsudoersrules.yourarelyseethePASSWDtag,asit'sthedefault.UseNOPASSWDtoturnoffthepasswordrequirement.petedbtest1=(oracle)NOPASSWD:/opt/oracle/bin/*
PetemayusesudotorunanyOraclecommandastheuseroracleonthehostdbtest1withoutenteringapassword.
SharingAuthenticationBetweenSessions
Sudonormallyincludestheterminaldeviceintheauthenticationtimestamp.Thatis,sudonotonlyusestheusernamebutalsotheterminaldevice(orTTY)toidentifyausersession'ssudoauthentication.
AssumeISSHintoaservertwice,andmysessionsusevirtualterminals/dev/vty2and/dev/vty3.IfIusesudointhevty2terminalwindow,andwanttouseitagaininthevty3window,Imustauthenticateinthevty3window.
Someoperatingsystemsincludeasudopackageconfiguredtopermitsharingsudoauthenticationsbetweenterminalsessions.IfyouopentwoSSHsessionstoaserverandauthenticateviasudoinonesession,theothersessioncanusethatsameauthenticationtimestamp.
Thisseemsstrangetomanypeople–itcertainlystruckmeasodd.Butit'sreallyhardtoisolatethetwoprocessesfromeachotherwhenthey'rebothownedbythesameuser.Usershavecompletecontrolovertheirownprocessses,afterall.Thismeansthatifaskilledintruderpenetratesauseraccountwhiletheuserisactiveinanothersession,theintrudercanusetoolslikeptraceandgdbtoruncommandsviasudoaslongasanyterminalsessionhasavalidtimestamp.Still,requiringseparateauthenticationforeachterminalwindowdoesincreasetheskillanattackerneedstofurtherpenetratethesystem–youraveragescriptkiddiewon'thavetheexpertiseneededtohijackanotherterminal'ssudosession.
Youcancontrolper-terminalauthenticationwiththettyticketsoption.Negatingthisoptionletsmultipleterminalsshareasingletimestampforauthentication.Unlessyouhaveveryspecificreasonsfordisablingper-terminaltimestamps,however,Istronglyencourageyoutoleaveiton.
QueryingSudoSudohastwouserfunctionsthatdon'truncommands.The–lflagtellssudotoprintouttheuser'ssudopolicy,sotheusercanseewhattheyhaveaccessto.The–vflagupdatestheuser'sauthenticationtimeout.Usersmustentertheirpasswordtousethesefunctions,butyoucanchangethesefeaturestoonlyrequireapasswordundercertainconditions.
Thelistpwoptioncontrolswhetherusermustenterhispasswordtolisthisaccess,whiletheverifypwoptioncontrolswhetherausermustenterhispasswordtoupdatehisauthenticationtimestamp.Eachoftheseoptionscanhaveoneoffourvalues:any,always,all,andnever.
Thedefault,any,meansthatifanyoftheuser'ssudoersruleshaveNOPASSWDor!authenticateset,theuserdoesn'tneedtoenterapasswordtousethefunction.Turningoffpasswordauthenticationforonecommandmeansenablingpasswordlessuseofsudo's–land–vflags.
Iftheseoptionsaresettoalways,theusermustenterapasswordeverytimetheywanttousethesefunctions.Eveniftheuser'sauthenticationtimestamphasnotexpired,theusermustalwaysenterapasswordtouse–lor–v.alwaysmeans"always."
Ifyousettheseoptionstoall,-land–vwillrequestapasswordunlesstheuserhaspasswordlessaccesstoalloftheirpermittedcommandsonthishost.Theydon'tneedpasswordlessaccesstoallpossiblecommands,mindyou,onlypasswordlessaccesstoallofthecommandsthattheycanrun.
Theneversettingmeansthatusersareneveraskedforapasswordtouse–lor–v.Heresudoerstellssudo–ltodemandapasswordforeveryuserexceptThea.Wealsodisableaskingfor
apasswordtoupdatetheauthenticationtimestamponthehostwww.Defaultslistpw=alwaysDefaults:thealistpw=neverDefaults@wwwverifypw=never
ChangingthelistpwandverifypwoptionsforcommandsorRunAsdoesn'tmakemuchsense,butyoucansensiblychangethemforhostsandusers.
LectureIusedthesudolectureformanyexamplesinChapter5,butlet'sgiveitmoreconcentratedtreatment.The"lecture"isthemessagedisplayedwhenyoufirstauthenticatetosudo.WetrustyouhavereceivedtheusuallecturefromthelocalSystemAdministrator.Itusuallyboilsdowntothesethreethings:
#1)Respecttheprivacyofothers.#2)Thinkbeforeyoutype.#3)Withgreatpowercomesgreatresponsibility.
Youthengetachancetoenteryourpassword.Thisisanicegeneralwarning,butthelectureandlecture_fileoptionsgiveyouachancetogivemorespecificlecturesasthesituationdemands.
Thelectureoptionacceptsthreevalues.Thedefault,once,tellssudotogiveeachuserthelectureonceandneveragain.Usingalwaystellssudotoalwayslecturetheuser,whileusingneveror!lecturedisablesthelectureentirely.
Usethelecture_fileoptiontogiveafilecontainingyourownlecture.Youcansetthelecturebasedonanydefaultsetting.SoTheamightsetthisconfiguration:Defaults:mikelecture=always,
lecture_file=/etc/sudo/mike-lecture
Themike-lecturefilemightcontainsomethinglikethis.Everythingyoudoislogged.AndTheastudiesthelogs.I'montoyou,mister.
ApparentlysomeonethinksI'mtrouble.
SudoandPAMPasswordsaren'tverystrongauthenticationtokens.Mostuserscreateterriblepasswords,andasufficientlypersistentintrudercaneventuallyguessevendecentpasswords.Addinganotherlayerofauthenticationtoyourprivilegedprocesses,oreliminatingpasswordsaltogether,canimproveyoursecurity.
PluggableAuthenticationModules,orPAM,permitsystemadministratorstoattachnewauthenticationsystemstoprograms.EachauthenticationsystemcomesinaPAMmodule,containingthecodeneededtousetheauthenticationsystem.Inadditiontotheusualpassword,Unix,Kerberos,andLDAPmodulesfoundonUnix-likesystems,youcaninstallPAMmodulesthatimplementGoogleAuthentication,RSAtokens,WindowsSMBauthentication,andmanymore.NotalloperatingsystemssupportPAM,butifyoursdoes,youcanleveragePAMtoauthenticatesudo.
JustasthisisnotabookonLDAP,thisisnotabookonPAM.ThissectionprobablycontainsenoughknowledgetogetmyexamplePAMmoduleworkingonyoursystemwithsudo,butitwon'tmakeyouintoaPAMwizard.Anddon'tforgetthatmanyvendorshavetheirownPAMsystem,whiletheopensourceworldhastwosimilarbutnotidenticalimplementations.IfyouwantanadvancedPAMconfiguration,checkyouroperatingsystem'sdocumentationtoseewhatyouhaveandwhatitcando.
LotsofthePAMmodulesaren'tsuitableformyenvironment,however.UsingGoogleAuthenticatornotonlyremovesthesourceoftrustfrommynetwork,itmeansthatifmyexternalnetworkconnectionfailsIcannotauthenticate.IwillnotauthenticateagainstaWindowsdomainordeployRSAtokensinthiscompany.TheSSHagentauthenticationmodule,however,isinteresting.
AnSSHagentrunsontheuser'sdesktopcomputer.Itholdsauser'sdecryptedSSHauthenticationkeysinmemory.IftheSSHclientorsessionneedstovalidateposessionofthekeys,itasksthedesktopagenttoperformthevalidation.Thisisstrongerthanpasswordauthentication,astheusermusthaveboththekeyandthepassphraseforthekey.Ofcourse,youshouldn'tallowallSSHserversaccesstoyouragent,butthat'sprettyeasilyconfigured.Ifthisparagraphmadenosensetoyou,permitmetorecommendmybookSSHMastery(TiltedWindmillPress,2012).
ThePAMmodulepam_ssh_agent_auth(http://pamsshagentauth.sourceforge.net/)permitsprocessestoauthenticateagainstyourSSHagent.I'llusethismoduleasanexampleofaddingsecuritysystemstosudo.
Prerequisites
BeforeconfiguringsudotouseSSHagentauthentication,checkthatyouhavealltheprerequisites.Youmusthaveuserauthorized_keysfilesonthelocalmachine.Thismeansthatifyou'reusinganSSH
serverthatgetsitskeysfromLDAPoranotherexternalsource,youcannotusepam_ssh_agent_auth.YourSSHclientmustforwardyourdesktopSSHagenttotheserver,andtheservermustacceptthe
agentforwarding.ToseeifthisworksinyourSSHsession,checkfortheenvironmentvariableSSH_AUTH_SOCK.
$echo$SSH_AUTH_SOCK/tmp/ssh-u2ThOMa9py/agent.24047
Ifthisvariablecontainsapath,eitheryouragentforwardingworksoryouhaveatrulybizarreproblem.Ifthisvariabledoesn'texist,checkyourSSHclientandserversettings.
Nowinstallpam_ssh_agent_auth.Unlikemuchmodernsoftware,pam_ssh_agent_authdoesn'thaveallkindsoffancyconfigurationoptions.Ifyouroperatingsystemhasapackagedversion–anditprobablydoes–useit.
SSHagentauthenticationneedstheenvironmentvariableSSH_AUTH_SOCK,whichSSHautomaticallysetstopointtoalocalsocketconnecttoyourSSHagent.Youneedtopermitthisenvironmentvariableinyoursudoerspolicy.IrecommendalsopassingSSH_CLIENT,SSH_TTY,andSSH_CONNECTIONsothatprogramslikesftpwork.
Sudodefaultstosettingtheauthenticationtimestampwhenyouauthenticate.Thisbehaviorwilldriveyoubuggywhentryingtodeployanewauthenticationsystem.Disablethetimestampbysettingtheoptiontimestamp_timeoutto0.Defaultsenv_keep+="SSH_CLIENTSSH_CONNECTIONSSH_TTYSSH_AUTH_SOCK",
timestamp_timeout=0
OncetheseprerequisitesworkyoucanproceedtoconfiguringthePAMmodule.
ConfiguringPAM
PAMkeepsauthenticationconfigurationsinsystemdirectoriessuchas/etc/pam.dor/usr/local/etc/pam.d.APAM-awareprogramsearchesforitsPAMinthesedirectories.Checkthesedirectoriesforafilenamedsudo.
PAMpoliciesincludefourdifferenttypesofrules:auth,account,session,andpassword.Changingauthenticationmethodsrequireschangingtheauthrules.NotallPAMpolicieshaveallruletypes–manypoliciesdon'thavepasswordrules.EachrulecallsaPAMmodulesuchaspam_unix,pam_ldap,pam_mkhomedir,andsoon.
ThePAMmodulepam_unixhandlestraditionalpasswordauthentication.Findanauthenticationruleinsudo'sPAMconfigurationsomewhatlikethisone.authrequiredpam_unix.sono_warntry_first_passnullok
Thisruletellssudotousepasswordsforauthentication.TouseSSHagentauthenticationinsteadofpasswords,replacethepasswordrulewithyourown.
authsufficientpam_ssh_agent_auth.sofile=~/.ssh/authorized_keys
Whatdoesthismean?Authenticatingwiththemethodinthesharedlibrarypam_ssh_agent_auth.soissufficienttologontothesystem.Thefile=textgivesthepathtotheuser'sauthorized_keysfile,whichiscommonlyin$HOME/.ssh/authorized_keys.Youmightneedtogivethefullpathtopam_ssh_agent_auth.so,dependingonhowyouroperatingsysteminstallsnewPAMlibrariesandhowyourPAMimplementationfindsthem.
SaveyourchangestothesudoPAMpolicy.Youshouldnowbeabletoauthenticatetosudowithyour
SSHagent.Flushyourauthenticationtimestamp(ifany)andtryit.$sudo–K$sudotouch/tmp/test
WhilemyPAMruleworksforthemostcommoncase,aservercanstoreitsauthorized_keysfilesinseveralways.Thepam_ssh_agent_authlibrarymustknowwherethekeysareandtheacceptablepermissionsonthekeyfiles.
authorized_keysPermissions
Inthesimplestcase,auserownstheirownauthorized_keysfile.Someenvironmentsdon'tletuserschangetheirownauthorized_keys,however.Instead,keyfileupdatesgothroughacentralmanagementsystemwhichcopiesthemtothetargethost.Insuchanenvironment,acompromisedusercannotchangethekeyfilesontheserver.Thequestionbecomes:whoownsthekeyfiles?
Theallow_user_owned_authorized_keys_fileoptiontellspam_ssh_agent_auththattheusercanowntheauthorized_keysfile.Thisoptionactivatesautomaticallywhenthekeyfileisintheuser'shomedirectory.
Withoutthisoptionset,andiftheauthorized_keysfileisnotintheuser'shomedirectory,pam_ssh_agent_authexpectsroottoownthekeyfile.Ifthefileisnotownedbyroot,authenticationfails.
authorized_keysLocation
Whilemosttutorialstellyoutoputauthorized_keysintheuser's$HOME/.sshdirectory,manyorganizationsuseotherstandards.Youmusttellpam_ssh_agent_authwheretofindthefiles.Themoduleincludesseveralescapecharactersforthispurpose.
Thetilde(~)and%hcharactersrepresenttheuser'shomedirectory.%Hrepresentstheshorthostname(withoutthedomainname),while%fmeansthefullyqualified
hostname.Finally,%urepresentstheusername.Supposeyoustoredyourkeysin/etc/sshkeys/,whereeachuserhasafilenamedaftertheirusername.
Thesekeyfilesareownedbyroot.authsufficientpam_ssh_agent_auth.sofile=/etc/sshkeys/%u
Ifuserscanwritetheirownkeyfilesinthisdirectory,youmustaddtheallow_user_owned_authorized_keys_fileoptionattheendofthePAMrule.
Debuggingpam_ssh_agent_auth
Ifsudopromptsyouforapasswordandwaitsforyoutodoso,youhaven'tremovedthepasswordpolicy.Ifsudopromptsyouforapasswordthreetimesinarowwithoutwaitingforyoutoenterthepassword,andthendisplaysafailuremessage,sudoisusingthePAMmodulebutcannotconnecttoyourSSHagent.Checkyouragentforwarding.Ifyoustillhaveproblems,configurelogginginsudo.conftoseewherethingsbreak.
Onceyougetpam_ssh_agent_authworkingwithsudo,youcanfurtherexpandauthentication
requirements.YouwanttorequireanSSHagent,apassword,andGoogleAuthentication?Youcandoit.It'skindofdaft,butyoucandoit.
Andgiventhis,youcannowmakesudodoanythingyouwant.
AfterwordYoushouldnowknowmoreaboutsudothanthevastmajorityofpeoplewhodidn'twriteit.Congratulations!Butthere'smoretolearn.Ifyouhaveaweirdsudoproblem,checkthesudowebsiteathttp://sudo.ws,thesudomanpages,andthearchivesofthesudo-usersmailinglist.Sudohasbeensuccessfullydeployedonmillionsofverydifferentsystems,anditcanworkforyoutoo.
Alwaysbeawarethatsudomightnotfityourorganization,however.Someapplicationsexpecttoowntheserver,andtryingtorestrictthoseapplicationsisfutileatbest.Ifyoumanageyourorganizationbyrunningshellscriptsasroot,runningthosesameshellscriptswithsudowillleavelotsofwaysforunauthorizeduserstoescalatetheirprivileges.Sudoisuseful,butasysadminwhounderstandswhenaspecifictoolwon'tsolvehisproblemismoreuseful.
Andthenexttimesomeonetellsyouthat"Sudoishowyougetroot,"treatthemtoashortsharpvisitfromtheSlapFairy.
[1]Ifyouhaven'tplayedwithAnsible(http://ansible.cc),youreallyshould.
[2]Ihaveveryfewunbreakablerulesforbeinga"real"sysadmin.Oneofthemis,realsysadminscanusevi.Viandedarethetwoeditors
youcanbeconfidentoffindingonanyUnix-likesystem."Can'tusevi"means"notasysadmin."[3]
Irecentlylearnedthattheipsetcommanduses-!asacommonargument.Presumablythedeveloperswereoutoflettersandnumbers,andwhentheyrunoutofsymbolsthey'llproceedtobloodsamples.[4]
ButifItellherwhathappenedtohercomfychair,I'llnevergetaccesstoanythingeveragain.[5]
Isaidthatwithastraightface?Wow.[6]
Runningashellthatcan'texecutecommandsisaneducation.Tryitsometime.[7]
Thisisalsoknownas"Managementwon'tletmedomyjob"Syndrome,whichisnotimprovedbydeveloping"Igavethemanexcusetofireme"Disorder.[8]
IfanEvilSecretAgencywithaccesstoSuperTopSecretDigestCrackingHardware™wantstocompromiseyourcomputer,hewon'tbotherreplacingbinarieswithtreacherousversionscarefullyengineeredtohavethesamechecksum.He'lluseyourkneecaps.Andahammer.[9]
Iknowyouhaveaprocedureforinstallingservers.Afteryearsinthisbusiness,Iamfirmlyconvincedthatnohumanbeingiscapableofinstallingtwoserversidentically.[10]
AcoupledistributionsoncerequiredbloodsacrificesattheseconddarkofthemooninamonthtomakesudoreadapolicyfromLDAP,butI'massuredthatthisbehaviorwascorrectedafterenoughusersfiledsufficientlydetailedbugreports.[11]
WhenCarlwantstoknowwhochangedhispassword,thebosscantellhim.AndI'llbeintroubleagain.[12]
I'dprobablybeinmyownmeetingwithHRalittleafter,ifIwasn'ttheowner'sbrother-in-law.[13]
Forthosereaderstooyoungtoremember:Windows95hadnosecuritysystem.