607

CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

  • Upload
    others

  • View
    22

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote
Page 2: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CentOS7ServerDeploymentCookbook

Page 3: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TableofContents

CentOS7ServerDeploymentCookbookCreditsAbouttheAuthorAbouttheReviewerwww.PacktPub.com

Whysubscribe?Preface

WhatthisbookcoversWhatyouneedforthisbookWhothisbookisforSections

GettingreadyHowtodoit…Howitworks…There'smore…Seealso

ConventionsReaderfeedbackCustomersupport

ErrataPiracyQuestions

1.GettingStartedwithCentOSIntroductionInstallingCentOSusingAnacondaingraphicsmode

GettingreadyHowtodoit...Howitworks...Seealso

InstallingCentOSusingAnacondaintextmodeGettingreadyHowtodoit...Howitworks...Seealso

CoordinatingmultipleinstallationsusingKickstartGettingreadyHowtodoit...Howitworks...Seealso

RunningacloudimagewithAmazonWebServices'EC2Gettingready

Page 4: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Howitworks...Seealso

InstallingacontainerimagefromtheDockerRegistryGettingreadyHowtodoit...Howitworks...Seealso

InstallingtheGNOMEdesktopGettingreadyHowtodoit...Howitworks...Seealso

InstallingtheKDEPlasmadesktopGettingreadyHowtodoit...Howitworks...Seealso

2.NetworkingIntroductionSettingastaticIPaddress

GettingreadyHowtodoit...Howitworks...Seealso

BindingmultipleaddressestoasingleEthernetdeviceGettingreadyHowtodoit...Howitworks...Seealso

BondingtwoEthernetdevicesGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringthenetworkfirewallwithFirewallDGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringthenetworkfirewallusingiptablesGettingreadyHowtodoit...Howitworks...

Page 5: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoInstallingaDHCPserver

GettingreadyHowtodoit...Howitworks...Seealso

ConfiguringanNFSservertoshareafilesystemGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringanNFSclienttouseasharedfilesystemGettingreadyHowtodoit...Howitworks...Seealso

ServingWindowsshareswithSambaGettingreadyHowtodoit...Howitworks...Seealso

3.UserandPermissionManagementIntroductionEscalatingprivilegeswithsudo

GettingreadyHowtodoit...Howitworks...Seealso

EnforcingpasswordrestrictionsGettingreadyHowtodoit...Howitworks...Seealso

SettingdefaultpermissionsfornewfilesanddirectoriesGettingreadyHowtodoit...Howitworks...Seealso

RunningbinariesasadifferentuserGettingreadyHowtodoit...Howitworks...Seealso

WorkingwithSELinuxforgreatersecurity

Page 6: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyHowtodoit...Howitworks...Seealso

4.SoftwareInstallationManagementIntroductionRegisteringtheEPELandRemirepositories

GettingreadyHowtodoit...Howitworks...Seealso

PrioritizingrepositoriesusingthePrioritiespluginGettingreadyHowtodoit...Howitworks...Seealso

Automatingsoftwareupdateswithyum-cronGettingreadyHowtodoit...Howitworks...Seealso

VerifyinginstalledRPMpackagesGettingreadyHowtodoit...Howitworks...Seealso

CompilingaprogramfromsourceGettingreadyHowtodoit...Howitworks...Seealso

5.ManagingFilesystemsandStorageIntroductionViewingthesizeoffilesandavailablestorage

GettingreadyHowtodoit...Howitworks...Seealso

SettingstoragelimitsforusersandgroupsGettingreadyHowtodoit...Howitworks...Seealso

CreatingaRAMdisk

Page 7: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyHowtodoit...Howitworks...Seealso

CreatingaRAIDGettingreadyHowtodoit...Howitworks...Seealso

ReplacingadeviceinaRAIDGettingreadyHowtodoit...Howitworks...Seealso

CreatinganewLVMvolumeGettingreadyHowtodoit...Howitworks...Seealso

RemovinganexistingLVMvolumeGettingreadyHowtodoit...Howitworks...Seealso

AddingstorageandgrowinganLVMvolumeGettingreadyHowtodoit...Howitworks...Seealso

WorkingwithLVMsnapshotsGettingreadyHowtodoit...Howitworks...Seealso

6.AllowingRemoteAccessIntroductionRunningcommandsremotelythroughSSH

GettingreadyHowtodoit...Howitworks...Seealso

ConfiguringamoresecureSSHloginGettingreadyHowtodoit...

Page 8: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Seealso

SecurelyconnectingtoSSHwithoutapasswordGettingreadyHowtodoit...Howitworks...Seealso

RestrictingSSHaccessbyuserorgroupGettingreadyHowtodoit...Howitworks...Seealso

ProtectingSSHwithFail2banGettingreadyHowtodoit...Howitworks...Seealso

ConfiningsessionstoachrootjailGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringTigerVNCGettingreadyHowtodoit...Howitworks...Seealso

TunnelingVNCconnectionsthroughSSHGettingreadyHowtodoit...Howitworks...Seealso

7.WorkingwithDatabasesIntroductionSettingupaMySQLdatabase

GettingreadyHowtodoit...Howitworks...Seealso

BackingupandrestoringaMySQLdatabaseGettingreadyHowtodoit...Howitworks...Seealso

Page 9: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringMySQLreplicationGettingreadyHowtodoit...Howitworks...Seealso

StandingupaMySQLclusterGettingreadyHowtodoit...Howitworks...Seealso

SettingupaMongoDBdatabaseGettingreadyHowtodoit…Howitworks...Seealso

BackingupandrestoringaMongoDBdatabaseGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringaMongoDBreplicasetGettingreadyHowtodoit...Howitworks...Seealso

SettingupanOpenLDAPdirectoryGettingreadyHowtodoit...Howitworks...Seealso

BackingupandrestoringanOpenLDAPdatabaseGettingreadyHowtodoit...Howitworks...Seealso

8.ManagingDomainsandDNSIntroductionSettingupBINDasaresolvingDNSserver

GettingreadyHowtodoit...Howitworks...Seealso

ConfiguringBINDasanauthoritativeDNSserverGettingready

Page 10: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Howitworks...Seealso

WritingareverselookupzonefileGettingreadyHowtodoit...Howitworks...Seealso

SettingupaslaveDNSserverGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringrndctocontrolBINDGettingreadyHowtodoit...Howitworks...Seealso

9.ManagingE-mailsIntroductionConfiguringPostfixtoprovideSMTPservices

GettingreadyHowtodoit...Howitworks...Seealso

AddingSASLtoPostfixwithDovecotGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringPostfixtouseTLSGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringDovecotforsecurePOP3andIMAPaccessGettingreadyHowtodoit...Howitworks...Seealso

TargetingspamwithSpamAssassinGettingreadyHowtodoit...Howitworks...

Page 11: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRoutingmessageswithProcmail

GettingreadyHowtodoit...Howitworks...Seealso

10.ManagingWebServersIntroductionInstallingApacheHTTPServerandPHP

GettingreadyHowtodoit...Howitworks...Seealso

Configuringname-basedvirtualhostingGettingreadyHowtodoit...Howitworks...Seealso

ConfiguringApachetoservepagesoverHTTPSGettingreadyHowtodoit...Howitworks...Seealso

EnablingoverridesandperformingURLrewritingGettingreadyHowtodoit...Howitworks...Seealso

InstallingNGINXasaloadbalancerGettingreadyHowtodoit...Howitworks...Seealso

11.SafeguardingAgainstThreatsIntroductionSendingmessagestoSyslog

GettingreadyHowtodoit...Howitworks...Seealso

RotatinglogfileswithlogrotateGettingreadyHowtodoit...Howitworks...

Page 12: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoUsingTripwiretodetectmodifiedfiles

GettingreadyHowtodoit...Howitworks...Seealso

UsingClamAVtofightvirusesGettingreadyHowtodoit...Howitworks...Seealso

CheckingforrootkitswithchkrootkitGettingreadyHowtodoit...Howitworks...Seealso

UsingBaculafornetworkbackupsGettingreadyHowtodoit...HowitworksSeealso

12.VirtualizationIntroductionCreatinganewvirtualmachine

GettingreadyHowtodoit...Howitworks...Seealso

CloningavirtualmachineGettingreadyHowtodoit...Howitworks...Seealso

AddingstoragetoavirtualmachineGettingreadyHowtodoit...Howitworks...Seealso

ConnectingUSBperipheralstoaguestsystemGettingreadyHowtodoit...Howitworks...Seealso

Configuringaguest'snetworkinterface

Page 13: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyHowtodoit...Howitworks...Seealso

Page 14: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CentOS7ServerDeploymentCookbook

Page 15: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CentOS7ServerDeploymentCookbookCopyright©2016PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:September2016

Productionreference:1270916

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

Birmingham

B32PB,UK.

ISBN978-1-78328-888-5

www.packtpub.com

Page 16: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Credits

Author

TimothyBoronczyk

CopyEditor

TomJacob

Reviewer

MitjaResman

ProjectCoordinator

KinjalBari

CommissioningEditor

KartikeyPandey

Proofreader

SafisEditing

AcquisitionEditor

RahulNair

Indexer

PratikShirodkar

ContentDevelopmentEditor

MehvashFatima

Graphics

KirkD'Penha

TechnicalEditors

DeveshChugh

SiddhiRane

ProductionCoordinator

ShantanuN.Zagade

Page 17: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AbouttheAuthorTimothyBoronczykisanativeofSyracuse,NewYork,whereheworksasaleaddeveloperatOptanix,Inc.(formerlyShoreGroup,Inc.).He'sbeeninvolvedwithwebtechnologiessince1998,hasadegreeinSoftwareApplicationProgramming,andisaZendCertifiedEngineer.Inwhatlittlesparetimehehasleft,Timothyenjoyshangingoutwithfriends,studyingEsperanto,andsleepingwithhisfeetofftheendofthebed.He'seasilydistractedbyshinyobjects.

Page 18: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AbouttheReviewerMitjaResmancomesfromasmall,beautifulcountrycalledSlovenia,locatedinsouthernCentralEurope.MitjaisafanofLinuxandisanopensourceenthusiast.MitjaisaRedHatCertifiedEngineerandLinuxProfessionalInstituteprofessional.Workingasasystemadministrator,MitjagotyearsofprofessionalexperiencewithopensourcesoftwareandLinuxsystemadministrationonlocalandinternationalprojectsworldwide.TheswissarmyknifesyndromemakesMitjaanexpertinthefieldofVMwarevirtualization,Microsoftsystemadministration,andlately,alsoAndroidsystemadministration.

Mitjahasastrongdesiretolearn,develop,andshareknowledgewithothers.ThisisthereasonhestartedablogcalledGeekPeek.Net(https://geekpeek.net/).GeekPeek.NetprovidesCentOSLinuxguidesandHowtoarticlescoveringallsortsoftopicsappropriateforbeginnersandadvancedusers.Hewroteabook,CentOSHighAvailabilitybyPacktPublishing,coveringthetopicofhowtoinstall,configure,andmanageclustersonCentOSLinux.

Mitjaisalsoadevotedfatherandhusband.Histwodaughtersandwifearetheoneswhotakehismindoffthegeekstuffandmakehimappreciatelife,lookingforwardtothingstocome.

Page 19: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

www.PacktPub.comForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatservice@packtpub.comformoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

https://www.packtpub.com/mapt

Getthemostin-demandsoftwareskillswithMapt.MaptgivesyoufullaccesstoallPacktbooksandvideocourses,aswellasindustry-leadingtoolstohelpyouplanyourpersonaldevelopmentandadvanceyourcareer.

Page 20: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

Page 21: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

PrefaceForoveradecade,theCentOSprojecthasprovidedthecommunitywithafree,enterprise-gradeoperatingsystemthroughtherebrandingandrecompilationoftheRedHatEnterpriseLinuxsource.SinceCentOSusersrelyalmostexclusivelyonthecommunityfortheirsupportneeds,IwaskeentowritethisbookwhenPacktapproachedmeabouttheproject'slatestrelease,CentOS7.Therecipeswechosecoverawiderangeoftopics,fromgettingstartedtomanagingmanycommonwebservices,andhopefullyadministratorsofanyskilllevelwillfindsomethingofinterest.

However,writingabookisahugeundertaking.Becauseofthis,IwanttothankthestaffatPackt,myfamily,andmyfriends,fortheirsupport.Thedogneedstobetakenforawalk,familyengagementsneedattending,andemergenciesariseattheworkplace.Withouttheunderstandingandencouragementofthosearoundmeandtheeditorialstaff,youwouldn'tbereadingthisbook.

Page 22: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WhatthisbookcoversTherecipespresentedinthisbookaimtomakeeventhemostdifficultconfigurationtaskseasybyprovidingstep-by-stepinstructionsanddiscussion.Here'saquickrundownofwhatyoucanexpectfromeachofthe12chapters.

Chapter1,GettingStartedwithCentOS,containsrecipesforinstallingCentOSusinggraphical,text-based,andkick-startapproaches.HowtosetupaCentOSplatformforprojectsrunningDockerandonAmazonWebServicesisalsodiscussed.

Chapter2,Networking,containsrecipestohelpyoucompletecommonnetworkingtasks,suchashowtosetupastaticIPaddress,assignmultipleaddressestoasinglenetworkinterface,bondmultipleinterfaceswiththesameaddress,andconfigurethesystem'sfirewallusingFirewallDandiptables.ItalsopresentsrecipesforconfiguringnetworkservicessuchasDHCP,NFS,andSamba.

Chapter3,UserandPermissionManagement,showsyouhowtoincreasethesecurityofyoursystembyenforcingpasswordrestrictions,adjustingthedefaultpermissionsgiventonewlycreatedfilesanddirectories,andtheuseofsudotoavoidcirculatingtherootpassword.HowtoworkwithSELinuxisalsodiscussed.

Chapter4,SoftwareInstallationManagement,providesrecipesfocusedonworkingwithsoftwarerepositoriesandinstallingsoftware.You'lllearnhowtoregistertheEPELandRemirepositories,prioritizetherepositoriespackagesareinstalledfrom,andupdateyoursoftwareautomatically.You'llalsolearnhowtocompileandinstallsoftwarefromsourcecode.

Chapter5,ManagingFilesystemsandStorage,presentsrecipesthatshowyouhowtosetupandworkwithRAIDandwithLVM.Theseservicesleverageyoursystem'sstoragetomaintainavailability,increasereliability,andtokeepyourdatasafeagainstinevitablediskfailures.

Chapter6,AllowingRemoteAccess,aimstohelpyouprovideremoteaccesstoyourCentOSsysteminasecuremanner.ItsrecipescoverusingSSH,configuringachrootjail,andtunnelingVNCconnectionsthroughanencryptedSSHtunnel.

Chapter7,WorkingwithDatabases,collectsrecipesthatprovideyouwiththenecessarystepstogetstartedwithvariousdatabaseservicessuchasMySQL,MongoDB,andOpenLDAP.You'llalsolearnhowtoprovidebackupandredundancyfortheseservices.

Chapter8,ManagingDomainsandDNS,takesusintotheworldofDNS.TherecipesshowyouhowtosetuparesolvingDNSservertodecreaselatencycausedbydomainlookupsandhowtomanageyourowndomainwithanauthoritativeDNSserver.

Chapter9,ManagingE-mails,willhelpyousetupyourownmailserver.Therecipesdiscuss

Page 23: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

configuringPostfixtoprovideSMTPservices,configuringDovecottoprovideIMAPandPOP3services,andsecuringtheseserviceswithTLS.You'llalsofindinstructionsonhowtosetupSpamAssassintohelpreduceunsolicitedbulke-mails.

Chapter10,ManagingWebServers,containsrecipesaboutconfiguringApachetoserverwebcontent.You'lllearnhowtosetupname-basedvirtualhosting,serverpagesoverHTTPS,andperformURLrewriting.HowtosetupNGINXasaloadbalancerisalsodiscussed.

Chapter11,SafeguardingAgainstThreats,containsrecipestohelpprotecttheinvestmentyou'vemadeinyourCentOSserver.Theycoverlogging,threatmonitoring,virusandrootkits,andnetworkbackups.

Chapter12,Virtualization,showsyouhowCentOScanfunctionasahostoperatingsystemtooneormorevirtualizedguests.Thisallowsyoutotakebetteradvantageofyourhardwareresourcesbyrunningmultipleoperatingsystemsonthesamephysicalsystem.

Page 24: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WhatyouneedforthisbookTofollowtherecipesinthisbook,firstandforemostyou'llneedasystemcapableofrunningCentOS7.Theminimumrequirements(andmaximumcapabilities)aredocumentedintheRedHatEnterpriseLinuxknowledgebaseavailableonlineathttps://access.redhat.com/articles/rhel-limits.Inbrief,you'llneedasystemthathasthefollowing:

x86_64processor(RHEL/CentOS7doesnotsupportx86)1GBRAM8GBDiskcapacity

ApartfromasystemtoinstallCentOSon,you'llalsoneedacopyoftheCentOSinstallationmediaandaworkingnetworkconnection.Youcandownloadacopydirectlyfromhttps://www.centos.org/download/orusingBitTorrent.

Page 25: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WhothisbookisforThisbookisforLinuxprofessionalswithbasicUnix/Linuxfunctionalityexperience,perhapsevenhavingsetupaserverbefore,whowanttoadvancetheirknowledgeinadministeringvariousservices.

Page 26: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SectionsInthisbook,youwillfindseveralheadingsthatappearfrequently(Gettingready,Howtodoit...,Howitworks...,There'smore...,andSeealso).

Togiveclearinstructionsonhowtocompletearecipe,weusethesesectionsasfollows.

Page 27: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThissectiontellsyouwhattoexpectintherecipe,anddescribeshowtosetupanysoftwareoranypreliminarysettingsrequiredfortherecipe.

Page 28: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit…Thissectioncontainsthestepsrequiredtofollowtherecipe.

Page 29: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks…Thissectionusuallyconsistsofadetailedexplanationofwhathappenedintheprevioussection.

Page 30: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

There'smore…Thissectionconsistsofadditionalinformationabouttherecipeinordertomakethereadermoreknowledgeableabouttherecipe.

Page 31: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoThissectionprovideshelpfullinkstootherusefulinformationfortherecipe.

Page 32: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:"Therepositories'configurationfilesarefoundinthe/etc/yum.repos.ddirectory."

Ablockofcodeissetasfollows:

[sshd]

enabled=true

bantime=86400

maxretry=5

Anycommand-lineinputoroutputiswrittenasfollows:

firewall-cmd--zone=public--permanent--add-service=dns

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:"SelectyourdesiredlanguageandclickonContinue."

Note

Warningsorimportantnotesappearinaboxlikethis.

Tip

Tipsandtricksappearlikethis.

Page 33: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook-whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.

Tosendusgeneralfeedback,[email protected],andmentionthebook'stitleinthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.

Page 34: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 35: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks-maybeamistakeinthetextorthecode-wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.

Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.

Page 36: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusatcopyright@packtpub.comwithalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.

Page 37: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

QuestionsIfyouhaveaproblemwithanyaspectofthisbook,[email protected],andwewilldoourbesttoaddresstheproblem.

Page 38: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter1.GettingStartedwithCentOSThischaptercontainsthefollowingrecipes:

InstallingCentOSusingAnacondaingraphicsmodeInstallingCentOSusingAnacondaintextmodeCoordinatingmultipleinstallationsusingKickstartRunningacloudimagewithAmazonWebServices'EC2InstallingacontainerimagefromtheDockerRegistryInstallingtheGNOMEdesktopInstallingtheKDEPlasmadesktop

Page 39: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionThischapter'srecipesfocusongettingupandrunningwithCentOSusingavarietyofinstallationmethods.You'lllearnhowtoperforminteractivegraphicalandtext-basedinstallationsusingAnacondaandperformanunattendedinstallationusingKickstart.You'llalsoseehowtorunCentOSinthecloudwithAmazonWebServicesandinaDockercontainerimage.Mostoftherecipesinthisbooktakeplaceatthecommandprompt,butsomerequireagraphicaldesktop,sowe'llfinishupwithalookatinstallingtheGNOMEandKDEPlasmadesktops.

Page 40: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingCentOSusingAnacondaingraphicsmodeInthisrecipe,you'lllearnhowtoinstallCentOSusingthegraphicalinstallerAnaconda.ThisisthemostcommonwaythatCentOSisinstalled,althoughthereareotherwaystoo(someofwhicharediscussedinlaterrecipes).Thisapproachisalsotheeasiestinstallationmethod,especiallyforsettingupsingle-serverdeployments.

Page 41: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipeassumesthatyouhaveacopyoftheCentOS7installationmedium.Ifyoudon't,visithttps://www.centos.organddownloadaminimalISOimage.You'llalsoneedtomakeaphysicaldiscfromtheimage.InstructionsforburningtheISOimagetodisccanbefoundathttps://www.centos.org/docs/5/html/CD_burning_howto.html.

Tip

Ifyoursystemdoesn'thaveanopticaldriveanditsBIOSsupportsbootingfromaUSBdevice,youcanalsowritetheISOimagetoaUSBstick.

Page 42: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallCentOSusingthegraphicalinstallerAnaconda:

1. Inserttheinstallationdiscintoyoursystem'sopticaldrive(orUSBstickintoaUSBport)andreboot.ThesystemshouldboottotheCentOS7installationmenu:

Theinstallerislaunchedfromtheinstallationmenu

Note

Ifyoursystemdoesn'tboottotheinstallationmenuthenthedrivemaynotbeconfiguredasabootdevice.TheexactstepstoverifyandadjusttheconfigurationvarybetweenBIOSvendors,butingeneralyou'llpressEsc,F1,F2,orDeletewhilethesystemisbootingtogainaccesstotheBIOSsettings.Thenyou'llfindthelistofbootdevicesandchangetheorderinwhicheachissearchedforabootrecord.

2. Usingthearrowkeys,makesurethattheInstallCentOS7optionishighlightedandpressEnter.

3. TheWELCOMETOCENTOS7screenconfirmswhichlanguagetouseduringtheinstallationprocess.SelectyourdesiredlanguageandclickonContinue:

Page 43: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Youcanchangethelanguageusedduringtheinstallationprocess

4. Thenextscreenisamenuthatorganizestheinstallationoptionsbycategory.We'llconfigurenetworkingfirst—clickonNETWORK&HOSTNAMEundertheSYSTEMcategory:

Note

Ifyoursystemdoesn'thaveamouse,youcannavigateusingTabtocyclethroughtheinputfields,usethearrowkeystoselecttheentry,andpressEntertoselectoractivateaninput.

Page 44: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theinstallationsummaryscreenorganizestheinstallationoptionsintocategories

5. Enterthesystem'shostnameintheHostnamefield.Then,selectthesystem'sprimarynetworkinterfaceandtoggletheswitchattherighttoONtoenableit.ClickontheDonebuttonwhenyou'refinishedtoreturntotheINSTALLATIONSUMMARYmenu:

Page 45: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheNETWORK&HOSTNAMEscreenletsusconfigurethesystem'snetworkinterfaces

6. ClickonDATE&TIMEundertheLOCALIZATIONcategory.7. Setyourtimezonebyeitherselectingyourregionandcityorbyclickingonyour

locationonthemap.Then,clickonDonetoreturntotheINSTALLATIONSUMMARYmenu:

Page 46: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheDATE&TIMEscreenletsusconfigurethesystem'stimezone

8. Ifyouknowwhatpurposethesystemwillserveonyournetworkandrequiresomethingmorethanaminimalinstallation,clickonSOFTWARESELECTIONundertheSOFTWAREcategory.Selecttheenvironmentandanyadditionaladd-onstoinstallthedesiredpackages.Whenyou'refinished,clickonDone:

Page 47: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheSOFTWARESELECTIONscreenletsusinstallpurpose-basedsoftware

Note

Softwarecaneasilybeinstalledusingyum,sodon'tworryifyouneedtoinstalladditionalsoftwareafteryoualreadyhaveCentOSupandrunning.TheSOFTWARESELECTIONsectionispurelyforconvenience.

9. ClickonINSTALLATIONDESTINATIONundertheSYSTEMcategory.10. ClickontheappropriatedriveintheLocalStandardDisksareatosettheinstallation

target.Ifthedriveisnotbootable,orifmultipledrivesareselected,clickontheFulldisksummaryandbootloader...linkatthebottomofthescreentoopentheSelectedDiskswindow.Then,selectthedriveyouwanttobethebootdevice,clickontheSetasBootDevicebutton,andclickonClose.Whenyou'refinished,clickonDone:

Page 48: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheINSTALLATIONDESTINATIONscreenletsussetthediskwhereCentOSwillbeinstalled

11. ClickontheBeginInstallationbuttontostarttheinstallationprocess.12. ClickonRootPassword.Intheinputfields,enterandconfirmthepasswordyouwantto

useforthesystem'srootaccount.ClickonDonewhenyou'vefinishedenteringthesedetails:

Note

You'llneedtopresstheDonebuttontwicetoreturntotheconfigurationscreenifyouspecifyapasswordthat'stooweak.Ifyouneedhelptocreateastrongpassword,visithttp://www.howtogeek.com/195430/how-to-create-a-strong-password-and-remember-it/.

Page 49: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheROOTPASSWORDscreenletsussettherootaccount'spassword

13. ClickonUserCreation.Intheinputfields,provideyourname,username,anddesiredpassword.Again,pressDonewhenyou'vefinishedenteringthesedetails:

TheCREATEUSERscreenletsuscreateanunprivilegeduseraccount

14. Whentheinstallationiscomplete,clickontheFinishConfigurationbutton.Anacondawillfinalizethesystem'sconfigurationandthebutton'slabelwillchangetoReboot.

15. RemovetheCentOSinstallationmediafromthedriveandrebootyoursystem.

Page 50: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...AfterinstallingCentOSusingAnacondaingraphicalmode,youshouldnowhaveabasicCentOS7systemupandrunning.TheprocessbeganwhenwebootedthesystemfromtheinstallationdiscandselectedInstallCentOS7fromtheinstallationmenu.Theinstaller'skernelloadedintomemoryandAnacondalaunchedingraphicalmode.

TheNETWORK&HOSTNAMEscreenshowsalistoftheavailablenetworkinterfacesandbasicinformationaboutthem,forinstance,thecard'sMACaddressandtransferrate.Bydefault,theinterfacesareconfiguredtouseDHCPtoobtaintheirIPaddresswhentheyareenabled.(ConfiguringastaticIPaddressisdiscussedinalaterrecipe.)

Thesystem'stimezoneissetontheLOCALIZATIONscreen.ThedateandtimefieldsaredisabledwhenNTPisenabledbecausethevalueswillbesetbytheNTPservice.Thesystemclock'stimecandriftformanyreasons,especiallyifthesystemisrunningonavirtualmachine,soallowingNTPtomanagethesystem'stimeisagoodideatoensureitstayscorrect.Ifthedateandtimefieldsaren'tsetbyNTP,makesuretheNetworkTimetoggleissetON.YoucanspecifyanNTPserverbyclickingonthebuttonwiththegearsicon.

TheINSTALLATIONDESTINATIONscreenletsussettheinstallationtargetforCentOSandspecifyhowthesystem'sdrivesarepartitioned.Youcanchoosetoconfigurethepartitionsifyouhavespecialrequirements,butinthisrecipeIletAnacondapartitionthedrivesautomatically.

WhileAnacondaisbusyinstallingCentOSandanyadditionalsoftwarepackagesyoumayhaverequested,itshowsustheConfigurationscreen.Thisscreengivesustheopportunitytosetapasswordforthesystem'sadministrativeaccount(root)andcreateanunprivilegeduseraccount.Youshouldonlysigninwithrootwhennecessary;foryournormalday-to-dayworkyoushoulduseyourunprivilegedaccount.Anacondafinalizestheinstallationbyconfiguringthesystem'sbootrecordandcreatingtheuseraccount.

Afterthesystemreboots,theGrubbootloaderpromptappearsandthearrowkeyscanbeusedtoselectabootconfiguration.There'salsoatimer,sopressingnothingwilleventuallybootthesystemusingthedefaultconfiguration.

Page 51: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationoninstallingCentOS7,refertotheRHEL7InstallationGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide).

Page 52: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingCentOSusingAnacondaintextmodeNext,you'lllearnhowtoinstallCentOSusingAnacondaintextmode.It'srecommendedthatyouinstallCentOSgraphicallybecausegraphicsmodeiseasiertouseandoffersmorefunctionality.However,itmaynotbeavailablewhenthesystemlackssufficientresourcestoruntheinstalleringraphicalmode,forexample,ifthedisplayadaptor'scapabilitiesarelimitedorifthereisreducedRAM.

Page 53: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipeassumesthatyouhaveacopyoftheCentOS7installationmedium.Ifyoudon't,visithttps://www.centos.orgtodownloadanISOimageandthenburntheimagetoadisc.

Page 54: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoperformatext-basedinstallationofCentOS:

1. Inserttheinstallationdiscintoyoursystem'sopticaldrive(orUSBstickintoaUSBport)andreboot.ThesystemshouldboottotheCentOS7installationmenu.

2. Usingthearrowkeys,makesuretheInstallCentOS7optionishighlightedandpressTab.Thecommandtoboottheinstallerkernelappearsatthebottomofthescreen.

3. AddthewordtexttotheendofthelistofargumentsandpressEnter.Anacondawilllaunchintextmode:

vmzlinuzinitrd=initrd.imginst.stage2=hd:LABEL=CentOS

\x207\x20x86_64rd.live.checkquiettext

Note

Anacondawilllaunchintextmodeautomaticallyifyoursystemhaslessthan768MBofRAM.

4. TheInstallationmenupresentstheinstallationoptionsbycategory.Type2andpressEntertoselectTimezonesettings:

Thetext-basedinstallationmenucategorizestheinstallationoptions

5. TheTimezonesettingsmenupresentsalistofregions.Enterthenumberforthedesiredvalue.

6. Youwillbegivenalistofavailabletimezonesintheselectedregion(paginatethrough

Page 55: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

thelistbypressingEnterifthelistislong).Enterthenumberforthedesiredtimezone.7. Ifyouknowwhatpurposethesystemwillserveandrequiresomethingmorethana

minimalinstallation,enter3toselectSoftwareselection.Hereyoucanselectgroupsofsoftwarepackagesforthatpurpose.Whenfinished,enterctocontinuebacktotheInstallationmenu.

8. Enter5toselectNetworksettings.9. Enter1tosetthesystem'shostname.TypethedesirednameandpressEnter.10. Enterthenumbertoconfigurethesystem'sprimarynetworkinterface.Then,enter7to

markConnectautomaticallyafterrebootand8tomarkApplyconfigurationininstaller.EnterctogobacktotheNetworksettingsmenuandcagaintoreturntotheInstallationmenu:

TheNetworksettingsmenuletsusconfigurethesystem'snetworkinterfaces

11. Enter6toselectInstallDestination.12. Ifthedesireddriveisnotalreadymarked,enterthenumberforthedrive.Then,entercto

continue.TheAutopartioningOptionsmenuisshowninthefollowingscreenshot:

Page 56: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheInstallDestinationmenuletussettheinstallationtargetandtheAutopartioningOptionsmenuletsusspecifyhowthediskwillbeused

13. Enterthenumberforthedesiredpartitioning(UseAllSpaceisthedefault)andthenctocontinue.

14. Selectthedesiredpartitionscheme(LVMisthedefault)andthenenterctoreturntotheInstallationmenu.

15. Enter8toselectCreateuser.16. Enter1tomarktheCreateuseroption.Provideyournameandsetausernameforthe

accountbyentering2and3respectively.Enter4tomarktheUsepasswordoptionandthen5tosetyourpassword.Then,enterctoreturntotheInstallationmenu:

Note

Youmustconfirmyoureallywanttouseyourpasswordifyouprovideapasswordthatistooweak.

Page 57: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheCreateUsermenuletuscreateanunprivilegeduseraccount

17. Enter9toselectSetrootpassword.Enterandconfirmthepasswordyouwanttouseforthesystem'srootaccount.

18. Afterallofthesectionsthatrequiredattentionhavebeenresolved,enterbtobegintheinstallationprocess.

19. Whentheinstallationiscomplete,removethemediafromthedriveandrebootthesystem.

Page 58: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipeshowedyouhowtoinstallCentOSusingAnacondarunningintextmode.Theprocessbeganwhenwebootedthesystemfromtheinstallationdisc,selectedInstallCentOS7fromtheinstallationmenu,andaddedthetextoptiontothebootparameters.Theinstaller'skernelloadedintomemoryandAnacondalaunchedintextmode.

Thetext-basedinstallationissimilartoinstallingCentOSingraphicalmode,answeringpromptsfortimezone,software,andnetworkinginformation.However,Anacondapresentsthepromptsinadifferentorderwhenrunningintextmodeandsomefunctionalityismissing.Forexample,wecan'tperformcustomdiskpartitioning.Nevertheless,textmodeenablesustoquicklyinstallabasicCentOSsystem.

Page 59: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationoninstallingCentOS7,refertotheRHEL7InstallationGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide).

Page 60: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CoordinatingmultipleinstallationsusingKickstartIfyou'replanningoninstallingCentOSonmultipleservers,it'smoreconvenienttoautomateasmuchoftheprocessaspossible.Inthisrecipe,you'lllearnhowtouseAnaconda'skickstart.cfgfiletoperformanunattendednetwork-basedinstallation.

Page 61: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresatleasttwosystemsonyournetwork:anexistingsystemrunninganHTTPservertohosttheinstallationfilesandKickstartconfiguration(therecipeInstallingApacheHTTPServerandPHPinChapter10,ManagingWebServers,showsyouhowtoinstallApache)andthetargetsystemonwhichwe'llinstallCentOS.You'llalsoneedtheinstallationmediaandadministrativeprivileges.

Page 62: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoperformunattendednetworkinstallationsusingtheKickstartmethod:

1. LogintothesystemrunningtheHTTPserverusingtherootaccount.2. Placetheinstallationdiscinthesystem'sopticaldrive.3. Mountthediscusingthemountcommandsothatitscontentsareaccessible:

mount/dev/cdrom/media

4. CreateanewdirectoryunderApache'swebroottohosttheinstallationfiles:

mkdir-p/var/www/html/centos/7/x86_64

5. Copythecontentsoftheinstallationdisctothenewdirectory:

cp-r/media/*/var/www/html/centos/7/x86_64

6. Copythekickstart.cfgfilecreatedbyAnacondawhenthesystemwasinstalledtoApache'swebroot:

cp/root/kickstart.cfg/var/www/html/kickstart.cfg

7. Unmountandremovetheinstallationdisc:

umount/media

eject/dev/cdrom

8. Insertthediscintothetargetsystem'sdriveandrebootit.ThesystemshouldboottotheCentOS7installationmenu.

9. HighlighttheInstallCentOS7optionandpressTab.10. Updatetheargumentsusedtoboottheinstallerkerneltoreadasfollows.ChangetheIP

addressasnecessarytopointtothesystemhostingtheKickstartfile:

vmlinuzinitrd=initrd.imgks=http://192.168.56.100/kickstart.cfg

11. PressEntertobegintheinstallationprocess.12. Oncetheinstallationprocessbegins,youcanejectthediscandbeginthenextsystem's

installation.Repeatsteps8-11foreachadditionalsystem.

Page 63: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Anacondawritestheconfigurationvaluesweprovidewhenperformingagraphicalortext-basedinstallationtokickstart.cfg.IfyouplanoninstallingCentOSonmultipleservers,it'smoreconvenienttousethefiletoprovidetheinterface'sanswers.Theremaininginstallationscanbeperformedmostlyunattendedandthesystems'configurationswillbemoreconsistent.

Thisrecipeshowedyouhowtomakethekickstart.cfgfileandtheCentOSinstallationfilesavailabletoothersystemsoverthenetwork,andupdatethebootcommandtotellAnacondawheretolookfortheinstallationfilesandpromptresponses.Sincethesoftwarepackagesareretrievedfromtheinstallationserverinsteadofthedisc,youcanejectthediscassoonastheinstallationprocessisunderwayanduseittobeginthenextprocessonyournextsystem.

Ofcourse,kickstart.cfgcanbeusedasastartingpoint,andyoucanedittheresponsesusingatexteditortofurthercustomizetheinstallations.Ifyoulike,youcancreatemultiplekickstartfilesinthewebroot,eachwithadifferentconfiguration.Justspecifythedesiredfilewhenyousettheinstaller'sbootarguments.

Tip

Althoughyoucanedityourkickstartfileswithabasictexteditor,dedicatedprogramsexistforeditingthemaswell.CheckoutKickstartConfigurator(http://landoflinux.com/linux_kickstart_configurator.html).

Page 64: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationoncoordinatingmultipleinstallationsofCentOS7,refertothefollowingresources:

RHEL7InstallationGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide)Anacondadocumentation(http://rhinstaller.github.io/anaconda/index.html)InstallPXEServeronCentOS7(http://www.unixmen.com/install-pxe-server-centos-7)

Page 65: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RunningacloudimagewithAmazonWebServices'EC2AmazonWebServices(AWS)isasuiteofserviceshostedwithinAmazon'snetworkinfrastructurewhichallowscompaniesandindividualstakeadvantageoftheircomputing/storagecapacityandworldwidedatacenters.ElasticCloudCompute(EC2)isavirtualizationplatformthatletsussetupvirtualsystemsondemand,usuallytohostwebsitesandwebapps.ThisrecipewillwalkyouthroughtheprocessofsettingupanewvirtualserverrunningCentOSontheAWSplatform.

Page 66: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipeassumesthatyouhaveanAWSaccount.Youcansignupforoneathttp://aws.amazon.com.Youwillneedtoprovideavalidcreditcard,althoughyouwillhaveaccesstoAmazon'sfreetierfor12months.

Page 67: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...TosetupanewAmazonMachineInstance(AMI)onAWS'sEC2platform,followthesesteps:

1. Loginathttps://aws.amazon.comandgototheAWSManagementconsole.UndertheComputecategory,clickontheEC2linktoaccesstheEC2managementpage.Then,clickontheLaunchInstancebutton:

TheEC2ManagementConsolepresentsanoverviewandquickaccesstoresources

2. OntheChooseanAmazonMachineImage(AMI)page,selectCommunityAMIsinthesidemenuandthenchecktheCentOSfilter.Alistofinstancescreatedbythecommunitywillbeshown.Selecttheoneyoudesire:

Note

Reviewthelistofavailableimagescarefully.Manyareavailable,createdusingdifferentversionsofCentOSandwithvariousconfigurations.

Page 68: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theimageselectionpagepresentsafilterablelistofmachineimagescreatedbycommunityusers

3. OntheReviewInstanceLaunchpage,reviewyourinstance'sresources(thenumberofvirtualCPUs,availablememory,andsoon)andclickontheLaunchbutton:

Note

AmazonguidesyouthroughselectinganAMIandconfiguringitinawizard-likefashion,listingthestepsatthetopofthepage.TheReviewandLaunchbuttonsjumpdirectlytothelaststep.Youcanusethelinksatthetopofthepagetogobacktoanearlierstepandadjusttheinstance'sconfiguration.

Page 69: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Reviewyourinstance'sresourcesontheReviewInstanceLaunchpage

4. Usingthedrop-downlist,selectCreateanewkeypair,enterasuitablefilenameforthekey,andclickontheDownloadKeyPairbutton.Afteryousavethedownloadedprivateencryptionkey,clickontheLaunchInstancesbutton:

Page 70: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

You'repromptedtocreateapairofencryptionkeysthefirsttimeyoulaunchtheimage

5. Onthelaunchstatuspage,clickontheViewInstancesbuttonatthebottomofthepage.Then,right-clickontherunninginstanceandselectConnectfromthecontextmenu.Selectthepreferredconnectionmethodandfollowtheinstructionsthatappearonthescreen.

Page 71: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipewalkedyouthroughthestepsnecessarytospinupanewCentOSAMIonAWS'sEC2platform.Tologintothesystem,apasswordorsetofencryptionkeysisneeded,andsincetheprimaryuseraccount'spasswordislikelytobeunknown,weoptedtogenerateanewpairofkeys.TheprivatekeyisdownloadedandthenusedwithyourSSHclienttoauthenticateyourlogin.

Onceyouhaveloggedintoyourrunningsystem,it'sworthviewingthecontentsofthe/etc/system-releasefiletoverifytherunningversionofCentOS.Also,youshouldusethepasswdcommandtochangetherootaccount'spasswordiftheaccountisn'talreadylockeddown.Thisisanimportantsecurityprecautionbecauseyoudon'tknowwhoknowsthedefaultpassword.You'llfindrecipesformanaginguserpermissionsinChapter3,UserandPermissionManagement,andrecipesformanagingremoteaccessinChapter6,AllowingRemoteAccess:

Afteryoulogin,verifythesystem'sversionnumberandupdatetherootpassword

Page 72: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithAMIsonAmazon'sEC2platform:

WhatIsAmazonEC2?(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)ConnecttoYourLinuxInstance(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html)RemoveSSHHostKeyPairs(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/building-shared-amis.html#remove-ssh-host-key-pairs)

Page 73: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingacontainerimagefromtheDockerRegistryThisrecipeshowsyouhowtoprocureaCentOSbaseforyourdevelopmentneedsusingDocker,avirtualizationstrategybasedontheconceptofcontainers.Eachcontainerwrapsthetargetsoftwareinitsownfilesystemsothatitcanrunregardlessoftheoperatingsystemonwhichit'sinstalled.DeveloperslikeDockerespeciallybecauseithelpsprovideconsistencybetweendevelopmentanddeploymentenvironments.

Page 74: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyTherecipeassumesthatyouhaveasystemwithDockerinstalled.Ifyoudon't,youcanobtaintheDockerinstallerfromhttp://www.docker.com.

Page 75: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallaCentOScontainerimagefromtheDockerRegistry:

1. OpentheDockerToolboxterminalprogram.2. Attheterminal'sprompt,invokethedockerpullcommandtoretrieveaCentOS7

container:

dockerpullcentos:7

3. Afterthecontainerhasbeendownloaded,youcanlaunchaninteractiveshellwithdockerrun:

dockerrun-i-tcentos:7/bin/bash

Page 76: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisreciperetrievestheofficialCentOScontainerfromtheDockerRegistryusingthedockerpullcommand.Byprovidingtheversiontag(:7),wecanmakesureweretrievedCentOS7asopposedtoanearlier(orperhapsnewer)version.

Alternatively,Kitematicisthegraphicalprogramwhichletsussearchforandretrievecontainersfromtheregistry.SimplylaunchKitematicandenterCentOSasthesearchterminthesearchbox.Then,lookfortheofficialCentOSrepositoryintheresultslist.

ThedefaultversionretrievedbyKitematicisthelatest.TospecificallyselectCentOS7oramaintenancerelease,clickontheentry'sellipsisbutton.SetthedesiredtagandthenclickontheCreatebutton:

KitematicdisplaystheresultsofsearchingforCentOS

Page 77: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationaboutworkingwithDocker:

Dockerhomepage(http://www.docker.com)UnderstandingtheDockerarchitecture(https://docs.docker.com/engine/understanding-docker)TheofficialCentOSDockerhub(https://hub.docker.com/_/centos)

Page 78: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingtheGNOMEdesktopThisrecipeshowsyouhowtoinstalltheGNOMEdesktopenvironment,whichprovidesagraphicaluserinterface(GUI)forworkingwithyourCentOSsystem.Usually,suchenvironmentsaren'tinstalledonserversystems,butitcanbeconvenientsometimestohaveoneavailable.Forexample,anadministratormightfeelmorecomfortableupdatingasystem'sconfigurationusinggraphicalprograms.

Note

GNOMEisn'ttheonlyGUIenvironmentavailable—otherpopularenvironmentsincludeKDE,XFCE,andFluxbox.IfGNOMEisn'tyourcupoftea,thenextrecipeshowsyouhowtoinstallKDE.

Page 79: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequiredbylogginginwiththerootaccount.

Page 80: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstalltheGNOMEdesktopenvironment:

1. InstalltheGNOMEDesktoppackagegroupwithyumgroupinstall:

yumgroupinstall"GNOMEDesktop"

2. Manuallystartthedesktopenvironmentusingstartx:

startx

3. Ifmorethanoneenvironmentisinstalled,you'llneedtospecifythepathtognome-session:

startx/usr/bin/gnome-session

4. Whenyou'redoneusingGNOMEandlogoutofthedesktop,you'llbereturnedtotheconsole.

5. Toconfigurethesystemtoautomaticallystartthegraphicalenvironmentwhenitboots,setthedefaultstartuptargettographical.target:

systemctlset-defaultgraphical.target

Page 81: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipeusesyumtoinstalltheGNOMEdesktopenvironment.AllofthenecessarycomponentsanddependenciesareinstalledbytheGNOMEDesktoppackagegroup.Packagegroupssavesustimeandhasslebecausetheyletusinstallacollectionofpackagesforacommontaskatthesametimeinsteadofindividualpackagesoneatatime.

yumgroupinstall"GNOMEDesktop"

UnlikeWindows,wherethegraphicaldesktopispartofitsoperatingsystem,Linuxsystemsdelegatebasicgraphicsandinputhandlingtoagraphicsserver.Thisapproachisonereasonwhythereareseveraldesktopenvironmentstochoosefrom—itabstractsmanyofthespecificsandprovidesacommonplatformontopofwhichanynumberofenvironmentscanrun,bothlocallyandacrossanetwork.CentOS'sdefaultgraphicsserverisXWindowSystem.

IfGNOMEistheonlydesktopenvironmentinstalled,it'llberunbydefaultwhenwelaunchXwithstartx.However,ifmorethanonedesktopisinstalled,weneedtotellXwhichonewewanttorun.ForGNOME,weprovidethepathtognome-session:

startx/usr/bin/gnome-session

Page 82: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheGNOMEdesktopprovidesagraphicalinterfaceforworkingwiththesystem

Thesystemdservicemanagerisresponsibleforstartingvariousserversandprocesseswhenthesystemboots.Thesystemctlcommandisourinterfacetotheservicemanagerandcanbeusedtosetthedefaultboottarget.ThedefaulttargetdictateswhetherthesystembootstoaterminalorGUI-basedloginscreen:

systemctlset-defaultgraphical.target

Whensettographical,systemdstartsXandtheGNOMEDisplayManagerwhenthesystemboots,whichpresentsuswithagraphicallogintoprovideouraccountdetails.Oncewe'reauthenticated,thedesktopsessionisinitiatedandwefindourselvesattheGNOMEdesktop.

Ifyounolongerwanttoboottothegraphicalenvironment,youcansetthedefaulttargetbacktomultiuserandthesystemwillboottotheterminal-basedloginscreenagain:

systemctlset-defaultmulti-user.target

Page 83: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Tip

Youcanchoosewhichdesktopenvironmentyouwanttouseifmorethanoneenvironmentisinstalledbyselectingitfromthegearbuttonontheloginscreen:

Youcanselectyourpreferreddesktopfromtheloginscreen

Page 84: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoThefollowingresourceswillprovideyouwithmoreinformationaboutinstallinggraphicaldesktopenvironmentsandusingtheGNOMEdesktop:

GNOMELibrary(https://help.gnome.org)RHEL7DesktopMigrationandAdministrationGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Desktop_Migration_and_Administration_Guide)GuildtoX11/StartingSessions(https://en.wikibooks.org/wiki/Guide_to_X11/Starting_Sessions)HowtoinstalldesktopenvironmentsonCentOS7(http://unix.stackexchange.com/questions/181503/how-to-install-desktop-environments-on-centos-7/181504#181504)

Page 85: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingtheKDEPlasmadesktopSeparatingthegraphicalinterfacefromtheoperatingsystemgivesusersthepowertochoosethegraphicalenvironmenttheylikebest.Don'tworryifyou'renotaGNOMEfanbecausetherearestillmanyotherdesktopsyoucanexplore!Thisrecipeshowsyouhowtoinstallanotherpopulardesktopenvironment,KDEPlasmaWorkspaces.

Page 86: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequiredbylogginginwiththerootaccount.

Page 87: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstalltheKDEPlasmaWorkspacesdesktopenvironment:

1. InstalltheKDEPlasmaWorkspacespackagegroup:

yumgroupinstall"KDEPlasmaWorkspaces"

2. Manuallystartthedesktopenvironmentusingstartkde.Whenyou'redoneusingKDEandlogoutofthedesktop,you'llbereturnedtotheconsole:

startkde

3. Toconfigurethesystemtoautomaticallystartthegraphicalenvironmentwhenitboots,usesystemctltosetthedefaultstartuptargettographical.target:

systemctlset-defaultgraphical.target

Page 88: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipeinstallstheKDEPlasmaWorkspacesdesktopenvironmentviaYum'spackagegroups.AllofthenecessarysoftwarecomponentsanddependenciestorunKDEareinstalledbytheKDEPlasmaWorkspacespackagegroup:

yumgroupinstall"KDEPlasmaWorkspaces"

ThestartkdescriptstartstheXserverandlaunchestheKDEenvironmenttogether.UnlikewithGNOME,we'renotinvokingstartxdirectly,sowedon'tneedtoprovideadditionalpathswhenmorethanoneenvironmentisinstalled:

startkde

KDEPlasmaWorkspacesisapopulargraphicaldesktopenvironmentforLinux-basedsystems

Page 89: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoThefollowingresourceswillprovideyouwithmoreinformationaboutinstallingandusingKDEPlasmaWorkspaces:

HowtoinstalldesktopenvironmentsonCentOS7(http://unix.stackexchange.com/questions/181503/how-to-install-desktop-environments-on-centos-7/181504#181504)KDEdocumentation(https://docs.kde.org)

Page 90: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter2.NetworkingThischaptercontainsthefollowingrecipes:

SettingastaticIPaddressBindingmultipleaddressestoasingleEthernetdeviceBondingtwoEthernetdevicesConfiguringthenetworkfirewallwithFirewallDConfiguringthenetworkfirewallusingiptablesInstallingaDHCPserverConfiguringanNFSservertoshareafilesystemConfiguringanNFSclienttouseasharedfilesystemServingWindowsshareswithSamba

Page 91: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionTherecipesinthischaptercovervariousnetworkingtasksthatshouldproveusefultoyouasaCentOSadministrator.You'lllearnhowtoconfigureastaticIPaddress,bindmultipleaddressestoasingleEthernetdevice,andbondtwodevicestogether.You'llalsoseehowtoconfigurethesystem'sfirewallusingFirewallDandiptables,andhowtosetupaDHCPservertodistributeIPaddresses,whichallowsothercomputersusingdynamicnetworkingconfigurationstoaccessthenetwork.TheremainingrecipeswillteachyouhowtosetupcentralizedfilestorageusingNFSandSamba.

Page 92: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingastaticIPaddressThisrecipeshowsyouhowtoconfigureastaticIPaddress.Unlessyouconfiguredastaticaddressduringinstallation,CentOSusestheDynamicHostConfigurationProtocol(DHCP)toobtainanIPaddresstocommunicateacrossthenetwork.Usingadynamicallyassignedaddressisfineformostdesktopandlaptopsystems,butthosethathoste-mailservers,filesharingandprintservices,andwebserversshouldhaveanaddressthatdoesn'tchange.Thestaticaddressprovidesastable,knownlocationonthenetworkwhereuserscanaccessasystem'sservices.

Page 93: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandadministrativeprivilegesprovidedbylogginginwiththerootaccount.ItassumesthatyourprimaryEthernetdeviceisnamedenp0s3andiscurrentlyconfiguredwithDHCP.Ifyourdeviceisnameddifferently,substituteitsnameappropriatelyinthefollowingcommands.

Page 94: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigureastaticIPaddress:

1. OpentheEthernetdevice'sconfigurationfile,foundunder/etc/sysconfig/network-scripts,withyourtexteditor:

vi/etc/sysconfig/network-scripts/ifcfg-enp0s3

2. ChangethevalueofBOOTPROTOtonone:

BOOTPROTO="none"

3. Attheendofthefile,addtheIPADDR,NETMASK,andBROADCASTentriestosetthedesiredIPaddress.Assignthemvaluesthatproperlyreflectyournetwork:

IPADDR="192.168.56.100"

NETMASK="255.255.255.0"

BROADCAST="192.168.56.255"

TheinterfaceisconfiguredwithastaticIPaddress

4. Saveyourchangesandclosethefile.5. Openthe/etc/sysconfig/networkfileusingyoureditor:

vi/etc/sysconfig/network

6. AddaGATEWAYentrytoidentifyyournetwork'sgateway:

Page 95: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GATEWAY="192.168.56.1"

7. Saveyourchangesandclosethefile.8. Restartthenetworkingservicefortheconfigurationchangestotakeeffect:

systemctlrestartnetwork.service

Page 96: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Inthisrecipe,youlearnedhowtoassignastaticIPaddresstoanEthernetdevice.ItassumedthenameofyourprimaryEthernetdevicetobeenp0s3,thusifcfg-enp0s3wouldbethenameofthedevice'sconfigurationfile.Ifyourdeviceisnameddifferently(forexample,eth0,eno1677,andsoon)thenyouneedtoadjusttherecipe'sdirectionsaccordingly.

First,wechangedthevalueforBOOTPROTOfromdhcp,theprotocolusedtoobtainanIPaddressdynamically,tononesincewearesettingtheaddressourselves.ThenweaddedtheIPADDR,NETMASK,andBROADCASTentriestoprovidethedetailsofthestaticIPaddress.Next,wespecifiedthenetwork'sdefaultgatewayusingGATEWAYin/etc/sysconfig/network.Thisallowsustoroutetrafficbeyondthelocalsubnetwork.

Afteryourestartthenetworkingservice,youcanconfirmthenewaddressusingtheipcommand.ipaddrshowwilldisplayinformationaboutthecurrentstateofyoursystem'snetworkdevices:

ipaddrshowdisplaysyoursystem'snetworkinginformation

Page 97: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonconfiguringnetworksettingsinCentOS,refertotheConfigureIPNetworkingchapterintheRHEL7NetworkingGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/ch-Configure_IP_Networking.html).

Page 98: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

BindingmultipleaddressestoasingleEthernetdeviceThisrecipeshowsyouhowtobindmultipleIPaddressestoasingleEthernetdevice.Theabilitytoassignmorethanoneaddresstothesamedevicecanbeuseful-themostobviousbenefitisthatyoudon'tneedtoprocuremultipleEthernetcards.Thecostofhardwarehasdroppedsubstantially,butITbudgetsstillruntight.Perhapsalessobviousbenefit,butonemorevaluable,isthegreaterflexibilityitgiveswhenconfiguringnetworkservices.Differentservices,suchase-mailandwebsites,canrunonthesamesystembutbeaccessedusingdifferentaddresses.

Page 99: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Gettingready

This recipe requires a CentOS system with a working network connection. It assumes thatyour primary Ethernet device is enp0s3 and is configured with a static IP address. You'll also need administrative privileges provided by logging in with the root account. Technet24.ir

Page 100: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstobindmultipleaddressestothesameEthernetdevice:

1. Makeacopyofthedevice'sconfigurationfile:

cp/etc/sysconfig/network-scripts/ifcfg-enp0s3

/etc/sysconfig/network-scripts/ifcfg-enp0s3:1

2. Openthenewfilewithyourtexteditor:

vi/etc/sysconfig/network-scripts/ifcfg-enp0s3:1

3. DeletetheUUIDentryentirely.IfaHWADDRentryexists,deletethatalso.4. UpdatetheNAMEandDEVICEvalues:

NAME="Systemenp0s3:1"

DEVICE="enp0s3:1"

5. ChangethevalueofIPADDRtotheIPaddressyouwishtouse:

IPADDR="192.168.56.101"

6. Saveyourchangesandclosethefile.7. Restartthenetworkingservicefortheconfigurationchangestotakeeffect:

systemctlrestartnetwork.service

Page 101: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Inthisrecipe,youlearnedhowtoassignmultipleIPaddressestothesameEthernetdevice.Wemadeacopyofoneoftheoriginalnetworkconfigurationfiles,takingcaretonameitappropriatelytocreateavirtualadapter,andediteditsconfigurationdetails.Sincethenameofthefirstdevice'sconfigurationisifcfg-enp0s3,thenewfileisnamedifcfg-enp0s3:1tocreatethefirstvirtualadapterassociatedwiththatdevice.Ifyouwanttoaddmoreadapters(assignmoreIPaddresses),repeatthestepsusingincrementingnumbers,forexample,enp0s3:2,enp0s3:3,andsoon.

Intheconfigurationfile,weremovedtheHWADDRandUUIDentriessincetheyarenotneededforavirtualadapter.ThenweupdatedtheDEVICEandNAMEentriestogivetheadapteritsownidentify,and,ofcourse,weupdatedtheIPADDRentrytoassignitsIPaddress:

MultipleIPaddressesareboundtoanEthernetdeviceviaavirtualadapter

Page 102: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonbindingmultipleaddressestothesameEthernetdevice:

CreateMultipleIPAddressestoOneSingleNetworkInterface(http://www.tecmint.com/create-multiple-ip-addresses-to-one-single-network-interface)AssignMultipleIPAddressesToSingleNetworkInterfaceCardOnCentOS7(http://www.unixmen.com/linux-basics-assign-multiple-ip-addresses-single-network-interface-card-centos-7)AddingSecondaryIPAddresses(https://dbiers.me/adding-secondary-ip-addresses-centosrhel/)

Page 103: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

BondingtwoEthernetdevicesInthisrecipe,you'lllearnhowtocombinemultipleEthernetdevicesasasinglenetworkdeviceinaconfigurationknownaschannelbonding.ChannelbondingallowsustobindmultipledevicestogethersothattheyappearasasingleinterfacetoserversrunningontheCentOSsystem.Itspurposeistoimproveyoursystem'soverallnetworkperformanceandprovideredundancyifoneofthenetworkdevicesfails.

Page 104: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithatleasttwoEthernetdevices.ItassumesthatyourprimaryEthernetdeviceisenp0s3.Ifyourdeviceisnameddifferently,substitutethenameappropriatelyintherecipe'scommands.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Page 105: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstobondtwoEthernetdevices:

1. Installthebind-utilsandethtoolpackages:

yuminstallbind-utilsethtool

2. Createanewconfigurationfileforthebondedinterface:

vi/etc/sysconfig/network-scripts/ifcfg-bond0

3. Addthefollowinglinestothefile,substitutingvaluesforIPADDR,NETMASK,andBROADCASTthatareappropriateforyournetwork:

BOOTPROTO="none"

DEVICE="bond0"

USERCTL="no"

ONBOOT="yes"

IPADDR="192.168.56.100"

NETMASK="255.255.255.0"

BROADCAST="192.168.56.255"

4. Saveyourchangesandclosetheconfigurationfile.5. Opentheconfigurationfileofthefirstdeviceyouwishtobond:

vi/etc/sysconfig/network-scripts/ifcfg-enp0s3

6. MakesureBOOTPROTOissettononeandONBOOTissettoyes.ThenremovetheIPADDR,NETMASK,andBROADCASTentriesiftheyexist.

7. AddtheSLAVEandMASTERentriesattheendofthefile:

SLAVE=yes

MASTER=bond0

8. Saveyourchangesandclosetheconfigurationfile.9. Repeatsteps5-8foreachadditionaldeviceyouwanttobond.10. Createtheconfigurationfileusedbythekerneltocontrolhowthebondinginterface

shouldbehave:

vi/etc/modprobe.d/bonding.conf

11. Addthefollowinglinestothefile:

aliasbond0bonding

optionsbond0mode=5miimon=100

12. Saveyourchangesandclosethefile.13. Registerthebondingmodulewiththesystem'skernel:

modprobebonding

14. Restartnetworkingservicesforthechangestotakeeffect:

systemctlrestartnetwork.service

Page 106: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote
Page 107: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Webeganbycreatingaconfigurationfileforthebondinginterfaceat/etc/sysconfig/network-scripts/ifcfg-bond0.BOOTPROTOwassettononebecausetheIPaddressissetstatically,DEVICEgivesanametotheinterface,USERCTLwassettonotoprohibitnonadministrativeusersfrombringingtheinterfaceupanddown,andONBOOTwassettoyessothattheinterfacewillbeautomaticallyactivated.WealsogavetheIPaddressinformationwithIPADDR,NETMASK,andBROADCAST:

BOOTPROTO="none"

DEVICE="bond0"

USERCTL="no"

ONBOOT="yes"

IPADDR="192.168.56.100"

NETMASK="255.255.255.0"

BROADCAST="192.168.56.255"

Thenweupdatedtheconfigurationfilesforeachdevicewewanttobond.WemadesureBOOTPROTOwassettononeandtherewasnoaddressinformationsincethedevicewillnolongerneeditsownIPaddress.AddingtheSLAVEandMASTERentries,weidentifiedthedeviceasbeingboundtothenewbond0device:

SLAVE=yes

MASTER=bond0

Byperformingthesesteps,wehavecreatedanewvirtualdeviceknownasthebondingmasterthatwilluseourrealEthernetdevicesasslaves.Ifoneslavedevicefails,theotherslavewillstillbeactive,providingredundancy.

Next,wecreatedanewconfigurationfilewithourpreferencesforthekernelbondingmodule.Themoduleisthekernelimplementationofthebondingdeviceandisresponsibleforcoordinatingthephysicaldevices:

aliasbond0bonding

optionsbond0miimon=100mode=5

miimon=100specifiesthatMIIlinkmonitoringwilloccurevery100millisecondstoverifythatthephysicaldevicesareactive.mode=5representsabasicconfigurationthatdoesn'trequireanyspecifictypeofnetworkswitchsupport.Itallowsoutgoingtraffictobedistributedaccordingtothecurrentloadoneachslavedevice.Therearefiveothermodeswhichgiveyouplentyofoptionsinconfiguringhowthedevicesworktogether,althoughyoushouldbeawarethatsomemodesmayrequirespecifichardwaresupport.Refertohttp://wiki.centos.org/TipsAndTricks/BondingInterfacesformoreinformation.

Aftermakingchangestothedevice'sconfigurationfiles,weregisteredthebondingkernelmoduleusingmodprobe:

modprobebonding

Page 108: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TwoEthernetdevicesareboundwiththesameIPaddressesthroughthebondingadapter

Page 109: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonbondingEthernetdevicesCentOS,refertotheConfigureNetworkBondingchapterintheRHEL7NetworkingGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/ch-Configure_Network_Bonding.html).

Page 110: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringthenetworkfirewallwithFirewallDNowyou'lllearnhowtoconfigurethenetworkingfirewallusingFirewallD.StartingwithCentOS7,FirewallDreplacesiptablesasthedefaultfirewallconfigurationutility(althoughiptablesisstillusedbehindthescenesbyFirewallD).Basedonwhichzonesandservicesyouconfigure,youcanincreasethenetworksecurityofyourserverbycontrollingwhattrafficisallowedordisallowedtoandfromthesystem.

Page 111: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Page 112: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ThiscollectionofcommandswillshowyouhowtoperformseveralbasicconfigurationtasksusingFirewallD'scommand-lineclient,firewall-cmd:

1. ToidentifythecurrentlyactivezonesandwhichEthernetdevicesareassignedtothem,usethe--get-active-zonesflag:

firewall-cmd--get-active-zones

2. Totemporarilychangewhichzoneadeviceisassignedto,usethe--zoneargumenttospecifythetargetzoneand--change-interfacetospecifytheEthernetdevice:

firewall-cmd--zone=public--change-interface=enp0s3

3. Topermanentlyassignadevicetoazone,addaZONEentrytothedevice'sconfigurationfile.Thischangewillnottakeeffectuntiltheservicehasbeenrestarted:

vi/etc/sysconfig/network-scripts/ifcfg-enp0s3

ZONE="public"

4. Toidentifythecurrentconfigurationforazone,usethe--zoneargumenttospecifythetargetzoneandinclude--list-all:

firewall-cmd--zone=public--list-all

5. Toallowtrafficthroughthefirewall,usethe--add-serviceor--add-portarguments:

TrafficforcommonservicesandprotocolssuchasHTTPandSMTPcanbeallowedbyname.Thefollowingaddsthehttpservicewhichopensport80(theportusedbyApacheandotherHTTPservers):

firewall-cmd--zone=public--permanent--add-service=http

Trafficcanalwaysbealloweddirectlygiventheportandnetworkprotocol.Thefollowingopensport8080toTCPtraffic,anotherportcommonlyusedtoservewebcontent:

firewall-cmd--zone=public--permanent--add-port=8080/tcp

6. Todisallowtrafficthatiscurrentlyallowedthroughthefirewall,usethe--remove-serviceor--remove-portarguments:

firewall-cmd--zone=public--permanent--remove-service=http

firewall-cmd--zone=public--permanent--remove-port=8080/tcp

7. Toreloadthefirewallaftermakingachange,use--reload:

firewall-cmd--reload

Page 113: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThedefaultinstallationofFirewallDmakesseveralpreconfiguredzonesavailable,forexample,public,dmz,work,home,andtrusted.Differentinterfacescanbeassignedtodifferentzonesandhavedifferentrulesapplied.Toseealloftheavailablezonesandtheirconfiguration,wecaninvokefirewall-cmdwiththe--list-all-zonesflag:

firewall-cmd--list-all-zones

Mostupdatesmadetothefirewallruleswilltakeeffectimmediatelybutaretemporary.Wesawthisearlierwhenwehadtoupdatethedevice'sconfigurationfileandrestarttheservicetomakeazonechangepermanent.Thisletsusexperimentwithdifferentsettingsbeforefinalizingtheconfiguration.Whenconfiguringservicesandports,the--permanentflagisusedtomakethechangespermanent.Ifyoudon'tprovidetheflag,thechangeswilltakeeffectimmediatelybutwillonlybetemporary(notpersistacrossasystemrebootorrestartofthefirewallservice):

firewall-cmd--zone=public--permanent--remove-service=http

Namedservicesarepreconfiguredportsettingsthatarecommontoaspecificnetworkserviceandareavailableforourconvenience.Forexample,SSHtrafficcommonlyconsistsofTCPpacketsdestinedforport22,sothesshservicereflectsthis.Intheexamples,weusedthehttpservice,whichconfiguredport80,thestandardportusedtoservewebpages.Whileassigningtheportdirectlyhasthesameeffect,servicesprovideconvenient,human-readablenamesandshouldbeusedwhenpossible.Togetalistofallavailableservices,use--get-services:

firewall-cmd--get-services

Page 114: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

firewall-cmdisacommand-lineclientforconfiguringfirewallrules

Note

NamedservicesaredefinedasXMLfilesunder/usr/lib/firewalld/services.Ifyouwanttoallowaccessforsometrafficbutaserviceisn'tdefined,andyouwouldprefertoperformtheconfigurationusingaserviceinsteadoftheportandprotocolforthesakeofreadability,youcancreateanewservicefileinthisdirectory.Copyanexistingfileasyourstartingpointandmodifyittosuityourneeds.

Page 115: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonworkingwithFirewallD,refertothefollowingresources:

RHEL7MigrationPlanningGuide:SecurityandAccessControl(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_%20Linux/7/html/Migration_Planning_Guide/sect-Red_Hat_Enterprise_%20Linux-Migration_Planning_Guide-Security_and_Access_%20Control.html)FirewallD(http://fedoraproject.org/wiki/FirewallD)HowToSetUpaFirewallUsingFirewallDonCentOS7(https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7)

Page 116: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringthenetworkfirewallusingiptablesInthisrecipe,you'lllearnhowtoreplaceFirewallDwiththeiptablesserviceandperformbasicfirewallconfigurations.iptableswasthedefaultmethodformanagingthefirewall'ssettingsinCentOSpriortoversion7.Someadministratorsmightpreferiptablesbecauseit'swithintheircomfortlevelormaybetheyhaveseveralolderserversrunninginthedatacenterandtheywanttomaintainsimilarityasmuchaspossible.

Page 117: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Page 118: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ThefollowingstepswillallowyoutoreplaceFirewallDwiththeiptablesservice:

1. StoptheFirewallDserviceanddisableit:

systemctlstopfirewalld

systemctlmaskfirewalld

2. Installtheiptables-servicespackagewhichcontainstheservice:

yuminstalliptables-services

3. Starttheserviceandregisteritsothatitwillstartautomaticallywhenthesystemisbooted:

systemctlstartiptables

systemctlenableiptables

Thefollowingcollectionofcommandswillshowyouhowtoperformseveralbasicconfigurationtasksusingiptables:

Usethe-Lflagtoprintthecurrentconfiguration.Addthe--line-numbersflagtodisplayeachrule'sIDnumberalongsideit:

iptables-L--line-numbers

UsethefollowingcommandtoallowTCPtrafficonport80fromtheenp0s3interfacethroughthefirewall:

iptables-AINPUT-ienp0s3--dport80-ptcp-jACCEPT

ToremovetherulethatallowsTCPtrafficonport80,executeiptables-L--line-numberstofindtherule'sIDandthenusethefollowing(replace##withtherule'sID):

iptables-DINPUT##

Reloadiptablesaftermakingconfigurationchangesforthemtobeineffect:

systemctlrestartiptables

Page 119: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ToreplaceFirewallDwiththeiptablesservicetomanagethenetworkfirewall,wefirststoppedanddisabledtheFirewallDservice;wedon'twantmultiplefirewalldaemonsrunningsinceitwouldleadtoconflicts.FirewallDusesiptablesbehindthescenessoiptablesisalreadyinstalled,buttheiptablesserviceisn't.So,nextweinstalledtheiptables-servicespackage:

yuminstalliptables-services

Wethensawhowtoperformbasicconfigurationstoallowanddisallowtraffic.Forexample,therecipepresentedthecommandtoaddarulethatallowsTCPtrafficthroughport80:

iptables-AINPUT-ienp0s3--dport80-ptcp-jACCEPT

The-Aargumentindicatesthatwewishtoaddafirewallruleandisfollowedbytheruletype.PossiblevaluesareINPUT,OUTPUT,andFORWARD,whichapplytoincomingtraffic,outgoingtraffic,andtrafficthatisrouted,respectively(ifthesystemisconfiguredasarouter,forexample).SinceINPUTisspecified,ourruleappliestoincomingtrafficonport80.

The-iargumentspecifiesthenetworkinterfacethatismonitoredbytherule.Inthiscase,theruleappliestoenp0s3.Then,--dportspecifiesthetraffic'sdestinationport,inthiscaseport80,and-pspecifiesthetransportprotocol,forexample,eitherTCPorUDP.

The-jargumentisthetargetactionforjumpto.Withiptables,rulesarestrungtogethertomakechainsoffilteringlogic.Imagineiptablescheckingtrafficagainsteachrulewe'vespecified;ifthefirstruledoesn'tmatch,itgoesontocheckthenextrule,andthenext,untilamatchisfound.Whenthematchingruleisfound,iptablesstopscheckingandjumpstothedesiredstate.PossiblestatesareACCEPTtoacceptthetraffic,REJECTtoactivelydenytheconnection,andDROPtosilentlyignoreit.

Wealsosawhowtodisplaytherulesthatarecurrentlydefinedusingthe-Lflagandthatusing--line-numberswilldisplayanidentifieralongsideeachrule:

iptables-L--line-numbers

Page 120: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

iptablesacceptsordeniestrafficbasedontheconfiguredrules

Knowingarule'sidentifierisconvenientifwewanttodeleteit.Byproviding-D,theruletype(INPUT,OUTPUT,orFORWARD),andtheID,wecansuccinctlyremovearulefromthechain:

iptables-DINPUT6

Alternatively,youcanrespecifytheentirerulewhilesubstituting-Awith-Dtodeleteit:

iptables-DINPUT-ienp0s3--dport80-ptcp-jACCEPT

Page 121: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithiptables:

HowtoMigratefromFirewallDtoiptablesonCentOS7(https://www.digitalocean.com/community/tutorials/how-to-migrate-from-firewalld-to-iptables-on-centos-7)HowtoListandDeleteiptablesFirewallRules(https://www.digitalocean.com/community/tutorials/how-to-list-and-delete-iptables-firewall-rules)25MostFrequentlyUsedLinuxiptablesRules(http://www.thegeekstuff.com/2011/06/iptables-rules-examples)Dropversusreject(http://www.chiark.greenend.org.uk/~peterb/network/drop-vs-reject)

Page 122: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingaDHCPserverThisrecipewillshowyouhowtosetupyourownDHCPserveronCentOS.DHCPisusedtoassignIPaddressesandothernetworkconfigurationdetailsondemandtoaclient.WhileasystemconfiguredwithastaticIPaddresswillalreadyknowallthenecessarynetworkingdetails,asystemconfiguredtouseDHCPbroadcastsarequestonthenetworkandwaitstoreceivearesponsefromtheDHCPserver.

Page 123: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Note

OnlyoneDHCPservershouldberunningonthenetworktopreventclientsfromreceivingconflictingresponsesthatcanresultinnetworkinstability.ManyroutersalreadyhaveaDHCPservicerunningonthem,socheckforthisonyourownnetworkbeforeproceeding.

Page 124: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupaDHCPserver:

1. Installthedhcppackage:

yuminstalldhcp

2. Copytheexampleconfigurationfileprovidedbythepackagetoserveasthestartingpointofyourserver'sconfiguration:

cp/usr/share/doc/dhcp-4.2.5/dhcpd.conf.example

/etc/dhcp/dhcpd.conf

3. Opentheconfigurationfileusingyourtexteditor:

vi/etc/dhcp/dhcpd.conf

4. Modifytheconfigurationwithvaluesthatmakesenseforyourenvironment.Inparticular,you'llwanttoaddressthefollowingoptions:domain-nameanddomain-name-servers,subnet,thedynamic-bootprange,broadcast-address,androuters.Hereisanexampleconfigurationforanetworkoftwosubnets:

#optiondefinitionscommontoallsupportednetworks

optiondomain-namelocaldomain;

optiondomain-name-serversns1.localdomain;

default-lease-time600;

max-lease-time7200;

#ThisDHCPserveristheofficialDHCPserverforthe

#localnetwork

authoritative;

#Noservicewillbegivenonthissubnet,butdeclaring

#ithelpstheservertounderstandthenetworktopology.

subnet192.168.56.0netmask255.255.255.0{

}

#Thisisabasicsubnetdeclaration

subnet192.168.56.0netmask255.255.255.128{

range192.168.56.110192.168.56.120;

optiondomain-name-serversns1.localdomain;

optiondomain-name"localdomain";

optionrouters192.168.56.1;

optionbroadcast-address192.168.56.127;

}

#Thisisthesecondsubnet

subnet192.168.56.128netmask255.255.255.128{

range192.168.56.200192.168.56.210;

optiondomain-name-serversns2.sub.localdomain;

optiondomain-name"sub.localdomain";

optionrouters192.168.56.129;

optionbroadcast-address192.168.56.255;

}

5. Saveyourchangesandclosethefile.6. Startthedhcpserviceandenableittostartatsystemboot:

Page 125: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

systemctlstartdhcpd

systemctlenabledhcpd

7. Openports67and68inthesystem'sfirewalltoallowtraffic:

firewall-cmd--zone=public--permanent--add-service=dhcp

firewall-cmd--reload

Page 126: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...AsystemconfiguredtouseDHCPwillbroadcastarequestandwaittoreceivearesponsefromtheDHCPserver.Theserver'sresponseletstheclientknowwhichIPaddress,netmask,gatewayinformation,andsoontouseonthenetwork.DHCP-provisionedaddressesareusuallyleased,whichmeansthatafterasetamountoftimetheyexpireandtheclientneedstosendanotherrequest.TheDHCPserver,inadditiontohandingoutconnectiondetails,mustkeeptrackoftheaddressesthathavealreadybeenleasedsothataclientdoesn'treceiveanaddressthat'salreadyinusebyanothersystem.

Webeganbyinstallingthedhcpdpackage,whichcontainstheserverandexampleconfigurationfiles.Copyingtheexampleconfigurationtouseasastartingpointforourownsavesusfromhavingtodrafttheentireconfigurationfromscratch:

cp/usr/share/doc/dhcp-4.2.5/dhcpd.conf.example/etc/dhcp/dhcpd.conf

Intheconfigurationfile,thereareseveralplaceswhereyouneedtoprovidevaluesthatmakesenseforyournetwork.Theminimalconfigurationfileprovidedasanillustrationintherecipereflectsanetworkdividedintotwosubnets.Thefirstsubnetis192.168.56.0/25andthesecondis192.168.56.128/25.Eachsubnethasitsowndeclaration.

Examiningthefirstsubnetdeclaration,thesubnet'sIDis192.168.56.0withanetmaskof255.255.255.128.TherangeoptionwillrestricttheDHCPserverinassigningIPaddressesintherangeof192.168.56.110to120(theotheraddressesarestillvalidandareavailableforstaticassignment).Subsequentoptionentriesprovidethesubnet'sbroadcast-addressandgateway,andoverridethedomainnameandnameserversdefinedglobally:

#Thisisabasicsubnetdeclaration

subnet192.168.56.0netmask255.255.255.128{

range192.168.56.110192.168.56.120;

optiondomain-name-serversns1.localdomain;

optiondomain-name"localdomain";

optionrouters192.168.56.1;

optionbroadcast-address192.168.56.127;

}

ConfiguringaDHCPserverproperlyrequiresanunderstandingofcomputernetworking.Itisacomplextopicand,assuch,wecan'tdiscusseveryoptionindetail.Iadviseyoutoreadthemanualpagefordhcpd.confforextraguidance.Thepagecanbeaccessedusingthemancommand:

man5dhcpd.conf

Page 127: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theconfigurationfilefordhcpdisdocumentedinamanualpage

OncetheDHCPserverwasconfiguredandrunning,wethenneededtopokeaholeinthefirewalltoallowrequestsandresponsestoflowfreely.DHCPrequestsoccurusingUDPandports57and58(youcanallowthemusingtheservicedefinedforFirewallD):

firewall-cmd--zone=public--permanent--add-service=dhcp

firewall-cmd--reload

Page 128: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonsettingupaDHCPserver,refertothefollowingresources:

Thedhcpd.confmanualpage(man5dhcpd.conf)RHEL7NetworkingGuide:DHCPServers(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/ch-DHCP_Servers.html)QuickStart:SetupCentOS7asaDHCPServer(www.yoyoclouds.com/2015/01/quick-start-setup-centos-7-as-dhcp.html)SubnetCalculator(www.subnet-calculator.com)

Page 129: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringanNFSservertoshareafilesystemNetworkFileSystem(NFS)isaprotocolforadistributedfilesystem.Thatis,wecanstorefilestoadirectoryonaremoteserverandclientscanmounttheshare.Theremotedirectorywillappeartotheclientasifitwerelocal,althoughalldatasavedtoitresidesontheserver.ThisrecipeshowsyouhowtoconfigureNFSonaserverandexposethestorageasanetworkshare.(ThenextrecipewillshowyouhowtoconfigureNFSonaclient.)

Page 130: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Page 131: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupanNFSserver:

1. Installthenfs-utilsandlibnfsidmappackages:

yuminstallnfs-utilslibnfsidmap

2. Createagloballyaccessibledirectorywhichwillserveastherootofthefileshare:

mkdir-m777/var/nfsshare

3. Open/etc/exportsandaddthefollowingentrytomarkthedirectoryforexportbyNFS.Whendone,saveandclosethefile:

/var/nfsshare192.168.56.0/24(rw,sync,root_squash)

Theexportsfileisverypicky.Makesurethere'snospacebetweenthenetworkandtheparenthesizedoptionsaswellasnospacesaroundthecommasthatseparatetheoptions.

4. Startthenecessaryservicesandregisterthemsothattheywillstartwhentheserverboots:

systemctlstartrpcbindnfs-server

systemctlenablerpcbindnfs-server

5. Openports111,2048,and2049inthefirewalltoallowtrafficthrough:

firewall-cmd--permanent--zonepublic--add-servicerpc-bind

firewall-cmd--permanent--zonepublic--add-servicemountd

firewall-cmd--permanent--zonepublic--add-servicenfs

firewall-cmd--reload

Page 132: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Inthisrecipe,youlearnedhowtosetupasharednetworkdirectoryusingNFS.Afterinstallingtheappropriatepackages,wecreatedtheshareddirectory,registeredittobeexported,andstartedthenecessarysystemservices.

/etc/exportsistheconfigurationfilethatmanageswhichfilesystemsareexportedandhow.Weaddedanentrythatidentifiedthedirectorywewanttoexport,followedbywhichclientstheyareexportedtoandtheoptionsthatgovernhowtheexportwillbetreated:

/var/nfsshare192.168.56.0/24(rw,sync,root_squash)

Intheexample,wemaketheshareavailableto192.168.56.0/24,inotherwords,anyhostonthenetwork.Alternatively,youcansharethedirectoryasinglehostorarangeofhosts.Anentrythatsharesthedirectorywithaspecifichostlookslikethefollowing:

/var/nfsshare192.168.56.101(rw,sync,root_squash)

Therw++optionallowsbothreadandwriteaccesstotheshare.syncflushesanychangestoafileimmediatelytodisk.Whilewritingtodiskmightmakeaccesstothefileslowerattimes,thedelaywon'tbenoticeableunlessyoursystemisunderhighload,anditwouldseemlikeafairtrade-offforthesafetythatimmediateflushesprovideintheeventofacrash.

NFSwilleffectivelysquashtherootuser'sownershipwhenroot_squashisprovidedbychangingtheownertonfsnobody.Thisisasecuritymeasurethatmitigatestheriskofarootuserontheclientsystemattemptingtowriteafiletothesharewithrootownership(otherwiseamalicioususercouldstoreafileandmarkitexecutablewhereitmightberunwithrootprivileges).Ifyouwanttosquashtheownershipofallfilestonfsnobdy,youcanusetheall_squashoption.

NFSreliesonafewotherservices,whichiswhywealsoenabledrpcbindandopenedfirewallportsforrpcbindandmountd.NFSworksontopoftheRemoteProcedureCall(RPC)protocol,andrcpindisresponsibleformappingtheRPC-basedservicestotheirports.Anincomingconnectionfromaclientfirsthitstherpcbindservice,providinganRPCidentifier.Rpcbindresolvestheidentifiertoaparticularservice(NFSinthiscase)andredirectstheclienttotheappropriateport.There,mountdhandlestherequesttodeterminewhethertherequestedshareisexportedandwhethertheclientisallowedtoaccessit.

Page 133: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationaboutconfiguringanNFSserver:

TheNetworkFilesystem(http://www.tldp.org/LDP/nag/node140.html)RHEL7StorageAdministrationGuide:NFSServerConfiguration(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Storage_Administration_Guide/nfs-serverconfig.html)HowtosetupNFSServeronCentOS7(http://www.itzgeek.com/how-tos/linux/centos-how-tos/how-to-setup-nfs-server-on-centos-7-rhel-7-fedora-22.html)

Page 134: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringanNFSclienttouseasharedfilesystemThisrecipecontinueswherethepreviousrecipeleftoff,showingyouhowtoconfigureNFSonaclientsystem.

Page 135: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatanNFSserverhasbeenconfiguredasexplainedinthepreviousrecipe.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

Page 136: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigureanNFSclient:

1. Installthenfs-utilsandlibnfsidmappackages:

yuminstallnfs-utilslibnfsidmap

2. Createthedirectorywhichwillserveasthemountpointfortheremotefilesystem:

mkdir/mnt/nfs

3. Starttherpcbindserviceandregisteritsothatitwillstartwhentheserverboots:

systemctlstartrpcbind

systemctlenablerpcbind

4. MounttheNFSsharetothemountpoint:

mount-tnfs192.168.56.100:/var/nfsshare/mnt/nfs

Page 137: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Liketheserverside,theclientsideofNFSreliesonRPC.So,westartedandenabledtherpcbindservice.Themountcommandisthenusedtomounttheremoteshare:

mount-tnfs192.168.56.100:/var/nfsshare/mnt/nfs

The-targumentindicatestheshare'sfilesystemtype,which,ofcourseis,nfs.Thelocationoftheremoteshareisalsoprovided,theIPaddressoftheserverandthedirectoryoftheshareddataseparatedbyacolon.Finally,themounttargetisgiven.

Tomanuallyunmounttheshare,theumountcommandisusedwiththemountpoint:

umount/mnt/nfs

WecanalsoconfigurethesystemtomounttheNFSshareautomaticallyatboottime.Open/etc/fstabusingyoureditorandaddthefollowingline:

192.168.0.100:/var/nfsshare/mnt/nfs/var/nfssharenfsdefaults00

Thesharewillbeautomaticallymountedwhenthesystemboots.Sincemountcanlookupinformationin/etc/fstab,theinvocationtomountthesharemanuallybecomesmuchsimpleronceit'sregisteredinthismanner.Youcannowmountthesharemanuallybyprovidingjustthemount:

mount/mnt/nfs

Page 138: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationaboutconfiguringanNFSclient:

Themountmanualpage(man8mount)SettingupanNFSClient(http://www.tldp.org/HOWTO/NFS-HOWTO/client.html)RHEL7StorageAdministrationGuide:NFSClientConfiguration(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Storage_Administration_Guide/nfs-clientconfig.html)HowtosetupNFSServeronCentOS7(http://www.itzgeek.com/how-tos/linux/centos-how-tos/how-to-setup-nfs-server-on-centos-7-rhel-7-fedora-22.html)

Page 139: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ServingWindowsshareswithSambaInthisrecipe,youwilllearnhowtoserveaWindowssharefromaCentOSsystemusingSamba.LikeNFS,aWindowsshareisadirectoryonaremoteserverthataclientmayaccesstostorefiles.SambaisaserverthatunderstandstheSMBprotocolusedbyWindowssothatitcanexportdirectoriesthataWindowsclientcanmount.

Page 140: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.You'llalsoneedadministrativeprivilegesprovidedbylogginginwiththerootaccount.

ThenameofyourWindowsworkgroupisneededtoconfigureSambaproperly.Beforeyoubegin,onyourWindowssysteminyournetwork,runnetconfigworkstationandrecordtheWorkstationdomainvalue:

netconfigworkstationdisplaysinformationabouttheWindowssystem'sworkgroupanddomain

Page 141: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupSambatosharedirectorieswithWindowssystems:

1. Installthesambapackage:

yuminstallsamba

2. CreateadedicatedgroupforSambausers:

groupaddsmbgroup

3. Createthedirectorywhichwillserveastherootofthefileshare.SetitsgroupownershiptothenewSambausersgroup:

mkdir-m770/var/sambashare

chgrpsmbgroup/var/sambashare

4. OpenSamba'sconfigurationfileusingyourtexteditor:

vi/etc/samba/smb.conf

5. Updatetheworkgroupparameterinthe[global]sectiontomatchtheWindowsworkgroupname.Feelfreetoreviewtheotherparametersintheconfigurationfileaseachisclearlydocumentedwithhelpfulcomments:

Workgroup=WORKGROUP

6. Attheendoftheconfigurationfile,addthefollowingcontent:

[share]

path=/var/sambashare

guestok=no

validusers=@smbgroup

writable=yes

createmask=0755

7. Saveyourchangesandclosethefile.8. Startthenecessaryservicesandregisterthemsothattheywillstartwhentheserver

boots:

systemctlstartsmbnmb

systemctlenablesmbnmb

9. Openports137-139and445toallowthenetworktraffic:

firewall-cmd--permanent--zonepublic--add-servicesamba

firewall-cmd--reload

10. Foreachuserwhowillconnecttotheshare,assignthemtotheusersgroupandregisterthepasswordtheywilluse:

usermod-a-Gsmbgrouptboronczyk

smbpasswd-atboronczyk

Page 142: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Inthisrecipe,youlearnedhowtoinstallandconfigureSambatoshareadirectorywhichaWindowsclientcanaccess.

WestartedbydoingabitofresearchusingthenetconfigcommandtodiscovertheWindowsworkgroupthatourclientbelongsto.Thisisimportantbecausetwosystemsonthesamenetworkbutidentifyingthemselvesaspartofdifferentworkgroupswillnotbeabletocommunicatewithoneanother.Intheexample,theworkgroup'snamewassimplyWORKGROUP.

Next,weinstalledthesambapackageandcreatedaspecialgroupnamedsmbgroup.We'llconfigureSambasothatanyuseraccountontheCentOSsystemwillbeabletoaccesstheshareaslongasit'sassignedtothesmbgroupgroup.Thenwecreatedthedirectorywewouldbesharingandsetitsgroupownershiptothenewgroup.

WetheneditedSamba'sconfigurationfile,specifyingthenameoftheWindowsworkgroupwelookedupearlierfortheworkgroupvalue,andaddedasectiontodefinethenewshare.Werestrictedthesharesothatonlyauthenticatedusersbelongingtosmbgroupcanaccessitbysettingguestoktonoandvalidusersto@smbgroup.Thewritableentryallowsuserstocreateandupdatefilesontheshare(otherwisethefileswouldberead-only),andthecreatemaskentrywasusedtospecifythedefaultfilepermissionsthatnewfileswillbeassignedintheLinuxfilesystem.Thenamesharewithinbracketsnotonlystartsthatconfigurationsectionbutalsoservesasthenamethesharewillbeexportedas(thatis,\\192.168.56.100\share).Youcanexportmultiplesharesaslongaseachnameisdistinct.

Foreachuseraccountthatwillbeusedtoconnecttotheshare,wemadesureitbelongedtothesmbgroupandusedthesmbpasswdcommandtospecifyapasswordtheaccountwouldusetoauthenticateitsSMBsessions.Thispasswordismaintainedseparatelyfromthesystem'scredentialsandisvalidonlyforauthenticatingtoSamba,soapassworddifferentfromtheaccount'sloginpasswordshouldbechosen.

ManagingSambausersisdoneusingsmbpasswd.The-aflagaddsanentryinSamba'saccountdatabase,andwecandeleteauserfromthedatabaseusingthe-xflag:

smbpasswd-xtboronczyk

OntheWindowssystem,youcanusethenetusecommandtomaptheremotesharetoadriveletter.Onceit'smapped,thedriveappearsinthelistofavailabledrives:

netuseZ:\\192.168.56.100\share/USER:tboronczyk

Alternatively,youcanmapthedrivethroughtheWindowsGUI,navigatingthroughComputer|Mapnetworkdrive|MapnetworkdriveinFileExplorerwhiletheThisPCbookmarkisselected:

Page 143: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheSambashareisavailableasanetworkmappeddrive

Page 144: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonworkingwithSamba,refertothefollowingresources:

Thesmb.confmanualpage(man5smb.conf)UsingSambaonCentOSWithWindows7/8(https://rcollier.me/2013/07/30/using-samba-on-centos-with-windows-78/)InstallAndConfigureSambaServerInCentOS7(http://www.unixmen.com/install-configure-samba-server-centos-7)

Page 145: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter3.UserandPermissionManagementThischaptercontainsthefollowingrecipes:

EscalatingprivilegeswithsudoEnforcingpasswordrestrictionsSettingdefaultpermissionsfornewfilesanddirectoriesRunningbinariesasadifferentuserWorkingwithSELinuxforgreatersecurity

Page 146: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionEachoftherecipesinthischapterpertaintousersandpermissions.You'lllearnhowtoletuserstemporarilyescalatetheirprivilegeswithoutrequiringtherootpasswordandhowtoenforcecomplexityrequirementsforusers.You'llalsolearnhowtospecifywhataccesspermissionsaregiventonewfilesanddirectoriesbydefaultandhowthetraditionalUnixpermissionsystemcanallowaprogramtorununderadifferentsecuritycontextthanthatoftheuserwholaunchedit.Finally,we'lllookatSELinux,asecondarypermissionsystemthathardensthesecurityofyourCentOSserver.

Page 147: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

EscalatingprivilegeswithsudoTherootaccountisLinux'sgodaccount,andithastheabilitytoperformprettymuchanyactivityonthesystem.Forsecurityreasons,youshoulduseanunprivilegeduseraccountforyourday-to-dayactivitiesanduserootonlywhenit'snecessaryforadministrationtasks.It'salsoimportanttokeeptheroot'spasswordsecret;themorepeoplewhoknowitspassword,theharderitistokeepitsecret.AquotebyBenjaminFranklincomestomind:Threecankeepasecretiftwoofthemaredead.

Ifmorethanoneadministratorhasbeentaskedwithmanagingasystem,keepingrootsecurecanbedifficult.sudosolvesthisproblembygivingusersawaytoexecutecommandswiththeprivilegesofanotheruser(mostcommonlyroot).Eachoftheadministratoraccountscanbeconfiguredusingoneofthemethodspresentedinthisrecipetoescalatetheirprivilegestemporarilywithsudo,androot'spasswordcanremainsecret.

Page 148: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemandadministrativeaccessprovidedbylogginginwiththerootaccount.You'llalsoneedoneortwounprivilegeduseraccountstoconfigure(refertotheuseraddmanpageman8useraddforinformationoncreatinguseraccounts).

Page 149: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Onewaytoallowanunprivilegedaccounttheuseofsudoistoassignitamembershipinthewheelgroup.Thisisdonewiththefollowingsteps:

1. Useusermodtoaddtheuseraccounttowheel:

usermod-a-Gwheeltboronczyk

2. Verifytheupdateusingthegroupscommand.wheelshouldlistoneofthegroupswhichtheaccountisamemberof:

groupstboronczyk

Anotherwaytograntaccesstosudoisbyconfiguringthesudoerspolicywhichidentifieswhichaccountscanusesudoandinwhatmanner.Youcaneasilyaddanaccounttothepolicywiththefollowingsteps:

1. Createanewfileinthe/etc/sudoers.ddirectorynamedaftertheuseraccount:

touch/etc/sudoers.d/tboronczyk

2. Openthefileandaddthefollowingdirective.Whenfinished,saveyourupdateandclosethefile:

tboronczykALL=ALL

Page 150: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Forausertousethesudocommandtheymustbesomehowlistedinthesudoerspolicy.Thisischeckedbysudotoverifywhethertheaccountisauthorizedtoperformtheattemptedaction.Thisrecipepresentedtwowaysofaccomplishingthis:byassigningtheuseraccounttothewheelgroup(whichisalreadyregisteredinthepolicy)orbyaddingtheaccountdirectlytothepolicy.

Inthefirstapproach,theusermodcommandassignstheusermembershipinwheel.The-Goptionspecifiesthenameofthegroupand-ainstructsusermodtoaddtheusertothatgroup.It'simportantthatyouprovide-asincewithoutitthelistofassignedgroupsisoverwrittenwithonlywhatisgivenwith-G(thatis,theaccountwouldbelongonlytowheel).

usermod-a-Gwheeltboronczyk

Thesecondapproachregisterstheaccountwiththesudoerspolicybycreatingafilefortheuserunder/etc/sudoers.d.Wealternativelycouldhaveaddedtheuser'sinformationtothe/etc/sudoersconfigurationfile,butthepolicyalreadyincludesanyfilesfoundinthesudoers.ddirectoryaspartofitsconfiguration.Creatingafileforeachuserinthedirectorywillbemoremanageablegivenalargenumberofuserswhenitistimetorevokeaccess.

Bothapproachesallowausertheuseofsudotoexecutecommandstheywouldn'tordinarilyhavesufficientrightsto.Forexample:

sudoumount/media

Thefirsttimeauserinvokessudo,amessageisdisplayedthatremindsthemtoberesponsiblewiththeirnew-foundpower.Theusermustprovidetheirpasswordtoverifytheiridentity;theverificationiscachedforfiveminutesfromthelastinvocationasanextrabitofprotectionagainstmalicioususerswhomightwalkuptoaterminalthatwascarelesslyleftloggedin.

sudoremindstheuserthatwithgreatpowercomesgreatresponsibly

Page 151: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thesudoerspolicyisflexibleenoughtoallowauseraccounttoexecutecertaincommandsinsteadofgivingcarteblancheaccess.Recalltheconfigurationdirectiveforourunprivilegeduseraccount:

tboronczykALL=ALL

TheusernameisspecifiedfollowedbyassigningtheALLaliastoALL.Asyoumightdeterminebylookingatthis,ALListhepredefinedaliasthatrepresentsallcommands.Wecanredefinethealiasforthegivenuserasalistofallowedcommands:

tboronczykALL=/bin/mount/bin/umount

Nowtheaccountcaninvokeanycommanditnormallyhasaccessto,butonlythemountandumountcommandswithelevatedprivileges(assumingtheaccountisn'tamemberofwheel).

Tip

Areyoutiredoftypingsudobeforeyourcommonly-usedadministrativecommands?Youcancreatealiasesforasmoothercommandlineexperience.Supposeyourunprivilegedaccountisallowedtousethemountandumountcommandswithsudo.Addingthefollowinglinestoyour~/.bashrcfilewillletyouinvokethemcommandswithoutexplicitlytypingsudo:

aliasmountsudo/bin/mount

aliasumountsudo/bin/umount

Multipledirectivesinthepolicycanapplytoanaccountinwhichcasetheyareappliedadditively,firsttolast.Toseethisinaction,supposeanaccountalreadyhasfullsudousagebyassignmentinthewheelgroup.Bydefault,theuserneedstoprovidetheirpasswordtoexecuteacommand.Wecanrelaxthisrequirementandallowtheusertouselstodisplaythecontentsofrestricteddirectorieswithoutapassword:

tboronczykALL=NOPASSWD:/bin/ls

Thewheelgroup'spolicyisappliedfirst,establishingthedefaultbehavior.ThenournewdirectiveusestheNOPASSWDtagtogranttheuserunauthenticatedaccesstothelscommand.Theuserwillstillneedtoprovidetheirpasswordforcommandssuchasmountandpasswdbutwon'tneedtoprovideittolistrestricteddirectories.

Page 152: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithsudototemporarilyelevateanaccount'sprivileges:

Thesudomanpage(man8sudo)Thesudoersmanpage(man5sudoers)CodeSnipcademy:Usingsudoandsuandtheirdifferences(https://code.snipcademy.com/tutorials/linux-command-line/permissions/sudo)

Page 153: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

EnforcingpasswordrestrictionsAweakpasswordcanbeoneoftheweakestsecuritypointsofanysystem.Simplepasswordsaresusceptibletobrute-forceattacksandlong-livedpasswords,iftheyarecompromised,provideawidewindowofopportunityformaliciousactivity.Becauseofthis,it'simportanttoensurethatyouruserschoosesufficientlycomplexpasswordsandchangethemregularly.Thisrecipeshowsyouhowtostrengthenyoursystem'ssecuritybyenforcingvariousrestrictionsonusers'passwords.You'lllearnhowtospecifytheminimumcomplexityrequirementsforapassword,howlongbeforeapasswordmustbechanged,andhowtolockdownanaccountafteranumberoffailedloginattempts.

Page 154: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemandadministrativeaccess,eitherprovidedbylogginginwiththerootaccountorbyusingsudo.

Page 155: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoenforcepasswordrestrictionsthatwillincreasethesecurityofyourCentOSsystem:

1. Theparametersgoverningpasswordagingarefoundin/etc/login.defs;openthefileusingyourtexteditorofchoice:

vi/etc/login.defs

2. LocatethepasswordagingcontrolssectionandupdatethevalueofPASS_MAX_DAYS,PASS_MIN_DAYS,PASS_MIN_LEN,andPASS_WARN_AGE:

PASS_MAX_DAYS90

PASS_MIN_DAYS0

PASS_MIN_LEN8

PASS_WARN_AGE15

3. Saveyourchangesandclosethefile.4. Thevaluesspecifiedinlogin.defswillbeappliedtonewaccountswhentheyare

created.Existingusersmusthavetheirpasswordparameterssetseparatelyusingthechagecommand:

chage--maxdays90--mindays0--warndays15tboronczyk

5. Theparametersgoverningtheacceptablecomplexityforpasswordsarefoundin/etc/security/pwquality.conf;openthefileforediting:

vi/etc/security/pwquality.conf

6. Uncommenttheminlenvaluetospecifythedesiredminimumpasswordcomplexityplus1.Forexample,aneight-characterpasswordconsistingofalllowercasecharacterswouldrequireaminlenof9:

minlen=9

7. Youmayuncommentothervaluesandsetthemaswellifyoulike.Eachvalueisprecededbyabriefdescriptivecommentofwhatitdoes.Torequireaminimumnumberofcharacterstobefromacertainclass(uppercase,lowercase,digits,andother/special),specifythevalueasanegativenumber.Forexample,ifpasswordsrequireatleastonenumericdigitandoneuppercasecharacterthenbothdcreditanducreditwouldbesetto-1:

Page 156: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Optionsforconfiguringyoursystem'spasswordcomplexityrequirementsarefoundinpwquality.conf

Page 157: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

8. Saveyourchangesandclosethefile.9. Nextwe'llupdatePAM'spassword-authandsystem-authmoduleconfigurationstolock

outanaccountafteranumberofunsuccessfullogin-attempts.Openthefile/etc/pam.d/password-auth:

vi/etc/pam.d/password-auth

10. Updatethegroupofauthlinesatthebeginningofthefiletoreadasfollows.Thesecondandfourthlineshavebeenaddedandincludepam_faillocktotheauthenticationstack:

authrequiredpam_env.so

authrequiredpam_faillock.sopreauthsilentauditdeny=3

unlock_time=600

authsufficientpam_unix.sonulloktry_first_pass

auth[default=die]pam_faillock.soauthfailauditdeny=3

unlock_time=600

authrequisitepam_succeed_if.souid>=1000quiet_success

authrequiredpam_deny.so

11. Updatethegroupofaccountlinestoreadasfollows.Thesecondlinehasbeenaddedtoincludepam_faillocktotheaccountstack:

accountrequiredpam_unix.so

accountrequiredpam_faillock.so

accountsufficientpam_localuser.com

accountsufficientpam_succeed_if.souid<1000quiet

accountrequiredpam_permit.so

Note

Becarefulwhenupdatingthepassword-authandsystem-authfiles.Theorderinwhichmodulesarelistedinastackissignificant!

12. Saveyourchangesandclosethefile.Thenrepeatsteps9to11withthefile/etc/pam.d/system-auth.

Page 158: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Properlyconfiguringtheauthenticationrequirementsforlocalaccountsisabitofafracturedexperience.First,there'sthetraditionalUnixpasswordfiles(/etc/passwdand/etc/groups)andtheshadow-utilspackage,whichaddsshadowingsupport(/etc/shadow).Together,theseformthecoredatabaseforlocalaccountcredentials.Inaddition,similartomostothermodernLinuxsystems,CentOSusesPAM,acollectionofpluggableauthenticationmodules.ThePAMstackisconfiguredbydefaulttolookupaccountinformationintheshadowfile,butitalsoprovidesadditionalfunctionalitythatPAM-awareprogramscanleverage,suchaspassword-strengthchecking.Asanadministrator,you'reresponsibleforconfiguringtheseservicessothattheyworkproperlyintandemandoperatewithintheacceptablesecurityguidelinessetbyyourorganization.

Inthisrecipe,wefirstupdatedthepasswordagingrelatedcontrolsfoundin/etc/logins.def:

PASS_MAX_DAYS90

PASS_MIN_DAYS0

PASS_MIN_LEN8

PASS_WARN_AGE15

PASS_MAX_DAYSdefineshowmuchtimecanpassbeforeapasswordmustbechanged.Bysettingthevalueto90,ausermustchangetheirpasswordatleastonceeverythreemonths(90days).PASS_MIN_DAYSspecifieshowmanydaysausermustwaittochangeanewpassword.Sincethisvalueis0,ausercanchangetheirpasswordanytimetheywant-evenseveraltimesadayiftheylike.PASS_WARN_AGEdefineshowmanydaysinadvanceauserwillbenotifiedoftheirpassword'spendingexpirationasPASS_MAX_DAYSapproaches.

Note

PASS_MIN_LENissupposedtosettheminimumpasswordlength,butyou'llfindPAM'spasswordcomplexityrequirementssupersedethis,makingthesettingprettymuchworthless.

Utilitiessuchasuseraddusethesesettingsasthedefaultswhencreatingentriesinthepasswordandshadowfiles.Theyaren'tappliedretroactivelytoexistinguserssoweneedtousechagetoupdatetheiraccounts:

chage--maxdays90--mindays0--warndays15tboronczyk

chagecansettheminimumandmaximumageofauser'spasswordandthenotificationwindowforpendingexpirations,butnotetheabsenceofaminimumlengthrequirement.

Wecanalsousechagetomakeauser'spasswordexpireimmediatelysothattheymustspecifyanewonethenexttimetheylogin.Todoso,weprovidethe--lastdaysargumentwithavalueof0:

chage--lastdays0tboronczyk

Tip

Page 159: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Ifyouhavemorethanahandfulofaccounts,youmaywanttoautomateusingchagewithsomebasicshellscripting.Here'saseriesofcommandspipedtogetherthatupdatealloftheexistinguseraccountsinanautomatedfashion:

getentshadow|awk-F:'substr($2,0,1)=="$"{print$1}'|xargs-n1

chage--maxdays90--mindays0

--warndays15

Thisworksbyretrievingthecontentsoftheshadowfileandusingawktospliteachrecordusing:asthefieldseparator.awklooksatthevalueinthesecondfield(theencryptedpassword)toseeifitbeginswith$,indicatingtheaccounthasapassword,tofilteroutdisabledaccountsandsystemaccountswithoutapassword.Theusernamefromeachmatchingrecordisthenpipedtoxargswhichthenfeedsthenamesoneatatimetochage.

AsthePAMmodulepam_pwqualitychecksthecomplexityofpasswords,wespecifyourpasswordcomplexityrequirementsinthemodule'sconfigurationfile,/etc/security/pwquality.conf.Itgaugesthequalityofapasswordusingacreditsystemwhereeachcharactercreditsapointtowardsthepassword'stotalscore.Thisscorethenmustmeetorexceedthevaluewegaveforminlen.

Thepageathttp://wpollock.com/AUnix2/PAM-Help.htmhasagoodexplanationofhowpam_pwqualitycalculatesapassword'scomplexity.Itexplainsthealgorithmasfollows:

AddoneforeachcharacterinthepasswordregardlessofthetypeofthecharacterAddonetothatforeachlowercaseletterused,uptoamaximumoflcreditAddonetothatforeachuppercaseletterused,uptoamaximumofucreditAddonetothatforeachdigitused,uptoamaximumofdcreditAddonetothatforeachsymbolused,uptoamaximumofocredit

Thepagealsopresentsafewcomplexitycalculationsfordifferentpasswordsandisworthreading.

Thenweupdatedthepassword-authandsystem-authfilestolockauser'saccountafterthreeunsuccessfulloginattempts.Differentauthenticationstacksneedtobeconfiguredbecausedifferentloginmethodswillinvokeadifferentauthenticationstack(thatis,alogginginoverSSHasopposedtologginginlocally):

authrequiredpam_env.so

authrequiredpam_faillock.sopreauthsilentauditdeny=3

unlock_time=600

authsufficientpam_unix.sonulloktry_first_pass

auth[default=die]pam_faillock.soauthfailauditdeny=3

unlock_time=600

authrequisitepam_succeed_if.souid>=1000quiet_success

authrequiredpam_deny.so

accountrequiredpam_unix.so

accountrequiredpam_faillock.so

accountsufficientpam_localuser.com

Page 160: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

accountsufficientpam_succeed_if.souid<1000quiet

accountrequiredpam_permit.so

Thepam_faillockmoduleisaddedatmultiplepositionsintheauthenticationstack.Thefirstappearanceintheauthblockperformsaprecheck(preauth)toseeiftheaccountisalreadylockedoutThesecondappearancetalliesthefailedattempt(authfail).Theargumentspecifiedbydenyisthenumberoffailedattemptspermittedbeforelockingtheaccount.unlock_timespecifieshowmuchtimethemoduleshouldwait(inseconds)beforeunlockingtheaccountsothatanotherloginattemptcanbemade.Astheexamplespecifies600seconds,auserwillhavetowait10minutesforthelockouttoexpire.Themodule'sappearanceintheaccountblockdeniesauthenticationtothelockedaccount.

Thefaillockcommandisusedtoviewthenumberoffailedloginattemptsandtounlockanaccount.Toseethefailedattempts,invokethecommandusingthe--userargumenttospecifytheaccount'susername:

faillock--usertboronczyk

Tomanuallyunlocktheaccountbeforeunlock_timehaselapsed,invokethecommandwiththe--resetargument:

faillock--usertboronczyk--reset

Page 161: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonhowuseraccountsareauthenticatedandhowtoenforcepasswordrestrictions:

Thechagemanpage(man1chage)Theshadowfilemanpage(man5shadow)Thepam_faillockmanpage(man8pam_faillock)LinuxDocumentationProject:PuttingtheShadowsuitetouse(http://tldp.org/HOWTO/Shadow-Password-HOWTO-7.html)TheLinux-PAMSystemAdministrator'sGuide(http://www.linux-pam.org/Linux-PAM-html/Linux-PAM_SAG.html)RHELSecurityGuide:PasswordSecurity(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html-single/Security_Guide/index.html#sec-Password_Security)

Page 162: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingdefaultpermissionsfornewfilesanddirectoriesLinux'spermissionssystemgovernswhetherausercanenteradirectoryorread,write,orexecuteafile.Bysettingthepermissionbitsonfilesanddirectories,accesscanbegrantedorrevokedtodifferentusersandgroupsofusers.However,it'spossibleforausertocreateafileandexpectothersintheirgrouptoaccessit,buttheinitialfilepermissionspreventsthis.Tohelpavoidthissituation,thisrecipeteachesyouhowtosetthedefaultpermissionsfornewfilesanddirectoriesbyspecifyingamaskvalue.

Page 163: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemandadministrativeaccess,eitherprovidedbylogginginwiththerootaccountorbyusingsudo.

Page 164: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstospecifythedefaultpermissionsfornewfilesanddirectories:

1. Tosetthemaskvalueglobally,openthe/etc/profilefile:

vi/etc/profile

2. Attheendofthefile,addthefollowingdirective(adjustingthevalueasdesired).Whenfinished,saveandclosethefile:

umask0007

3. Tooverridetheglobalmaskandsetthemaskonaper-userbasis,opentheuser's~/.bashrcfile:

vi/home/tboronczyk/.bashrc

4. Attheendofthefile,addthefollowing(againadjustingthevalueasnecessary).Thensaveandclosethefile:

umask0007

5. Totemporarilysetthemaskonlyforthedurationofyoursession,executetheumaskcommandatthecommandprompt:

umask0007

Note

Youcanexecuteumaskatthecommandpromptwithoutprovidingamaskvaluetoseewhatyourcurrentmaskvalueis.

Page 165: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thisrecipepresentsthreewaysamaskvaluecanbeset,whichisresponsiblefordeterminingwhatpermissionsaresetonnewlycreatedfilesanddirectories.However,tounderstandhowthemaskworks,youneedtounderstandthetraditionalread,write,andexecutepermissionsystem.

DirectoriesandfilesintheLinuxfilesystemareownedbyauserandgroup,andtheyareassignedasetofpermissionsthatdescribewhocanaccessit.Whenausertriestoaccessaresource,thesystemcomparesitsownershipinformationwithrequestinguseranddeterminesiftherequestedaccessshouldbegrantedaccordingtothepermissions.

Thethreepermissionsareread,write,andexecute.Sinceaccesstoeachcanbeonlyoneofthetwovalues(allowedordisallowed),andbecausesuchbinaryoptionscanberepresentedwith1foryesand0forno,asequenceof1'sand0'scanbeviewedasabitpatternwhereeachpermissionisgivenadifferentpositioninthesequence.Thefollowingfigureshowshowalistofbinaryyes'sandno'scanbeconvertedtoahuman-friendlyvalue:

Binaryvaluesrepresentwhetherauserhaspermissiontoaccessaresource

Fromthefileordirectory'sperspective,therearethreetypesofusers.Theuseriseitherthefile'sowner,amemberoftheowninggroup,orneither(everyoneelse).

Theresourceisgivenasetofpermissionsforeachtypeofusers,asshowninthefollowingfigure:

Page 166: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thefullpermissionsetofafileordirectoryincludesthethreetypesofusers

ThisisthelogicbehindthetraditionalUnixpermissionsystem,butdon'tworryifthisseemsintimidatingatfirst.Determiningthepermissionsforaclassofusersisreallyjustamatterofaddition.Startwith0fornoaccessatall.Toallowreadaccess,add4.Forwriteaccess,add2.Forexecute,add1.Thesevaluescomefromviewingthevalueofthepermissioninthebitstringasabinarynumber,buttheyareeasyenoughtomemorize.Thus,toallowallaccess,weadd4+2+1whichequals7.Toallowonlyreadandexecuteaccess,4+1equals5.Themoreyouworkwithpermissions,themoreyou'llcometorecognizecertaincombinationsautomatically.

Whenafileiscreated,thesystembeginswith666asadefaultvalue,givingreadandwriteaccesstoallthreeclassesofusers.Directoriesstartwith777sincetheexecutablepermissiononadirectoryiswhatallowsausertotraverseintoit.Thesystemthensubtractsthecreatinguser'sumaskvalueandtheresultdetermineswhatpermissionswillbeassignedtotheresourcewhenit'screated.

Supposewecreateanewdirectoryandourumaskvalueis0027.Thesystemsubtracts7fromtheallotherusers'fieldand2fromthegroup'sfield.7-7is0,and7-2is5,sothedefaultpermissionforanewdirectoryis750.

Becausewestartwithonebitlessinthedefaultvalueforfiles,it'spossibletoendupwithanegativepermissionnumber.Ifumaskmasksoutallofthepermissionsusingthevalue7,butthestartingvalueis666forfiles,6-7gives-1.Itdoesn'tmakesensetogobeyond0sothesystemtreatsitas0.So,amaskof0027givesus650forthefile'spermissions.

The/etc/profileand~/.bashrcfilesareexecutedwheneverauserlogsintoconfiguretheirsession'senvironment.Callingumaskinprofilehastheeffectofsettingthemaskforallusers..bashrcisexecutedafterprofileandisuserspecific;so,itscalltoumaskoverridesthepreviouslysetvalue,settingthemaskforthatspecificuser.

Page 167: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationaboutumask:

Wikipedia:Umask(http://unix.stackexchange.com/questions/102075/why-are-666-the-default-file-creation-permissions)Whyare666thedefaultfilecreationpermissions?(https://en.wikipedia.org/wiki/Umask)Controllingfilepermissionswithumask(http://linuxzoo.net/page/sec_umask.html)

Page 168: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RunningbinariesasadifferentuserEveryprogramonCentOSrunswithintheenvironmentofauseraccountregardlessofwhethertheprogramisexecutedbyauserorrunasanautomatedsystemprocess.However,sometimeswewanttheprogramtorunwithdifferentrestrictionsandaccessthoserightstheaccountisallowed.Forexample,ausershouldbeabletousethepasswdcommandtoresettheirpassword.Thecommandneedswriteaccessto/etc/passwdbutwedon'twanttheuserrunningthecommandtohavesuchaccess.Thisrecipeteachesyouhowsettingaprogram'sSUIDandSGIDpermissionbitsallowsittoexecutewithintheenvironmentofadifferentuser.

Page 169: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystem.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorbytheuseofsudo.

Page 170: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoallowaprogramtoexecuteasadifferentuser:

1. Identifythefile'sownerandgroupdetailsusingthelscommand.Thethirdfieldinitsoutputliststheownerandthefourthfieldliststhegroup:

ls-lmyscript.sh

The-loptiondisplaysthefilelistinginlong-formwhichincludesownershipinformation

2. Ifnecessary,changethefile'sownershipusingchownsothattheowneristheonewhoseenvironmentyouwantthescripttoexecutein:

chownnewuser:newgroupmyscript.sh

3. SettheSUIDbittoallowtheprogramtorunasifitwereinvokedbyitsowner:

chmodu+smyscript.sh

4. SettheSGIDbittoallowtheprogramtorunasifitwereinvokedbyamemberofits

Page 171: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

group:

chmodg+smyscript.sh

Page 172: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Whenafile'sSUIDandSGIDbitsareset,theprogramrunswithintheenvironmentofitsownerorgroupinsteadoftheuserwhoinvokedit.Thisisusuallydonewithadministrativeprogramsthatanunprivilegedusershouldhaveaccesstobuttheprogramitselfrequiresadministrativepermissionstofunctionproperly.

ThebitsaresetusingchownwithusettotargettheSUIDbit.AscriptwiththeSUIDbitsetwillexecutewiththeprivilegesitsownerhas.gissettotargettheSGIDbitwhichallowsthescripttoexecutewiththeprivilegesofamemberofitsgroup.Intuitively,+setsthebitand-removesthebit,laterallowingtheprogramtoexecuteintheinvokinguser'senvironment.

chmodu-smyscript.sh

chmodg-smyscript.sh

SUIDandSGIDmaybesetnumericallyaswell-thevalueforSUIDis4andthevalueforSGIDis2.Thesecanbesummedtogetherandappearastheleft-mostdigitinthenumericpermissionvalue.Forexample,thefollowingsetstheSUIDbit,theread,write,andexecutebitsforthefile'sowner;read,write,andexecutebitsforgroupmembers;andreadandexecutebitsforeveryoneelse:

chmod4775myscript.sh

However,thenumericapproachrequiresyoutospecifyallofthefile'spermissions.IfyouneedtodothatandwanttosettheSUIDorSGIDbitsatthesametime,it'snotaproblem.Otherwise,it'sprobablymoreconvenienttouse+or-toaddorsubtracttheindentedbits.

Settingbitsusingmnemoniccharacterswithchmodalsoworkswiththestandardpermissions.u,g,andatargetthedesiredbitsforitsowner(uforuser),group(gforgroup),andeverybodyelse(aforall).Thecharactersforreadaccessisr,writew,andexecutex.Hereareafewexamplesusingmnemoniccharacters:

Allowthefile'sownertoexecutethefile:

chmodo+xmyscript.sh

Allowagroupmembertoreadthefile:

chmodg+rmyfile.txt

Preventeveryonewhoisnottheowneroramemberofthegroupfromwritingtothefile:

chmoda-wreadonly.txt

Page 173: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourceformoreinformationaboutchmodandsettingtheSUIDandSGIDbits.

Thechmodmanpage(https://linux.die.net/man/1/chmod)HowtosettheSetUIDandSetGIDbitforfilesinLinuxandUnix(http://linuxg.net/how-to-set-the-setuid-and-setgid-bit-for-files-in-linux-and-unix/)Wikipedia:Setuid(https://en.wikipedia.org/wiki/Setuid)

Page 174: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WorkingwithSELinuxforgreatersecurityThisrecipeshowsyouthebasicsofworkingwithSecurity-EnhancedLinux(SELinux),akernelextensionthataddsanextralayerofsecuritytoyourCentOSinstallation.Becauseitrunsatthekernellevel,SELinuxcancontrolaccessbeyondthereachofthetraditionalfilesystempermissions,includingrestrictingrunningprocessesandotherresources.

Unfortunately,someadministratorsdisableSELinuxbecauseadmittedlyitcanbeasourceoffrustration.They'recomfortablewiththeuser/group/allandread/write/executeapproachandsuddenlyfindthemselvesatalosswhenSELinuxblockssomethingthatseemsasitshouldbeavailable.However,theextralayerofsecuritythatSELinuxprovidesisworththeeffortofinvestigatingsuchproblemsandadjustingitspoliciesifnecessary.

Page 175: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystem.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.Thedemonstratedcommandscomefromthepolicycoreutils-pythonpackage,sobesuretoinstallthepackagefirstusingtheyuminstallpolicycoreutils-pythoncommand.

Page 176: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ThiscollectionofcommandswillintroduceyoutoworkingwithSELinuxinvariouscontexts,whichareasfollows:

UsesestatustoverifywhetherSELinuxisenabledandtoseewhatpolicyisloaded:

SELinuxisenabledonthissystemandcurrentlyenforcingthetargetedpolicy

Useid-ZtoseewhichSELinuxaccount,role,anddomainyouraccountismappedto.Usels-Ztoseethesecuritycontextofafileordirectory:

Page 177: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Bothidandlscandisplaysecuritycontextrelatedinformation

Usesemodule-ltoreviewthelistofloadedpolicymodulesinthecurrentpolicy.Theoutputcanbequitelengthyandyoumayfinditbeneficialtopaginateitusinglessormore:

semodule-l|less

Usesemodule-dandprovideamodule'snametodisableaspecificpolicymodule:

semodule-dmysql

Youcanverifythatthemoduleisdisabledbyreviewingthelistofpolicymoduleswithsemodule-lagain.Theworddisabledshouldappeartotherightofthemodulename.

Usesemodule-etoenableaspecificpolicymodule:

semodule-emysql

Usesemanagebooleantoselectivelyenableordisablefeaturesofanactivemodule.The-largumentoutputslistofavailablefeatureswiththeircurrentanddefaultvalues:

semanageboolean-l|less

Use-mfollowedby--onor--offandthefeaturenametoaffectthedesiredfeature:

semanageboolean-m--ondeny_ptrace

Page 178: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

semanageboolean-lshowswhichfeaturesofapolicymodulecanbetoggledonandoff

Page 179: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...SELinuxviewsthesystemintermsofobjects,subjects,domains,andtypes.Anobjectisanyresourcewhetherit'safile,directory,networkport,memoryspace,andsoon.Asubjectisanythingthatactsonanobject,suchasauserorarunningprogram.Adomainistheenvironmentinwhichthesubjectoperates,orinotherwordsthecollectionofresourcesavailabletothesubject.Typesaresimplycategoriesthatidentifythepurposeofanobject.Withinthisframework,SELinux'ssecuritypoliciesorganizeobjectsintorolesandrolesintodomains.

Domainsaregrantedordeniedaccesstotypes.Auserisallowedtoopenaspecificfile,forexample,becausetheybelongtoaroleinadomainthathaspermissiontoopenthattypeofobject.Todecidewhetherauserhastheabilitytodosomething,SELinuxmapsthesystem'suseraccountstooneoftheusers(androlesanddomains)initsowndatabase.Bydefault,accountsmaptoSELinux'sunconfined_uuserwhichisassignedtheunconfined_rroleandoperatesintheunconfined_tdomain.

Thisrecipeshowedusthatid-Zcanbeusedtoretrievetheuser,role,anddomainthatouruseraccountmapstoandls-Zretrievesafile'ssecuritylabeling.Ofcourse,thevaluesdisplayedbythecommandsaredifferentdependingonthefile.Forexample,thebinaryfile/bin/cpexecutesasthesystem_uuser,isamemberoftheobject_rrole,andisinthebin_tdomain.

ThesestatuscommandoutputsbasicstatusinformationaboutSELinux,suchaswhetherit'senabled,enforcingitspolicies,andhowit'senforcingthem.SELinuxcanruninenforcingmode,inwhichitactivelyenforcesitspolicies,orinpermissivemode,inwhichitwillnotpreventanyactionsbutwilllogamessageifanactionwouldhavebeenpreventedbythepolicy.YoucansetSELinuxtopermissivemodewithsetenforce0.

Thesemodulecommandisusedtomanagepolicymodules.Forthesakeofkeepingeverythingorganized,apolicyisacollectionofmodulesandeachmoduleisconcernedwithaspecificprogramoractivity.Therearededicatedmodulesforthemostcommonapplications,suchasMySQL,ApacheHTTPserver,andSSHd,whichdescribewhichdomainshaveaccesstowhichtypes.Thisrecipeshowedushowwecanenableordisablethesemodulesusingthe-eand-dargumentstosemodule:

semodule-dmysql

semodule-emysql

Finally,therecipepresentedthesemanagecommand,whichmanagesvariousaspectsofSELinux.Wesawitsbooleansubcommand,usingittolistthespecificprotectionswecantoggleonoroff.

ItprobablygoeswithoutsayingthatwhileSELinuxdoesagreatjobinprotectingyoursystembyaddinganextralayerofaccesscontrols,fullyunderstandingitandwritingcustompolicies

Page 180: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

isaseriousundertaking.Entirebookshavebeenwrittenonthissubjectandthereisaplethoraofresourcesavailableonline.TheSELinuxUsersandAdministrator'sGuidethatispartoftheRedHatEnterpriseLinux7documentationandathree-partseriesintroducingthebasicconceptsofSELinuxbyDigitalOceanaregreatstartingpoints,andI'velistedtheirURLshere.IalsorecommendthebookSELinuxbyExample:UsingSecurityEnhancedLinuxbyDavidCaplan,KarlMacMillan,andFrankMayer.

Page 181: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithandbetterunderstandingSELinux:

Wikipedia:Security-EnhancedLinux(https://en.wikipedia.org/wiki/Security-Enhanced_Linux)SELinuxProjectWiki(http://selinuxproject.org/page/Main_Page)RHEL7SELinuxUser'sandAdministrator'sGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide/part_I-SELinux.html)CentOSWiki:SELinux(http://wiki.centos.org/HowTos/SELinux)AnIntroductiontoSELinuxonCentOS7(http://www.digitalocean.com/community/tutorials/an-introduction-to-selinux-on-centos-7-part-1-basic-concepts)

Page 182: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter4.SoftwareInstallationManagementThischaptercontainsthefollowingrecipes:

RegisteringtheEPELandRemirepositoriesPrioritizingrepositoriesusingthePrioritiespluginAutomatingsoftwareupdateswithyum-cronVerifyinginstalledRPMpackagesCompilingaprogramfromsource

Page 183: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionThischapterpresentsrecipesformanagingtheinstallationofsoftwareonyourCentOSsystem.You'lllearnhowtoaddnewpackagerepositoriestoprovideawiderselectionofsoftwarethanwhat'sfoundinthemainCentOSrepositories,andalsohowtoprioritizetherepositoriestocontrolthosefromwhichapackageisinstalled.You'llalsolearnhowtoautomatesoftwareupdatestokeepupwiththelatestsecuritypatchesandbugfixes,andhowtoverifytheinstalledpackagestomakesureamalicioususerhasn'ttamperedwithyoursoftware.Finally,you'lllearnaskillthat'sslowlyfadingbutisessentialifyouwanttomodifytheopensourcesoftwareonyoursystem:howtocompilesoftwarefromsource.

Page 184: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RegisteringtheEPELandRemirepositoriesAcleanCentOSinstallationwillhavethemainsupportedrepositoriesenabled,fromwhichwecaninstallawidevarietyofsoftware.Wecanalsoregisterthird-partyrepositoriestomakeadditional(ornewer)softwareavailabletous.Thisrecipeteachesyouhowtoaddtwosuchrepositories,specificallythepopularExtraPackagesforEnterpriseLinux(EPEL)andRemirepositories.

Page 185: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 186: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ToregistertheEPELrepository,installtheepel-releasepackage:

yuminstallepel-release

ToregisterandenabletheREMIrepository,followthesesteps:

1. Downloadtherepository'sconfigurationpackage:

curl-Ohttp://rpms.famillecollet.com/enterprise/remi-release-7.rpm

2. Installthedownloadedpackage:

yuminstallremi-release-7.rpm

3. Deletethefilesinceit'snolongerneeded:

rmremi-release-7.rpm

4. OpentheRemirepository'sconfigurationfile:

vi/etc/yum.repos.d/remi.repo

5. Locatetheenabledoptioninthe[remi]sectionandchangeit'svalueto1toenableit:

enabled=1

6. Saveyourchangesandclosethefile.

Page 187: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...TheEPELrepositoryhostssoftwarepackagesthatcomplementthoseintheofficialCentOSrepositories.Itcanbeautomaticallyconfiguredbyinstallingtheepel-releasepackageavailableintheofficialrepositories:

yuminstallepel-release

Remiisapopularthird-partyrepositoryprovidingnewerversionsofsoftwarefoundintheofficialrepositories.Wedownloadedtheconfigurationpackagefortherepositoryfromtheproject'sserverusingcurl:

curl-Ohttp://rpms.famillecollet.com/enterprise/remi-release-7.rpm

Weusedthe-Oargument(anuppercaseletterO,notzero)sothatthefilewillbesavedtodisk,otherwiseitscontentswouldbedumpedtothescreen.Therecipedidn'tidentifyaspecificdirectoryyoushoulddownloadthefileto.Youcandownloadittoyourhomedirectory,oreven/tmpifyoulike,sincethefileisn'tneededafterthepackageisinstalled.

Afterthepackageisdownloaded,wecaninstallitusingyum:

yuminstallremi-release-7.rpm

Note

Manytimestherearealternativewaystoaccomplishthesametask.Forinstance,therpmcommandcanalsobeusedtoinstallthepackageafteritisdownloaded:

rpm-ivremi-release-7.rpm

The-iargumentinstallsthepackageand-vinstructsrpmtobeverboseinitsoutputsowecanseeit'sactivities.

Theremi-releasepackageinstallstheconfigurationsforthreeRemirepositories:theRemi,SafeRemi,andRemi'sPHP7repositories.SafeRemiisenabledbydefaultbecauseitspackagesareconsideredsafetousewiththeofficialCentOS-Baserepository.However,theRemirepositoryisdisabledsoweneedtoedit/etc/yum.repos.d/remi.repo:

Page 188: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheRemirepositoryisenabledbyupdatingitsconfigurationfile

REMIispopularforprovidingnewerreleasesofPHP.IfyouwanttoupgradeyourexistingPHPinstallationwithaversionfoundinRemiyoucanenablethedesiredsectioninremi.repoorinremi-php70.repo.

Afteryou'veinstalledtheEPELrepositoryandinstalledandenabledtheRemirepository,youcanaskyumtolisttheavailablerepositories.TheEPELandRemirepositoriesshouldappearinitsoutput:

yumrepolist

Page 189: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheEPELandRemirepositoriesareenabledandreadytogo!

Tip

RemiusesthesamepackagenamesasthosefoundintheofficialCentOSrepositories.LikeRemi,theIUSrepositoryprovidesnewerversionsofsoftwarefoundintheofficialrepositories,butusesdifferentpackagenames.SomemanagedserviceprovidersrecommendusingIUSoverRemibecausetheyupdateserversnightlyandthedifferingpackagenameshelppreventunplannedupgrades.Ifyou'recontractedwithsuchaproviderandnotusingthePrioritiesplugin(discussedinthenextrecipe),besuretoheedtheiradvice.MoreinformationonIUScanbefoundattheirwebsite,https://ius.io/.

Page 190: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationontheEPELandRemirepositories,refertothefollowingresources:

FedoraProject:EPEL(http://fedoraproject.org/wiki/EPEL)Remi'sRPMrepository(http://rpms.famillecollet.com/)InstallEPELandadditionalrepositoriesonCentOSandRedHat(http://www.rackspace.com/knowledge_center/article/install-epel-and-additional-repositories-on-centos-and-red-hat)

Page 191: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

PrioritizingrepositoriesusingthePrioritiespluginAlthoughpackagemanagersmakeinstallingandupdatingsoftwareanalmosttrivialtask,therecanstillbesomepainpointsifwe'renotcareful.Forexample,wecanconfiguremultiplerepositories,includingthird-partyrepositoriesnotmaintainedbyCentOS,andtheversionofapackageinonerepositorycanconflictwiththesameinanother.ThisrecipeusesthePrioritiesplugintoprioritizetherepositoriesweusetohelpavoidsuchpitfalls.

Page 192: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 193: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoprioritizewhichrepositoriesyumdownloadssoftwarefrom:

1. Openthe/etc/yum.conffilewithyourtexteditor.Locatethepluginsoptionandverifythatitsvalueissetto1toenablepluginsupport.Updatethevalueifnecessary:

plugins=1

2. Installtheyum-plugin-prioritiespackage:

yuminstallyum-plugin-priorities

3. Tosetarepository'spriority,openitsrespectiveconfigurationfilefoundunder/etc/yum.repos.d.Addthepriorityoptionasanewentrywithineachdesiredsection:

priority=10

4. Whenyou'refinished,saveandclosetherepository'sconfigurationfile.

TheCentOS-Baserepositoryisgivenarelativelyhighpriorityforbasepackages

Page 194: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Inthisrecipe,weinstalledthePrioritiespluginandprioritizedourrepositoriesbyupdatingtheirconfigurationfiles.Byprioritizingonerepositoryoveranother,wecanmoreeasilycontrolthepackagesandsoftwareversionsinstalledonoursystem.

First,wecheckedtomakesureYum'spluginsupportisenabled.Weopeneditsconfigurationfileat/etc/yum.confandverifiedthevalueofthepluginsoption:

plugins=1

Next,weinstalledtheyum-plugin-prioritiespackage:

yuminstallyum-plugin-priorities

Prioritiescomeswithitsownminimalconfigurationfileat/etc/yum/plugins/priorities.conf.There,theenabledoptionlet'sustogglewhetherthepluginisactiveornot.Thismeanswecanprioritizetherepositoriesaswelike,buttemporarilydisableprioritizationforanyreasonwithoutremovingandthenre-addingpriorityvaluesintherepositories'configurationfiles:

enabled=1

Thelaststepistoedittherepositories'configurationfilesfoundinthe/etc/yum.repos.ddirectory.Eachrepositoryhasitsownfile,forexample,theCentOS-Baserepository'sfileis/etc/yum.repos.d/CentOS-Base.repo,whichconfiguresdetailsaboutconnectionsandsecuritykeysforeachchannel.Toprioritizeourrepositories,wesimplyopenthedesiredfilesandaddanewlineforthepriorityoptioninthedesiredsections:

priority=10

Prioritiesareassignedasanumberintherangeof1to99,where1isthehighestpriorityand99isthelowestpriority.Anyrepositoryorchannelwedon'texplicitlysetapriorityforwilldefaulttopriority99.Repositoriesthataremeanttoworktogether(likeEPELandRemi)canbeassignedthesamepriority.

Note

Don'tuseconsecutiveprioritynumbers,like1,2,3....Settingprioritiesasmultiplesof5or10,forexample5,10,15...or10,20,30...allowsyoutolateraddadditionalrepositorieswithoutre-prioritizingexistingones.

Whenprioritiesareassignedandenabledandwhenwetrytoinstallorupdateapackagewhichisfoundinmultiplerepositories,thepackagewillberetrievedfromwhicheverrepositorythathasthehighestpriority.Inthisway,wecancontrolifathird-partyrepositorycanreplaceimportantbasepackages,orifupdatesfromsupportedCentOSrepositoriescanreplacethird-partypackagesonahighly-customizedsystem.

Page 195: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertotheCentOSWiki'syum-plugin-prioritiesarticleformoreinformationonthePrioritiespluginathttps://wiki.centos.org/PackageManagement/Yum/Priorities.

Page 196: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Automatingsoftwareupdateswithyum-cronWeknowtheimportanceofstayingontopofanysecurityalertsandapplyingimportantupdates,butitcanbeatediousandtime-consumingtasktomakesureallofthesoftwareonyourCentOSsystemisupdated,especiallywhenyou'remanagingmorethanoneserver.Thisrecipeshowsyouhowtoautomatetheupdateprocessensuringyoursystemstaysuptodatewithouttheneedfordailyinteraction.

Page 197: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 198: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Toautomatesoftwareupdatesusingyum-cron,performthefollowingsteps:

1. Installtheyum-cronpackage:

yuminstallyumyum-cron

2. Startandenabletheservice:

systemctlstartyum-cron

systemctlenableyum-cron

3. Performasystemupdatetoensureeverythingisuptodatebeforeyum-crontakesover:

yumupdate

Page 199: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...

Our first action step was to install the yum-cron package, but you'll notice that the invocation also updates Yum itself. Although we only have to specify yum-cron, including yum works around a particular versioning bug (you can read the bug report athttps://bugzilla.redhat.com/show_bug.cgi?id=1293713):

yum install yum yum- cron

The package installs the yum-cron command and a daily cron job to trigger it and a systemctl

unit used to enable and disable updating. Starting the service with systemctl results in the creation of a special lock file. Cron runs the daily cron job every day to invoke yum-cron, which checks whether the lock file exists. If the file exists, then it knows it should check forupdates. Otherwise, it knows daily updating is disabled (the service is stopped) and does nothing.

The yum-cron.config configuration file in /etc/yum can be used to modify the general behavior of yum-cron. The most important option is update_cmd because it lets us specifywhat type of update to perform. It's possible for yum-cron to perform different update strategies, and if you want to perform a more targeted update beyond the default then you canchange the value of the update_cmd option.

Servers that fill different roles may require different update strategies; for example, you might want to apply only critical security updates on a production server and leave the other software installed at their specific versions. Comments in the configuration file list what values are valid for update_cmd and what they mean. default performs a general system-wideupdate, whereas a value such as security only applies security-related updates:

update_cmd = security

Also of interest in yum-cron.conf is the emit_via option. The stdio value means any logging messages that may be generated by yum-cron will be passed through a standard output.Usually, this is captured by cron and written to /var/log/cron. Cron can be configured to e- mail the output, but you can also specifically configure yum-cron to e-mail the messages. If you want the output sent to you by yum-cron, change the value of emit_via to email and the value of email_to to your e-mail address:*emit_via = email

email_to = tboronczyk@ example.com

Page 200: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

yum-cron'sconfigurationfileletsusspecifyaspecificupdatepolicyandnotificationoptions

Page 201: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonautomatingsoftwareupdates:

Configureautomaticupdates(http://www.certdepot.net/rhel7-configure-automatic-updates)EnablingautomaticupdatesinCentOS7andRHEL7(http://linuxaria.com/howto/enabling-automatic-updates-in-centos-7-and-rhel-7)

Page 202: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

VerifyinginstalledRPMpackagesIt'sbeensaidthesafestsystemisonethat's"poweredoff,castinablockofconcrete,andsealedinalead-linedroomwitharmedguards."(GeneSpafford)YourCentOSsystemisprobablyconcrete-free,whichmeansit'sattheriskofattack.Thisrecipeshowsyouhowtoaudityoursystemusingrpmtomakesureitsinstalledsoftwarehasn'tbeencompromisedbyanattacker.

Page 203: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 204: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ItisimportanttofirstmakeabackupoftheRPMdatabaseat/var/lib/rpm.Therearemanywaystodothis,butforthesakeofthisexample,we'llmakeanISOimageofthedirectorywhichyoucanthenarchiveorburntodisc:

1. InstallthegenisoimageandwodimpackagesforthenecessarytoolstocreateISOimagesandtoburnthemtodisc:

yuminstallgenisoimagewodim

2. CreatetheISOimagewithgenisoimage:

genisoimage-orpm-db-bckup.iso-R-v/var/lib/rpm

Ifdesired,burntheimagewithwodim:

wodim-vdev=/dev/cdromrpm-db-bckup.iso

YoucandeletetheISOfileafterburningittodiscifyouhavenoplanstouseitinthefuture.

Whenthetimecomestoverifyyoursystem,followthesesteps:

1. Makethebackupdatabaseavailable.Ifyou'veburnedtheISOfiletodisc,andassumingthatit'slocatedat/dev/cdrom,usemountlikethis:

mount/media/dev/cdrom

2. IfthebackupisanISOfile,usemountlikethis:

mount-olooprpm-db-bckup.iso/media

3. Verifytheintegrityoftheinstalledrpmpackageagainstthebackupcopyofthedatabase.rpmreturnsalistofthefilesthataredifferentfromtheoriginalpackage,soasuccessfulauditshouldhavenooutput:

rpm-V--dbpath=/mediarpm

4. Verifytheintegrityofallofthepackagesinstalledonthesystem:

rpm-Va--dbpath=/media

Page 205: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Anattackercanalterfilesandreplaceprogramswithmaliciouscopiesonyoursystem.Luckily,wecanidentifythesechangesusingrpmtoverifytheintegrityoffilesinstalledfromapackage.Buttodothis,wealsoneedadatabasethatwecantrust.Theintegrityofthedatabaseusedtocomparefiledetailsisimportantbecauseasmartattackermayalsothinktomakechangesthereaswell.It'simportanttomakearead-onlybackupofthedatabaseregularly,perhapsbeforeandaftereverytimeyouinstallanewpackageorinstallupdates.Thenyoucancomparethestateofthesystem'ssoftwareagainstatrustedbackupandbefullyconfidentwiththeresults.

Youcanbackuptoanymediumyouwish:aremovableUSBthumbdrive,awritableCDorDVDdisc,remotestorage,orevenahigh-capacitytapecartridge.Theimportantthingisthatit'strustworthy.Therecipedemonstratedmakingabackupofthe/var/lib/rpmdatabaseasanISOfile,whichcanbeburnedtodiscorcopiedaroundas-isandmountedread-onlywhenneeded.

genisoimage-orpm-db-bckup.iso-R-v/var/lib/rpm

Note

Long-timeLinuxusersmayrememberthemkisofsandcdrecordprograms.genisoimageandcdrecordareclones,andtheformerstillexistsinCentOSintheformofsymlinkspointingtogenisoimageandcdrecord.

The-oargumentgivesthenameoftheISOfilethatwillbecreated.-Rcreatestheindexesnecessarytopreservethelengthandcasingofthefilenamesinourimage,and-vindicatesthatgenisoimageshouldbeverbosesothatwecanseeitsprogress.Whenit'sfinished,we'llhavetherpm-db-backup.isofile.

Note

rpm-db-bckup.isoisasuitablenameifyou'regoingtoburnthefiletodiscanddeleteit.IfyouplanonarchivingtheISOfileinstead,you'llwanttoconsiderincludingatimestampinthenameofwhenthebackupwastakensothatyoucankeepthingsorganized.Forexample,thefollowingcommandusesdatetoincludethedateandtimeinthefilename:

genisoimage-orpm-db-bckup-$(date+"%Y-%m-%d_%H%M").iso-R-v/var/lib/rpm

Next,therecipeshowedhowtousewodimtoburntheISOtodisc:

wodim-vdev=/dev/cdromrpm-db-bckup.iso

The-vargumentputswodiminverbosemodeandthedevargumentidentifiestheCD/DVDdrive.Therecipeassumedthat/dev/cdromistheappropriatedeviceandyoumayneedtomodifythecommanddependingonyoursystem'sconfiguration.

Page 206: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Tomakethetrusteddatabaseavailable,wemountedthediscorISOfile.Tomountthedisc,wewouldplacethediscinthedriveandissuethefollowingcommand(/dev/cdromisthedeviceand/mediaisthemountpointitsfilesystemwillbemadeavailableon):

mount/dev/cdrom/media

TomountanISOfile,weissuethefollowingcommandinstead:

mount-olooprpm-db-bckup.iso/media

Afterthetrusteddatabasewasmadeavailable,weusedrpmwiththe-Voption,whichverifiesaninstalledpackage.Bydefault,rpmusesthefilesin/var/lib/rpmasthedatabase,soweusedthe--dbpathoptiontooverridethisandinsteadpointtoourtrustedcopy:

rpm-V-dbpath=/mediarpm

Whilewecanprovideoneormorepackagenamestocheck,the-aoptionwillverifyallofthepackagesinstalledonthesystem:

rpm-Va--dbpath=/media

rpmrunsthroughaseriesoftests,checkingthesizeoffilesandtheirpermissions,andreportsthosethatfailoneormoretests.Nooutputmeansthefilesinstalledonyoursystemareexactlyastheywerewhentheywerefirstinstalledbythepackage(s).Otherwise,rpmdisplaysadotforthoseteststhatpassandoneofthefollowingmnemonicindicatorstoshowwhichtestsfail:

S:ThesizeofthefilehaschangedM:Thefile'spermissionshavechanged5:TheMD5checksumofthefiledoesnotmatchtheexpectedchecksumL:ThesymlinkhaschangedD:ThedevicehaschangedU:TheuserownerofthefilehaschangedG:TheowninggroupofthefilehaschangedT:Thefile'stimestamphaschanged

rpmwillalsoreportifafileismissing.

However,notalldiscrepanciesarebad.It'suptoustoknowwhatchangesareacceptableornot.Changestoaconfigurationfile,forexample,maybeacceptable,butchangestoabinaryutilityarecertainlyanindicationoftrouble.rpmdifferentiatesconfigurationfilesbylistingcnexttothetestresults,whichhelpsusdifferentiatethemfromothertypesoffiles:

Page 207: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Differencesarereportedwhenverifyingtheintegrityofthissystem'spackages

Page 208: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonverifyingtheintegrityofinstalledsoftware:

Therpmmanualpage(man8rpm)VerifyingfileswithRedHat'sRPM(http://www.sans.org/security-resources/idfaq/rpm.php)wodimcannotopenSCSIdrive(http://www.linuxquestions.org/questions/linux-software-2/wodim-cdrecord-cannot-open-scsi-drive-4175544944/)

Page 209: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CompilingaprogramfromsourceModern-daypackagemanagersmakeiteasytoinstallsoftware;withjustasinglecommand,wecaninstallaprogramanditsdependenciesfromanyofourconfiguredrepositories.YetanimportantvalueintheLinuxcommunityandfreesoftwaremovementistheabilitytomodifyyoursoftwareasyouseefit(perhapsyouwanttofixabugoraddanewfeature).Forsoftwarewritteninacompiledlanguage,suchasC,thisoftenmeansmodifyingtheprogram'ssourcecodeandcompilingthecodeintoanexecutablebinary.ThisrecipewalksyouthroughcompilingandinstallingtheGNUHelloprogram.

Page 210: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Anunprivilegeduseraccountcapableofescalatingitsprivilegesusingsudoshouldalsobeavailable.

Page 211: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Performthefollowingstepstocompileandinstalltheprogramfromthesourcecode:

1. Usingsudotoelevateyouraccount'sprivileges,installthegccpackage:

sudoyuminstallgcc

2. DownloadtheGNUHellosourcecode:

curlftp://ftp.gnu.org/gnu/hello/hello-2.10.tar.gz|tar-zx

3. Entertheproject'sdirectory:

cdhello-2.10

4. Runtheconfigurescriptusingthe--helpargumenttoviewtheproject'sbuildoptions.Theoutputcanbequitelengthyandyoumayfinditbeneficialtopaginatethecontentusingless:

./configure--help|less

5. Runtheconfigurescriptagain,thistimespecifyinganydesiredbuildoptionstogenerateaMakefilefile:

./configure--prefix=/usr/local

6. InvokemakewhichusesMakefileasaguidetocompiletheproject:

make

7. Usingsudotoagainescalateyourprivileges,installtheprogramanditssupportingfiles:

sudomakeinstall

8. Now,wecanrunthehelloprogramtodisplayafriendlygreeting:

hello

Page 212: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thisrecipetaughtyouthecanonicalconfigure,make,andmakeinstallrouteofcompilingandinstallingsoftwarefromthesourcecode.

TheminimalCentOSinstallationdoesnotincludeaCcompiler(aprogramthattranslatessourcecodewrittenintheCprogramminglanguageintoabinary,machine-executableformat),sothefirstthingwedidwasinstalltheGNUCompilerCollection.Becausethepackagewillbeinstalledsystem-wide,elevatedprivilegeswereneededforyum:

sudoyuminstallgcc

Note

SincetheGNUHelloprojectiswritteninCandincludesapregeneratedconfigurescript,gccisallweneed.Theremaybeotherprojectsthoughforwhichyou'llneedadditionalsoftware,suchasautoconf,togenerateaconfigurescripts,orcompilersupportforotherlanguageslikeFortran,C++,Objective-C,andGo.Foramorecapablebuildenvironment,considerinstallingtheDevelopmentToolspackagegroup:

sudoyumgroupinstall"DevelopmentTools"

Next,wedownloadedacopyoftheproject'ssourcecodefromitsFTPserver.Thecodeisdistributedasacompressedarchivewhichweretrievedusingcurl.Weomittedthe-Oargumentthatweusedinpreviousrecipesbutpipedtheoutputdirectlytotartodecompressit.Thisresultsinthecreationofadirectorynamedhello-2.10thatcontainstheproject'ssourcecode:

curlftp://ftp.gnu.org/gnu/hello/hello-2.10.tar.gz|tar-zx

Quiteoften,aprojectwillincludeseveralinformativetextfiles,sofeelfreetolookaroundatthedirectory'scontent.Somecommonfilesare:

README:Thisgivesageneraloverviewoftheproject(name,version,description,andsoon)CHANGELOG:ThisliststhechangesmadeineachreleaseINSTALL:ThiscontainsinstallationinstructionsLICENCE:Thiscontainslicenseinformationgoverningtheuseanddistributionoftheproject'scode

IftheprojectusestheGNUAutotoolsbuildsystem(whichGNUHellouses),wecanexpecttofindaconfigurescriptinthecollectionofsourcefiles.Thejobofconfigureistoscanoursystem'sbuildenvironmenttoensurethatanynecessarytoolsanddependenciesareavailableandtogeneratetheMakefilefile.Makefilewillcontaininstructionsthatcompileandinstalltheprogram,andanyoptionswepasstoconfigureultimatelyfindtheirwayintoMakefile.

Toseewhatoptionsareavailabletous,wefirstranconfigurewith--help:

Page 213: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

./configure--help|less

Someoftheoptionsmaybeuniquetotheprojectwhileothersaremoregeneral,havingtodowithsettingpathsandsuchasusedinlaterpartsofthebuildprocess.Someimportantgeneraloptionsareasfollows:

--prefix:Thebasehierarchyinwhichtheprogramanditsfileswillbeinstalled--disable-FEATURE:Thiscompilestheprogramwithoutenablingthetargetfeaturethatwouldotherwisebeenabled--enable-FEATURE:Thiscompilestheprogramwiththeoptionaltargetfeatureenabled--with-PACKAGE:Thislinkstoaspecificlibraryneededforsomefeature

Thesecondtimeweranconfigure,wedidsoprovidingthe--prefixoption:

./configure--prefix=/usr/local

Theprefixvalueof/usr/localmeansthatthisdirectorywillbeprefixedtothevariouspathswherethedifferentfileswillbeinstalledto.Forexample,whenweinstalltheprogram,thecompiledhellofileiscopiedtoPREFIX/bin,whichis/usr/local/bin,theproject'smanualpagewillbeinstalledunderPREFIX/share/man,whichis/usr/local/share/man,andsoon.

Note

ThisrecipeinstallsGNUHelloasasystem-wideaccessibleprogram.Butdon'tforget,youcanusethe--prefixoptiontocompileandinstallfilestopersonaldirectoriestoo:

./configure--prefix=/home/tboronczyk/.personal

OnceconfiguregeneratedMakefile,weexecutedthosestatementswithmaketocompiletheproject:

make

Bydefault,makelooksforafilenamedMakefileinthecurrentdirectorytorun.Ifforwhateverreasonthetargetscriptisnameddifferently,wecantellmakewhichfiletousewithits-foption:

make-f./Makefile

Also,Makefilefilesoftencontainseveralsetsofinstructionsortargets.Somecommontargetsareasfollows:

all:Compilestheprogramcheck:Runsanytestsuitesthataccompanytheprojecttoverifyitsproperfunctioningclean:Deletesanyintermediatefilescreatedduringthecompilationprocessdistclean:Deletesthefilescreatedduringtheconfigurationprocessorcompilationprocess,leavingonlythosefilesintheoriginaldistributiondist:Createsanarchivetodistributetheprograminstall:Installsthecompiledprogramandanyothernecessaryfilestotheirfinalhome

Page 214: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

onthesystemuninstall:Deletesfilesthatwereinstalledbyinstall

Thedefaulttargetifnoneareprovidedisall.

Ideally,wedon'twanttocompilesoftwareasrootbecauseit'spossibleforaMakefiletocreatearbitraryfilesinanylocation,somethingwhichcanbetakenadvantageofbyanattacker.Executingthefileasastandarduserblocksthisattackvectorsimplybecausetheunprivilegedaccountdoesn'thavewrite-accesstosensitivedirectories.Thisiswhyweusedsudoonlyfortheinstalltargetwhenwemovedtheprogramanditsfilestothedirectoriesunder/usr/local.

Page 215: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonbuildingsoftware:

GNUHello(http://www.gnu.org/software/hello)RHEL7DeveloperGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Developer_Guide/index.html)AutotoolsMythbuster(http://autotools.io/)CentOSWiki:SetupanRPMBuildEnvironment(http://wiki.centos.org/HowTos/SetupRpmBuildEnvironment)

Page 216: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter5.ManagingFilesystemsandStorageThischaptercontainsthefollowingrecipes:

ViewingthesizeoffilesandavailablestorageSettingstoragelimitsforusersandgroupsCreatingaRAMdiskCreatingaRAIDReplacingadeviceinaRAIDCreatinganewLVMvolumeRemovinganexistingLVMvolumeAddingstorageandgrowinganLVMvolumeWorkingwithLVMsnapshots

Page 217: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionTherecipesinthischapterfocusonleveragingyourCentOSsystem'sstoragetomaintainavailability,increasereliability,andtokeepyourdatasafeagainstinevitablediskfailures.You'lllearnhowtodeterminehowmuchspaceyourfilestakeupandhowmuchstorageisstillavailable.Then,you'llseehowtoputlimitsinplacetoensurethatusersusethesystem'sstorageresourcesequitably.We'llalsocreateaRAMdisk,amemory-basedlowlatencystorageforfrequentlyaccesseddata.Thenyou'lllearnhowtocreateandmanageRAIDarraystoprovidereliablestorage,andhowtoworkwithLVMvolumestoallocatelogicaldrivesfromstoragepoolstobetterutilizeyoursystem'stotalstoragecapacity.

Page 218: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ViewingthesizeoffilesandavailablestorageProgramsandservicescanbehaveunexpectedlyorstopworkingentirelywhenstoragespacerunstight,soit'simportanttoknowhowmuchspaceisavailableonoursystem.Thisrecipeintroducesahandfulofcommandsusedtodeterminehowlargeyourfilesanddirectoriesareandhowmuchstorageisusedandisavailable.

Page 219: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaworkingCentOSsystem.Administrativeprivilegesmaybeneededdependingonthepermissionsofthedirectoriesandfilesyouwanttoinspect.

Page 220: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Todisplaythestoragecapacityofamountedfilesystem,usethedfcommand:

df-h/

Toviewthesizeofafile,usethelscommand:

ls-shfile.txt

Todeterminethesizeofadirectory(thesumofsizesofallofitsfiles),usetheducommand:

du-sh~

Page 221: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thedfcommandreturnsinformationabouthowmuchfreespaceisavailableonamountedfilesystem.Theprecedingexampleaskedfordetailsabouttherootfilesystem.

df-h/

The-hargumentformatstheinformationinahuman-readableformat,listingthevaluesasmegabytes,gigabytes,andsoon,asopposedtoblockcounts.Wheninvokedwithoutanyarguments,dfdisplaysitsinformationin512-byteblockcountsforallmountedfilesystems.Wecanspecifyoneormoremountpointswiththiscommand,inwhichcasedfreportsonlyonthosefilesystems.

Valuespresentedasmegabytesandgigabytesaremoreinformativethanwhengiveninblockcounts

Theoutput'sfirstcolumn,labeledFilesystem,andthelast,labeledMountedon,identifiesthefilesystemandmountpointit'sbeenmadeavailableon,respectively.TheSizecolumnshowsthetotalamountofspacethefilesystemprovides.TheUsedcolumnshowshowmuchofthatspaceisoccupiedandtheAvailcolumnshowshowmuchisstillavailable.Use%showshowmuchspaceisoccupiedasapercentage.

Whiledfgivesusahigh-levelviewofouroverallstorageusage,toviewthesizeofindividualfileswecanusels.Thecommandsupportsalargenumberofargumentsthatshowmetainformationforfilesanddirectories,suchastheirownershipdetails,createtime,andsize.

Thisrecipeusedthe-sargumenttoreturnthefile'ssizeand-htoagaindisplaythevalueinahuman-readableformat:

ls-hsfilename.txt

Ifyouuselstoshowthesizeofadirectory,itwilllikelyreport4.0Kregardlessofwhichdirectoryyouchoose.Thisisbecausedirectoriesaren'treallycontainersholdingfileslikewe

Page 222: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

usuallyimagine;adirectoryisreallyaspecialfilethatcontainsanindexlistingthefilesthatarewithinit.Thisindexoccupiesablock'sworthofstorage.lsreportstheamountofspacethedirectoryoccupiesasafile,notthesumofthesizesofitsfiles.

Toviewthetotalsizeofallofthefilesinadirectory,whichisusuallywhatwewantwhentalkingaboutdirectorysize,weneedtousetheducommand:

du-hs~

The-sargumentprintsonlythevalueforthecurrentdirectoryand-hformatsthevalueinahuman-readableformat.Withoutanyarguments,dualsodisplays512-byteblockcountsforallfilesanddirectorieswithinthecurrentdirectory.However,directoriesaretreatedascontainerssothevaluesreflecttheblockcountofalloftheircontainedfiles.Wecanalsolistoneormorefilesordirectories,inwhichcasedureportsbackonlyonthosetargets.Bytargetingallofthefiles/directorieswithinadirectoryandpipingtheoutputthroughsort,wecanusedutoidentifytargetsthatconsumethemoststorage:

du-hs./*|sort-hr

sort's-hargumentorganizesthehuman-readablenumberscorrectly(forexample,4.0Kislessthan3Meventhough3islessthan4inanumericalsort)and-rreversestheordertodisplaythelargestentriesfirst:

Sortingcanhelpidentifywhatconsumesthemoststorage

Page 223: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonthecommandsmentionedinthisrecipe,refertotheirrespectivemanpages:

Thedfmanualpage(man1df)Thedumanualpage(man1du)Thelsmanualpage(man1ls)

Page 224: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingstoragelimitsforusersandgroupsImposinglimitsontheamountofstorageausercanconsumeisaneffectivewaytomanageresourcesandensuretheyaremadeavailabletoeveryonefairly,especiallyinamultiuserenvironment.Thisrecipeshowsyouhowtoenablequotasandsetlimitsbyusersandgroups.

Page 225: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.Itassumes/homemountsitsownfilesystem.

Page 226: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstosetupquotasandspecifystoragelimits:

1. Openthe/etc/fstabfileforediting:

vi/etc/fstab

2. Toenableuserquotas,whichenforceusagelimitsbasedonuseraccounts,adduquotatothemountoptionsfor/home.Forgroupquotas,addgquota.Bothuquotaandgquotacanbegiventogethertoenableboth:

/dev/mapper/centos-home/homexfsdefaults,uquota,gquota00

3. Saveyourchangesandclosethefile.4. Rebootthesystem:

shutdown-r+5'Rebootrequiredforsystemmaintenance'

5. Whenthesystemreboots,launchthexfs_quotashellinexpertmode:

xfs_quota-x/home

6. Setlimitsforauseraccountusingthelimitcommand:

limitbsoft=5gbhard=6gtboronczyk

7. Usethequotacommandtoverifythattheuser'slimitshavebeenset:

quota-htboronczyk

8. Setlimitsforagroupusinglimit-g:

limit-gbsoft=20gbhard=21gusers

9. Usequota-gtoverifythatthegroup'slimitshavebeenset:

quota-ghusers

10. TypequitorpressCtrl+Dtoexittheshell:

quit

Page 227: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Quotasarenotenabledbydefaultandmustbeenabledexplicitlyinthefilesystem'smountoptions;so,weupdated/etc/fstabandaddedtheuquotaand/orgquotaoptionfor/home:

/dev/mapper/centos-home/homexfsdefaults,uquota,gquota00

Weshouldneverunmountafilesystemthat'sinusebecausewedon'twanttoriskcorruptingorlosingdata.So,it'simportantthatnooneelseisloggedinwhenweremount/home.Ifyou'reloggedinasrootandyou'recertainyou'retheonlyuserloggedin,youcanremountthefilesystemwithumountimmediatelyfollowedbymount.Butifothersareloggedon,it'sbesttoperformarebootastherecipesuggests.Whenthesystemreboots,itwillhaveautomaticallymounted/homeandthequotaoptionswillbeineffect:

shutdown-r+5'Rebootrequiredforservermaintenance'

Next,weranxfs_quotaasaninteractiveshelltoentercommandstomanageourquotas.Weusedthe-xargumenttostarttheshellinexpertmode(thecommandsweneedtomanagequotasareonlyavailableinexpertmode)andgavethefilesystem'smountpointonwhichwe'regoingtosetquotas:

xfs_quota-x/home

Note

Thetraditionalquotautilitiescanbeusedtomanagebasicquotas,butxfs_quotaletsustakeadvantageoftheadditionalquotafunctionalityuniquetoXFS.Forexample,usingxfs_quotawecanalsomanageprojectquotas.

Thetwocommandswiththemostinterestforusarelimitandquota.limitisusedtosetthequotalimitsandquotaisusedtoreportthequotainformation.

Wecansetfourlimitswithlimit.Theyareasfollows:

isoft:Thissetsasoftlimitonthenumberofinodesusedihard:Thissetsahardlimitonthenumberofinodesusedbsoft:Thissetsasoftlimitonthenumberofblocksusedbhard:Thissetsahardlimitonthenumberofblocksused

Aninodeisadatastructureusedbyfilesystemstotrackfilesanddirectories.Eachfileanddirectoryarerepresentedbyaninode,sosettingalimitonthenumberofinodesausercanhaveessentiallylimitsthenumberoffiles/directoriestheycanhave.

Blocksrepresentthephysicalstorage,andsettingaquotaonthenumberofblocksforauserlimitstheamountofstoragespacetheirfilescanconsume.Thetypicalblocksizeis512bytes,meaningtwoblocksareusedtostore1KBofdata.Therecipe'sexamplessetasoftblocklimitof5GBfortheuseraccountandahardlimitof6GB.Thesuffixesk,m,andgareused

Page 228: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

tospecifyvaluesaskilobytes,megabytes,andgigabytes,respectively:

limitbsoft=5gbhard=5500mtboronczyk

Note

Commandscanberuninxfs_quotawithoutenteringtheinteractiveshellbyusing-c:

xfs_quota-x-c'limit-ubsoft=5gtboronczyk'/home

Ahardlimitspecifiesavaluethattheuserabsolutelycannotsurpass.Forexample,auserwithahardlimitof100inodesandhaving99fileswillonlybeabletocreateonemorefile.Anattempttocreateafilebeyondthatwillbemetwithanerror.

Ontheotherhand,asoftlimitdefinesalimitausercansurpassforasmallamountoftime.Oncethelimitisexceeded,theuserentersagraceperiod.Auserwithasoftblocklimitof5GBwillbeabletoconsumemorethan5GBofstorage,butonlyforacertainamountoftime.Ifthey'restillviolatingthelimitbytheendofthegraceperiod,thesoftlimitwillbetreatedasahardlimitandtheywon'tbeabletosaveanymoredata.

Note

Thegraceperiodis7daysbydefault.Wecanchangethiswiththetimercommand,using-itochangetheinodestimerand-btochangetheblocktimer:timer-b3dtboronczyk

Toreviewthecurrentquotas,thequotacommandisused.-hpresentsthevaluesinhuman-readablevalues:

quota-htboronczyk

Thedefaultoutputshowsthefilesystemanditsmountpointandtheuser'sblockquotadetails:thenumberofblocksconsumed(undertheBlocksheader),softlimit(Quota),hardlimit(Limit),andtheelapsedtimeofasoft-limitviolation'sgraceperiod(Warn/Time).-iwillretrievethesameinformationforinodequotas,and-band-icanbeusedtogethertodisplaybothsetsofinformationatthesametime:

quota-bihtboronczyk

Blockandinodequotascanbedisplayedatthesametime

Page 229: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thelimitandquotacommandsalldefaulttoworkingwithauser'squota,althoughwecanexplicitlymanageauser'squotausingthe-uargument.Tomanageagroup'squota,weuse-g:

quota-ghusers

Asmentionedearlier,xfs_quotaalsoallowsustomanageprojectquotas.Theseareessentiallylimitsplacedonspecificdirectoriesthatareenforcedregardlessofuserorgroupownership.Touseprojectquotas,usethepquotamountoption:

/dev/mapper/centos-home/homexfsdefaults,uquota,pquota00

Note

Projectquotasandgroupquotascannotbeusedtogether;mountwillfailtomountthefilesystemifbothpquotaandgquotaaregiven.Dependingonthefilesystem,thismaypreventyoursystemfrombooting.

Next,createthefile/etc/projid.EachlineisanentrymadeupofanarbitraryprojectnameandauniqueIDnumberseparatedbyacolon:

echo"my_project:42">>/etc/projid

Then,createthefile/etc/projects.ItsentriesaremadeupoftheprojectID,aseparatingcolon,andtheproject'sdirectory.Together,theprojectsandprojidfilesdefinetherelationshipbetweentheproject'snameanditsdirectory:

echo"42:/home/dev/project">>/etc/projects

Withthetwoconfigurationfilesinplace,thefinalstepistoinitializetheproject'squotatrackinginxfs_quotausingproject-c:

project-cmy_project

Withtheinitialsetupstepscomplete,youcanusethelimitandquotacommandstomanagetheproject'squotasusingthe-pargument:

limit-pbsoft=10gbhard=11gmy_project

Page 230: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithquotas:

Thexfs_quotamanualpage(man8xfs_quota)EnableUserandGroupDiskQuotaonCentOS7(http://www.linuxtechi.com/enable-user-group-disk-quota-on-centos-7-rhel-7/)

Page 231: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CreatingaRAMdiskThisrecipeteachesyouhowtotakeadvantageofRAM'slowlatencyusingaRAMdisk,asectionofmemorymadeavailableasifitwereastandardstoragedevice.RAMdisksoftenstorevolatiledatathatisconstantlyreadandupdatedinmemory.Forexample,ondesktopsystemsthey'reusedforstoringabrowser'scachetospeedupwebsurfing.Inserverenvironments,RAMdiskscanstorecachedataforhigh-loadproxyservicestoreducelatency.

Page 232: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.

Page 233: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...PerformthefollowingstepstocreateanduseaRAMdisk:

1. CheckwhetherthereissufficientmemoryavailablefortheRAMdiskusingfreecommand(apracticalRAMdiskwillneedtobesmallerthantheamountoffreememory):

free-h

2. Usemounttomountatmpfsfilesystematthedesiredmountpoint,givingthetargetsizeasamountoption:

mount-ttmpfs-osize=512Mtmpfs/mnt

3. WhentheRAMdiskisnolongerneeded,unmountthefilesystem:

umount/mnt

Page 234: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Wheneverweaccessdataonaharddrive,itsmotorsmustfirstspinupthestorageplattersandpositionthemagneticheadatthecorrectlocation.Thesemechanicalactionsmakeaccesspainfullyslowcomparedtoaccessingdataalreadyresidentinsystemmemory(RAM).Exactmeasurementsdependontheindividualsystemanditshardware,butdiskaccesstakessomewhereintheneighborhoodof10millisecondsor10,000,000nanoseconds.Memoryaccessonlytakesabout200nanoseconds,soit'ssafetosayaccessingRAMisatleast10,000timesfasterthandiskevenasalowestimate.

BeforecreatingtheRAMdisk,youshouldfirstreviewtheamountoffreememoryavailableonyoursystemusingthefreecommand:

free-h

freecommandrespondswithhowmuchmemoryisavailableandhowmuchmemoryisinuse.The-hargumentformatstheoutputinahuman-readableformat(listingthevaluesinmegabytesandgigabytesinsteadofbytes).WecanseenumbersforRAM,swapdisks,andanyspecialbuffersusedbythekernel,butwe'rereallyinterestedintheamountofusedandfreememorylistedbytheMemandSwapentries.Alowamountoffreememoryandahighamountofusedswapisanindicationthatweprobablywon'thavesufficientmemoryforapracticalRAMdisk:

Withonly1GBofRAM,thissystemhasresourcestosupportonlyarelativelysmallRAMdisk

Next,weusedmounttomakethedesiredamountofmemoryavailableatthegivenmountpoint.Therecipeused/mnt,butyou'refreetousewhatevermountpointyouseefit:

mount-ttmpfs-osize=512Mtmpfs/mnt

Theinvocationspecifiestmpfsasthemountdeviceand/mntasthemountpoint.-tspecifiestheunderlyingfilesystem,inthiscase,tmpfsand-ospecifiesourmountoptionsforthefilesystem.Alistofpossibleoptionsforthetmpfsfilesystemcanbefoundinthemountmanpage,butthemostimportantoptionissize,whichsetsthedesiredsizeofthefilesystem.

Note

It'spossibletospecifyavalueforsizethat'sgreaterthantheamountofavailableRAMbutmostofthetimethisisn'tdesirable.TheextradataismarshaledtoswaponceRAMis

Page 235: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

exhaustedandthiswillincreaselatency,negatingthebenefitsofusingaRAMdiskinthefirstplace.

Remember,RAMdisksserveaslowlatencytemporarystorageforvolatiledata.Becauseitsdataisstoredinmemory,thecontentsofthediskarelostwheneitherthesystemshutsdownorthediskisunmounted.NeverstorepersistentdatatoyourRAMdisk.

Page 236: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationaboutRAMdisks:

Themountmanualpage(man8mount)HowtocreateaRAMdiskinLinux(http://www.jamescoyle.net/how-to/943-create-a-ram-disk-in-linux)Whatis/dev/shmanditspracticalusage?(http://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html)

Page 237: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CreatingaRAIDInthisrecipe,you'lllearnhowtoconfigurearedundantarrayofdisks(RAID).Configuringanarrayofdiskstoprovideredundantstorageisanexcellentwaytoprotectyourdatafromdrivefailures.Forexample,ifyourdataresidesonasinglediskandthatdrivefails,thenthedataislost.You'llhavetoreplacethedriveandrestorethedatafromyourlatestbackup.ButiftwodisksareinaRAID-1configuration,yourdataismirroredandcanstillbeaccessedfromtheworkingdrivewhentheotherfails.Thefailuredoesn'timpactaccesstothedataandyoucanreplacethefaultydriveatamoreconvenienttime.

Page 238: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaworkingCentOSsystemandelevatedprivileges.Itassumesthatatleasttwonewdiskshavebeeninstalled(identifiedas/dev/sdband/dev/sdc)andwewillpartitionandconfigurethem.

Page 239: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...PerformthefollowingstepstocreateaRAID:

1. Uselsblktoidentifythenewstoragedevices.2. Launchcfdisktopartitionthefirstdrive:

cfdisk-z/dev/sdb

cfdiskpresentsauser-friendlyinterfaceforpartitioningstoragedevices

3. Tocreateasinglepartitionthatoccupiestheentiredisk,usetheleftandrightarrowkeystoselectNewandpressEnter.ThenselectPrimaryandacceptthedefaultsize.

4. SelectWriteandconfirmtheactionbytypingyeswhenprompted.SelectQuittoexitcfdisk.

5. Repeatsteps1to4topartitiontheseconddrive.6. Installthemdadmpackage:

yuminstallmdadm

7. Usemdadm-Ctocreateanewarrayusingthetwopartitions.ThefollowingexamplecreatesaRAID-1(mirroring)configuration:

mdadm-Cmd0-l1-n2/dev/sdb1/dev/sdc1

8. Usethe-DoptiontoexaminetheRAID:

Page 240: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mdadm-D/dev/md/md0

9. FormattheRAIDusingtheXFSfilesystemwithmkfs.xfs:

mkfs.xfs/dev/md/md0

10. MounttheRAIDforuse:

mount/dev/md/md0/mnt

Page 241: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Therearemanywaystoconfigurediskstoworktogether,especiallywhenitcomestothingslikedatamirroring,striping,andparitychecking.Someconfigurationsareimplementedatthehardwarelevelandotherscanbeimplementedusingsoftware.ThisrecipeusedmdadmtosetupmultipledisksinaRAIDconfiguration,specificallyRAID-1.

TheStorageNetworkingIndustryAssociationhasstandardizedseveraldifferentRAIDconfigurations.Someofthemorecommonconfigurationsareasfollows:

RAID-0:Dataisdistributedevenlyacrosstwoormoredisks.Thisconfigurationoffersnoredundancy,andthefailureofasinglediskinthearraywillresultindataloss.However,itoffersincreasedperformancesincedatacanbereadandwrittentodifferentdiskssimultaneously.RAID-1:Dataisduplicatedbetweendisks.Writeactivityisslowerbecausethesamedatamustbewrittentoeachdisk,butthisconfigurationoffersexcellentredundancy;thedataremainsaccessibleaslongasthereisatleastonefunctioningdisk.RAID-5:Blocksofdataandparityinformationaresplitbetweentwoormoredisks.Ifamemberofthearrayfails,parityinformationonanotherdiskcanbeusedtoreconstructthemissingdata.Writeperformanceisslower,butreadperformanceisincreasedsincedatacanbereadsimultaneouslyfromdifferentdisks.Thisconfigurationcanwithstandthefailureofasingledisk,althoughthefailureofaseconddiskwillresultindataloss.RAID-6:ThisconfigurationissimilartoRAID-5,butmaintainsanextraparityblock.Thearraycanwithstandtwodiskfailuresbeforedataislost.

Thereareotherstandardconfigurationsaswell(RAID-2,RAID-3,andsoon),andevennon-standardconfigurations,butthesearerarelyusedinpractice.Aswitheverythinginlife,therearetrade-offsbetweenthedifferentRAIDconfigurations,andselectingtherightconfigurationforyouwilldependonhowyouwanttobalanceredundancy,fault-tolerance,andlatency.

lsblkprintsinformationfortheblockdevices(storagedisks)attachedtoourCentOSsystem,anditshouldberelativelyeasytoidentifythenamesofthenewdevicessimplybylookingatthedrivesizesandlackofpartitions.Thisrecipeassumesthatthenewdevicesare/dev/sdband/dev/sdc;you'llneedtousewhateverisappropriateforyoursystemwheninvokingthecfdiskandmdadmcommands:

Page 242: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Severalunconfigureddrivesareinstalledonthesystem

Anewprimarypartitioniscreatedoneachdiskthatoccupiesitsentirecapacity.Therecipeusescfdisk,aprogramthatoffersaconsole-basedgraphicalinterfacetomanipulatepartitions.However,thereareotherpartitioningutilitiesinstalledinCentOSthatyoucanuseinsteadifyou'recomfortablewiththem,suchasfdisk,sfdisk,andparted.

Oncethedisksarepartitioned,we'rereadytoconfiguretheRAID.ThemdadmprogramusedtosetupandadministerRAIDsisinstalledusingyum:

yuminstallmdadm

mdadm-CcreatesanewRAIDconfigurationandrequiresanametoidentifyit.md0isusedintherecipewhichresultsincreatingthedevice/dev/md/md0.Theotherargumentsdescribethedesiredconfiguration:

mdadm-Cmd0-l1-n2/dev/sdb1/dev/sdc1

The-l(alower-caseL)optionspecifiesthestandardRAIDlevel,inthiscase1(thenumber1)representsRAID-1.IfyouwantedtosetupRAID-5instead,you'duse-l5.The-noptionspecifiesthenumberofpartitionstheRAIDwilluse,andthenwelistthepartitions.Therecipeconfigurestwopartitions,/dev/sdb1and/dev/sdc1.

mdadm-Ddisplaysinformationforagivenarraythat'susefulinexaminingtheconfigurationandverifyingitshealth.TheoutputlistsdetailssuchastheRAIDlevel,availablestoragesize,whichpartitionsmakeupthearray,whetheranypartitions/devicesarefailing,resyncstatus,andotherusefulinformation:

mdadm-D/dev/md/md0

Page 243: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mdadmdisplaysthestatusofthenewRAIDconfiguration

Note

mdadm-Eretrievesinformationforoneormorepartitionsthatmakeupthearray:

mdadm-E/dev/sdb1/dev/sdc1

Next,thestoragespaceisformattedwithanXFSfilesystemusingthemkfs.xfscommand:

mkfs.xfs/dev/md/md0

Finally,theRAID-backedstoragespaceisreadyforuse.Therecipedemonstratesmountingitmanuallywiththemountcommand,althoughyoucanalsoaddanentryto/etc/fstabforthefilesystemtobemountedautomaticallywheneverthesystembootsup.

Page 244: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationonsettingupRAIDs,refertothefollowingresources:

Thecfdiskmanualpage(man8cfdisk)Themdadmmanualpage(man8mdadm)Themkfs.xfsmanualpage(man8mkfs.xfs)LinuxRAIDWiki:LinuxRAID(https://raid.wiki.kernel.org/index.php/Linux_Raid)MdadmCheatSheet(http://www.ducea.com/2009/03/08/mdadm-cheat-sheet/)IntroductiontoRAID(http://www.tecmint.com/understanding-raid-setup-in-linux/)StandardRAIDlevels(https://en.wikipedia.org/wiki/Standard_RAID_levels)

Page 245: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ReplacingadeviceinaRAIDWhenanarraymemberfails,it'simportanttoreplaceitassoonaspossiblebecausethefailureofadditionaldrivesincreasesthechanceofdataloss.Thisrecipeteachesyouhowtoproperlyreplaceabaddriveandrebuildthearray.

Page 246: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.ItassumesthataRAID-1configurationhasbeensetupasdescribedinthepreviousrecipeandthedrivethatwillbereplacedis/dev/sdb.

Page 247: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoreplaceafaileddiskinaRAID:

1. Markthefailedpartitionasfaultywithmdadmusingthe-foption:

mdadm/dev/md/md0-f/dev/sdb1

2. RemovethepartitionfromtheRAID'sconfigurationwith-r:

mdadm/dev/md/md0-r/dev/sdb1

3. Physicallyreplacethefaultydisk.4. Partitionthenewdrivewithcfdisk:

cfdisk-z/dev/sdb

5. Usethe-aoptiontoaddthepartitiontotheRAID:

mdadm/dev/md/md0-a/dev/sdb1

Page 248: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...It'simportanttoreplacebadmembersassoonyoubecomeawareofthefailurebecause,dependingonthefaulttoleranceofyourconfiguration,thefailureofaseconddevicemayresultinfulldataloss.

Amembermustbemarkedfaultybeforewecansafelyremoveit,sothefirststepistofailthepartition.Todothis,weusedmdadm.The-fargumentspecifiesthepartitionwewantfailed:

mdadm/dev/md/md0-f/dev/sdb1

Then,toremovethepartitionfromtheRAID,weusedthe-rargument:

mdadm/dev/md/md0-r/dev/sdb1

Nowthatthedeviceisnolongerinuse,wecanreplacethephysicaldrive.Whetherthedrivecanbehot-swappedwhilethesystemisrunningorifasystemshutdownisnecessarydependsonyourhardware.

Oncethereplacementpartitionwasready,weaddedittotheRAIDwiththe-aargument.TheRAIDwillbegintorebuilditself,distributingdataandparityinformationtothenewpartition,assoonasthepartitionisadded:

mdadm/dev/md/md0-a/dev/sdb1

Thelastrecipeshowedhowthe-D(and-E)argumentofmdadmisusedtoretrievestatusinformationabouttheRAID.Youcanreviewtheoutputtomonitortherebuild'sprogress,butamoreconcisereportisavailablevia/proc/mdstat.Thecontentsshowthespeedatwhichtherebuildisbeingprocessedandestimatethetimeitwilltakeforittocomplete.Usingwatchtorepeatedlydisplay/proc/mdstat,youcancreateamake-shiftdashboardtomonitortheprocess:

watch-n10-xcat/proc/mdstat

TheestimatedtimeforthisRAID'srebuildtocompleteisaboutanhourandahalf

Page 249: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonreplacingfaileddrivesinaRAID:

Themdadmmanualpage(man8mdadm)ReplacingafailedharddriveinasoftwareRAID(https://www.howtoforge.com/replacing_hard_disks_in_a_raid1_array)FivetipstospeedupRAIDre-buildingandre-syncing(http://www.cyberciti.biz/tips/linux-raid-increase-resync-rebuild-speed.html)

Page 250: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CreatinganewLVMvolumeLogicalVolumeManager(LVM)abstractsdatastorageawayfromthephysicalhardware,whichletsusconfigurethepartitionsononeormorephysicaldrivestoactasonelogicaldevice.Wealsohavethefreedomtolateraddorremovephysicalpartitionsandgroworshrinkthelogicaldevice.Thisrecipeshow'syouhowtocreateanewLVMgroupandalogicaldevicefromthegroup'sstorage.

Page 251: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaworkingCentOSsystemandelevatedprivileges.Itassumesthatatleasttwonewdiskshavebeeninstalled(identifiedas/dev/sdband/dev/sdc)andwewillpartitionandconfigurethem.

Page 252: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...PerformthesestepstosetupanewLVMgroupandcreateavolume:

1. Uselsblktoidentifythenewstoragedevices.

Note

YoucansetupLVMwithRAIDstorageaswell.Skiptostep5andreplacethepartitionswithRAIDdevices(forexample,/dev/md/md0)inthegivencommands.

2. Launchcfdisktopartitionthefirstdriveandcreateasinglepartitionthatoccupiestheentiredisk:

cfdisk-z/dev/sdb

3. Repeatstep2topartitiontheseconddrive.4. Usepvcreatetoregisterthenewpartitionsasphysicalvolumes:

pvcreate/dev/sdb1/dev/sdc1

5. Verifythatthephysicalvolumesarelistedintheoutputofpvs:

pvs

6. Usingvgcreate,groupthephysicalvolumestoformavolumegroup:

vgcreatevg0/dev/sdb1/dev/sdc1

7. Verifythatthegroupislistedintheoutputofvgs:

vgs

8. Usinglvcreate,createalogicalvolumefromthestoragepoolprovidedbythevolumegroup:

lvcreate-nmyvol-L500Gvg0

9. FormatthevolumeusingtheXFSfilesystem:

mkfs.xfs/dev/vg0/myvol

10. Mountthevolumeforuse:

mount/dev/vg0/myvol/mnt

Page 253: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...LVMisanotherapproachtoconfiguremultiplestorageunitstoworktogether,focusingonpoolingtheirresourcestogetherinaflexibleway.Theseunitscanbediskpartitions,aswellasRAIDarrays,andsothegenerictermvolumeisused.

Therecipestartswiththeassumptionthatwehavetwonewdisksasourstoragevolumesandprovidesstepsforidentifyingthedevicesandpartitioningthemusinglsblkandcfdisk.Ituses/dev/sdband/dev/sdcasthedevices,butyoushouldusewhateverisappropriateforyoursystem.Oncethedisksarepartitioned,we'rereadytoregisterthepartitionsasphysicalvolumeswithpvcreate.ThetermphysicalvolumedescribesstorageavailableasaphysicalpartitionorRAID.

pvcreate/dev/sdb1/dev/sdc1

Next,thephysicalvolumesaregroupedasavolumegroupusingvgcreate.Therecipecreatedavolumegroupnamevg0usingthesdb1andsdc2partitions.

vgcratevg0/dev/sdb1/dev/sdc1

Thedesirednameforthevolumegroupispassedfirsttovgcreate,followedbythephysicalvolumeswewanttogrouptogether.Ifsdb1andsdc1bothhaveacapacityof1TBeach,theirstorageiscombinedandthevolumegroupwillhave2TB.Ifweweretolateradda500GBvolumetothegroup,thegroup'sstoragecapacitywouldincreaseto2.5TB.

Thepvsandvgscommandsreturnbasicinformationaboutphysicalvolumesorvolumegroups,respectively,andtherecipeusesthemtoverifythateachregistrationwassuccessful.pvsreportsthephysicalvolumesthatareregisteredandwhichgrouptheyareassignedto,anyattributes,andtheirstoragecapacity.vgsliststhegroups,thenumberofphysicalvolumesthatmakeupeachgroup'spool,thenumberoflogicalvolumesusingstoragefromthegroup,andthegroups'capacities.

pvsandvgsareusedtoreviewthestatusofphysicalvolumesandvolumegroups

Page 254: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Anewlogicalvolumeiscreatedfromthepooledstorageofthevolumegroupusingthelvcreatecommand:

lvcreate-nmyvol-L500Gvg0

The-noptionprovidesthenameforthelogicalvolumeand-Lprovidestheamountofstoragetoallocatethevolumefromthepool.Thefinalargumentisthenameofthevolumegroupusedtosupportthevolume.Thevaluesgivenintherecipe'sexamplecreatesavolumenamedmyvolwithacapacityof500GBbackedbythevg0group.Logicalvolumesareorganizedunder/devbygroup,sothevolumeisavailableas/dev/vg0/myvol.

Finally,thevolumeisformattedwiththeXFSfilesystemusingmkfs.xfs:

mkfs.xfs/dev/vg0/myvol

Thelogicalvolumeisnowreadyforuseandcanbemountedmanuallywithmountand/oranentrycanbemadein/etc/fstabtomountthevolumeautomaticallyatsystemboottime.

Page 255: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoFormoreinformationongettingstartedwithLVM,refertothefollowingresources:

Thelvcreatemanualpage(man8lvcreate)Thepvcreatemanualpage(man8pvcreate)Thevgcreatemanualpage(man8vgcreate)LinuxPartitionHOWTO(http://tldp.org/HOWTO/Partition/index.html)LVMmadeeasy(http://www.tuxradar.com/content/lvm-made-easy)ManageLVMvolumeswithSystemStorageManager(http://xmodulo.com/manage-lvm-volumes-centos-rhel-7-system-storage-manager.html)

Page 256: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RemovinganexistingLVMvolumeTheflexibilityofLVMallowsustoallocatethepooledstorageofphysicalvolumeshoweverweseefit.Thisrecipeshowsushowtodeletealogicalvolumeandfreeitsstoragebacktothevolumegroupforusebyotherlogicalvolumes.

Page 257: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.Itassumesthatalogicalvolumehasbeencreatedasdescribedintheprecedingrecipe.

Page 258: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...PerformthefollowingstepstoremoveanLVMvolume:

1. Unmountthefilesystemwithumount:

umount/mnt

2. Open/etc/fstabandverifythatthereisn'tanentrytoautomaticallymountthefilesystem.Ifthereis,removetheentry,saveyourchanges,andclosethefile.

3. Uselvremovetodeletethelogicalvolume:

lvremovevg0/myvol

4. Reviewtheoutputofvgstoverifytheremoval.

Page 259: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Deletingavolumefreesitsstoragebacktothevolumegroup,whichcanthenbeusedtocreatenewlogicalvolumesorsupportgrowinganexistingvolume.Thisrecipetaughtyouhowtodestroyalogicalvolumeusingthelvremovecommand.

Becauseavolumecan'tbefreedifit'sinuse,thefirststepistomakesurethatitsfilesystemisunmounted.Ifthefilesystemismountedautomatically,itsentryin/etc/fstabshouldalsoberemoved.

Next,lvremoveisinvokedwiththenameofthelogicalvolumetofreeit:

lvremovevg0/myvol

Note

Youcandeleteallofthevolumesfromapoolbyprovidingjustthepoolname:

lvremovevg0

Therecipesuggestscheckingtheoutputofvgstoverifythatthelogicalvolumewasremoved.Intheoutput,thenumberoflogicalvolumesunderthe#LVcolumnshouldhavedecreasedandtheamountoffreespaceundertheVFreecolumnincreasedappropriately.

Page 260: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonremovingavolume:

Thelvremovemanualpage(man8lvremove)Thevgsmanualpage(man8vgs)

Page 261: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AddingstorageandgrowinganLVMvolumeThesizeoflogicalvolumesdoesn'tneedtobefixedandwe'refreetoallocatemorestorageforonefromitsvolumegroup.Thisrecipeteachesushowtoaddmorestoragetothegroupandthengrowthesizeofthelogicalvolumetotakeadvantageofit.

Page 262: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.Itassumesthatanewdiskhasbeeninstalledandpartitioned(identifiedas/dev/sdd1)andalogicalgroupandvolumehavebeenconfiguredasdescribedinpreviousrecipes.

Page 263: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoaddstorageandincreasethesizeofanLVMvolume:

1. Registerthenewpartitionasaphysicalvolume:

pvcreate/dev/sdd1

2. Reviewtheoutputofpvstoconfirmthatthevolumewasregistered:

pvs

3. Usevgextendtoaddthephysicalvolumetothedesiredvolumegroup:

vgextendvg0/dev/sdd1

4. Reviewtheoutputofvgstoconfirmthatthevolumewasaddedtothegroup:

vgs

5. Uselvextendtoincreasethesizeofthedesiredlogicalvolume:

lvextendvg0/myvol-L+500G

6. Reviewtheoutputoflvstoconfirmthenewcapacity:

lvs

7. Expandthefilesystemwithxfs_growtousethenewcapacity:

xfs_grow-d/mnt

Note

AnXFSfilesystemmustbemountedtoexpanditssize;ifit'snotalreadymounted,you'llneedtodosobeforeexecutingxfs_grow.

8. Confirmthenewsizeofthefilesystemusingdf:

df-h/mnt

Page 264: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Therecipeassumedthatanewpartitionhasbeenprepared,whichwasthenregisteredasaphysicalvolumeusingthepvcreatecommand.Thenthephysicalvolumewasassignedtothevg0volumegroupusingvgextend,increasingthegroup'savailablestorage:

vgextendvg0/dev/sdd1

lvextendwasinvokedtogrowthesizeofalogicalvolume,vg0/myvol:

lvextendvg0/myvol-L+500G

The-Largumentspecifiestheamountofstoragetoallocatefromthepool.It'svaluecanbeanabsolutevalue,forexample,-L500G,inwhichcasethevolumewillberesizedtohavethatmuchcapacity.Arelativevaluecanalsobeusedtoincreasethevolume'scurrentcapacitybysomeamount.Therecipeused-L+500Gtogrowthesizeofthelogicalvolumebyanadditional500GB.

Note

Youwillreceiveanerrorifyouprovideavaluefor-Llessthanthelogicalvolume'scurrentcapacitybecauselvextendonlyincreasesthecapacityofavolume.Thelvreducecommandisusedtoreducethesizeoflogicalvolumes:

lvreducevg0/myvol-L500GB

Givenastraightvalue,-Lspecifiesthetotalcapacityforthevolume.Intheprecedingcommand,thecapacityforvg0/myvolisreducedto500GB.Givenarelativevalue,forexample-L-500GB,lvreducereducesthevolume'scapacitybythespecifiedamount.

Whenfinished,thelogicalvolume'scapacitycanbeconfirmedbyinspectingtheoutputofthelvscommand.Thecommandreportsthelogicalvolumesthatexistandtowhichgrouptheyareassigned,theirattributes,storagecapacity,andotherstatistics.

Thecapacityofthelogicalvolumehasincreasedbutthefilesystemneedstoberesizedtouseit

Page 265: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Finally,thefilesystemneedstobeexpandedtomakeuseoftheadditionalspaceavailabletoitwithxfs_growfs.Filesystemsmustbemountedfortheutilitytowork,andtherecipeassumesthatit'smountedat/mnt.The-dargumentinstructsxfs_growtoincreasethesizeofthefilesystemasmuchaspossible(theentiresizeofthevolume).

xfs_growfs-d/mnt

Alternatively,youcangiveaspecificsizewith-D.Itsvalueisgiveninblockcounts,sosomemathwillberequiredtogrowthefilesystemtothedesiredsize.Forexample,let'ssayyouhavea1TBfilesystemandtheblocksizeis4,096bytes(thedefault).Theblockcountwillbe268,435,456blocks.Ifyouwanttogrowthefilesystemanadditional500GB,thetargetblockcountwillbe399507456:

xfs_growfs-D399507456/mnt

Tomakelifealittleeasier,here'satablethatpresentsblockcountsforcommonsizes:

Theseblockcountscanbeusedwithxfs_growfstogrowanXFSfilesystem

Whileit'spossibletoreducethesizeofalogicalvolume,it'sonlypossibletogrowanXFSfilesystem.IfyouwanttoreducethesizeofanXFS-supportedvolumeyou'llhavetomoveitsdatatoasafelocation,removeandrecreatethelogicalvolumewithasmallersize,andlatermovethedataback.

Page 266: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationongrowinganLVMvolume:

Thexfs_growfsmanualpage(man8xfs_growfs)LinuxguidetotheXFSfilesystem(http://landoflinux.com/linux_xfs_filesystem_introduction.html)Extend/ReduceLVM'sinLinux(http://www.tecmint.com/extend-and-reduce-lvms-in-linux/)HowtogrowanXFS-formatteddisk(http://superuser.com/questions/1000092/how-to-grow-xfs-formated-disk/1001486#1001486)

Page 267: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WorkingwithLVMsnapshotsAlogicalvolume,alsocalledalinearvolume,isjustonetypeofvolumewecancreate;LVMalsoletsuscreatesnapshotvolumes.Asnapshotvolumeisassociatedwithalogicalvolumeandkeepstrackofchangesmadetothelogicalvolume'sdata.Wecanthenmergethesnapshotbackintothelogicalvolumetorollbackthedata.Thisrecipewillshowyouhowtodojustthat.

Page 268: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithadministrativeprivilegesprovidedbylogginginwiththerootaccountorusingsudo.Itassumesthatalogicalvolumehasbeenconfiguredandsufficientstorageexistsinitsvolumegroupforthesnapshot.

Page 269: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ThefollowingcommandsshowyouhowtoworkwithLVMsnapshots.Beforeyoubegin,youshouldverifythatthereissufficientstorageavailableinthevolumegrouptosupportthesnapshotusingvgs.

1. Uselvcreate-stocreateasnapshotvolume:

lvcreate-s-L100M-nmyvolsnapvg0/myvol

2. Asnapshotvolumemaybedeletedusinglvremove:

lvremovevg0/myvolsnap

3. Asnapshotvolumemaybemountedandaccessedwithmount:

mount-oro/dev/vg0/myvolsnap/mnt

4. Torestorealogicalvolumetothestateitwasinwhenthesnapshotwasmade,makesureneitheraremountedanduselvconvert:

lvconvert-v--mergevg0/myvolsnap

Page 270: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thisrecipepresentedcommandstocreateasnapshotvolumewhichthentracksthechangesmadetoalogicalvolumeandtomergethesnapshotbackintothelogicalvolume.

Snapshotsarecreatedusingthelvcreatecommandwiththe-sflag.-ngivesthenameforthesnapshotand-Lspecifieshowmuchstoragewillbeallocatedforitfromthevolumegroup.Thefinalargumentisthelogicalvolumethesnapshotiscreatedfrom:

lvcreate-s-L100M-nmyvolsnapvg0/myvol

Thevaluesgivenintheexamplecreateasnapshotofvg0/myvolnamedmyvolsnapwithacapacityof100MB.Storageforthesnapshotvolumeisallocatedfromthesamegroupasitslogicalvolumesothatthereshouldbesufficientstoragetosupportthesnapshot.Luckily,snapshotvolumesdon'tcopyallofthedatafromtheoriginalvolume.Instead,theyuseacopy-on-writestrategywhereonlythedifferencesarerecordedtothesnapshotwhenthedataismodified.

Ifthedeltasexceedthesnapshotvolume'scapacity,LVMwon'tbeabletocontinuetorecordchangesandthesnapshotwillnolongerbevalid.Forthisreason,youshouldperiodicallymonitorthesnapshot'sstorageusageandeitherresizethesnapshotordiscardthesnapshotandcreateanewonewithalargercapacityifnecessary.Aswithothervolumes,lvremoveisusedtodeletesnapshotvolumes:

lvremovevg0/myvolsnap

Asnapshotcanalsobemountedandaccessedlikeotherlogicalvolumes.LVMtransparentlyreadsunmodifieddatafromtheoriginallogicalvolumesothatthedataappearsasafullcopy.Dependingontheyourreasonsforcreatingasnapshot,youmaywanttousetheromountoptiontomountthevolumeread-onlytopreventinadvertentchangesfrombeingintroduced:

mount-oro/dev/vg0/myvolsnap/mnt

lvconvertisusedtochangeavolume'stypeandothercharacteristics.Youshouldunmountboththelogicalandsnapshotvolumesbeforecallinglvconvertsothatthemergeprocesscanbeginimmediately.Otherwise,LVMwillscheduletheprocesstobeginafterbothhavebeenunmountedandeitherthelogicalorsnapshotvolumeismountedagain.

Torevertthelogicalvolume'sdata,wetargetitssnapshotvolumeandusethe--mergeoption:

lvconvert-v--mergevg0/myvolsnap

Mergingthesnapshotvolume'sdatatoitslogicalvolumerollsbackthechangestothelogicalvolume'sdata,basicallyrestoringittothestateitwasinatthetimethesnapshotwascreated.Whenfinished,thesnapshotisautomaticallydeleted.-vputslvconvertintoverbosemode,whichisusefultomonitoritsprogressandtoknowwhenthemergeiscompleteandthesnapshothasbeendeleted.

Page 271: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithsnapshots:

Thelvconvertmanualpage(man8lvconvert)Howtotakeasnapshotlogicalvolumeandrestore(http://www.tecmint.com/take-snapshot-of-logical-volume-and-restore-in-lvm/)Howtotakevolumesnapshots(http://www.unixarena.com/2013/08/linux-lvm-how-to-take-volume-snapshot.html)

Page 272: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter6.AllowingRemoteAccessThischaptercontainsthefollowingrecipes:

RunningcommandsremotelythroughSSHConfiguringamoresecureSSHloginSecurelyconnectingtoSSHwithoutapasswordRestrictingSSHaccessbyuserorgroupProtectingSSHwithFail2banConfiningsessionstoachrootjailConfiguringTigerVNCTunnelingVNCconnectionsthroughSSH

Page 273: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionTherecipesinthischapterwillhelpyouprovideremoteaccesstoyourCentOSsysteminasecurity-consciousway.You'lllearnhowtoexecutecommandsonaremotesystemthroughSSH,configuretheOpenSSHSSHservertoincreasesecuritysurroundingremotelogins,andusekey-basedauthenticationtoconnect.You'llalsolearnhowtoallowordenyaccesstodifferentusers,configureFail2bantoautomaticallyblocksuspectedIPaddressestoprotectyourserverfrombruteforceattacksbetter,andrestrictuserstoachrootjailoncethey'veloggedin.TheconcludingrecipesshowyouhowtoprovideremoteaccesstoacompletedesktopenvironmentusingVNC,andhowtosecurethataccessbytunnelingVNCtrafficthroughanSSHtunnel.

Page 274: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RunningcommandsremotelythroughSSHThisrecipeshowsyouhowtoexecuteone-shotcommandsonaremotesystemthroughSecureShell(SSH).Havingtheabilitytoruncommandswithoutestablishingafullinteractivesessioncanbeconvenientbecauseyoucanavoidrunningasecondterminal;everythingcanbedonedirectlyfromthesamecommandline.

Page 275: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaremotesystemrunningtheOpenSSHserverandalocalcomputerwiththeOpenSSHSSHclientinstalled(bothshouldbeinstalledbydefaultonCentOS).TheexamplesassumethattheremotesystemisconfiguredwiththeIPaddress192.168.56.100.Also,youwillneedauseraccountavailableontheremotesystem.

Page 276: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...ThefollowingexamplesshowyouhowtoruncommandsonaremotesystemfromyourlocalsystemthroughSSH:

Toexecuteacommandremotely,usesshandspecifythehostnameorIPaddressofthetargetsystemfollowedbythecommandanditsarguments:

ssh192.168.56.100uname-a

Toexecutethecommandasadifferentuser,provideausernamewiththeremotesystem'saddress:

[email protected]

Iftheremotecommandrequiressudo,supplysshwiththe-targument:

ssh-t192.168.56.100sudomount/mnt

Usethe-Xargumenttoforwardtheremotesystem'sX11displaytoexecuteagraphicalprogram:

ssh-X192.168.56.100gnome-calculator

Usequoteswhenyouexecuteacomplexcommand,forexample,aseriesofcommandsorwhenusingI/Oredirection.Thisavoidsambiguitybetweenthelocalandremoteshells:

ssh192.168.56.100"tartvzfarchive.tgz>contents.txt"

Youcanpipeinputfromthelocalsystemtoremotecommandsthatreadfromstdin:

catfoo.txt|ssh192.168.56.100"cat>foo.txt"

Page 277: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...sshisusedmainlytologintoaremotesystemandaccessaninteractiveshellbecauseit'spossiblethatmanypeopledon'tknowthatcommandscanbeexecutedremotelywithoutashell.Thisrecipepresentedseveralexamplesthatillustratehowyoucanusesshtorunremotecommands,eachofwhichfollowthisgeneralinvocationpattern:

ssh[options][user@]hostcommand

Anythingprovidedaftertheremotehostisacceptedasthecommandtoexecuteremotelybysshasdemonstratedinthefollowingtwoexamples.Thefirstinvokesunametoprintinformationabouttheremotesystemsuchasthekernel,processor,andoperatingsystem,andthesecondrunsidtodisplaytheusernameofthecurrenteffectiveuserID:

ssh192.168.56.100uname-a

[email protected]

sshdoesn'tlaunchaninteractiveshellwhenrunningthesecommandsasthere'snoreasonforittoallocateatty/pseudo-terminal;itactsastheshellitselfandroutesinputandoutputbetweentheremoteandlocalsystems.However,somecommandsrequireaterminaltofunctionproperly.Forexample,sudousestheterminaltoensuretheuser'spasswordisn'tprintedonthescreenastheytypeit.Withoutaterminal,sudorefusestorunandreportsbackthatyoumusthaveattytorunsudo.Wecanprovidethe-targumentwhenexecutingsuchcommandstoforcesshtoallocatearemoteterminalresource:

ssh-t192.168.56.100sudomount/mnt

The-XargumentforwardstheX11displayandallowsustorungraphicalprograms.Theprogramappearsasifitwererunninginourlocaldesktopenvironment,althoughinrealityit'srunningontheremotesystem:

ssh-X192.168.56.100"gnome-calculator"

Page 278: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GraphicalapplicationscanberunusingX11forwarding

Tomakesureaninvocationisinterpretedhowyouintend,youmayneedtoquotecommands.ThisisespeciallytruewhenusingI/Oredirectionorwhenyouarerunningmultiplecommands.Toseewhy,considerthefollowingexample:

ssh192.168.56.100"tartvzfarchive.tgz>contents.txt"

taroutputsalistoffilesinthearchivewhichisthenredirectedtocreatethecontents.txtfile.Everythinghappensremotely—tarrunsontheremotesystemandthenewfileiscreatedontheremotesystem.

Now,here'sthesameinvocationbutwithoutquoting:

ssh192.168.56.100tartvzfarchive.tgz>contents.txt

tarstillexecutesremotely,butthelocalshellinterpretstheredirectandcontents.txtiscreatedonthelocalsystem.

Page 279: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

I/Oredirectionispossibleinbothdirections.Thatis,wecanpipeinputfromthelocalsystemtotheremotesystem'sstdin:

catfoo.txt|ssh192.168.56.100"cat>foo.txt"

Inthisexample,foo.txtisreadbycatandthecontentsarepipedtotheremotesystem.There,aremotelyrunninginstanceofcatwillbewaitingtoreadtheinput.Whenitdetectstheendofthetransmission,catoutputswhatitreceived,whichisthenredirectedtocreatefoo.txtontheremotesystem.Inessence,we'vejustmadeacopyoffoo.txtfromthelocalsystemtotheremotesystem.

Page 280: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonrunningcommandsremotelythroughSSH:

Thesshmanualpage(man1ssh)PipingwithSSH(http://linux.icydog.net/ssh/piping.php)Commandlinefu.comSSHcommands(http://www.commandlinefu.com/commands/matching/ssh/c3No/sort-by-votes)

Page 281: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringamoresecureSSHloginSSHisconsideredasecurealternativetoolderprotocols,suchasTelnet,rsh,andrlogin,becauseitencryptstheconnectionbetweentheclientandserver.Thisencryptionprotectsthetrafficfromanyne'er-do-wellswhomaybeeavesdroppingonthenetwork.However,yoursystemcanstillfallvictimtothedenialofserviceattacksoramalicioususerwhotakesadvantageofanidlesessionthatwascarelesslyleftunattended.ThisrecipetakesthefirststepsinhardeningSSHbyupdatingtheserver'sconfigurationtoincreasesecuritysurroundingremotelogins.

Page 282: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemrunningtheOpenSSHserver.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 283: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoincreasethesecurityofyourSSHlogins:

1. OpentheSSHserver'sconfigurationfilewithyourtexteditor:

vi/etc/ssh/sshd_config

2. LocatetheLoginGraceTimeoption.Uncommentitandchangeitsvalueto30secondstolimittheamountoftimeusersaregiventoprovidetheircredentials:

LoginGraceTime30

3. FindanduncommentthePrintLastLogoptionandchangeitsvaluetoyestoshowtheuserthetimeandlocationoftheirlastlogin:

PrintLastLogyes

4. UncommenttheBanneroptionandsetitsvalueto/etc/bannertodisplayaloginwarningtousers:

Banner/etc/banner

5. Saveyourchangesandclosetheconfigurationfile.6. Createthe/etc/bannerfilewiththefollowing(orsimilar)verbiage:

Thiscomputersystemisforauthorizeduseonly.Allactivityis

loggedandmonitored.Usersaccessingthissystemwithout

authority,orinexcessoftheirauthority,maybesubjectto

criminal,civil,andadministrativeaction.Continuingtouse

thissystemindicatesyourconsenttothesetermsandconditions

ofuse.

7. RestarttheSSHserverfortheconfigurationchangestotakeeffect:

systemctlrestartsshd.service

8. Toautomaticallylogoutsessionsafter10minutesofinactivity,createthe/etc/profile.d/timeout.shfilewiththefollowing:

exportTMOUT=600

Page 284: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThefirstoptionweadjustedintheSSHserver'sconfigurationfilewasLoginGraceTime,todeterminehowlongauserisallowedtoentertheirusernameandpassword.Bydefault,theconnectionattempttimesoutiftheuserdoesn'tprovidetheircredentialswithintwominutes.Wereducedthistimeto30seconds,butyoucansetamoreappropriatevalueifyoufindthisnottobelongenough:

LoginGraceTime30

Then,settingthePrintLastLogoption'svaluetoyescausesthetimeandlocationoftheuser'slastlogintobedisplayed.Thisishelpfulbecauseanunknowntimeorlocationcanalertauseriftheiraccounthasbeencompromisedandisbeingusedforunauthorizedaccess:

PrintLastLogyes

Next,weconfiguredaloginbanner.Astrongly-wordedwarningisn'tlikelytodeteramalicioususer,butmanyorganizationsrequirethemtobeprominentlydisplayedwhenauserlogsinforlegalreasons.Suchmessagesareconsideredtobesufficientnotificationinsomejurisdictionstoinformusersthattheiractionsaremonitoredandtheyshouldhavenoexpectationsofprivacyforwhattheydoonthesystem.Thisgivestheorganizationbetterlegalstandingtoprosecuteanyabuse.

Todisplaythewarningbeforetheloginprompt,wesetBannerwiththepathtoafilecontainingourmessage.Thenwecreatedthefilewiththedesiredtext:

Banner/etc/banner

Theuserispresentedwithabannermessagebeforeloggingintotheremotesystem

Note

nroffcanbeusedtojustifythebanner'stext:

(echo-e".ll75\n.pl0\n.nh";cat)|nroff>/etc/banner

Page 285: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

catreadstextfromstdin(pressCtrl+Dwhenyou'refinished)andboththeecho'dinstructionsandthetextarepipedtonroffforformatting.

.lltellsnrofftosetthelinelengthat75characters.It'sagoodideatouseavaluelessthan80becausethetraditionalterminaldisplays80charactersperline.

.plsetsthepagelength,andsettingit0preventsnrofffromaddingadditionalwhitespaceafterthetextinanattempttofillthelengthofsomeimaginaryprintedpage.

.nhpreventsnrofffromhyphenatingwordsattheendofaline.

Ifyouwanttodisplaythebanneraftertheuserlogsininsteadofbefore,youcanusethemessageofthedayfileinstead.Inthiscase,uncommentthePrintMotdoptionandsetitsvaluetoyesandthensaveyourtextin/etc/motd.

Finally,wecreatedthe/etc/profile.d/timeout.shfiletosettheTMOUTenvironmentvariable.SettingTMOUTunder/etc/profile.dappliesitgloballytoalluserswhentheylogin.Totargetindividualusersinstead,orifyouwanttooverridetheglobalvalueforspecificusers,youcanplacetheexportintheir~/.bash_profilefile:

exportTMOUT=600

Nowwiththevariableset,bashautomaticallyclosestheuser'ssessionifit'sbeeninactiveforthespecifiedamountoftimewiththemessagetimedoutwaitingforinput:auto-logout.Thevalueisgiveninseconds,withtherecipe'sexampleclosingidlesessionsafter10minutes.

Page 286: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationontighteningsecurityonSSHlogins:

Thesshd_configmanualpage(man5sshd_config)RHEL7SystemAdministrator'sGuide:OpenSSH(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-OpenSSH.html)CentOSWiki:SecuringOpenSSH(https://wiki.centos.org/HowTos/Network/SecuringSSH)ShouldIusealoginbanner?(http://serverfault.com/questions/24376/should-i-use-a-login-banner-and-if-so-what-should-it-say)

Page 287: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SecurelyconnectingtoSSHwithoutapasswordThisrecipeteachesyouhowtogenerateakeypairandsetupkey-basedauthenticationforSSHsessions,allowingyoutosecretlyconnecttoaremotesystemwithoutusingapassword.Key-basedauthenticationisconsideredmoresecurethanusingapasswordbecauseaweakpasswordcanbeeasytoguessandastrongpasswordcanbeeasytoforgetandmorelikelytobewrittendown.Ineithercase,anattackerhasafairlygoodchanceofdiscoveringauser'spassword.Withkey-basedauthentication,ausermustsupplythecorrectprivatekeyfile,whichispracticallyimpossibletocrackorspoof.

Page 288: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaremotesystemrunningtheOpenSSHserverandalocalcomputerwiththeOpenSSHSSHclientinstalled.ItsexamplesassumethattheremotesystemisconfiguredwiththeIPaddress192.168.56.100.Also,youwillneedanavailableuseraccountontheremotesystem.

Page 289: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstosetupkey-basedauthenticationforSSHsessions:

1. Onthelocalcomputer,usethessh-keygencommandtocreateapairofauthenticationkeys.Acceptthedefaultpath/filenameforthekeysandleavethepassphraseempty:

ssh-keygen-b3072-C"TimothyBoronczyk"

2. Createthe.sshdirectoryifitdoesn'talreadyexistinyourremotehomedirectory:

ssh192.168.56.100"mkdir-m700.ssh"

3. Appendthecontentsofid_rsa.pubto.ssh/authorized_keysontheremotesystem:

cat.ssh/id_rsa.pub|ssh192.168.56.100"cat>>

.ssh/authorized_keys"

4. Securetheauthorized_keysfile'spermissions:

ssh192.168.56.100"chmod640.ssh/authorized_keys"

5. Verifythatyoucanconnecttotheremotesystemwithoutprovidingapassword:

ssh192.168.56.100

6. Repeatsteps2through5foranyadditionalremotesystemsyouwanttologintousingkey-basedauthentication.

Page 290: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Key-basedauthenticationisconsideredmoresecurethanusingpasswordsbecauseit'snearlyimpracticaltocrackasuitableencryptionkeywhilebruteforcingapasswordistrivial.ThisrecipeusedtheOpenSSHsuite'sssh-keygenprogramtogenerateanewpairofkeys,whichwethenusedtoauthenticateourSSHsession:

ssh-keygen-b3072-C"TimothyBoronczyk"

-Cembedsabriefcommentinthekeywhichisusefulforidentifyingtheownerorpurposeofakeyand-bsetsthenumberofbitsusedforthekey'smodulus.Themorebitsused,thelargerthenumberthatcanberepresented,whichmeansgreaterresistancetocrackingattacks.If-bisn'tprovided,thedefaultvalueis2,048bits.Basedontheestimatesoftherateatwhichcomputingpowerincreases,2,048isgenerallythoughttobesuitableuntilaroundtheyear2030(researchersdevelopedasuccessfulattackagainst1,024-bitkeysin2010).A3,072-bitkeyisconsideredsuitablebeyond2030.

Weacceptedthesuggested~/.ssh/id_rsavalueasthenameoftheoutputfilewhenprompted(thisiswheresshlooksforourprivateidentitykeybydefaultwhenweconnecttoaremoteserver).Wealsodidn'tprovideapassphrase.Ifweweretogiveone,thenthekeywouldbeencryptedandwe'dneedtoprovidethepasswordtodecryptthekeyeverytimewewantedtouseit.

Whenssh-keygenisfinished,theprivatekeyid_rsaandthepublickeyid_rsa.pubcanbefoundinthe.sshdirectory:

Page 291: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thepairofkeysisgeneratedforpassword-lessauthentication

Then,wecreatedthe.sshdirectoryinourhomedirectoryontheremotesystem.Youcanexecutethemkdircommandwhilebeingloggedintotheremotesystem,otherwiseyoucanexecutethecommandremotelythroughSSH:

ssh192.168.56.100"mkdir-m700.ssh"

Next,weaddedthepublickeyto.ssh/authorized_keysontheremotesystem:

cat.ssh/id_rsa.pub|ssh192.168.56.100"cat>>.ssh/authorized_keys"

Becauseproperpermissionshelpensurethesecurityofyourkeys,sshwon'tconsiderthemsafetouseifthepermissionsaretoolax.Thepermissionsonthe.sshdirectoryshouldberead,write,andexecutepermissionsonlyfortheowner(700),readpermissionsfortheownerandgroup,andwritepermissionsfortheowner(640)onauthorized_keys.Asimplechmodcallensuresthateverythingiscorrect:

ssh192.168.56.100"chmod640.ssh/authorized_keys"

Whenweconnect,sshseestheid_rsafileandsendsourprivatekeyaspartoftheconnectionrequest.Theserverchecksforthecorrespondingpublickeyintheauthorized_keysfile,andifeverythingmatchesupthenwe'reauthorizedandloggedin.

Page 292: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonusingkey-basedauthenticationwithOpenSSH:

RHEL7SystemAdministrator'sGuide:OpenSSH(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-OpenSSH.html)SSHpasswordversuskeyauthentication(http://security.stackexchange.com/questions/33381/ssh-password-vs-key-authentication)

Page 293: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RestrictingSSHaccessbyuserorgroupDependingontheroleofyoursystemandwhichuseraccountsareconfiguredonit,youmaynotwantallofitsregistereduserstohaveaccessthroughSSH.ThisrecipeshowsyouhowtoconfiguretheSSHservertorestrictremoteuseraccessbyexplicitlygrantingordenyingtheusersaccess.

Page 294: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemrunningtheOpenSSHserver.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 295: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstorestrictusers'SSHaccess:

1. OpentheSSHserver'sconfigurationfilewithyourtexteditor:

vi/etc/ssh/sshd_config

2. FindthePermitEmptyPasswordsoption.Uncommentitandsetitsvaluetonotodisallowaccountswithemptypasswords:

PermitEmptyPasswordsno

3. Todisallowremoteaccesswiththerootaccount,locateanduncommentthePermitRootLoginoptionandsetitsvaluetono:

PermitRootLoginno

4. DenyremoteaccessforspecificuseraccountsbyaddinganentryforDenyUsers.Theoption'svalueshouldbeaspace-separatedlistofusernamesyouwanttodeny:

DenyUsersbbarrerajbhusembutterfield

5. DenyremoteaccessforuserswhoaremembersofaspecificgroupbyaddinganentryforDenyGroups:

DenyGroupsusersnoremote

6. AddanAllowUsersentrytodenyaccesstoeveryoneexceptthoseinthelistofpermittedusers:

AllowUsersabelltboronczyk

7. AddanAllowGroupsentrytodenyaccesstoeveryoneexceptthoseinthelistofpermittedgroups:

AllowGroupsitadminremote

8. Saveyourchangesandclosethefile.9. RestarttheSSHserverforthechangestotakeeffect:

systemctlrestartsshd.service

Page 296: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...First,weuncommentedPermitEmptyPasswordsandsetitsvaluetono.Thispreventsuseraccountsthatdon'thaveapasswordfrombeingusedtologinoverSSH:

PermitEmptyPasswordsno

Passwordsarethefirstlevelofdefenseinprotectingourselvesfrommaliciousattacksusingcompromiseduseraccounts.Withoutastrongpassword,anyonecanloginsimplybyknowingtheusername.Thisisascarythoughtbecauseusernamescanbeeasilyguessedandsometimesareevenpubliclyavailableintheformofe-mailaddressesandsoon.

Next,weuncommentedthePermitRootLoginoptionandsetitsvaluetono.ThispreventsrootfromestablishinganSSHsessiondirectly:

PermitRootLoginno

SuchrestrictionswereofcriticalimportancewhenprotocolssuchasTelnetwereusedbecausetheusernameandpasswordwereoftensentacrossthenetworkinplaintext—anattackercouldeasilymonitorthenetworktrafficandcapturethepassword.However,eventhoughSSHmakesthisconcernmootbyencryptingitstraffic,thepasswordisstillvulnerablefrombruteforcecrackingattacks.Forthisreason,it'swisetorequireuserstoauthenticateusingtheirunprivilegedaccountfirstandthenusesuorsudotoelevatetheirprivilegeswhennecessary(refertoChapter3,UserandPermissionManagement).

TherecipethenpresentedtheDenyUsers,DenyGroups,AllowUsers,andAllowGroupsoptionsasawaytorestrictSSHaccessonalargerscale.

TheDenyUsersoptionprohibitsspecificusersfromloggingin.Whileotheruseraccountswillbeabletoaccessthesystemremotely,theuserslistedunderDenyUserswillseethemessagePermissionDenied.Therecipe'sexampledeniesaccesstotheusersbbarrera,jbhuse,andmbutterfield:

DenyUsersbbarrerajbhusembutterfield

TheDenyGroupsoptionworkssimilarly,butdeniesusersbasedontheirgroupmembership;thefollowingexampledeniesaccesstoanyonewho'samemberoftheusersgrouporthenoremotegroup:

DenyGroupsusersnoremote

Thedenialoptionsareusefulforblacklistingasmallnumberofusers.Toblockallusersexceptforaselectfew,weusetheallowoptions.AllowUsersdeniesaccesstoeveryoneexceptthosespecified.AllowGroupsisitscounterpartallowingonlythoseuserswhoaremembersofthespecifiedgroup:

AllowUsersabelltboronczyk

Page 297: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AllowGroupsitadminremote

Theoptionscanalsohavevaluesthatuse*and?aswildcards.*matcheszeroormorecharactersand?matchesasinglecharacter.Forexample,thefollowingdeniesallusers:

DenyUsers*

Note

AllowUsersandAllowGroupsdenyallusers/groupsexcepttheonestheylist.BecarefulifyoudependonSSHtoadministeryourserversbecauseit'sveryeasytoblockyourselfwiththese.BeforeloggingoutofyourcurrentSSHsession,checkthatyoucansuccessfullyloginusingasecondterminal.Ifthere'saproblem,you'llstillbeloggedinwiththefirstsessionandwillabletofixtheissue.

Page 298: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingformoreinformationonrestrictingremoteSSHaccess:

Thesshd_configmanualpage(man5sshd_config)RHEL7SystemAdministrator'sGuide:OpenSSH(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-OpenSSH.html)SSHhowtodenyallusersexceptforone?(http://www.linuxquestions.org/questions/linux-security-4/howto-sshd-deny-all-users-except-for-one-368752/)

Page 299: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ProtectingSSHwithFail2banAdeterminedattackermaytrytobruteforceauser'spasswordtogainaccessorattemptrepeatedloginstoconsumenetworkandsystemresourcesaspartofadenialofserviceattack.Fail2bancanhelpprotectyoufromsuchattacksbymonitoringaserver'slogfiles,identifyingsuspiciousactivity,andautomaticallybanningtheIPaddressesresponsiblefortheactivity.ThisrecipeteachesyouhowtoinstallFail2bantosafeguardyoursystem.

Page 300: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemrunningtheOpenSSHserver.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.Thefail2banpackageishostedbytheEPELrepository;iftherepositoryisnotalreadyregistered,refertotheRegisteringtheEPELandRemirepositoriesrecipeinChapter4,SoftwareInstallationManagement.

Page 301: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoprotectyoursystemwithFail2ban:

1. Installthefail2banpackage:

yuminstallfail2ban

2. Createthejailconfigurationfile/etc/fail2ban/jail.localusingthefollowingcontents:

[sshd]

enabled=true

bantime=86400

maxretry=5

3. StarttheFail2banserviceandenableitsautomaticstart-upwhenthesystemboots:

systemctlstartfail2ban.service

systemctlenablefail2ban.service

4. Toviewthesshdjail'sstatus,usefail2ban-clientwiththestatuscommand:

fail2ban-clientstatussshd

Page 302: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...You'velearnedhowtoinstallFail2banandconfigureautomatedIPblockingafterseveralfailedloginattempts.Youalsolearnedhowtomanuallybanandunbanaddressesusingfail2ban-client.

AFail2banjailconfigurationbringstogetherfilterandactiondefinitionstoperformanactivitywhenevercertainpatternsareobservedinaserver'slogfile.Filtersspecifythepatterndefinitionsforidentifyinginterestinglogentries,forexample,repeatedauthenticationfailures.Actions,ontheotherhand,definethecommandsthatrunwhenafilterismatched.Fail2banisshippedwithseveralpredefinedfiltersforcommonserverssuchasApache,MySQL,Sendmail,andSSH,andseveralpredefinedactionssuchasmanagingiptableentriestoblockandunblockIPaddresses,sendinge-mailnotifications,andtriggeringDNSupdates.

Thereareseveraljailsdefinedin/etc/fail2ban/jail.conf.Toactivatethesshdjail,wecreatedthejail.localfilewithentriesthatoverrideandextendthedefaultjaildefinition:

[sshd]

enabled=true

bantime=86400

maxretry=5

Intuitively,theenabledoptionenablesordisablesthejail.maxretry,whichwesetto5,isthenumberoffailedloginattemptspermittedbeforeFail2banenactstheban.bantimesetshowlongthebanwilllast,whichwesetto86400seconds.Withthisconfiguration,usersareallowedupto5failedattemptsbeforetheirIPaddressisbannedfor24hours.

Theexistingdefinitionfromjail.confalreadyidentifiesthedefaultportandthelogfilelocation.Ifyou'rerunningSSHonanonstandardport,youcanoverridetheoriginaldefinition'ssettingusingport.ThelocationoftheSSH'slogfilecanbeoverriddenwithlogfile.

fail2ban-clientisusedtointeractwiththeFail2banservice.Itsstatuscommandoutputsinformationabouttheservice'scurrentstate,andifstatusisfollowedbyajailnamethenstatusinformationaboutthejailisreturnedinstead.Perhapsofparticularinterestinthejail'sstatusisalistofIPaddressesthathavebeenbanned:

fail2ban-clientstatussshd

Page 303: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thejail'sstatusoutputpresentsthelistofbannedaddresses

Theclientalsohasgetandsetcommandstoinspectandupdatevariouspropertiesoftherunningservice.Forexample,getsshdbantimereturnstheconfiguredbanduration.setsshdbantimetemporarilyupdatesthedurationuntiltheserviceisrestarted.

YoucanmanuallybananIPaddressbysettingthejail'sbanipproperty:

fail2ban-clientsetsshdbanip10.25.30.107

Tomanuallyunbananaddress,setunbanip:

fail2ban-clientsetsshdunbanip10.25.30.107

Beingabletomanuallyunbanaddressesisimportantincasealegitimateaddressisbannedforsomereason.Ifthereareaddressesthatshouldneverbeblocked,perhapsatestintegrationserverexecutingfailedloginsonpurpose,orperhapsanadministrator'scomputer,youcanidentifythemusingtheignoreipoptioninyourjail.localconfigurationfileandFail2banwillavoidbanningthoseaddresses:

ignoreip=10.25.30.107

Page 304: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonFail2ban:

Thefail2ban-clientmanualpage(man1fail2ban-client)Fail2banWiki(http://www.fail2ban.org/wiki/index.php/Main_Page)PermanentlybanrepeatoffenderswithFail2ban(http://stuffphilwrites.com/2013/03/permanently-ban-repeat-offenders-fail2ban/)MonitoringtheFail2banlog(http://www.the-art-of-web.com/system/fail2ban-log/)

Page 305: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiningsessionstoachrootjailThisrecipeteachesyouhowtosetupachrootjail.Achrootcallchangestheuser'sviewofthefilesystemhierarchybysettingaparticularpathastheroot;fortheuser,thepathappearsas/andtheyareunabletotraversebeyondit.Thiscreatesasandboxorjail,confiningtheusertoasmallbranchoftherealhierarchy.Chrootjailsarecommonlyusedforsecuritypurposes,forexample,usercontainmentandhoneypotsandalsoforapplicationtestingandinrecoveryprocedures.

Page 306: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemrunningtheOpenSSHserver.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 307: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoconfigureachrootjailandconfineuserstoit:

1. Downloadthecpchrootscriptneededtocopycommandsandtheirdependenciesintothechrootenvironment:

curl-Lo~/cpchroottinyurl.com/zyzozdp

2. Makethescriptexecutableusingchmod:

chmod+x~/cpchroot

3. Createthe/jaildirectoryanditssubdirectoriestomimicarootfilesystem:

mkdir-p/jail/{dev,home,usr/{bin,lib,lib64,share}}

cd/jail

ln-susr/binbin

ln-susr/liblib

ln-susr/lib64lib64

4. Executethechrootscripttocopythedesiredprogramsandcommands:

~/cpchroot/jailbashcatcpfindgreplessls

mkdirmvpwdrmrmdir

5. Copytheterminfodatabase:

cp-R/usr/share/terminfo/jail/usr/share

6. Createthespecialdevicefilesunder/jail/devusingmknod:

cd/jail/dev

mknodnullc13

mknodzeroc15

mknodrandomc18

7. Createagroupforchroot'dusers:

groupaddsandbox

8. Openthe/etc/ssh/sshd_configfilewithyourtexteditorandaddthefollowingtotheendofthefile:

MatchGroupsandbox

ChrootDirectory/jail

9. Saveyourchangesandclosetheconfigurationfile.10. RestarttheSSHserverforthechangestotakeeffect:

systemctlrestartsshd.service

Tocreateanewchroot'duser,createtheuserwithuseraddandassignthemtothesandboxgroup:

Page 308: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

useradd-s/bin/bash-m-Gsandboxrdiamond

Then,movetheirhomedirectorytoresideunderthechrootjail:

mv/home/rdiamond/jail/home

Tochrootanexistinguser,assignthemtothesandboxgroupandmovetheirhomedirectorytothejail:

usermod-Gsandboxbbarrera

mv/home/bbarrera/jail/home

Page 309: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Identifyingandcopyingdependenciesistediousanderror-proneifdonemanually.So,I'vewrittenahelperscripttoautomatetheprocessoffindingandcloningprogramswiththeirdependenciesintothejail.Ourfirststepsweretodownloadthescriptusingcurlandthenmakeitexecutableusingchmod:

curl-Lo~/cpchroottinyurl.com/zyzozdp

chmod+x~/cpchroot

ThescriptishostedonGitHub,butitsdirectURLwasprohibitivelylongsoIusedaURL-shorteningservicetoshortentheaddress.Weneedtoprovide-Lforcurltofollowanyredirects(theservicerespondswitharedirecttoGitHub)and-osetsthenameofthedownload,inthiscasecpchroot,inyourhomedirectory.

Note

Ifyou'rehavingproblemsbecauseoftheURL-shorteningservice,youcanfindthedirectlinkbyvisitinghttps://gist.github.com/tboronczyk/00d77b1baafd13daab3b,clickingontheRawbutton,andthencopyingtheURLthatappearsinyourbrowser'saddressbar.

Next,wecreatedthe/jaildirectorycontainingadirectorystructurethatmimicstherootfilesystem.Whenauserlogsinandischroot'd,theyandeverythingtheydowillbecontainedto/jail.Theywillnotbeabletotraverseoutsidethatdirectory,soweneedtoreplicatethedirectorylayouttheprogramsexpect:

mkdir-p/jail/{dev,home,usr/{bin,lib,lib64,share}}

cd/jail

ln-susr/binbin

ln-susr/liblib

ln-susr/lib64lib64

Weusedmkdirwiththe-poptionandtookadvantageofshellexpansiontocreatemostofthelayoutwithasinglecommand.CentOSsetsupitstop-level/bin,/lib,and/lib64directoriesassymboliclinkstothecorrespondingdirectoriesunder/usr,whichweduplicatedusinglnwithinthe/jaildirectory.Thefinallayoutlookslikethefollowingonepresented:

Page 310: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thelayoutofthesandboxrootmimicsthatofthehost'srootfilesystem

Next,weusedthescripttocopythedesiredcommandstothejail.Thescriptdoesthehardworkoffindingeachprogram'sbinaryandidentifiesallofthelibrariesitdependson,andthenitcopieseverythingintotheappropriatelocationinthesandboxedfilesystem:

~/cpchroot/jailbashcatcpfindgreplesslsmkdirmvpwdrmrmdir

Itsfirstargumentisthedirectoryactingasourchroot'droot,andthenfollowingthatisalistofoneormoreprogramswewanttomakeavailabletotheuser.Therecipeprovidesadozenprogramsasanexample,andyoushouldfeelfreetoaddoromitsomeasyouseefit.Ataminimum,youneedashell(bash).Irecommendthatyouincludeatleastlsandpwdsothattheusercannavigate.

Page 311: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Then,wecopiedtheterminfodatabasetothejail:

cp-R/usr/share/terminfo/jail/usr/share/

Someprograms,suchasscreen,less,andvi,usetheterminfodatabasetomakesuretheiroutputdisplayscorrectly.Thedatabaseisacollectionoffilesthatdescribethecapabilitiesofdifferentterminaltypes,suchasthenumberoflinesperscreen,howtoclearthescreen,whatcolorsaresupported,andsoon.Ifthisinformationisn'taccessible,userswillbewarnedthattheterminalisnotfullyfunctionalandtheoutputmaybegarbled.

Tofinishmakingthejail,wecreatedthe/dev/null,/dev/zero,and/dev/randomdeviceswiththemknodcommand:

cd/jail/dev/

mknodnullc13

mknodzeroc15

mknodrandomc18

mknodisusedtocreatespecialfilessuchascharacterfilesandblockfiles.Thesefilesarespecialbecausetheycangeneratedata(asisthecasewithnullandzero)orrepresentphysicaldevicesandreceivedata.Bothnullandzeroarecharacterfiles,asindicatedbytheletterc,sincewereadfromthemonecharacteratatime.Blockfiles,ontheotherhand,operatewithseveralcharactersatatime.Aphysicalstoragediskisoftenrepresentedasablockdevice.

Wealsoneedtoprovideamajorandminornumberwhencreatingacharacterorblockdevice.Thesevaluesarepredefinedandunderstoodbythekernelastohowthedevicefileshouldbehave.1and3arethemajorandminornumbersthatdefineanulldevice.1and5definethefileasanullbytesource.YoucanseethefulllistofmajorandminornumberassignmentsintheLinuxAllocatedDevicedocumentlistedinthisrecipe'sSeealsosection.

Afterthechrootenvironmentwassetup,weturnedourattentiontoconfiguretheSSHserver.First,wecreatedthesandboxgroup,whichcanbeassignedtoanyuserwewantcontained:

groupaddsandbox

Next,weaddedaMatchblocktotheSSHserver'sconfigurationfiletargetingthenewgroup:

MatchGroupsandbox

ChrootDirectory/jail

Matchstartsanewconditionalsectionintheconfigurationfilethatappliesonlywhenitsconditionismatched.Inthiscase,we'rematchingtheuser'sgrouptosandbox.Whentheuserisamemberofthegroup,theChrootDirectoryoptionisappliedanditsets/jailastheuser'srootdirectory.Nowwhenauserconnects,anythingtheydowillbeconfinedtothechrootjail,includingactionsthathappenautomaticallysuchaslaunchinganinteractiveshell(bash).

Bashtriestoplacetheuserintheirhomedirectoryaftersigningin.However,iftheirhome

Page 312: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

directoryisn'taccessible,theuserwillseetheerrormessageCouldnotchdirtohomedirectoryandfindthemselvesintherootdirectory.Toavoidthis,wemovedtheirhomedirectoryintothejail:

mv/home/jbhuse/jail/home/

Note

Youmightbetemptedtospecifythehomedirectorywhencreatinganewuser,asfollows:

useradd-m-D/jail/home/jbhuse-Gsandboxjbhuse

Unfortunately,thisdoesn'twork.Thehomedirectoryiscreatedinthedesiredlocation,theuserischroot'd,andthepathisviewedinrelationto/jailsothatbashlooksfor/jail/jail/home/jbhuse.Thisiswhytherecipedemonstratesmovingthehomedirectoryasasecondstep.Theentryin/etc/passwdstays,/home/jbhuseisinterpretedas/jail/home/jbhuse,andallisrightwiththeworld.

Page 313: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingformoreinformationonsettingupchrootenvironments:

Thesshd_configmanualpage(man5sshd_config)HowtoConfigureSFTPwithChroot(http://www.unixmen.com/configure-sftp-chroot-rhel-centos-7)Safelyidentifydependenciesforchrooting(http://zaemis.blogspot.com/2016/02/safely-identify-dependencies-for-chroot.html)Linuxallocateddevices(https://www.kernel.org/doc/Documentation/devices.txt)

Page 314: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringTigerVNCVirtualNetworkComputing(VNC)worksbycapturingthedisplay'sframebufferandmakingitavailableacrossthenetwork.ThisrecipeshowsyouhowtoinstallTigerVNCandconfigureittoprovideremoteusersaccesstotheirgraphicaldesktopenvironmentasiftheywerephysicallyinfrontofthesystem.

Page 315: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequirestwosystems,aCentOSsystemtohosttheVNCserver(remotesystem)andalocalcomputerwithaVNCclienttoconnecttoit.ItassumesthattheremotesystemisrunningtheOpenSSHSSHserverandagraphicaldesktopenvironmentsuchasGNOMEorKDE.Administrativeprivilegesarerequiredontheremoteserver,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.ThelocalcomputerisexpectedtohaveaVNCclientinstalled.

Page 316: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallandconfigureTigerVNC:

1. Ontheremotesystem,installtheTigerVNCserverpackage:

yuminstalltigervnc-server

2. Copytheexampleunitfileprovidedwiththepackageto/etc/systemd/system,adjustingitsnametoincludetheusernameofthepersonusingVNC:

cp/usr/lib/systemd/system/[email protected]

/etc/systemd/system/[email protected]

3. Openthenewunitfilewithyourtexteditor:

vi/etc/systemd/system/[email protected]

4. Replacethe<USER>placeholderthatappearsinthe[Service]section'sExecStartandPIDFileentries:

ExecStart=/usr/sbin/runuser-ltboronczyk-c"/usr/bin/

vncserver%i"

PIDFile=/home/tboronczyk/.vnc/%H%i.pid

5. Saveyourchangesandclosethefile.6. Repeatsteps2to5foreachuserwhowilluseVNCtoconnecttotheirdesktop.7. Reloadsystemd'sconfigurationtomakeitawareofthenewunitfiles:

systemctldaemon-reload

8. Openports5900through5903inthesystem'sfirewalltoacceptincomingVNCrequests:

firewall-cmd--zone=public--permanent--add-service=vnc-server

firewall-cmd--reload

9. TheusersusingVNCshouldsetthepasswordthey'llusetoauthenticatewiththeVNCserverusingvncpasswd:

vncpasswd

10. Whenauserwantstoconnect,specifyadisplaynumberafter@intheunit'snamewhenstartingTigerVNC:

systemctlstartvncserver-tboronczyk@:1.service

11. Stoptheserverwhenit'snotinuse:

[email protected]

Page 317: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...AlongwiththeVNCserver,thetigervnc-serverpackageinstallsasystemdunitfiletostartandstoptheserver.However,there'ssomeconfigurationweneedtoattendtobeforeusingitbecausetheserverrunsundertheuser'saccounttoobtaintheirdesktop.

WhenTigerVNCstarts,itconnectstotheXserverandlogsintotheuser'sdesktopjustasiftheuserwassittinginfrontofthesystemitself.Thismeanseachuserneedstheirowninstanceoftheserverrunningandweneedtoconfigureitforeachuser.Wemadeacopyoftheoriginalunitfilefoundunder/usr/lib/systemd/system,oneforeachuser.

cp/usr/lib/systemd/system/[email protected]/etc/systemd/system/

[email protected]

Thenameofthecopiedfilecontainstheusernamesothatwecankeepeverythingorganized.They'replacedunder/etc/systemd/systembecausesystemdlooksin/etc/systemdforunitsbeforesearching/usr/lib/systemd(infact,manyentriesin/etc/systemdaresymboliclinkstotheiroriginalfilesunder/usr/lib/systemd).So,placingthecopiesthereletsuskeeptheoriginalintactandsafeguardsusfromloosingourconfigurationintheeventofanupgradewheretheoriginaluntilfileisreplaced.

ThissystemhasVNCaccessconfiguredforseveralusers

Wereplacedanyoccurrenceofthe<USER>placeholderunderthe[SERVICE]sectionineachconfigurationfilewiththeappropriateusername:

ExecStart=/usr/sbin/runuser-ltboronczyk-c"/usr/bin/vncserver%i"

PIDFile=/home/tboronczyk/.vnc/%H%i.pid

ThecommandspecifiedintheExecStartentryisinvokedwhenwestarttheserverusingsystemctlstart;itusesrunusertorunTigerVNCundertheuser'saccount.The-l(lowercaseL)argumentprovidestheusernameand-cspecifiesthecommandanditsargumentsthatrunuserwillexecute.ThePIDFileentryspecifiesthedirectoryinwhichtherunningprocesswillkeeptrackofitsprocessID.

Note

Page 318: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

DanWalsh,theauthorofrunuser,wroteablogentryentitledrunuservssudetailingthebackstorybehindthecommand.Youcanreaditonlineathttp://danwalsh.livejournal.com/55588.html.

The@symbolappearinginthefilenamehasspecialsignificancetosystemd.Anythingafteritandbeforethefilesuffixispassedtothecommandsintheunitfilereplacing%i.Thisletsuspasslimitedinformationtotheserver,forexample,thedisplaynumberforTigerVNCtorunon.Whenwestarttheserverasshownintherecipe,:1isgivenafter@.ThevalueisparsedbysystemdandTigerVNCisstartedondisplay1.Ifweuse:2,theserverwillstartondisplay2.WecanstartmultipleinstancesofTigerVNCfordifferentusersorevenforthesameuseraslongasthedisplayisdifferentforeach:

systemctlstartvncserver-tboronczyk@:1.service

Trafficforthedisplay'scorrespondingportshouldbeallowedbythefirewall.Display0usesport5900,display1usesport5901,display2usesport5902,andsoon.Ifyou'reusingFirewallD,thepredefinedvnc-serverserviceopensports5900-5903:

firewall-cmd--zone=public--permanent--add-service=vnc-server

Ifyouneedadditionalportsorifyoudon'tneedtoopentheentirerange,youcanopenjustwhatyouneedusing--add-port:

firewall-cmd--zone=public--permanent--add-port=5901/tcp

TheuserneedstosetaVNCpasswordusingvncpasswdbeforetheycanconnecttothedisplay.Thepasswordmustbeatleastsixcharacterslong,althoughonlythefirsteightcharactersaresignificant.Moreover,thepasswordisstoredintheuser's~/.vnc/directory.Inthelightoftheseissues,it'srecommendedthattheuserdoesn'tusethesamepasswordastheiraccountpassword.It'salsowisetoruntheVNCserveronlywhenneededsinceanyonewhoknowsthedisplaynumberandpasswordcanconnecttoit.

TheuseralsoneedsaVNCclienttoconnectfromtheirlocalcomputer.CentOSuserscaninstallthetigervncpackagetouseTigerVNC'sclient.OtherpopularclientsareVinagreforUbuntu,RealVNCforTightVNConWindows,andChickenoftheVNCforOSX:

yuminstalltigervnc

TheIPaddressorhostnamefortheremotesystemandthedisplay(port)thatVNCisrunningareneededtoestablishtheconnection.Theycanbeprovidedindifferentwaysdependingontheclient,butthestandardformatacceptedbymostclientsappendsthedisplaytothesystem'saddress,forexample,192.168.56.100:1.Theuserwillthenbepromptedfortheirpassword,andifallgoeswellthey'llbeconnectedtotheremotedisplay:

Page 319: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AuserpreparestoconnecttoaremotedisplayusingVNC

Page 320: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonrunningTigerVNCandhowsystemduses@infilenames:

TigerVNC(http://tigervnc.org/)RHEL7SystemAdministrator'sGuide:TigerVNC(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-TigerVNC.html)ArchWiki:TigerVNC(https://wiki.archlinux.org/index.php/TigerVNC)The@symbolandsystemctl(http://superuser.com/questions/393423/the-symbol-and-systemctl-and-vsftpd/393429#393429)UnderstandingSystemdUnitsandUnitFiles(https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files)

Page 321: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TunnelingVNCconnectionsthroughSSHThepreviousrecipeshowedyouhowtogiveremoteaccesstotheuser'sdesktopthroughVNC.However,thereareclearlysomesecurityconcernsiftheserviceisrunningonanuntrustednetwork.Onlythedisplaynumberandpasswordarerequiredtoconnect,andthepasswordcanberelativelyeasyforamalicioususertocrackgiventhatonlythefirsteightcharactersaresignificant.Moreover,thetrafficisunencryptedanditmaybesnooped.Tohelpmitigatetheserisks,thisrecipeteachesyouhowtoroutetheVNCconnectionthroughanencryptedSSHtunnel.

Page 322: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequirestwosystems,aCentOSsystemhostingtheVNCserver(remotesystem)andalocalcomputerwithaVNCclienttoconnecttoit.ItassumesthattheremotesystemisrunningtheOpenSSHSSHserverandTigerVNCserverandisconfiguredwiththeIPaddress192.168.56.100.Italsoassumesthatyouhaveadministrativeprivileges.TheVNCservershouldbeconfiguredasdescribedinthepreviousrecipe.ThelocalcomputershouldhavetheOpenSSHSSHclient(ssh)andaVNCclientinstalled.

Page 323: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstorouteVNCconnectionsthroughanencryptedSSHtunnel:

1. Ontheremoteserver,[email protected]:

vi/etc/systemd/system/[email protected]

2. LocatetheExecStartentryandaddthe-localhostargumenttothevncservercommandinvokedbyrunuser:

ExecStart=/usr/sbin/runuser-ltboronczyk-c"/usr/bin/vncserver

-localhost%i"

3. Saveyourchangeandclosethefile.4. Repeatsteps1to3asnecessaryfortheotherusers'configurationfiles.5. Reloadsystemd'sconfigurationtomakeitawareoftheupdates:

systemctldaemon-reload

6. StarttheVNCserver:

systemctlstartvncserver-tboronczyk@:1.service

7. Onyourlocalsystem,establishanSSHsessiontotheserverwith-Ltodefinethetunnel:

ssh-L5901:localhost:5901192.168.56.100

8. Connecttothetunnel'slocalendpoint(localhost:1)usingaVNCclient.

Page 324: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipeshowedyouhowtosecureVNCbytunnelingitstrafficthroughSSH.WeconfiguredtheTigerVNCservertoonlyacceptconnectionsfromitslocalhostandthensetupatunnelonthelocalclientsidetoroutetrafficthroughanSSHconnection.ThishelpsmitigatesomeoftheaforementionedsecurityrisksbecauseproperauthenticationisneededtoestablishthetunnelandencrypttheVNCtraffic.

First,youeditedtheExecStartcommandintheunitfilesusedtostartinstancesoftheVNCserver.The-localhostargumenttovncserverinstructstheservertocommunicateonlywiththelocalsystem;anyincomingconnectionsoriginatingfromthenetworkwillberefused:

ExecStart=/usr/sbin/runuser-ltboronczyk-c"/usr/bin/vncserver

-localhost%i"

Ontheclientside,theusernowneedstoestablishanSSHtunnelusingsshbeforetheycanconnecttotheremotedisplay:

ssh-L5901:localhost:5901192.168.56.100

The-Largumentdefinesthetunnelaslocal-port:target-host:target-port.Thetargethostandportrepresentthefinaldestinationinrelationtotheserversshisconnectedto.Forexample,weknowthattherecipeisrunningtheuser'sdesktopondisplay1whichusesport5901.WealsoknowthatTigerVNCserverisrunningon192.168.56.100butconfiguredtolistenonlytoitslocalhost.Thismeans,weneedtoconnecttolocalhost:5901from192.168.56.100.Thus,localhost:5901isthetargetinrelationtothatsystem.

Oncetheuserhasanestablishedtunnel,theycanminimizethesession'sterminal.(Don'tcloseit!)sshisconnectedtotheremotesystemwhilealsolisteningonthelocalport(also5901).Ontheremoteserver,sshhasestablishedasecondconnectiontothetargethostandport.TheVNCclientwillconnecttothelocalportbyusingtheaddresslocalhost:1wherethetrafficisthenroutedthroughtheSSHtunneltotheremoteserverandthenforwardedtothefinaldestination.

Theremotesystemactsasagatewayastraffictravelsthroughitfromtheclient'stunneltothefinaldestination.Keepinmind,unlessatunneltothetargethasalsobeencreatedontheremoteserver,thesecondlegofthedata'sjourneyisnotencrypted.Thisisn'taconcernforthisrecipebecausetheremoteandtargethostsarethesame.Ifyourfinaldestinationisanythingotherthanlocalhost,ensurethatthenetworkistrustedorcreateasecondtunnel.

Note

RoutingtrafficwithSSHinthisfashioncanbedonetosecureotherservicesaswell,forexample,NFS,FTP,HTTP,POP3,andSMTP.Theoverallprocessisthesame:configuretheservertolistenlocallyandthenestablishthetunnelontheclient.

Page 325: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcestolearnmoreaboutSSHtunneling:

Thesshmanualpage(man1ssh)SecuringnetworktrafficwithSSH(https://security.berkeley.edu/resources/best-practices-how-articles/securing-network-traffic-ssh-tunnels)SSHtunnelingmadeeasy(http://www.revsys.com/writings/quicktips/ssh-tunnel.html)

Page 326: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter7.WorkingwithDatabasesThischaptercontainsthefollowingrecipes:

SettingupaMySQLdatabaseBackingupandrestoringaMySQLdatabaseConfiguringMySQLreplicationSettingupaMySQLclusterSettingupaMongoDBdatabaseBackingupandrestoringaMongoDBdatabaseConfiguringaMongoDBreplicasetSettingupanOpenLDAPdirectoryBackingupandrestoringanOpenLDAPdirectory

Page 327: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionThischapterfocusesonthreedatabases.First,you'lllearnhowtoinstalloneofthemostwidelyusedrelationaldatabaseservers,MySQL.You'llalsolearnhowtosetupmaster-slavereplicationtomaintainmirrorcopiesofyourMySQLdatabases,andhowtostandupaMySQLclustertoprovidescalable,high-availabilitydatastorage.Next,we'llmovetotheworldofNoSQLdatabases.You'lllearnhowtoinstallthepopulardocument-orienteddatabaseserverMongoDB,andhowtoconfigureaMongoDBreplicaset(replication).Thenyou'lllearnhowtosetupanLDAPdirectoryserverusingOpenLDAP.Foreachofthesedatabases,thechapteralsohasrecipestoshowyouhowtoperformbasicbackupandrestoretaskstokeepyourdatasafe.

Page 328: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingupaMySQLdatabaseThisrecipeshowsyouhowtoperformabasicinstallationofthepopularMySQLdatabaseserveronCentOS.MySQListhesecondmostwidelyuseddatabasesystemtoday,whichisfoundacrossmanydifferentindustriesprovidingdatastorageforeverythingfromdynamicwebsitestolarge-scaledatawarehouses.

Page 329: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandadministrativeprivilegeseitherusingtherootaccountorsudo.

Page 330: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallMySQLandcreateanewdatabase:

1. DownloadtherepositoryconfigurationpackagefortheOracle-maintainedMySQLrepository:

curl-LOdev.mysql.com/get/mysql57-community-release-el7-

7.noarch.rpm

2. Installthedownloadedpackage:

yuminstallmysql57-community-release-el7-7.noarch.rpm

3. NowthattheMySQLrepositoryisregistered,installthemysql-community-serverpackage:

yuminstallmysql-community-server

4. StarttheMySQLserverandenableittostartautomaticallywheneverthesystemreboots:

systemctlstartmysqld.service

systemctlenablemysqld.service

5. Openport3306inthesystem'sfirewalltoallowoutsideconnectionstoMySQL:

firewall-cmd--zone=public--permanent--add-service=mysql

firewall-cmd--reload

6. RetrievethetemporarypasswordforMySQL'srootuserfromtheserver'slogfile:

grep"temporarypassword"/var/log/mysqld.log

7. Setanewpasswordforrootusingmysqladmin.Whentheprogrampromptsforthecurrentpassword,enterthetemporarypasswordfoundinthelogs:

mysqladmin-uroot-ppassword

8. UsemysqltoconnecttotheMySQLserverusingtherootaccount:

mysql-uroot-p

9. Tocreateanewdatabase,executeaCREATEDATABASEstatement:

CREATEDATABASEpackt;

10. ExecuteaCREATEUSERstatementtocreateaMySQLuseraccountforworkingwiththedatabase:

CREATEUSER"tboronczyk"@"localhost"IDENTIFIEDBY"P@$$W0rd";

11. ExecuteaGRANTstatementtoassigntheappropriateprivilegestotheaccountforthenewdatabase:

GRANTCREATE,DROP,ALTER,LOCKTABLES,INDEX,INSERT,UPDATE,

SELECT,DELETEONpackt.*TO

"tboronczyk"@"localhost";

Page 331: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

12. ExecuteFLUSHPRIVILEGEStoinstructMySQLtorebuilditsprivilegescache:

FLUSHPRIVILEGES;

13. ExittheMySQLclientandreturntotheterminal:

exit

Page 332: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...WebeganbydownloadingthepackagethatregisterstheOracle-maintainedMySQLrepositoryonoursystem.MySQLisinstalledfromtheOraclerepository,becausetheCentOSrepositoriesinstallMariaDBinstead.Afteraseriesofacquisitionsbetween2008and2010,theMySQLcodebaseandtrademarkbecamethepropertyofOracle.WidespreadconcernoverOracle'sstewardshipandthefutureofMySQLpromptedoneoftheoriginaldevelopersofMySQLtoforktheprojectandstartMariaDB.In2014,theRedHatandCentOSrepositoriesreplacedMySQLasthedefaultdatabasewithMariaDB(welcometotheworldofopen-sourcepolitics).

Note

MariaDB'sgoalistoremainafree,open-sourceprojectundertheGNUGPLlicenseandtobean"enhanced,drop-inreplacement"forMySQL.Fornow,differencesbetweenthetwoarenegligibletothecasualuser.Butintheworldofforkedreplacements,it'smainlytheprogramminginterfacesandcommunicationprotocolsthatremaincompatible.Corefunctionalitymayremainthesameinitially,butnewfeaturesareaddedindependentlyastimegoesonandtheproducts'featuresetsbegintodiverge.MariaDBacknowledgesthiswithajumpinversioningnumbers.MariaDB5.1offersthesamefeaturesasMySQL5.1,asdoesMariaDB5.5forMySQL5.5.However,MariaDBdoesn'tplantoimplementallofMySQL5.6'sfeaturesandchangedtheirversionnumberto10.0.Forthosekeepingscoreathome,theOracle-maintainedrepositoryhostsMySQL5.7atthetimeofthiswriting.TheCentOSrepositoriescurrentlyofferMariaDB5.5.

Theserverthathoststhepackageassumesthatpeopledownloadthefileusingawebbrowserandissuesaredirecttobeginthedownload.Sincewe'reusingcurl,wesuppliedthe-Largumenttofollowtheredirectstoreachtheactualpackage:

curl-LOdev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm

Next,weinstalledthedownloadedpackage.Oncetherepositoryisregistered,we'reabletoinstallMySQLwiththemysql-community-serverpackage.Thepackageinstallstheserverbinaries,andtheclientutilitiestoworkwithMySQLareinstalledasdependencies:

yuminstallmysql57-community-release-el7-7.noarch.rpm

yuminstallmysql-community-server

MySQLmaintainsitsownuseraccountsanditsadministrativeuserisnamedroot.JustlikeCentOS'srootuser,youshouldn'tusetheaccountforregularactivities;itshouldbereservedforadministrativetaskssuchascreatingnewusers,grantingprivileges,andflushingtheserver'scaches.Otherless-privilegedaccountsshouldbeusedforeverydayactivities.Toprotecttherootaccount,itspasswordisrandomlygeneratedthefirsttimewestarttheMySQLserver.WeneededtosearchthelogfilewhereMySQLrecordedthepasswordsothatwecansetanewpasswordofourownchoosing:

Page 333: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

grep"temporarypassword"/var/log/mysqld.log

Knowingthetemporarypassword,weusedmysqladmintochangeit.The-uoptiongivestheusernameoftheMySQLaccount,-ppromptsusfortheaccount'spassword,andpasswordistheutility'ssubcommandusedtochangepasswords.Weenteredthetemporarypasswordwhenpromptedfortheoriginalandthenwewereaskedtoenterandconfirmthenewpassword:

mysqladmin-uroot-ppassword

Note

ArandomdefaultpasswordforrootisanewbehaviorstartingwithMySQL5.6,whichwritesthepasswordto/root/.mysql_secret,whereas5.7writesittothelogfile.Inolderversions,andthusMariaDBsince5.5isinstalledbytheCentOSrepositories,thepasswordisempty.Thevalidate_passwordpluginisalsoactivatedinMySQL5.7.Itrequiresthepasswordtobeeightcharactersormorewithatleastonenumber,oneupperandonelowercasecharacter,andonespecialcharacter(thatis,punctuation).Considertheserequirementswhenchoosingroot'snewpassword.

Thetemporarypasswordisneededtosetroot'spermanentpassword

ThereareseveralclientsthatwecanusetoconnecttoMySQLandinteractwithourdatabases.Thisrecipeusedmysqlsinceitwillhavebeeninstalledbydefaultasadependency.Again,-uidentifiestheaccount'susernameand-ppromptsusforitspassword:

mysql-uroot-p

Whenrunningininteractivemode,theclientdisplaysthepromptmysql>atwhichwesubmitourSQLstatements.Aftereachquery,theclientdisplaystheserver'sresponse,howlongthestatementtooktoexecute,andiftheserverreportedanyerrorsorwarnings.

WeissuedaCREATEDATABASEstatementattheprompttocreatethenewdatabasenamedpackt:

Page 334: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CREATEDATABASEpackt;

ThenwecreatedanewuseraccountwithCREATEUSERtoavoidusingrootforourday-to-daywork.Theaccountisnamedtboronczykandisallowedtoauthenticatefromthelocalhost:

CREATEUSER"tboronczyk"@"localhost"IDENTIFIEDBY"P@$$w0rd";

Asystem'shostnameorIPaddresscanreplacelocalhostiftheaccountwillconnecttotheserverfromadifferentsystem.MySQLtreatseachusernameandhostnamepairtobeseparateaccountsthough,forexampletboronczyk@localhostandtboronczyk@192.168.56.100aredifferentaccountsandcanhavedifferentprivilegesassignedtothem.

Note

Youcanusewildcardsinthehostnametocreateanaccountthatcanconnectfrommultiplesystems.The%wildcardmatcheszeroormorecharacters,soitcanbeusedtorepresentanysystem:

CREATEUSER"tboronczyk"@"%"IDENTIFIEDBY"P@$$w0rd";

Newaccountsarecreatedwithoutanyprivileges,sowemustassignthembyexecutingaGRANTstatement:

GRANTCREATE,DROP,ALTER,LOCKTABLES,INSERT,UPDATE,SELECT,

DELETEONpackt.*TO"tboronczyk"@"localhost";

Thestatementassignsthefollowingprivilegestotheuserforalltables(denotedby*)inthepacktdatabase:

CREATE:ThisallowstheusertocreatedatabasesandtablesDROP:ThisallowstheusertodeleteentiretablesanddatabasesALTER:ThisallowstheusertochangethedefinitionofanexistingtableLOCKTABLES:ThisallowstheusertolockatableforexclusivereadorwriteaccessINDEX:ThisallowstheusertocreatetableindexesINSERT:ThisallowstheusertoaddrecordstoatableUPDATE:ThisallowstheusertoupdaterecordsinatableSELECT:ThisallowstheusertoretrieverecordsfromatableDELETE:Thisallowstheusertodeleterecordsfromatable

AfulllistofprivilegesandwhattheypermitausertodocanbefoundintheofficialMySQLdocumentationonlineathttp://dev.mysql.com/doc/refman/5.7/en/grant.html.

Next,weinstructedMySQLtorebuilditsprivilegescacheusingFLUSHPRIVILEGES:

FLUSHPRIVILEGES;

WhenMySQLstartsup,itcachestheuserandpermissionsinformationinmemory(you'llrecallfromChapter5,ManagingFilesystemsandStorage,thatreadingfrommemoryismuch

Page 335: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

fasterthanreadingfromdisk)andthenchecksthecacheeverytimeauserperformsanactiontoverifyiftheyhavesufficientprivileges.WeneedtotellMySQLtoupdateitscachewheneverwecreateordeleteauseraccountorgrantorrevokeanaccount'sprivileges,orelseourchangeswillgounnoticeduntilthenexttimeMySQLstarts.

WhenusingmysqltoconnecttoMySQL,youmayfrequentlyinvokeitwithadditionaloptions.Acommonoptionis-h,whichidentifiesthehostnameorIPaddressoftheremoteserverifMySQLisrunningonadifferentsystem.-eexecutesastatementdirectlyinsteadoflaunchingmysqlininteractivemode.Also,toworkwithaspecificdatabase,thenamecanbegiveneitheraftertherestofthecommandoryoucanuse-Dtospecifyit.ThefollowingexampledemonstratesallofthesebyconnectingtotheMySQLserveron192.168.56.100andexecutingaSELECTstatementagainstitssakiladatabase:

mysql-utboronczyk-p-h192.168.56.100-Dsakila-e"SELECT

last_name,first_nameFROMactor"

Page 336: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithMySQL:

Themysqlmanualpage(man1mysql)MySQL5.7referencemanual(http://dev.mysql.com/doc/refman/5.7/en)JumpStartMySQL(http://www.amazon.com/Jump-Start-MySQL-Timothy-Boronczyk/dp/0992461286)MySQLTutorial(http://www.mysqltutorial.org/)

Page 337: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

BackingupandrestoringaMySQLdatabaseThisrecipeshowsyouhowtobackupyourMySQLdatabasesusingmysqldump.TheutilityconnectstotheMySQLserver,queriesthestructureofthedatabaseanditsdata,andoutputsthedataintheformofSQLstatements.Thebackupcanthenbeusedtorestorethedatabaseorpopulateanewdatabasewiththedata.

Page 338: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresarunningMySQLserverandaccesstoeitherMySQL'srootuseroranotheruserwiththenecessaryprivilegestoperformthebackup.

Page 339: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstomakeabackupofaMySQLdatabase:

1. ConnecttotheMySQLdatabaseyouwanttobackup:

mysql-uroot-ppackt

2. ExecuteaFLUSHTABLESstatementtosetthedatabase'stablesread-only:

FLUSHTABLESWITHREADLOCK;

3. Openasecondterminal,leavingthefirstoneactivewiththemysqlclientstillrunning.4. Inthenewterminal,usemysqldumptoexportthetabledefinitionsanddata:

mysqldump-uroot-ppackt>backup.sql

5. Returntothefirstterminaloncethebackupiscompleteandexitmysqltounlockthetables.

BecausethebackupconsistsofSQLstatements,youcanrecreatethedatabasebyimportingthestatementswithmysql:

mysql-uroot-ppackt<backup.sql

Page 340: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Theconsequencesoflostdatacanrangefrommildirritationtoseriouseconomicrepercussions,soit'simportanttoprotectyourselfwithbackups.Justthinkwhatwouldhappenifyourbanklostallofyourfinancialrecords!Themoreimportantyourdataistoyouandthemoredifficultitistoberecreatedifitweretobelost,themoreimportantitistohavebackupsincasesomethingbadhappens.

Priortomakingthebackup,weconnectedtotheserverandexecutedFLUSHTABLES.ThestatementforcesMySQLtofinalizeanydataupdatesthatmaybependingandthensetsthetablesread-onlytopreventmodificationstothedatawhilethebackupisinprogress.Thisensuresthatthedatainourbackupisconsistent:

FLUSHTABLESWITHREADLOCK;

Thetablesremainread-onlyuntilwereleasethelock,eitherbyexecutinganUNLOCKTABLESstatementorbyterminatingtheconnectiontotheMySQLserver,soweleftthecurrentsessionrunningandopenedasecondterminaltoperformthebackup.Whilethetablesareread-only,anyqueriesthatretrievedatawillexecute,butthosethatupdateorinsertdatawillbeblocked.

Note

ConsidersettingupMySQLreplicationasdescribedintheConfiguringMySQLreplicationrecipeandthenbackuptheslave'scopyofthedatabasetoavoidanydowntime.Stopreplicationontheslave,usemysqldumptoexportthedata,andthenresumereplication.Themaster'stablesdon'tneedtobelockedandanychangesmadeonthemasterwhilereplicationissuspendedwillbereplicatedoncetheslavecomesbackonline.

Then,weusedmysqldumptoexportallofthetabledefinitionsanddatafromthedatabase:

mysqldump-uroot-ppackt>backup.sql

Keepyourselforganizedbyincludingthedateinyourbackupfilenames:

mysqldump-uroot-ppackt>backup-$(date+%F).sql

mysqldumpqueriesthedatabasetoretrievethedata,sowhicheveraccountweusetoperformthebackup,itmusthavethenecessaryprivileges.Whatexactlythosepermissionsare,ultimatelydependsonyourdatabase'sschema.Forexample,theaccountneedstheSHOWVIEWprivilegeifyourdatabaseusesviews.Thesameholdstruefortheaccountusedtorestorethedatabase.Youshouldkeepthisinmindifyouwanttousededicatedaccountsforyourbackupandrestoreactivities.

Tobackuponlycertaintables,youcanlistthemafterthedatabase.Forexample,thefollowingbacksupthecustomersandaddressestables:

mysqldump-uroot-ppacktcustomersaddresses>backup.sql

Page 341: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Therearealsoseveraloptionsyoucanprovidetomysqldumpthataffectwhatitincludesinthebackup.Here'salistofsomeofthemorecommonlyusedones:

--no-add-drop-table:ThisdoesnotincludeaDROPTABLEstatementbeforeanyCREATETABLEstatementsintheoutput.Withoutdroppingatablefirst,theimportprocessmayfailontheCREATETABLEstatementwhenthebackupisrestoredonasystemthatalreadyhasthetablesdefined.--events:Thisexportsthedefinitionsforanystoredeventsassociatedwiththedatabase.--hex-blob:Thisoutputsbinaryvaluesusingthehexadecimalnotation.Thiscanhelpprotectagainstcertainbytesequencesbeingincorrectlyinterpreted,causingarestoretofail.--tables:Thisbacksuponlythespecifictables.Thisisanalternatewayofspecifyingtablesinsteadoflistingthemafterthedatabasename.--routines:Thisexportsthedefinitionsforanystoredproceduresassociatedwiththedatabase.--where:ThisisaWHEREconditionusedtoreturnonlyspecificrows.Forexample,--tablescustomers--where"last_nameLIKE'B%'"willonlyexportrowsfromthecustomerstableforcustomerswhoselastnamestartswithB.

Youcanfindacompletelistofoptionsintheonlinedocumentationathttp://dev.mysql.com/doc/refman/5.7/en/mysqldump.html.

Page 342: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonmakingbackupswithmysqldump:

Themysqldumpmanualpage(man1mysqldump)MySQL5.7ReferenceManual:mysqldump(http://dev.mysql.com/doc/refman/5.7/en/mysqldump.html)BackupandRestoreMySQLDatabaseUsingmysqldump(http://www.thegeekstuff.com/2008/09/backup-and-restore-mysql-database-using-mysqldump)

Page 343: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringMySQLreplicationThisrecipeteachesyouhowtoconfigureMySQL'smaster-slavereplicationtomaintainmirrorcopiesofyourdatabasesinnearrealtime.

Toreplicatedata,themasterMySQLserverrecordsdetailsaboutanychangesthattakeplace(inserts,updates,andsoon)toafileknownasthebinarylog.Eachslaveserverconnectstothemaster'ssystem,readstheinformationfromthelogfile,andthenduplicatesthechangetomaintaintheirownlocalcopyofthedatabase.Eachslaveserverisresponsibleforitself,whichmeanswecanbringaslavedownformaintenancewithoutaffectingtheavailabilityofthemaster.Onceitcomesbackonline,theslaveresumesreplicationfromwhereitleftoff.

Replicationcanbeusefulinmanysituations.Forexample,ifafullcopyofthedatabaseismaintainedonaslave,youcanswapoutthemasterserverwithlittleeffortforafailoverordisaster-recoverysituation.Forenvironmentswherescalabilityandperformanceareaconcern,writeoperationscanbeperformedbythemasterwhileintensivereadoperationscanbehandledbyacollectionofread-onlyslavesbehindaloadbalancer.

Page 344: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipedemonstrateshowtoconfigureMySQLreplicationusingtwosystems.ThefirstsystemisthemasterMySQLserver,whichwe'llassumehastheIPaddress192.168.56.100.Thesecondsystemistheslaveserverandhastheaddress192.168.56.101.You'llneedadministrativeaccessonbothsystemseitherusingtherootaccountorsudotocompletetheconfiguration.

BothsystemsshouldhaveMySQLinstalledasdiscussedbytheearlierSettingupaMySQLdatabaserecipe.Ifyou'resettingupreplicationafteroneormoredatabaseshavealreadybeencreatedonthemaster,followtheBackingupandrestoringaMySQLdatabaserecipetobackthemupandimportthemtotheslavebeforeconfiguringreplication.Thisensuresthatreplicationstartswithalldatabasesinsync.

Page 345: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoconfiguremaster-slavereplicationforMySQL:

1. UseyourtexteditortoopenthemasterMySQLserver'sconfigurationfileat/etc/my.cnf:

vi/etc/my.cnf

2. Inthe[mysqld]section,addanewentryfortheserver-idoptionandsetitsvalueto1:

server-id=1

3. Locatethelog_binoptionanduncommentit:

log_bin

4. Saveyourchangesandclosetheconfigurationfile.5. Restarttheserversothatthechangeswilltakeeffect:

systemctlrestartmysqld.service

6. Connecttothemasterserverusingmysqlandcreateanewaccountforslavestouse.TheaccountrequirestheREPLICATIONSLAVEprivilege:

CREATEUSER"slave"@"192.168.56.101"IDENTIFIEDBY"S3CR3t##";

GRANTREPLICATIONSLAVEON*.*TO"slave"@"192.168.56.101";

FLUSHPRIVILEGES;

7. ExecuteSHOWMASTERSTATUStodeterminethemaster'scurrentpositioninwritingtothebinarylog.NotethevaluesreturnedforFileandPosition,astheinformationwillberequiredtoconfiguretheslave:

SHOWMASTERSTATUS;

Themaster'sstatusincludesthenameofthelogfileandtheserver'swriteposition

8. Useyoureditortoopentheslave'sconfigurationfile.Addanewentryfortheserver-idoptionandsetitsvalueto2:

server-id=2

9. Addanentryfortheread-onlyoption:

Page 346: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

read-only

10. Saveyourchangesandclosethefile.11. Restarttheslaveforthechangestotakeeffect:

systemctlrestartmysqld.service

12. Toconfigurecommunicationwiththemaster,connecttotheslaveusingmysql,andexecuteaCHANGEMASTERstatement.ThevaluesshouldreflectthosereturnedbySHOWMASTERSTATUSinstep7:

CHANGEMASTERTO

MASTER_HOST="192.168.56.100",

MASTER_USER="slave",

MASTER_PASSWORD="S3CR3t##",

MASTER_LOG_FILE="localhost-bin.000003",

MASTER_LOG_POS=1235;

13. StartthereplicationprocessbyexecutingSTARTSLAVEontheslavesystem:

STARTSLAVE;

14. ExecuteSHOWSLAVESTATUStoverifyreplicationisrunning.ThevaluesreturnedforSlave_IO_RunningandSlave_SQL_RunningshouldbothbeYes:

SHOWSLAVESTATUS\G

SHOWSLAVESTATUSreturnsafairamountofinformation-listedasatable,columnwrappingmakestheoutputimpossibletoread.Using\Gtoexecutethestatement(asopposedtothesemicolon)willmakemysqldisplaytheresultsverticallywhich,inthiscase,ismuchmorereadable.

15. Tostopreplication,executeSTOPSLAVEontheslavesystem.

Page 347: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Configurationbeganinthemaster's/etc/my.cnffile,whereweaddedtheserver-idoptiontogivetheserveranumericidentifier.Eachserverinthereplicationsetupusesthisvaluetoidentifyitselftotheothers,soitmustbeuniqueacrosstheenvironment.Then,weuncommentedthelog_binoptiontoinstructtheservertorecordthedetailsofeachchangetothebinarylog.

Themasterserver'sconfigurationfilesetstheserveridentifierandenableslogging

Next,wecreatedadedicatedaccountonthemasterserverandgrantedittheREPLICATIONSLAVEprivilege.Theslavewillusethisaccounttoconnecttothemasterandreadfromthelog:

CREATEUSER"slave"@"192.168.56.101"IDENTIFIEDBY"S3CR3t##";

GRANTREPLICATIONSLAVEON*.*TO"slave"@"192.168.56.101";

Finally,weexecutedSHOWMASTERSTATUScommand.ThevaluesofFileandPositionintheresultidentifythenameofthebinarylogfileandtheserver'scurrentpositioninit.Asthemasterwritestothelog,thepositionincreasesandthesuffixattachedtothelog'sfilenamechangeswhenthelogfilesarerotated.Weneedtoknowthecurrentpositionsowecanconfiguretheslavetobeginreading/replicatingfromthatpointonward.

Page 348: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Ontheslave,wesettheserver'suniqueidentifierandaddedtheread-onlyoptionintheconfigurationfile.Ifsomeoneweretomakeachangeintheslave'sdatabasethatconflictswithanincomingupdatefromthebinarylog,thenreplicationwouldbreak.Theread-onlyoptionisasafeguardthatpreventsusersfromupdatingtheslavedatabasesdirectly,ensuringallupdatescomefromthemaster.

Next,wesetuptheslave'sreplicationprocessusingCHANGEMASTERstatement.TheCHANGEMASTERstatementidentifiesthemaster,setstheusernameandpasswordtheslavewillusetoconnect,andidentifiesthenameofthelogandthecurrentpositiontostartreplicatingfrom:

CHANGEMASTERTO

MASTER_HOST="192.168.56.100",

MASTER_USER="slave",

MASTER_PASSWORD="S3CR3t##",

MASTER_LOG_FILE="localhost-bin.000003",

MASTER_LOG_POS=1235;

ReplicationisstartedwithSTARTSLAVEandstoppedwithSTOPSLAVE.TheSHOWSLAVESTATUSreturnsinformationaboutthecurrentstateofreplication:

Wecanchecktheslave'sstatustoseewhetherreplicationisrunningwithoutanyissues

MySQLcreatestwobackgroundprocesseswhenreplicationisrunning-onecommunicates

Page 349: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

withthemaster(theIOprocess)andtheotherexecutestheSQLstatementstomaintainthelocaldatabase(theSQLprocess).TheSlave_IO_Runningvalueshowswhetherthecommunicationprocessisrunningornot,whilethevalueofSlave_SQL_Runningreflectswhetherornottheexecutionprocessisrunning.BothvaluesshouldbeYeswhenreplicationisrunning.

Ifthere'saproblemwithreplication,theLast_IO_ErrorandLast_SQL_Errorentrieswillreportanyerrorsthrownfortheirrespectiveprocesses.YoucanalsotellhowfarbehindtheslaveisfromthemasterbycomparingthevaluesoftheMaster_Log_FileandRead_Master_Log_PosfieldswithwhattheSHOWMASTERSTATUSreturns.

Thecurrentconfigurationenablestheslavetoreplicateeverydatabasefromthemaster,butwecanalsorestrictreplicationtocertaindatabasesbyaddingthereplicate-do-dbentriesintheslave'smy.cnffile.Multipleentriesmaybegiven,whichwillhaveoneentryperdatabase:

replicate-do-db=packt

replicate-do-db=acme

replicate-do-db=sakila

Alternatively,wecanusethereplicate-ignore-dboptiontoreplicateeverythingexceptspecificdatabases:

replicate-ignore-db=mysql

Replicationcanbefilteredatthetable-levelaswell,targetingandignoringspecifictablesinadatabaseusingthereplicate-do-tableandreplicate-ignore-tableoptions:

replicate-do-table=acme.customers

replicate-do-table=acme.addresses

Page 350: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonreplicatingMySQLdatabases:

MySQL5.7ReferenceManual:Replication(http://dev.mysql.com/doc/refman/5.7/en/replication.html)MySQLReplicationonRHEL7(https://www.youtube.com/watch?v=kIfRXshR2zc)MySQLHighAvailabilityArchitectures(http://skillachie.com/2014/07/25/mysql-high-availability-architectures)ReplicationTipsandTricksinMySQL(http://www.linux-mag.com/id/1661/)

Page 351: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

StandingupaMySQLclusterThisrecipeguidesyouthroughtheprocessofsettingupaMySQLcluster.Clustereddatabasesmeetthechallengesofscalabilityandhigh-availabilitybypartitioningthedataacrossmultiplesystemsandmaintainingreplicastoavoidsinglepointsoffailure.

Themembersofaclusterarereferredtoasnodes.TherearethreenodetypesinaMySQLcluster:datanodes,APInodes,andthemanagementnode.Datanodesareresponsibleforstoringdata.UsersandprocessesthenconnecttoanAPInodetoaccessthedatabase.Themanagementnodemanagestheclusterasawhole.Althoughmultiplenodescanbeinstalledonthesamesystem,forexample,bothanAPInodeandadatanodemaybehostedonthesamesystem.However,hostingmultipledatanodesonthesamesystemisobviouslynotagoodideabecauseitnegatesMySQL'seffortstodistributethedata.

Page 352: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipedemonstrateshowtodeployaMySQLclusterusingfoursystems.Thefirstsystemwillhostthemanagementnodeandwe'llassumethatithastheIPaddress192.168.56.100.ThesecondsystemwillhosttheAPInodeandhavetheaddress192.168.56.101.Theremainingsystemswillbeconfiguredwithdatanodesandusetheaddresses192.168.56.102and192.168.56.103.You'llneedadministrativeaccessonallfoursystemseitherusingtherootaccountorsudo.

Page 353: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupaclusteredMySQLdatabase:

1. DownloadtheclusterarchivefromtheMySQLwebsiteandextractitspackagesusingtar:

curl-Ldev.mysql.com/get/Downloads/MySQL-Cluster-7.4/

MySQL-Cluster-gpl-7.4.10-1.el7.x86_64.rpm-bundle.tar|tarx

2. Oneachsystem,installperl-Data-Dumperandreplacetheinstalledmariadb-libspackagewiththedownloadedMySQL-Cluster-sharedpackage:

yuminstallperl-Data-DumperMySQL-Cluster-shared-gpl-*.rpm

yumerasemariadb-libs

3. InstalltheMySQL-Cluster-serverandMySQL-Cluster-clientpackagesoneachsystem:

yuminstallMySQL-Cluster-{server,client}-gpl-*.rpm

4. Onthesystemhostingthemanagementnode,createthe/var/lib/mysql-clusterdirectory:

mkdir/var/lib/mysql-cluster

5. Createthecluster'sconfigurationfileforthemanagementnodeat/var/lib/mysql-cluster/config.iniasfollows:

[ndbddefault]

NoOfReplicas=2

DataMemory=100M

IndexMemory=10M

ServerPort=2202

[ndb_mgmd]

hostname=192.168.56.100

[mysqld]

hostname=192.168.56.101

[ndbd]

hostname=192.168.56.102

[ndbd]

hostname=192.168.56.103

6. Startthemanagementnode:

ndb_mgmd-f/var/lib/mysql-cluster/config.ini

7. Openport1186inthemanagementnodesystem'sfirewall:

firewall-cmd--zone=public--permanent--add-port=1186/tcp

firewall-cmd--reload

8. Oneachdatanode'ssystem,createthefile/etc/my.cnfusingthefollowing:

[mysql_cluster]

ndb-connectstring=192.168.56.100

Page 354: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

9. Starteachdatanode:

ndbd

10. Openport2202inthedatanodes'systems'firewall:

firewall-cmd--zone=public--permanent--add-port=2202/tcp

firewall-cmd--reload

11. Create/etc/my.cnfonthesystemhostingtheAPInodeusingthefollowing:

[mysqld]

ndbcluster

default-storage-engine=ndbcluster

[mysql_cluster]

ndb-connectstring=192.168.56.100

12. StartMySQLserverastheAPInode:

mysqld_safe&

13. Retrievetherootaccount'stemporarypasswordthatwascreatedwhentheMySQLserverwasinstalled.It'srecordedin/root/.mysql_secret:

cat/root/.mysql_secret

14. Setanewpasswordfortherootaccountusingmysqladmin.Whenpromptedforthecurrentpassword,entertheoneidentifiedinthepreviousstep:

mysqladmin-uroot-ppassword

15. Openport3306intheAPInodesystem'sfirewall:

firewall-cmd--zone=public--permanent--add-service=mysql

firewall-cmd--reload

16. Verifythestatusoftheclusterusingthendb_mgmclientonthesystemhostingthemanagementnode:

ndb_mgm-eSHOW

Page 355: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipetaughtyouhowtosetupaMySQLclustereddatabasewithtwodatanodes:oneAPInodeandonemanagementnode.Themanagementnodeconsistsofthendb_mgmdprocessthatprovidesconfigurationinformationtotheothernodesandmonitorsthem.Onthedatanodes,thendbdprocesshandlesthestorage,partitioning,andreplicationoftheclustereddata.AMySQLserverawareofthemanagementnodeandthedatanodesactsastheAPInodethroughwhichuserscanworkwiththeclustereddatabase.

ThepackagesavailableintheOracle-maintainedrepositoryarebuiltwithoutsupportforNetworkDatabase(NDB),sowefirstdownloadedanarchivefromtheMySQLwebsitethathaspackageswhichwillinstallaversionofMySQLthatsupportsNDB/clustering:

curl-Ldev.mysql.com/get/Downloads/MySQL-Cluster-7.4/MySQL-

Cluster-gpl-7.4.10-1.el7.x86_64.rpm-bundle.tar|tarx

MySQLabstractsthedetailsofexactlyhowdataisphysicallyorganizedandmanipulated,delegatingthistoitsvariousstorageengines.Differentengineshavedifferentabilities.SincetheNDBengineistheonethatimplementsclustering,weneedabuildthatsupportstheengine.Insteadofwritingcurl'soutputtoafileaswe'vedoneinotherrecipes,thistimewepipedtheoutputdirectlytotarwiththexargumenttoexpandthearchiveonthefly.

Afterwards,weinstalledtheperl-Data-DumperpackagefromtheCentOSrepositoryandreplacedthemariadb-libspackagealreadyinstalledwiththejustdownloadedMySQL-Cluster-sharedpackageoneachsystem:

yuminstallperl-Data-DumperMySQL-Cluster-shared-gpl-*.rpm

yumerasemariadb-libs

TheMySQL-Cluster-sharedpackageprovidesthesharedlibrariesusedbyotherprogramstoworkwithMySQL.TheselibrariesreplacetheMariaDBversioninstalledfromtheCentOSrepositoriesbydefaultandsaveusfromexperiencinglibraryconflictsthatwouldpreventacleaninstall.Sinceit'snolongerneededafterwards,weuninstalledthemariadb-libspackage.

Someofthepost-installationstepsperformedbyYumafteritinstallstheMySQL-Cluster-serverpackagearescriptedinPerlandusePerl'sData::Dumpermodule.ThismakesthePerl-Data-DumperpackageadependencyfortheMySQL-Cluster-serverpackage.However,abugcausesYumtomissthis,soweinstalledthepackageourselvessothattheMySQL-Cluster-serverpackage'sinstallationwillproceedsmoothly.Itwouldn'tpreventthepackagefrominstalling,butitwouldhaverequiredustocompletesomeadditionalconfigurationstepsmanually.

Withtherequirementsinplace,wetheninstalledtheMySQL-Cluster-serverandMySQL-Cluster-clientpackagesoneachsystem:

yuminstallMySQL-Cluster-{server,client}-gpl-*.rpm

Page 356: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Configurationfortheoverallclusterisprettymuchcentralizedwiththemanagementnodein/var/lib/mysql-cluster/config.ini.Thefileisdividedintoseveralsections,thefirstbeing[ndbdefault],whichprovidesthedefaultconfigurationvaluesthatshouldbeusedforthecluster.Thevalueshereapplytoeachnodeoftheclusterunlessoverriddenbyamorespecificdirectiveintherespectivenode'sconfigurationsection:

[ndbddefault]

NoOfReplicas=2

DataMemory=100M

IndexMemory=10M

ServerPort=2202

TheNoOfReplicasoptionsetsthenumberofreplicasinthecluster.Itsvaluemaybesetto1or2,although2istherecommendedvalue.Recallthatnotonlyaclustereddatabaseispartitionedacrossthedatanodesbutitisalsoreplicated;eachnodehostsapartitiontypically1/nthesizeofthedatabase(wherenisthenumberofdatanodes)andalsoareplicaoftheothernodes.Theclustercanstillfunctionifasystemgoesofflinebecauseitsdataisstillavailableinthereplica.Avalueof1forNoOfReplicasmeansthattherewouldbeonlyonecopyofthedatabase(noreplica)andtheavailabilityofthedatabasedependsonalldatanodesbeingup.

ThedatanodesholdtheirworkingcopyofthedatabaseinRAMtoreducelatencywhileperiodicallysyncingthedatatodisk.TheDataMemoryoptionspecifieshowmuchRAMshouldbereservedforthedatabythenodesandIndexMemoryspecifieshowmuchmemoryshouldbereservedforprimarykeysanduniqueindexes.Whatevervaluesyouprovide,besurethatsufficientresourcesareavailabletoavoidRAMswapping.

TheServerPortoptionspecifiestheportnumberthenodeswillusetocommunicatewithoneanother.Bydefault,MySQLwoulddynamicallyallocateportstomakeiteasiertorunmultiplenodesonthesamesystem,butsincethisreciperunseachnodeonitsownhostsystemandweneedtoknowtheporttoallowtrafficthroughthefirewall,wespecifiedtheportourselves.

Thesubsequentsectionsintheconfigurationusethehostnameoptiontospecifytheaddressesatwhichthemanagementnode(viathe[ndb_mgmtd]section),theAPInode(the[mysqld]section),andthedatanodes(the[ndbd]section)arerunning.Asmadeevidentbythemultiple[ndbd]sections,multiplesectionsofthesametypewillappearifthereismorethanonenodeofthattyperunninginthecluster:

[ndb_mgmd]

hostname=192.168.56.100

[mysqld]

hostname=192.168.56.101

[ndbd]

hostname=192.168.56.102

[ndbd]

hostname=192.168.56.103

Page 357: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Ontheremainingsystems,/etc/my.cnfiscreatedastheconfigurationfileusedbythedatanodesandtheAPInode.Eachincludesa[mysql_cluster]section,whichgivesthendb-connectstringoption:

[mysql_cluster]

ndb-connectstring=192.168.56.100

Thendb-connectstringoptionspecifiestheaddressofthesystemthathoststhemanagementnode.AsthedataandAPInodescomeonline,theycommunicatewiththemanagertoreceivetheirconfigurationinformation.Ifyourclusterhasmorethanonemanagementnode,theadditionalnodescanbelistedintheconnectionstringseparatedbycommas:

ndb-connectstring="192.168.56.100,192.168.56.105,192.168.56.106"

Additionally,theAPInode'sconfigurationincludesthe[mysqld]section.ItincludesthendbclusteroptiontoenabletheNDBengineandthedefault-storage-engineoptioninstructingMySQLtouseNDBtomanageallnewtablesunlessotherwisespecifiedinthetable'sCREATETABLEstatement:

[mysqld]

ndbcluster

default-storage-engine=ndbcluster

WhenauserorprocesscreatesanewtablewiththeCREATETABLEstatement,theycanspecifywhichofMySQL'sstorageenginesshouldbeusedtomanageitsdatawiththeENGINEdirective,forexample:

CREATETABLEusers(

idINTEGERUNSIGNEDNOTNULLPRIMARYKEY,

first_nameVARCHAR(50)NOTNULLDEFAULT'',

last_nameVARCHAR(50)NOTNULLDEFAULT''

)

ENGINE=NDBCluster;

ThedefaultengineisInnoDBengine.However,onlydatainNDB-managedtablesmaketheirwaytothecluster.Ifatableismanagedbyanotherengine,thedataresideslocallyontheAPInodeandisnotavailabletoothernodesinthecluster.Topreventunexpectedproblemsandanyconfusionthiscancause,wechangedthedefaultenginesothattableswillusetheNDBenginewhentheENGINEdirectiveisn'tprovided.

TheorderinwhichnodesarestartedwhenbringinguptheMySQLclusterisimportant,sinceonenodemaydependontheothers.Themanagementnodeisstartedfirst,followedbythedatanodes,andthentheAPInode.

ThepasswordforMySQL'srootaccountontheAPInodeisrandomlygeneratedthefirsttimetheserverisstarted,anditiswrittentothe/root/.mysql_secretfile,justasweusedmysqladmintochangeitintheSettingupaMySQLdatabaserecipe:

cat/root/.mysql_secret

Page 358: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mysqladmin-uroot-ppassword

TheSHOWcommandsenttothendb_mgmclientonthemanagementnode'ssystemallowsustoviewthestatusoftheclusterandensureeverythingisupandrunningasitshouldbe.Theclientcanbeinvokedininteractivemode,orcommandscanbepassedtoitdirectlyusingthe-eargument:

ndb_mgm-eSHOW

ThestatusoftheMySQLclustercanbeviewedusingthendb_mgmclient

Page 359: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithMySQLclusters:

MySQLReferenceManual:MySQLClusterCoreConcepts(http://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-basics.html)MySQLReferenceManual:MySQLClusterInstallation(http://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-installation.html)MySQLReferenceManual:MySQLClusterNodes,NodeGroups,Replicas,andPartitions(http://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-nodes-groups.html)MySQLReferenceManual:OnlineBackupofMySQLCluster(http://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-backup.html)SetUpaMySQLClustertheEasyWay(http://youtube.com/watch?v=64jtbkuPtvc)HighAvailabilityMySQLCookbookbyAlexDavies(https://www.packtpub.com/big-data-and-business-intelligence/high-availability-mysql-cookbook)

Page 360: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingupaMongoDBdatabaseAlthoughrelationaldatabaseshavedominatedtheworldofdatastorage,therehavealwaysbeenothersystemsthatspecializeinalternativewaysofworkingwithdata,forexampledocumentandobject-orienteddatabases,key-valuedatabases,andhierarchicaldatabases.ThepopularityofthesealternativedatabaseshasexperiencedaresurgencethankstotherecentNoSQLandBigDatamovements.ThisrecipeteachesyouhowtoinstallMongoDB,amoderndocument-orienteddatabasesystem.

Page 361: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandadministrativeprivilegesbyeitherusingtherootaccountorsudo.ItalsoassumesyouhaveregisteredtheEPELrepository(seetheRegisteringtheEPELandRemirepositoriesrecipeinChapter4,SoftwareInstallationManagement).

Page 362: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit…FollowthesestepstoinstallMongoDBandcreateanewdatabase:

1. Installthemongodb-serverandmongodbpackagesfromtheEPELrepository:

yuminstallmongodb-servermongodb

2. Open/etc/mongod.confwithyourtexteditor:

vi/etc/mongod.conf

3. Locatetheauthentryanduncommentit,makingsureitsvalueistrue:

#Runwith/withoutsecurity

auth=true

4. Locatethebind-ipoptionandcommentitout:

#Commaseparatedlistofipaddressestolistenon

#bind_ip=127.0.0.1

5. Saveyourchangestotheconfigurationfileandcloseit.6. StarttheMongoDBserverandenableittostartautomaticallywheneverthesystem

reboots:

systemctlstartmongod.service

systemctlenablemongod.service

7. Openport27017inthesystem'sfirewall:

firewall-cmd--zone=public--permanent--add-port=27017/tcp

firewall-cmd--reload

8. ConnecttotheMongoDBserverwithmongo:

mongo

9. Setadminastheactivedatabase:

useadmin

10. ExecutecreateUser()tocreateanewuserformanaginguseraccounts:

db.createUser({

user:"admin",

pwd:"P@$$W0rd",

roles:[{role:"userAdminAnyDatabase",db:"admin"}]

})

11. Authenticateyourselfusingthenewlycreatedadminaccount:

db.auth({user:"admin",pwd:"P@$$W0rd"})

12. Setpacktastheactivedatabase:

usepackt

Page 363: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

13. Createauseraccountforworkingwiththedatabase:

db.createUser({

user:"tboronczyk",

pwd:"S3CR3t##",

roles:[{role:"readWrite",db:"packt"}]

})

14. Exittheclientandreturntotheterminal:

exit

Page 364: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...MongoDBisthemostpopularinitsclassofdatabasesandisusedbymanyhigh-profilecompanies,includingeBay,Craigslist,SAP,andYandex.ThenecessarypackagesareavailableintheEPELrepository;mongodb-servercontainstheMongoDBserverapplicationandthemongodbpackagecontainstheclientandotherutilitiesforworkingwiththeserveranddatabases:

yuminstallmongodb-servermongodb

MongoDBrunswithoutsecurityenabledbydefaultandanyonemayperformanyactionagainstanydatabase.Topreventthis,weenabledsecuritybyuncommentingtheauthoptioninMongoDB'sconfigurationfile(/etc/mongod.conf).Oncesecurityisenabled,usersmustauthenticatethemselvesbeforetheycanworkwithadatabase,andtheserververifiesthattheaccounthastherighttoperformtherequestedaction:

auth=true

ThecurrentconfigurationpermitsMongoDBtolistenforconnectionsonlyontheloop-backinterface(127.0.0.1),sowealsocommentedoutthebind_ipoption:

#bind_ip=127.0.0.1

Leftunbound,MongoDBwillbeaccessibleviaallofthesystem'saddresses.Alternatively,ifthesystemhasmultipleaddresses(perhapsthesystemhasmultipleinterfacesoryou'veimplementedtheBindingmultipleaddressestoasingleEthernetdevicerecipeinChapter2,Networking)andyouwantMongoDBtorespondononlyoneofthem,youcanleavetheoptionactivewiththedesiredIPaddressasitsvalue.

Afterupdatingtheconfigurationfile,westartedtheserverandopenedMongoDB'sdefaultportinthesystem'sfirewalltoallowremoteconnections:

firewall-cmd--zone=public--permanent--add-port=27017/tcp

firewall-cmd--reload

Next,weusedthemongoclienttoestablishaconnectiontotheMongoDBserverrunningonthelocalhost:

mongo

WesetadminastheactivedatabaseandexecutedthecreateUser()methodtocreateanadministratoraccountdedicatedtomanagingMongoDB'sdatabaseusers:

useadmin

db.createUser({

user:"admin",

pwd:"P@$$W0rd",

roles:[{role:"userAdminAnyDatabase",db:"admin"}]

})

Page 365: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ThecreateUser()methodacceptsadocumentwithpropertieslistingthenewaccount'susername(user),password(pwd),androles(roles)andaddsittothesystem.userscollectionintheactivedatabase(admin).Useraccountsarestoredatthedatabaselevelandthedatabasestoringauser'sdetailsisknownasthatuser'sauthenticationdatabase.Usersmayworkwithotherdatabases,buttheymustauthenticateagainsttheirauthenticationdatabasefirst.Eveniftheirusernamesarethesame,accountscreatedindifferentdatabasesareconsideredseparateandmayhavedifferentpermissions.

Therolespropertyisanarrayofobjects,eachlistingarolethattheuserisamemberofwhentheyworkwiththegivendatabase.Inthecaseofadmin,theuserisamemberoftheuserAdminAnyDatabaserole.MongoDB'spermissionsystemisbasedonrole-basedaccesscontrol(RBAC).ThefocusofRBACisonusersandwhatrolestheyplayasopposedtograntingindividualpermissionstoeachaccount.Permissionsareassignedtoaroleandthenuseraccountsaregivenmembershipintheroleinheritingitspermissions.

userAdminAnyDatabaseisabuilt-inroleconfiguredwiththenecessarypermissionstocreateanddeleteuseraccounts,assignmembershipinarole,andmanageuserpasswordsforanydatabase.MongoDBshipswithseveralpredefinedrolesbesidesuserAdminAnyDatabase.Theyincludethefollowing:

dbAdmin:TheseusersareresponsibleforadministeringthedatabaseuserAdmin:Theseusersareresponsibleforadministeringotherusersread:TheseareusersthatonlyreaddocumentsfromthedatabasereadWrite:Theseareuserswhoreaddocumentsandalsoneedwriteaccesstoinsert/modifythemdbOwner:Theseareuserswhoownthedatabase(combinesthedbAdmin,userAdmin,andreadWriteroles)

Therearealsothebackupandrestorerolesforusersresponsibleforperformingdatabasebackups,rolesformanagingMongoDBclusters,andadditionalglobalversionsofsomeoftheaforementionedroles,suchasreadAnyDatabase,foruserswhoneedread-accesstoallofMongoDB'sdatabases.Acompletelistofrolescanbefoundintheofficialdocumentationonlineathttps://docs.mongodb.com/manual/reference/built-in-roles/.

Note

Theprinciplesofleastprivilegeencourageustoavoidover-usingtheglobalroles;it'sbettertocreateusersthatworkwiththeirowndatabases.Ifanaccountneedstoworkwithadatabaseoutsideitsauthenticationdatabase,multiplerolescanbeassignedasfollows:

db.createUser({

user:"tboronczyk",

pwd:"S3CR3t##",

roles:[

{role:"read",db:"admin"},

{role:"readWrite",db:"packt"},

{role:"readWrite",db:"acme"}

Page 366: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

]

})

Next,weusedthenewadminusertocreateanewuserforthepacktdatabase(andtocreatethepacktdatabaseitselfasasideeffect):

db.auth("admin","P@$$W0rd")

usepackt

db.createUser({

user:"tboronczyk",

pwd:"S3CR3t##",

roles:[{role:"readWrite",db:"packt"}]

})

DatabasesandcollectionsareimplicitlycreatedbyMongoDBwhenthefirstdocumentisinserted,andsinceMongoDBstoresnewusersintheactivedatabase,settingpacktastheactivedatabaseandcreatingauserisenoughtotriggeritscreation.

Theauth()methodassumesthattheactivedatabaseistheauthenticationdatabasefortheprovidedcredentials.Inthisinstance,authenticationissuccessfulbecauseadminwasalreadytheactivedatabase;attemptingtoauthenticateasadminafterswitchingtopacktwouldfail.However,theidentitypersistsafterauthenticationuntilthenexttimewecallauth()orweexittheclient.So,eventhoughweswitcheddatabases,we'restilloperatingwithintherolesandprivilegesoftheadmindatabase'sadminuser.

Althoughtherecipeconnectedtotheserverwithabaremongoinvocation,theactivedatabasecanbespecifiedonthecommandline.mongoalsooffersseveraloptions,forexample,toconnecttoaMongoDBserverrunningonadifferentsystemandprovideauthenticationcredentials.--hostidentifiestheremotehostnameorIPaddresswhereMongoDBisrunning,andthe--usernameand--passwordoptionsallowyoutoprovideyouraccount'sauthenticationdetails:

mongo--host192.168.56.100--usernametboronczyk--password""packt

Ifthedatabaseisgivenintheinvocationwhen--usernameand--passwordareusedaswell,MongoDBassumesthatthedatabaseistheaccount'sauthenticationdatabase.Iftheaccountbelongstoanotherdatabase,itsauthenticationdatabasecanbegivenusingthe--authenticationDatabaseoption:

mongo--authenticationDatabaseadmin--usernameadmin--password

""packt

The--passwordoptionexpectsavalue,butMongoDBwillpromptyouforapasswordwhenitsvalueisempty.Isuggestthatyouuseanemptystring("")forthevalue,asIhavedonehere,toforcethepasswordprompt.

Note

Neverenterapasswordaspartofacommand'sinvocationforsecurityreasons.Thepassword

Page 367: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mayappearintheoutputofpswhilethecommandisrunningandwillalsoappearinyourshell'shistory.

Page 368: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithMongoDB:

TheMongoDBmanual(http://docs.mongodb.org/manual)MongoDBManual:Role-BasedAccessControl(http://docs.mongodb.org/manual/core/authorization)MongoDBTutorialforBeginners(http://www.youtube.com/watch?v=W-WihPoEbR4)Wikipedia:Role-basedaccesscontrol(https://en.wikipedia.org/wiki/Role-based_access_control)

Page 369: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

BackingupandrestoringaMongoDBdatabaseThisrecipeteachesyouhowtobackupaMongoDBdatabaseusingthemongodumputilityandrestoreitusingmongorestore.

Page 370: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresarunningMongoDBserverandaccesstoauseraccountwithmembershipintheuserAdminrole.

Page 371: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstobackupaMongoDBdatabase:

1. ConnecttoMongoDBasauserwithmembershipintheuserAdminrole:

mongo--usernameadmin--password""admin

2. Createanaccountwithmembershipinthebackupandrestorerolestobeusedforcreatingandrestoringbackups:

db.createUser({

user:"backupusr",

pwd:"B@CK&4th",

roles:[

{role:"backup",db:"admin"},

{role:"restore",db:"admin"}

]

})

3. Usemongodumponthecommand-linetoexportaMongoDBdatabase:

mongodump--authenticationDatabaseadmin--usernamebackupusr

--password""--dbpackt

4. Torestoreadatabasefromthebackupmadebymongodump,usethemongorestoreprogram:

mongorestore--authenticationDatabaseadmin--usernamebackupusr

--password""--drop--dbpacktdump/packt

Page 372: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Theaccountusedtomakeabackupmusthavetheprivilegesassignedtothebackuproleandtherestoreaccountmusthavethoseassignedtotherestorerole.So,weconnectedtotheMongoDBserverandcreatedanaccountwithmembershipinbothrolespriortousingtheutilities:

db.createUser({

user:"backupusr",

pwd:"B@CK&4th",

roles:[

{role:"backup",db:"admin"},

{role:"restore",db:"admin"}

]

})

Thenewaccountisthenusedwithmongodumptobackupourdatabase:

mongodump--authenticationDatabaseadmin--usernamebackupusr

--password""--dbpackt

Theprecedinginvocationexportseverythinginthepacktdatabaseasspecifiedbythe--dbargument.If--dbisnotgiven,mongodumpexportsalloftheavailabledatabasesexceptfortheserver'slocaldatabase.It'spossibletoexportjustaspecificcollectionfromthedatabaseusingthe--collectionargument:

mongodump--dbpackt--collectionauthors

Bydefault,mongodumpcreatesalocaldirectorynameddumptoorganizetheexporteddata.Withindumpexistsadirectoryforeachexporteddatabaseandwithinthataretwofilesforeachcollection.ThefirstfileisaBSONfile,abinaryJSON-likeformatusedbecauseitoffersarichersetofdatatypesthanJSONdoes.Forexample,JSONdoesn'tdefineadatetype.WhereasJSONoffersonlyasinglenumerictype,BSONsupports32and64-bitintegersanddoubles.ThesecondfileisametadataJSONfilethatstoresdetailsaboutthecollection,suchasanycollectionoptionsorindexdefinitions.

Note

mongodumpwilloverwriteanyexistingfilesifthedumpdirectoryalreadyexists.Toavoidproblems,youcanspecifyadifferentlocationwiththe--outargument:

mongodump--dbpackt--outdump-$(date+%F)

Page 373: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theexportedcollectiondataisorganizedbydatabaseinthedumpdirectory

Thepathtothecollectionfilesisthengiventomongorestoretoimportthedatadumpedbymongodump.Thedatabasetowhichthecollectionswillbeinsertedisnamedusingthe--dbargument:

mongorestore--authenticationDatabaseadmin--usernamebackupusr

--password""--drop--dbpacktdump/packt

mongorestoreonlyinsertsthedata;ifdocumentswiththesame_idfieldalreadyexistinacollectionthenthoserecordsareskipped,notupdated.Thismayormaynotbedesireddependingonthecircumstances.Sotobesurethattherestoreddatamatcheswhatwasexported,the--dropargumentisused,whichinstructsmongorestoretodroptheexistingcollectionfirstbeforeimportingthebackup.

Apartfrommongodumpandmongorestore,thereisalsomongoexportandmongoimport.mongoexportexportsacollection'sdatatoeitheraJSONorCSVfileandmongoimportimportsdatafromtheseformats.KeepinmindhoweverthatJSON'stypesystem(andcertainly"types"inCSV)islessgranularthanBSON'sandsomefidelitycanbelost.Forreliablebackups,mongodumpandmongorestorearepreferred.

ThedefaultexportformatofmongoexportisJSON.Toexportacollection'sdatatoCSVinstead,usethe--csvargument:

mongoexport--dbpackt--collectiontitles--csv--outtitles.csv

Specificfieldscanbetargetedforexportaswellbyprovidingacomma-separatedlistofnamesusingthe--fieldsargument:

Page 374: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mongoexport--dbpackt--collectiontitles--fieldsisbn,title,

authors,year,language,pages--csv--outtitles.csv

Someargumentsworthnotingwhenimportingdatawithmongoimportare--type,whichspecifiestheimportfile'stype(eitherJSONforCSV),--headerline-toskipthefirstrowofdatainthecaseofcolumnheadersinaCSVfile,--fields-toimportonlyspecificfieldsfromthefile,and--upsert,whichperformsanupsertactiononexistingdocumentsinsteadofskippingthem:

mongoimport--dbpackt--collectiontitles--fieldsisbn,title,

authors--typecsv--upsert<titles.csv

Page 375: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonbackingupandrestoringMongoDBdatabases:

Themongodumpmanualpage(man1mongodump)Themongorestoremanualpage(man1mongorestore)Themongoexportmanualpage(man1mongoexport)Themongoimportmanualpage(man1mongoimport)MongoDBManual:MongoDBBackupMethods(http://docs.mongodb.org/manual/core/backups)BSON:BinaryJSON(http://bsonspec.org/)

Page 376: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringaMongoDBreplicasetThisrecipeteachesyouhowtoconfigurereplicationusingMongoDBreplicasets.

Whenreplicationisperformedusingreplicasets,oneinstallationofMongoDBidentifiesastheprimaryserverwhileothersintheclusteraresecondaries.Theprimaryserveracceptswrites,whicharereplicatedtothesecondaries,whilethesecondariesservicereadrequests.Iftheprimaryservergoesdown,thesecondaryserversautomaticallycallaquorumandpromoteoneofthesecondariestofilltheprimary'srole.Theoldprimaryrejoinstheclusterwhenitcomesbackonline.Thisconfigurationprovidesredundancy,distributedread/writeaccess,andautomaticfailoverforhigh-availability.

Page 377: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisrecipedemonstratesconfiguringreplicasetsusingthreesystems.Thefirstsystemwillbethecluster'sprimaryserverandweassumethatitsIPaddressis192.168.56.100.Theothertwosystemswillbesecondaryserversusingtheaddresses192.168.56.102and192.168.56.103.MongoDBshouldbeinstalledonallthreesystems.You'llalsoneedadministrativeaccesstocompletetheconfigurationandaccesstoauseraccountwithmembershipintheuserAdminrole.

MongoDBreplicationreliesonhostnames.Beforeyoubeginthisrecipe,makesurethatthesystemsareaccessibletooneanotherbythehostname.Ifthesystemsareinaccessibleandyouareunabletoaddthenecessaryrecordstoyournetwork'sDNS,youcanoverridelocalresolutionforthehostsinquestionbyaddingentriesto/etc/hosts,similarlytothefollowing:

192.168.56.100benitobenito.localdomain

192.168.56.101javierjavier.localdomain

192.168.56.102geomargeomar.localdomain

Page 378: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigurereplicationusingMongoDBreplicasets:

1. Ontheprimarysystem,navigateto/var/lib/mongodbanduseopenssltocreateasharedsecret.Thissecretservesasthepasswordeachserverwillusetoauthenticateitselfasamemberofthereplicationcluster:

cd/var/lib/mongodb

opensslrand756-base64-outrs0.key

2. Securethefile'spermissions;itshouldbeownedbymongodbandonlyreadablebyitsowner:

chownmongodb.mongodbrs0.key

chmod600rs0.key

3. Open/etc/mongod.confwithyourtexteditor:

vi/etc/mongod.conf

4. LocatethereplSetoption,uncommentit,andassignitthevaluers0:

#Argis<setname>[/<optionalseedhostlist>]

replSet=rs0

5. UncommentthekeyFileoptionandprovidethepathtothefilecontainingthesharedpassword:

#Privatekeyforclusterauthentication

keyFile=/var/lib/mongodb/rs0.key

6. Saveyourchangesandclosethefile.7. RestarttheMongoDBserver:

systemctlrestartmongod.service

8. Copythesharedsecrettoeachofthesecondarysystems:

scprs0.key192.168.56.101:/var/lib/mongodb/rs0.key

scprs0.key192.168.56.102:/var/lib/mongodb/rs0.key

9. Repeatsteps2-7oneachoftheothersecondarysystems.10. ConnecttotheprimaryMongoDBserverandcreateanaccountwithmembershipinthe

clusterManagerroletobeusedforconfiguringandmanagingthereplicacluster:

db.createUser({

user:"repladmin",

pwd:"dupl1C@t3",

roles:[{role:"clusterManager",db:"admin"}]

})

11. Authenticatingyourselfusingtherepladminuser:

db.auth("repladmin","dupl1C@t3")

Page 379: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

12. Usethers.initiate()methodtoinitializethecluster:

rs.initiate()

13. Registerthesecondarymembersusingrs.add():

rs.add("192.168.56.101")

rs.add("192.168.56.102")

Page 380: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Clustersmustcontainanoddnumberofserversbecausetherehastobeamajorityvotetoapproveasecondary'sproposaltotakeontheroleofprimaryiftheprimaryserverbecomesunavailable.Threeserverswereused,whichistheminimumnumberforaclusterthatprovidesproperredundancyandavailability.

Clustermembersidentifythemselvestooneanotherusingasharedreplicasetnameandpassword,whichweprovideineachserver'smongod.confconfigurationfile.ThenameisspecifiedusingthereplSetoption:

replSet=rs0

Thepasswordvaluecanbeanythingupto1,024characters.Forsecurityreasons,alongrandomstringispreferredforresistanceagainstbruteforceanddictionaryattacks.Wecangeneratesuchvaluesusingopensslrand:

opensslrand756-base64-outrs0.key

randgeneratesthenumberofrandombyteswerequest,inthiscase756bytes.-base64encodesthemusingtheBase64encodingschemetorepresentthebytessafelyasplaintext.Encodingincurssomeoverhead,andBase64encodesthreebytesasfourcharactersandpadstheresultwhenlessthanthreebytesareavailable.So,Base64-encodingthe765randombytesresultsin1,024charactersoftextsuitableforourneeds.

Theresultingkeyfilecontainingthepasswordiscopiedtoeachsystem.Itsownershipissettothesystem'smongodbuserandaccesspermissionstothefilearerevokedforeveryoneexceptthatuser:

chownmongodb.mongodbrs0.key

chmod600rs0.key

ThefileisspecifiedintheconfigurationfileusingthekeyFileoption:

keyFile=/var/lib/mongodb/rs0.key

ManagementoftheclusterrequirespermissionsassignedtotheclusterManagerrole,sowethencreatedanaccountwithmembershipinthatrole,andthenweauthenticatedourselvesusingthenewaccount:

db.createUser({

user:"repladmin",

pwd:"dupl1C@t3",

roles:[{role:"clusterManager",db:"admin"}]

})

db.auth("repladmin","dupl1C@t3")

Westartedtheclusterusingrs.initiate()ontheprimaryserverandthenregisteredthesecondaryserversusingrs.add():

Page 381: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

rs.initiate()

rs.add("192.168.56.101")

rs.add("192.168.56.102")

Afterrs.initiate()isinvoked,you'llnoticethemongoclient'spromptchangestors0:primarytonotifyusthatwe'reconnectedtotheprimaryserverinthers0replicationgroup.Ifyouweretologintoasecondaryserver,thepromptwouldreadrs0:secondary.

Alternatively,theclustercanbeconfiguredbypassinganobjectthatspecifiesthesecondaryserversasanargumenttors.initiate().Theobject's_idpropertyisthenameofthesetandthememberspropertyisanarrayofsecondaryhosts:

rs.initiate({

_id:"rs0",

members:[

{_id:0,host:"192.168.56.100"},

{_id:1,host:"192.168.56.101"},

{_id:2,host:"192.168.56.102"}

]

})

Page 382: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithMongoDBreplicasets:

MongoDBManual:Replication(http://docs.mongodb.org/manual/core/replication-introduction)MongoDBReplicationandReplicaSets(http://www.youtube.com/watch?v=CsvbG9tykC4)

Page 383: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingupanOpenLDAPdirectoryThisrecipeteachesyouhowtoinstallOpenLDAP,anopen-sourceimplementationofanX.500directoryserver.TheX.500seriesofprotocolswasdevelopedinthelate1980stosupportthestorageandlookupofnames,e-mailaddresses,computersystems,andotherentitiesinahierarchicalfashion.Eachentryisanodeinadirectoryinformationtree(DIT)andisidentifiedbyitsdistinguishedname(DN).Informationabouttheentryisrepresentedaskey/valuepairsknownasattributes.

Page 384: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandadministrativeprivilegeseitherbyusingtherootaccountorsudo.

Page 385: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupanOpenLDAPdirectory:

1. Installtheopenldap-serverandopenldap-clientspackages:

yuminstallopenldap-serversopenldap-clients

2. CopythedatabaseconfigurationfileincludedwithOpenLDAPtotheserver'sdatadirectory.Ensurethefileisownedbytheldapuser:

cp/usr/share/openldap-servers/DB_CONFIG.example

/var/lib/ldap/DB_CONFIG

chownldap.ldap/var/lib/ldap/DB_CONFIG

3. UseslappasswdtogenerateapasswordhashforOpenLDAP'sManageraccount.Enterthedesiredpasswordwhenprompted:

slappasswd

4. StarttheLDAPserverandoptionallyenableittostartautomaticallywheneverthesystemreboots:

systemctlstartslapd.service

systemctlenableslapd.service

5. Openport389inthesystem'sfirewalltoallowoutsideconnectionstotheserver:

firewall-cmd--zone=public--permanent--add-service=ldap

firewall-cmd--reload

6. Createthefileconfig.ldifusingthefollowingcontent.TheDIT'ssuffixisbasedonthedomainldap.example.comandthevalueforolcRootPWisthepasswordhashobtainedinstep3:

dn:olcDatabase={2}hdb,cn=config

changetype:modify

replace:olcSuffix

olcSuffix:dc=ldap,dc=example,dc=com

-

replace:olcRootDN

olcRootDN:cn=Manager,dc=ldap,dc=example,dc=com

-

add:olcRootPW

olcRootPW:{SSHA}cb0i4Kwzvd5tBlxEtwB50myPIUKI3bkp

dn:olcDatabase={1}monitor,cn=config

changetype:modify

replace:olcAccess

olcAccess:{0}to*bydn.base="gidNumber=0+uidNumber=0,

cn=peercred,cn=external,cn=auth"readbydn.base="cn=

Manager,dc=ldap,dc=example,dc=com"readby*none

7. Invokeldapmodifytoexecutetheoperationsinconfig.ldif:

ldapmodify-YEXTERNAL-Hldapi:///-fconfig.ldif

Page 386: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

8. Useldapaddtoimportthecosine,inetorgperson,andnisschemasfoundin/etc/openldap/schema:

cd/etc/openldap/schema

ldapadd-YEXTERNAL-Hldapi:///-fcosine.ldif

ldapadd-YEXTERNAL-Hldapi:///-finetorgperson.ldif

ldapadd-YEXTERNAL-Hldapi:///-fnis.ldif

9. Createthefileroot.ldifwiththefollowingcontent:

dn:dc=ldap,dc=example,dc=com

objectClass:dcObject

objectClass:organization

o:MyCompany'sLDAPDatabase

10. Useldapaddtoimportroot.ldif,authenticatingyourselfwiththeManageraccount:

ldapadd-D"cn=Manager,dc=ldap,dc=example,dc=com"-W-H

ldapi:///-froot.ldif

Page 387: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Wefirstinstalledtheopenldap-serverpackage,whichcontainstheLDAPserver(slapd)andsomesupportingutilities,andtheopenldap-clientspackage,whichinstalledthebasicutilitiesusedforworkingwiththedirectoryserver:

yuminstallopenldap-serversopenldap-clients

OpenLDAPusestheBerkeleyDB(BDB/HDB)databaseforbackenddatastorage,indexing,andcaching.Thedatabaseisconfiguredseparatelyfromthedirectoryserverandanexampleconfigurationfileisinstalledalongwiththeserver.Wecopiedtheexampleintotheserver'sdatadirectorybutleftitwithitsdefaultvalues;thedefaultsarefinetostartwithalthoughyou'llwanttoreviewthesettingsperiodicallyafteryoudeployOpenLDAPtoensurethebestperformance(man5slapd-bdbprovidesdescriptionsofthefile'sconfigurationoptions):

cp/usr/share/openldap-servers/DB_CONFIG.example

/var/lib/ldap/DB_CONFIG

Thedirectory'sadministrativeuserManagerdoesn'thaveanassignedpasswordatfirst.OpenLDAPexpectsthepasswordtobehashedsowecreatedasuitablevalueusingslappasswd:

slappasswd

ThedefaulthashingalgorithmusedbyslappasswdissaltedSHA(SSHA)asindicatedbythe{SSHA}prefixinitsoutput.It'spossibletohashthepasswordusingadifferentalgorithmifrequiredbyspecifyingitusingthe-hargument.Thepossiblevaluesare{CRYPT},{MD5},{SMD5}(saltedMD5),{SHA},or{SSHA}.Thesaltedalgorithmsarepreferredovertheirnonsaltedcounterpartsbecausetherandomlygeneratedsaltslappasswdincorporatesintothehashmakesthehashresistanttorainbowattacks.

OpenLDAPhasdeprecateditsfile-basedconfigurationapproachinfavorofonlineconfiguration,storingparametersinaconfigDITsothattheycanbeupdatedwithoutneedingtorestartthedirectoryserverforthechangestotakeeffect.Soafterstartingtheserver,wewrotethenecessaryoperationstoconfig.ldifthatwillmakeourupdatesandthenexecutedthemasabatchwithldapmodify:

ldapmodify-YEXTERNAL-Hldapi://-fconfig.ldif

The-HargumentprovidesoneormoreURIsfortheserverswewanttoconnectto.Wecanspecifythetransportprotocol,hostnameorIPaddress,andport,buttheURIisnotafullRFC-4516styleLDAPURI(othercomponentssuchasthebaseDNaregivenusingotherarguments).Thesupportedprotocolsareldap,ldaps(LDAPoverSSL),andldapi(LDAPoverIPC/unix-socket).Nohostnameisrequiredtoaccessthelocalhost,sojustldapi://isused.

The-YargumentspecifyingEXTERNALastheauthenticationmechanismallowstheuseof

Page 388: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mechanismsexternaltotheserver'sSASLmethods.Whenpairedwithldapi,EXTERNALusesourloginsession'susernametoauthenticateus.

ThedefaultbehaviorforldapmodifyistoreadinputfromSTDIN,butthe-fargumentcanspecifyaninputfileinstead.Sincethestatementsareratherverbose,usinganinputfileisagreatideabecauseyoucanreviewthemforanymistakesbeforehand.IfyoudowanttoprovidethemviaSTDINhowever,Irecommendthatyouusethe-cargumenttorunldapmodifyin"continuousmode".Theprogramterminateswhenitencountersanerrorbydefault,butincontinuousmodeitwillkeeprunning.Thiswillgiveyoutheopportunitytoresubmittheoperationifthere'saproblem,withoutreconnecting:

ldapmodify-YEXTERNAL-Hldapi:///-c

OurfirstoperationchangedtheDIT'ssuffixfromthedefaultdc=my-domain,dc=comtosomethingmoreappropriate.Therecipeusesldap.example.comforexamplepurposes,butofcourseyoumaysubstituteyourowndomainaccordingly:

dn:olcDatabase={2}hdb,cn=config

changetype:modify

replace:olcSuffix

olcSuffix:dc=ldap,dc=example,dc=com

ThesuffixisstoredintheolcSuffixattributeoftheolcDatabase={2}hdb,cn=configentryandrepresentsthetopleveloftheDIT.Traditionally,thesuffixisbasedonadomainnameandisexpressedasaseriesofdomaincomponents(DC),sothedomainldap.example.combecomesdc=ldap,dc=example,dc=com.

Thesuffixappearsinafewotherplaces,soweneededtoupdatethoseaswell-theolcRootDNattribute,whichliststhenameoftheDIT'sadministrativeuser,andinthepermissionstatementinolcAccessthatgrantsaccesstoManagerandthesystem'srootaccount.Additionally,weaddedtheolcRootPWattributethatstorestheManager'spasswordhash.Wedon'thavetospecifytheDNmultipletimesforattributesonsameentry.Rather,wecanseparatetheoperationswithasinglehyphen:

replace:olcRootDN

olcRootDN:cn=Manager,dc=ldap,dc=example,dc=com

-

add:olcRootPW

olcRootPW:{SSHA}3NhShraRoA+MaOGSrjWTzK3fX0AIq+7P

dn:olcDatabase={1}monitor,cn=config

changetype:modify

replace:olcAccess

olcAccess:{0}to*bydn.base="gidNumber=0+uidNumber=0,

cn=peercred,cn=external,cn=auth"readbydn.base="cn=

Manager,dc=ldap,dc=example,dc=com"readby*none

Next,weimportedthecosine,nis,andinetorgpersonschemas.CreatingnewschemasfromscratchcanbeadauntingtaskasafairamountofplanningisrequiredtoidentifywhattypesareneededandwhatPEN/OIDsshouldbeallocated.Importingtheseschemasprovidedwith

Page 389: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

OpenLDAPgivesusaccesstovarioususefulpredefinedtypes:

ldapadd-YEXTERNAL-Hldapi:///-fcosine.ldif

ldapadd-YEXTERNAL-Hldapi:///-finetorgperson.ldif

ldapadd-YEXTERNAL-Hldapi:///-fnis.ldif

cosinedefinesastandardX.500directoryservicesschemathatwasoriginallydevelopedfortheCOSINEPARADISEProjectandisoutlinedinRFC-4524.Itgivesustypessuchasdocumentanddomainobjectsandattributessuchashost,mail,anddocumentAuthor.inetorgpersondefinestheinetOrgPersonclass,apersonobjectthatattemptsto"meettherequirementsfoundintoday'sInternetandintranetdirectoryservicedeployments"asdescribedbyRFC-2798andRFC-4524.nisdefinesaNetworkInformationServicesschemawithuserandhostattributesusefulforsettingupcentralizedauthentication,suchasuidNumber,gidNumber,ipNetworkNumber,andipNetmaskNumber.

Ifyoulookatthecontentsofthesefiles,you'llfindthatobjectidentifiers(OIDs)playanimportantroleinschemadefinitions,providinggloballyuniqueidentificationofvariousobjectclassesandattributes.OIDsareastringofnumbersseparatedbydots,readlefttoright,witheachpositionrepresentingalevelinthedistributedhierarchy.Toplevelsofthehierarchyaremaintainedbyvariousstandardsbodiesandregistryauthorities,andInternetAssignedNumbersAuthority(IANA)allowsindividualstoregisterfortheirownbranchundertheOID1.3.6.1.4.1.Forexample,1.3.6.1.4.1.4203isassignedtotheOpenLDAPproject.

Finally,weneedtodefinethedomaincomponentobject(dcObject)first.Thisobjectistherootofourlocalbranchofthedirectoryunderwhichfutureentriescanbeadded.IfyourexperiencecentersmostlyonworkingwithrelationaldatabasessuchasMySQLorwithmodernNoSQLdatabasessuchasMongoDB,youcanthinkofdcObjectasthedatabase:

dn:dc=ldap,dc=example,dc=com

objectClass:dcObject

objectClass:organization

o:MyCompany'sLDAPDatabase

Whileusingldapaddtoimportthedefinition,weprovidedthe-DargumenttospecifytheManageraccountand-Wtobepromptedfortheaccount'spassword:

ldapadd-D"cn=Manager,dc=ldap,dc=example,dc=com"-W-Hldapi:///

-froot.ldif

Page 390: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithOpenLDAP:

Theldapmodifymanualpage(man1ldapmodify)OpenLDAP(http://www.openldap.org/)UnderstandingtheLDAPProtocol,DataHierarchy,andEntryComponents(http://www.digitalocean.com/community/tutorials/understanding-the-ldap-protocol-data-hierarchy-and-entry-components)HowtoUseLDIFFilestoMakeChangestoanOpenLDAPSystem(http://www.digitalocean.com/community/tutorials/how-to-use-ldif-files-to-make-changes-to-an-openldap-system)HowtoGetYourOwnLDAPOID(http://ldapwiki.willeke.com/wiki/How%20To%20Get%20Your%20Own%20LDAP%20OID

Page 391: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

BackingupandrestoringanOpenLDAPdatabaseThisrecipeteachesyouhowtobackupanOpenLDAPdatabasebyexportingthedirectorytoanLDIFfile,whichcanthenbeimportedlatertorestorethedatabase.

Page 392: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandadministrativeprivilegeseitherusingtherootaccountorsudo.

Page 393: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...TobackupanLDAPdirectory,exportthedirectoryusingtheslapcatutility:

slapcat-b"dc=ldap,dc=example,dc=com"-lbackup.ldif

Torebuildthedirectoryfromanexport,followthesesteps:

1. StoptheLDAPserver:

servicestopslapd.service

2. Importthefileusingslapadd:

slapadd-fbackup.ldif

3. Ensurethedatafilesareownedbytheldapuser:

chown-Rldap.ldap/var/lib/ldap/*

4. RestarttheLDAPserver:

servicerestartslapd.service

Page 394: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...slapcatexportstheLDAPdatabase'scontentstoLDIF-formattedoutput.ThecontentissenttoSTDOUTbydefault,soyoushouldeithercaptureitusingtheshell'sredirectoperators(>or>>)orusingthecommand's-l(lowercaseL)argument,whichspecifiesthenameofanoutputfile:

slapcat-b"dc=ldap,dc=example,dc=com"-lbackup.ldif

Thesuffixofthetargeteddirectoryisgivenusingthe-bargument.Ifthereareanysubordinatedirectories,they'llbeexportedaswellbydefault.Toeliminatesubordinatesfromtheexportandtoexportonlythetop-leveldirectorycontents,usethe-gargument:

slapcat-b"dc=ldap,dc=example,dc=com"-g-lbackup.ldif

slapcatreturnsentriesintheorderitencountersthemwhilescanningthedatabase.Thismeansit'spossibleforanobject'sdefinitiontoappearintheexportafterthatofanentitywho'sattributesreferenceit.Thisisn'taproblemforslapaddbecauseofhowitimportsdataasopposedtoldapadd,sotheformerutilityshouldbeusedtorestorethedirectory.Otherwiseyou'llhavetoeditthefiletoensuretheorderingwon'tposeaproblem;somethingI'msureyou'llagreeisn'tappealinggiventheformat'sverbosity:

slapadd-fbackup.ldif

Whenperformingexportsandimports,theLDAPservershouldnotberunning.Thismakesanywriteactionsimpossibleduringtheprocesstoguaranteetheintegrityandconsistencyofthedata.

slapaddwritesfilesdirectlytotheserver'sdatadirectorysothatthefileswillbeownedbyroot(theuseraccountusedtorunslapadd),sotheirownershipneedstobesettoldapaftertheimportbutbeforetheserverisstartedsothattheprocesscanaccessthem:

chown-Rldap.ldap/var/lib/ldap/*

Page 395: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithOpenLDAPbackups:

OpenLDAPFAQ-O-Matic:HowdoIbackupmydirectory(http://www.openldap.org/faq/data/cache/287.html)OpenLDAPAdministrator'sGuide:Maintenance(http://www.openldap.org/doc/admin24/maintenance.html)

Page 396: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter8.ManagingDomainsandDNSThischaptercontainsthefollowingrecipes:

SettingupBINDasaresolvingDNSserverConfiguringBINDasanauthoritativeDNSserverWritingareverselookupzonefileSettingupaslaveDNSserverConfiguringrndctocontrolBIND

Page 397: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionInthischapter,you'llfindrecipesthatcoverworkingwithBINDinvariouscapacitiestomanageyourdomaininfrastructurebetter.You'lllearnhowtoconfigureBINDasaresolvingDNSservercapableofcachinglookupresultswhichcanhelpreducelatency,andalsohowtoconfigureBINDasanauthoritativeDNSservertoprovideauthoritativeresponsespubliclyforyourdomainorforresourcesonyourprivateintranet.Alsodiscussedarehandlingreverselookuprequestsandensuringyourresourcesremainaccessiblebyconfiguringredundant,secondaryauthoritativeDNSserversthatperformmaster/slave-styletransfersofzonerecords.Finally,you'lllearnhowtosetupanduserndc,averyusefuladministrationclientforBINDservers.

Page 398: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingupBINDasaresolvingDNSserverThisrecipeteachesyouhowtosetuparesolvingDNSserverusingBIND.DomainNameService(DNS)istheunsungworkhorseoftheInternet,whichtranslatesmemorablenamessuchasfacebook.comandgoogle.comtoIPaddressessuchas172.217.18.238and31.13.76.68.

CommunicationacrosstheInternetusesIPaddressestoidentifysystems,butnumbersarehardforpeopletoremember.Forexample,it'seasierforustoremembergoogle.comthan172.217.18.238(ortheIPv6address2607:f8b0:4006:80e::200e).So,whenyoutypegoogle.cominyourbrowser'saddressbar,yoursystemqueriesaDNSservertoresolvethenametoitsIPaddressandthenrequeststhepagefromthewebserveratthataddress.Whenyouwriteane-mail,aDNSserverretrievestheIPaddressoftherecipient'smailserverbeforethemessageissent.

AresolvingDNSservermaintainedbyyourserviceproviderisprobablythefirstservertoreceivesuchlookuprequestsanditwillrespondimmediatelyifitalreadyhappenstoknowtheaddress.Ifnot,itcontactstheDNSserversintherequesteddomain'sparentzoneandreceiveseitherareferraltotheauthoritativeDNSserveroftherequesteddomainortoserversinthenextzoneintheDNShierarchy.Iftherequestreachesthetopofthehierarchywithoutbeingreferredtoanauthoritativeserver,thenthedomaindoesn'texist.Otherwise,theauthoritativeserversendstheaddressbacktoyourresolvingserver.Theresolverthencachestheresponsesothatfuturelookupswillcompletefaster.

Dependingonyournetworkandhowmanyserversareinvolvedinresolvinganaddress,DNSlookupscanbecomeasignificantsourceoflatency.Addressrecordsshouldbefoundwithinthefirstoneortwohops,andtheresolvingservershouldbephysicallyclosetotheuserforbestperformance.Becauseofthis,settingupalocalDNSservertocachelookupresultscangreatlyimprovehowusersexperiencethespeedofyournetwork.

Page 399: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatthesystemisconfiguredwiththeIPaddress192.168.56.10.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 400: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallBINDasaresolvingDNSserver:

1. Installthebindandbind-utilpackages:

yuminstallbindbind-utils

2. OpenBIND'sconfigurationfileat/etc/named.confwithyourtexteditor:

vi/etc/named.conf

3. Findthelisten-onoptioninsidethebracesofoptions.Updateitslisttoreflectthesystem'sIPaddressesBINDwilluse:

listen-onport53{127.0.0.1;192.168.56.10;};

4. Changethevalueoflisten-on-v6similarlyifyouwanttoserviceIPv6requests.Otherwise,updatethevaluetonone:

listen-on-v6port53{none;}

5. Updatetheallow-queryoptionwiththelistofIPaddressesthatBINDisallowedtoacceptrequestsfrom:

allow-query{localhost;192.168.56.0/24;};

6. Saveyourchangestotheconfigurationfileandcloseit.7. StartBINDwithsystemctl,optionallyenableittostartautomaticallywhenthesystem

reboots:

systemctlstartnamed.service

systemctlenablenamed.service

8. EnableFirewallD'sdnsservicetoopenport53toTCPandUDPtraffic:

firewall-cmd--zone=public--permanent--add-service=dns

firewall-cmd--reload

9. Requestalookupusingdigtotesttheconfiguration:

[email protected]

Page 401: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...BINDisconfiguredasaresolvingDNSserverbydefaultbutwestillwanttoupdateafewoptionstodefinehowitacceptslookuprequests.Thefirstchangeistothelisten-on*optionsfoundintheoptionssectionwhichspecifytheportandnetworkinterfaceBINDlistensonforrequests.listen-onappliestoIPv4networksandlisten-on-v6appliestoIPv6.Inbothcases,thestandardportforDNStrafficisport53:

listen-onport53{127.0.0.1;192.168.56.10;};

listen-on-v6port53{none;}

Next,weupdatedtheallow-queryoption,providingawhitelistofsystemsthatBINDmayacceptrequestsfrom.AddressescanbeprovidedindividuallyorwritteninCIDRnotation:

allow-query{localhost;92.168.56.0/24;}

Usingthepredefinedvaluessuchasany,localhost,localnets,andnoneisalsoacceptable.Intuitively,anyrepresentsalladdresses,allowingBINDtolistenonallofthesystem'sconfiguredaddressesoracceptrequestsfromanysource,whereasnonedisallowseverything.localhostrepresentsallofthesystem'saddressesandlocalnetsrepresentsalladdressesonallofthenetworksthesystemisamemberof.

Note

Becarefulthatthelocalinlocalhostandlocalnetsdoesn'tgiveyouafalsesenseofsecurity.Ifyoursystemisconnectedtomultiplenetworks,forexample,apublicnetwork(suchastheInternet)andaprivateinternalnetwork,bothofthemareconsideredlocal.AllowingaccessfromuntrustednetworksisaseriousriskwithoutthenecessarysecuritymeasuresinplacebecauseanopenDNSservercanbeabusedbymalicioususersintentoncarryingoutseveraltypesofdenialofserviceattacks.

AfterBIND'sconfigurationisupdatedandit'supandrunning,wecantesteverythingbysendingalookuprequestwithdigandinspecttheresponse:

[email protected]

RequestscanbesenttoaspecificDNSserverwithdigbyprovidingthetargetedserver'[email protected]'tgivenintheinvocation,digwillsendtherequesttotheserverslistedinyoursystem's/etc/resolve.conffile.

AftertheaddressoftheDNSserver,wegavetheresourcenamewe'reinterestedinfollowedbythedesiredrecordtype.Intheprecedingexample,theAddress(A)recordforgoogle.comissought.Othertypescanbequeriedtoo,suchastheNameServer(NS)andMailExchange(MX)records.

Page 402: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

digqueriestheDNSserversanddisplaystheirresponse

Theresponsefromdigisorganizedintoseveralsections.TheANSWERSECTIONshowstheArecordwerequested.TheAUTHORITYSECTIONliststheauthoritativeDNSserversconfiguredfortherequesteddomain,andtheADDITIONALSECTIONshowstheIPaddressesoftheauthoritativeservers.Variousmetadataisincludedthroughout,suchaswhichflagsweresetintherequest,whichDNSserverwasqueried,andhowlongthelookuptooktocomplete.

Whenyou'resatisfiedwiththetestingresults,youcanconfigurethesystemsonyournetworktousethenewDNSserver.Thisistypicallydonebyaddinganameserverentryineachsystem's/etc/resolv.conffilethatprovidestheDNSserver'saddress:

Page 403: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

nameserver192.168.56.10

resolv.confmaybedynamicallygenerateddependingonhowthesystem'sinterfacesareconfigured.Ifthisisthecase,anychangesyoumakeinthefilewillbeoverwritten.You'llneedtoinspecttheinterfaces'configurationfiles(forexample,/etc/sysconf/network-scripts/ifcfg-enp0s3),andifPEERDNSissettoyesthenresolv.confismaintainedbythenetworkmanager.AddtheDNSentryintheinterface'sconfigurationandtheDNSserver'saddresswillmakeitswayintoresolve.confthenexttimetheinterfaceisbroughtup:

DNS=192.168.56.10

Bouncetheinterfaceafterupdatingtheconfigurationforthechangetotakeeffectandverifythecontentsofresolve.conf:

ifdownenp0s3&&ifupenp0s3

cat/etc/resolv.conf

ResolvingDNSserversaresometimescalledrecursiveserversbecausetheysendlookuprequeststoeachlevelinthezonehierarchyuntiltheyfindananswer.ForwardingDNSserversfunctionsimilarlytoresolving/recursiveservers,inthatbothtypesacceptlookuprequestsandcachetheresultsforexpediency;however,forwardingserverssendtheirrequeststoanotherDNSserverandwaitfortheresponse,delegatingtheresolutionprocessinsteadoftrackingdowntheansweritself.ThiscanoffloadalotofthenetworkchatterproducedbyaresolvingDNSservertryingtoservicearequest.

ToconfigureBINDtorunasaforwardingDNSserver,open/etc/named.confagainandaddtheforwardersandforwardoptionstotheoptionsblock:

forwarders{8.8.8.8;8.8.4.4;};

forwardonly;

TheforwardersoptionprovidesalistofDNSserversresponsibleforresolvinglookuprequests.TheexampleidentifiesGoogle'spublicDNSserversbutyourserviceprovidershouldalsomaintainpublicDNSserversthatyoucanuseifyouprefer.

forwardonlyforcesBINDtoforwardrequeststotheresponsibleserverslistedinforwarders.Onlywhentheresponsibleserverfailstoreturnanaddressorareferral,willBINDcontacttherootserversforthedomain'sauthoritativeDNSserversandservicetherequestitself.Recursionisn'tcompletelyturnedoffonaforwardingserverbutitisgreatlyreduced.

Page 404: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoThefollowingresourceswillprovideyouwithmoreinformationonhowDNSworksandhowtoconfigureBIND:

Thedigmanualpage(man1dig)AnIntroductiontoDNSTerminology(http://www.digitalocean.com/community/tutorials/an-introduction-to-dns-terminology-components-and-concepts)DNSforRocketScientists(http://www.zytrax.com/books/dns/)HowDNSWorks(http://howdns.works/)BIND9AdministratorReferenceManual(http://www.isc.org/downloads/bind/doc/)RHEL7NetworkingGuide:BIND(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/sec-BIND.html)DNS&BINDbyCricketLiuandPaulAlbitz(http://shop.oreilly.com/product/9780596100575.do)

Page 405: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringBINDasanauthoritativeDNSserverAbenefittohierarchicalstructuresisthattheresponsibilityforsubordinatenodescanbedelegated.AlthoughtheInternetCorporationforAssignedNamesandNumbers(ICANN)hasauthorityovertheDNSdirectory,itdelegatestheresponsibilitytoaccreditedregistrarsfortop-leveldomains,suchascom,net,andorg,anddelegatestotheappropriategovernmentalagenciesforcountrytop-leveldomains,suchasca,de,andes.Registrarsdelegateresponsibilitytoyouwhenyouregisteradomainandyoumayfurtherdelegatetheresponsibilityforyoursubdomainshoweveryouplease.EachboundaryformedbydelegatingresponsibilitycreateswhatisknownasaDNSzone.

ThisrecipeteachesyouhowtoconfigureBINDtooperateasanauthoritativeDNSserverforyourzone.Ifyourecallthepreviousrecipe'sdiscussiononhowaDNSrequestpropagates,you'llrememberthatauthoritativeservershavethefinalsayforaresolution.ThisisbecauseitsinformationcomesfromoutsidetheDNSsystem,fromanadministratorwhomanuallyconfiguresthezone'sinformation.You'llalsolearnhowtowriteazonefilewithinformationsuchasmappinghostnamestoIPaddresses,which,Ipromise,isn'tasscaryasitmightlookatfirstglance.

Page 406: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithBINDconfiguredasaresolvingDNSserver,asdescribedinthepreviousrecipe(BIND'sconfigurationwillbeupdatedtooperateasanauthoritativeserver).Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

FollowingtheadviceofRFC-2606(ReservedTopLevelDNSNames),I'llusetheexample.comdomainforillustration.Ifyouhaveyourowndomainnamethenfeelfreetosubstitute.Alsoforthesakeofillustration,therecipewillreflectanetworkofvariousserversthathandlethedifferentservicesonecommonlyfindsinadomain,suchase-mailserversandwebservers.Thesystemsareasfollows:

ns1:Hoststhedomain'sprimaryauthoritativeDNSserverwiththeIPaddress192.168.56.10(thisisthesystemwe'llbeworkingon)ns2:HostsasecondaryauthoritativeDNSserverwiththeaddress192.168.56.20mail:Hoststheprimarye-mailserverwiththeaddress192.168.56.12mail2:Hostsasecondarye-mailserverwiththeaddress192.168.56.22www:HostsawebandFTPserverwiththeaddress192.168.56.100

Page 407: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigureBINDasanauthoritativeDNSserver:

1. Open/etc/named.confwithyourtexteditor:

vi/etc/named.conf

2. Verifythatthelisten-on*andallow-queryoptionsareconfiguredasdescribedinthepreviousrecipe:

listen-onport52{127.0.0.1;192.168.56.10;};

listen-on-v6port52{none;};

allow-query{192.168.56.0/24;};

3. ChangethevalueoftherecursionoptiontonotodisableBIND'srecursivelookupbehaviorcompletely:

recursionno;

4. Attheendofthefile,addthefollowingzoneconfiguration:

zone"example.com."in{

typemaster;

file"/var/named/zones/example.com.fwd";

allow-transfer{none;};

};

5. Saveyourchangesandclosethefile.6. Createthe/var/named/zonesdirectory:

mkdir/var/named/zones

7. Createthezonefile/var/named/zones/example.com.fwdwiththefollowingcontent(ourdiscussioninHowitworks...willhelpyouunderstandthemeaningofeachrecord):

$TTL1d

$ORIGINexample.com.

;startofauthorityresourcerecord

@INSOAns1hostmaster.example.com.(

2016041501;serial

12h;refresh

5m;retry

2w;expire

3h);negativeTTL

;nameserverrecords

INNSns1

INNSns2

ns1INA192.168.56.10

ns2INA192.168.56.20

;mailrecords

@INMX10mail

INMX20mail2

mailINA192.168.56.12

mail2INA192.168.56.22

;webserverrecords

Page 408: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

@INA192.168.56.100

wwwINCNAME@

ftpINCNAME@

8. Ensurethatthedirectoryandzonefilehavethecorrectownershipandaccesspermissions:

chownroot.named/var/named/zones

chmod750/var/named/zones

chmod640/var/named/zones/*

9. RestartBINDfortheconfigurationchangestotakeeffect:

systemctlrestartnamed.service

10. Requestalookupusingdigtotesttheconfiguration:

[email protected]

Page 409: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...TheonlyrecordsanauthoritativeDNSservershouldservearethosewithauthoritativeinformationaboutitszones,sowebeganbydisablingrecursioninBIND'sconfigurationfile.Whendisabled,BINDwon'tforwardrequestsortrytoresolvealookuprequestfornon-authoritativerecords:

recursionoff;

ThenweaddedashortsectionattheendoftheconfigurationfilethatspecifieshowtheBINDservershouldfunctionfortheexample.com.zone:

zone"example.com."in{

typemaster;

file"/var/named/zones/example.com.fwd";

allow-transfer{none;};

};

Thesectionstartswiththekeywordzonetodenoteazoneconfigurationandisfollowedbythezone'snamegivenasafullyqualifieddomainname(FQDN).FQDNsalwaysendwithadotbecausetheyincludeallofthedelegatedpaths,includingtheroot.SincetherootoftheDNSsystemdoesn'thaveaname,itsseparatorappearsasatrailingdot.Thus,example.com.isfullyqualifiedbutexample.comisnot.(SomepeoplemisusethetermFQDNwhenthey'rereallytalkingaboutpartiallyqualifieddomainnames.Thisisoneofmyirrationalpetpeevessoconsideryourselfwarned.)

Note

Thinkingabouthowyounavigatethefilesystemcanhelpyouunderstandingthedifferencebetweenthefullyqualifiedandpartiallyqualifiednames.Navigation,whentheabsolute(fullyqualified)path/var/namedisgiven,beginsattherootofthefilesystem,descendsintothevardirectory,andthenintonamed.Therootdirectoryhasnonameotherthanitsseparator.However,therelative(partiallyqualified)pathvar/nameddoesn'tstartwiththeseparator.Itsnavigationbeginswherethecurrentdirectoryhappenstobeatthemoment.Domainnamesaresimilar,buttheylisttraversethehierarchybackwardstowardtheroot,andthedotisusedasaseparatorinsteadofaslash.

Thetypemasteroptionspecifiesthisserverasthezone'sprimaryauthoritativeDNSserver.Acommondeploymentstrategysetsupseveralauthoritativeserversinamaster/slaveconfiguration.Anadministratorupdatesthezoneinformationontheprimary,whichisidentifiedasthemaster;theinformationisthentransferredtooneormoreslavesactingassecondaryauthoritativeDNSservers.You'lllearnhowtosetthisupintheSettingupaslaveDNSserverrecipe,butfornowwe'llonlyfocusontheprimaryserver.

Theallow-transfersoptionliststheslavesystemsthisserverisallowedtorespondtowhenarequestisreceivedforzoneinformationtransfers,butsincewedon't(yet)haveasecondaryauthoritativeDNSserverconfigured,we'veusednonetodisabletransfers.Thishelpsto

Page 410: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

protectusfromaspecifictypeofdenialofserviceattack.ResourcerecordsaresmallenoughtofitinaUDPpacketortwoduringnormallookupactivity,butzonetransferstransmitalloftherecordsinbulkoverTCP.Malicioususersrepeatedlysendingtransferrequestsinquicksuccessioncansaturateyournetwork.

Thezone'sinformationisstoredinatextfileknownasazonefilewhoselocationisgivenwiththefileoption.Theconventionfollowedinthischapterplacesthefilesinazonedirectoryunder/var/namedandusesfwdandrevasfileextensionstoindicatewhetherthefileisaforwardlookuporareverselookupzonefile.Thus,ourfileissavedas/var/named/zones/example.com.fwd.

Thisrecipe'sfileisaforwardzonefilebecauseitmapsnamestotheirIPaddresses.Areverselookupzonemapstheinverserelationship,whichisaddressestonames.TheyarediscussedintheWritingareverselookupzonefilerecipe.

Note

I'veseenahandfulofdifferentconventionsfollowedwhenitcomestonamingzonefiles.Someadministratorsusezonorzoneasthefile'sextension.Somewillseparatethezonefilesinthedirectoriesnamedfwd-zoneandrev-zone.Honestly,itreallydoesn'tmatterwhatyoudoaslongasyoustayconsistentsystemctlrestartnamed.servicentandyourfilesarewellorganized.

$TTListhefirstdirectivegiveninthezonefileandgivesthedefaultlengthoftimearesolvingDNSservermaycacherecordsitreceivesfromtheauthoritativeserver.SpecificrecordsmayprovidetheirownTTL,whichoverridesthisdefaultvalue:

$TTL14400

The$ORIGINdirectiveprovidestheFQDNidentifyingthezone.Any@appearinginthefilewillbereplacedbythevalueof$ORIGIN:

$ORIGINexample.com.

Theremainingentriesarecollectivelycalledresourcerecordsandaremadeupofaseriesoffieldsintheordernamettlclasstypevalues.Thenamefieldgivesthenameoftheresourcethatownstherecord.Ifblank,itsvaluedefaultstothenameusedinthepreviousrecord.ttlisalsooptional,defaultingtothevalueof$TTL.Andforourpurposes,classwillalwaysbeINbecausewe'rewritingtheInternetresourcerecords.TheotherclassesareCHforChaosandHSforHesiodbuttheyaren'tinwidespreaduse.

Thefirstrecordinthefilemustbethestartofauthority(SOA)recordwhichidentifiesthatthisserveristheauthoritativeDNSserverforthezone.ThevaluesforaSOArecordarethenameoftheprimaryauthoritativeserverforthezone(wesuppliedns1),ane-mailaddressforthepersonresponsibleforthezone(hostmaster.example.com.),aserialnumber(2016041501),refreshduration(12h),retryduration(5m),expirationduration(2w),andthelengthoftime

Page 411: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

negativeresponses(sentwhentherequestedrecorddoesn'texist)fromtheservercanbecached(3h).Recordsareusuallywrittenassingle-lineentries,butparenthesespermitustosplittherecordoverseverallines:

;startofauthorityresourcerecord

@INSOAns1hostmaster.example.com.(

2016041501;serial

12h;refresh

5m;retry

2w;expire

3h);negativeTTL

The@variablethatwouldnormallyappearinthee-mailaddressesischangedtoadotinhostmaster.example.com.because@hasspecialmeaninginzonefiles.Alsonoticewhichnamesarefullyqualified.Namesthataren'tfullyqualifiedwillhavetheFQDNappendedautomatically,sons1isunderstoodasns1.example.com..Ifthee-mailaddress'sdomainpartwasn'tfullyqualifiedthenhostmaster.example.comwouldbetreatedashostmaster.example.com.example.com.,whichcertainlyisn'twhatwewant.

ValuesbeyondthatintheSOArecordareprimarilyofinteresttotheslaveDNSservers.Therefreshvalueinformstheslavehowoftenitshouldtrytorefreshitscopyofthezonefile.Theretrydurationtellstheslavehowlongitshouldwaitbetweenconnectionattemptsifthemasterisunreachable,andtheexpiryvaluespecifieshowlongtheslavecansatisfylookuprequestsasanauthoritativeserverwithitscopyofthezonefileifcontactwiththemasteriscompletelylost.ThenegativeTTListhelengthoftimearesolvershouldcachenegativeresponsesfromaDNSserver,forexample,NXDOMAINandNODATAresponses.

Theserialnumberisanarbitrarythat10-digitvalueslavescanusetodifferentiatethisversionofthezonefilefrompreviousversions.Anytimeyouupdatethefile,youmustalsoupdatetheserialnumber.Apopularconventionistousethecurrentdatefollowedbyasequencecounter.Forexample,April15,2016iswrittenas20160415andthentwoadditionaldigitsareaddedtoidentifymultipleupdatesduringthesameday(2016041501,2016041502,2016041503,andsoon).

Next,wegavetheNSrecordsthatidentifythezone'sauthoritativeDNSservers.TheSOAandNSrecordsaremandatoryineveryzonefile:

;nameserverrecords

INNSns1

INNSns2

ns1INA192.168.56.10

ns2INA192.168.56.20

TheNSrecordsidentifythenamesoftheauthoritativeservers.Intheprecedingexample,wedefinedn1andn2asthezone'sauthoritativeDNSserverswhichareunderstoodasns1.example.com.andns2.example.com.sincetheyarenotfullyqualified.TheArecordsmapanametoitsaddress(AAAAisusedforIPv6addresses).Therecordswewroteintheexamplesayns1.example.com.canbereachedat192.168.56.10andns2.example.com.canbereached

Page 412: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

at192.168.56.20.

Note

TheNSrecordsbelongtothezonebutIleftthefirstfieldoftheNSrecordsblanksincethefielddefaultstothenameusedinthelastrecord.Inthiscase,thenamehappenstobe@fromtheSOArecord(whichis$ORIGIN).Anyofthefollowingalternativesmeanthesameandareequallyacceptable:

@INNSn1

$ORIGININNSn1

example.com.INNSn1

However,becarefulbecausetheMXrecordsalsobelongtothezone.Aswebeginthenextsetofrecords,thelastnameisns2fromthatserver'sArecord.ThismeansthefirstMXrecordmustprovideeither@,$ORIGIN,orexample.com..

TheMXrecordsdefinethenamesoftheserversresponsibleforhandlinge-mailforthezone.Themailersareassignedarelativepreferenceandaclientwilltrytocommunicatewiththemailserverwiththelowestpreferencefirst.Iftheserverisunreachable,theclientattemptstoconnecttothenextlowestuntilitexhauststhelist:

;mailrecords

@INMX10mail

INMX20mail2

mailINA192.168.56.12

mail2INA192.168.56.22

Ourconfigurationdefinestheprincipalmailservermail.example.com.withtheIPaddress192.168.56.12andarelativepreferenceof10.Thesecondserver,perhapsabackupintheeventofanoutage,ismail2.example.com.at192.168.56.22withapreferenceof20.

Last,wedefinedrecordsthatidentifyourzone'swebserverandotheraliasesforthesystem:

;webserverrecords

@INA192.168.56.100

wwwINCNAME@

ftpINCNAME@

TheubiquityofwwwappearingatthebeginningofURLshaswanedsincethegoodolddaysofthedot-comera.Still,manyzonesresolvetheaddressesbothwithandwithoutwwwtothesameIP.Ourconfigurationdoesthesame,returning192.168.56.100forlookupsofbothexample.comorwww.example.com.ThisisaccomplishedbycreatingtheArecordthatmapsthedomaintothewebserver'saddressandthenaCanonicalName(CNAME)recordthataliaseswwwtothedomain'sArecord.OurconfigurationalsoaliasesftptotheArecordsothatuserscanuploadtheirsite'sfilestothewebserverusingtheaddressftp.example.com.

Page 413: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonrunningaDNSserverandmanagingyourdomain:

BIND9AdministratorReferenceManual(http://www.isc.org/downloads/bind/doc)FiveBasicMistakesNottoMakeinDNS(http://archive.oreilly.com/pub/a/sysadmin/2007/04/26/5-basic-mistakes-not-to-make-in-dns.html)BINDfortheSmallLAN(http://www.madboa.com/geek/soho-bind)RFC-1034:DomainConceptsandFacilities(https://tools.ietf.org/html/rfc1034)RFC-1035:DomainNames-ImplementationandSpecification(https://tools.ietf.org/html/rfc1035)RFC-1912:CommonDNSOperationalandConfigurationErrors(https://tools.ietf.org/html/rfc1912)

Page 414: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

WritingareverselookupzonefileUntilnowwe'vetreatedDNSrequestsasforwardfacinglookups,translatingresourcenameslikewww.example.comtoanIPaddress.However,servicescanalsoaskaDNSservertoresolveinformationintheoppositedirectionbyprovidinganIPaddressandwanttoknowwhatnameit'sassociatedwith.Reverselookupssuchastheseareespeciallyusefulforloggingorauthenticationandsecuritypurposes.Forexample,asystemcanqueryaDNSservertoverifythataclientreallyisconnectingfromthesystemtheyclaim.Toaccommodatesuchrequests,thisrecipeshowsyouhowtowriteareverselookupzonefile.

Page 415: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithBINDinstalledandconfiguredasdescribedinthepreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 416: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoaddareverselookupzone:

1. OpenBIND'sconfigurationfile:

vi/etc/named.conf

2. Addthefollowingzoneentry:

zone"56.168.192.in-addr.arpa."in{

typemaster;

file"/var/named/zones/example.com.rev";

allow-transfer{none;};

};

3. Saveyourchangesandclosetheconfigurationfile.4. Createthe/etc/named/zones/example.com.revfilewiththefollowingcontent:

$TTL1d

$ORIGIN56.168.192.in-addr.arpa.

;startofauthority

@INSOAns1.example.com.hostmaster.example.com.(

2016041501;serial

12h;refresh

5m;retry

2w;expire

3h);errorTTL

;nameservers

INNSns1.example.com.

INNSns2.example.com.

10INPTRns1.example.com.

20INPTRns2.example.com.

;mailservers

12INPTRmail.example.com.

22INPTRmail2.example.com.

;webservers

100INPTRexample.com.

100INPTRwww.example.com.

100INPTRftp.example.com.

5. Ensurethatthezonefilehasthecorrectownershipandaccesspermissions:

chownroot.named/var/named/zones/example.com.rev

chmod640/var/named/zones/example.com.rev

6. RestartBINDfortheconfigurationchangestotakeeffect:

systemctlrestartnamed.service

7. PerformareverseDNSlookupusingdigtotestthezone:

[email protected]

Page 417: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Reverselookupzonesarejustlikeanyotherzonesdefinedbyazonefile.So,hopefullynothinginthisrecipecameasabigsurprisetoyou.Nevertheless,therearestillafewpointsworthreviewing.

First,thezone'snameisconstructedbycombiningthenetwork'saddresswiththespecialdomainin-addr.arpa,whichisusedtodefinereverse-mappedIPaddresses(ip6.arpaisusedforIPv6).Theorderoftheaddress'soctetsisreversedtomaintainconsistencywithdomainnamesthatreadfromthemostspecifictothemostbroad.Thus,56.168.192.in-addr.arpa.istheFQDNforreverselookupsonaddressesinthe192.168.56/24addressspace:

zone"56.168.192.in-addr.arpa."in{

typemaster;

file"/etc/named/zones/example.com.rev";

allow-transfer{none;};

};

Note

Thisrecipenamesthezonefileasexample.com.revsothatitwillsortalongsidetheforwardzonefileexample.com.fwdindirectorylistings.Otherconventionsmightnamethefileas56.168.192.in-addr.arpa.zone.Again,regardlessofwhateverconventionyouchoose,thekeythingistobeconsistent.

Keepinmindtheexpansionandsubstitutionruleswe'vediscussedwhenwritingareversezonefile,mostimportantlythatpartiallyqualifiednamesareinterpretedinthecontextof$ORIGIN.WecangetawaywritingjusttheprimaryauthoritativeDNSserver'shostnameinaforwardlookupzone'sSOArecord,butweneedtomakesurethatthenamesarefullyqualifiedinareversefiletopreventthemfrombeingtreatedasns1.56.168.192.in-addr.arpa.:

;startofauthority

@INSOAns1.example.com.hostmaster.example.com.(

2016041501;serial

12h;refresh

5m;retry

2w;expire

3h);errorTTL

Apointerrecord(PTR)relatesanIPaddressbacktoaresourcename.ApartfromtheSOAandNSrecords(astheyaremandatoryrecordsinanyzonefile),theonlyothertypeofrecordthatcanappearinareversefileisPTR.AconsequenceofthisisthatmultiplerecordsareneededtocorrectlyinverseanyaliasescreatedwiththeCNAMErecordsintheforwardfile.Sinceweusedwwwandftpasaliasesforexample.com.,whichresolveto192.168.56.100,threerecordsfortheaddressappearsinthereversezonefileasfollows:

100INPTRexample.com.

100INPTRwww.example.com.

100INPTRftp.example.com.

Page 418: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Wecantestthezoneconfigurationwithdigusingthe-xargument:

[email protected]

-xletsdigknowthatwe'reperformingareverselookup.WeprovidetheIPaddressaswewouldnormallywriteitanddigwillreverseitsoctetsandappendthein-addr.arpadomainforuswhenitsendstherequest.

Page 419: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithreversezonesandlookups:

BIND9AdministratorReferenceManual(http://www.isc.org/downloads/bind/doc/)DNSReverseMapping(http://www.zytrax.com/books/dns/ch3/)Classlessin-addr.arpa.delegation(http://www.indelible.org/ink/classless)

Page 420: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SettingupaslaveDNSserverRedundancyisimportanttoensurekeyservicesremainavailableintheeventofanissue.AsDNSisoneofthemostcriticalcomponentsofanetwork,whetherit'saprivateintranetorthepublicInternet,havingonlyoneauthoritativeDNSserverisunwise.Infact,IANA'sTechnicalRequirementsforAuthoritativeNameServersdocumentstatesthattheremustbeaminimumoftwodifferentauthoritativenameserversforthezone.ThisrecipeshowsyouhowtoconfigureasecondBINDinstallationtoactasasecondaryauthoritativeserverthatreceivesitszoneinformationfromtheprimaryinamaster/slaveconfiguration.Alookuprequestcanthenbesatisfiedbyeitherserverandbeconsideredanauthoritativeresponse.

Page 421: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequirestwoCentOSsystemswithBINDinstalledandconfiguredasdescribedinearlierrecipes.UsethenetworkdescribedbytheConfiguringBINDasanauthoritativeDNSserverrecipe.Thisrecipeassumesthatthesystemtoserveasthemasterisconfiguredas192.168.56.10andtheslaveis192.168.56.20.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 422: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigureBINDasasecondaryauthoritativeDNSserverthatreceivesitszoneinformationfromtheprimary:

1. OnthesystemrunningtheslaveinstanceofBIND,opennamed.confandconfiguretheexample.com.zoneasfollows:

zone"example.com."in{

typeslave;

file"/var/named/slaves/example.com.fwd";

masters{192.168.56.10;};

allow-transfer{none;};

notifyno;

};

2. Configureitsreversezoneasfollows:

zone"56.168.192.in-addr.arpa."in{

typeslave;

file"/var/named/slaves/example.com.rev";

masters{192.168.56.10;};

allow-transfer{none;};

notifyno;

};

3. Saveyourchangesandclosethefile.4. Restarttheslavefortheconfigurationchangestotakeeffect:

systemctlrestartnamed.service

5. OnthesystemrunningthemasterinstanceofBIND,opennamed.conf.6. Updatetheexample.com.zone'sallow-transferentrywiththeaddressesoftheslave.

Thezone'sconfigurationshouldlooklikethis:

zone"example.com."in{

typemaster;

file"/var/named/zones/example.com.fwd";

allow-transfer{192.168.56.20;};

};

7. Makethesamechangetothereversezoneconfiguration:

zone"56.168.192.in-addr.arpa."in{

typemaster;

file"/var/named/zones/example.com.rev";

allow-transfer{192.168.56.20;};

};

8. Savethechangesandclosethefile.9. Restartthemasterfortheconfigurationchangestotakeeffect:

systemctlrestartnamed.service

10. Ontheslave,testtheconfigurationusingdigtorequestazonetransfer:

Page 424: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...SlaveserversrequestazonetransferwhennotifiedbytheprimaryauthoritativeDNSserverthatthezone'srecordshavechangedandwhenthecopyofthezonefilemaintainedbytheslaveexpiresaccordingtotheSOArecord.Inthisrecipe,webeganwithtwosystemsrunningBINDandeditedtheirconfigurationstoallowthetransfer.Webeganonthesystemtargetedastheslave,configuringboththeforwardandreverselookupzoneswe'veworkedwithearlier:

zone"example.com."in{

typeslave;

file"/var/named/slaves/example.com.fwd";

masters{192.168.56.10;};

allow-transfer{none;};

notifyno;

};

zone"56.168.192.in-addr.arpa."in{

typeslave;

file"/var/named/slaves/example.com.rev";

masters{192.168.56.10;};

allow-transfer{none;};

notifyno;

};

Thetypeslaveoptioninstructsthisservertoactasasecondaryserverforthezone.Sincedesignatingthemasterandslaveisdoneonaper-zonebasis,it'spossibleforthesameinstanceofBINDtobethemasterforonezoneandaslaveforanother.Themastersoptionprovidestheaddressoftheprimaryserver.

ThefileoptionprovidesthelocationwhereBINDwillwritethetransferredzoneinformation.Notonlyisitgoodfortheorganizationtokeepthetransferredzonesseparatefromanyprimaryzonefilesonthesystem,butit'salsogoodforsecurity.BINDneedswritepermissionstothedirectorytosavethetransferredfiles,buttheprimaryzonefilesshouldberead-onlytoanyoneexcepttheadministrator(thatis,root)asasafeguardfromanytampering.Ourconfigurationsavesthemto/var/named/slaves,whichwascreatedwhenweinstalledthebindpackageandalreadyhastheappropriatepermissions.

Theallow-transfersoptionliststhesystemsthisserverisallowedtorespondtoforzonetransferrequests.Toprotectourselvesfrompossibleabuse,wesetthevaluetonone,whichdisallowstransfersfromthesecondaryserver.AlltransferswillbeservicedbytheprimaryauthoritativeDNSserver,andeventhenitwillonlysendthemtotheslave.

BINDsendsanotificationtothesecondaryauthoritativeserverslistedinazone'sNSrecordseachtimethezoneisreloaded.There'snoreasonfortheslavetosendanotificationtoothersecondaries(ifyouconfiguremorethanoneslave)becausetheyarealreadynotifiedbytheprimary,soweturnedoffthisbehaviorwithnotifyno.

However,ifyouwantyoucansendnotificationstootherserversalongwiththoselistedinthezonefilewiththealso-notifyoption.Thisisusefulifyouhaveadditionalsecondaryservers

Page 425: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

whichyoudon'twanttomakepublicwithNSrecordsorifyouwanttonotifysomeotherautomatedprocess.Simplyprovidetheaddressesoftheserversyouwanttonotifywithalso-notify:

also-notify{192.168.56.200;192.168.68.200;};

Tonotifyonlythoseserverslistedinalso-notifyandnotthesecondaryauthoritativeservers,setnotifytoexplicit:

also-notify{192.168.56.200;192.168.68.200;};

notifyexplicit;

Next,weupdatedthemaster'sconfiguration,givingtheslave'saddresswithallow-transferstopermitthemastertorespondtozonetransferrequestsfromtheslave:

zone"example.com."in{

typemaster;

file"/var/named/zones/example.com.fwd";

allow-transfer{192.168.56.20;};

};

AfterrestartingBINDforourchangestakeeffect,wecantesttheconfigurationbyusingdigtorequestazonetransferfromthemasterwhileontheslavesystem:

[email protected]

Note

RemembertoincrementtheserialnumberintheSOArecordwheneveryouupdateazoneconfiguration.Theslavecheckstheserialbeforeupdatingitszoneinformationandwon'tupdateitifthevaluehasn'tchanged.

Page 426: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonconfiguringandworkingwithzonetransfers:

BIND9AdministratorReferenceManual(http://www.isc.org/downloads/bind/doc/)DNSforRocketScientists(http://www.zytrax.com/books/dns/)Technicalrequirementsforauthoritativenameservers(http://www.iana.org/help/nameserver-requirements)HowtheAXFRprotocolworks(http://cr.yp.to/djbdns/axfr-notes.html)APatternforDNSArchitecture(http://www.allgoodbits.org/articles/view/5)SecuringanInternetNameServer(http://resources.sei.cmu.edu/library/asset-view.cfm?assetid=52493)

Page 427: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringrndctocontrolBINDrndcistheclientutilityformanagingBINDservers.However,beforeyoucanuseit,bothrndcandBINDneedtobeconfigured.Thisrecipeshowsyouhowtoconfigurethemandthenshowsyouafewcommandsformanagingtheserver'scache.

Page 428: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithBINDinstalledandconfiguredasdescribedinthepreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 429: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoconfigurerndc:

1. Usetherndc-confgenutilitytogeneratethenecessarykeyfile:

rndc-confgen-a-c/etc/rndc.key

2. Createthe/etc/rndc.conffilewiththefollowingcontent:

include"/etc/rndc.key";

options{

default-key"rndc-key";

default-server127.0.0.1;

default-port953;

};

3. Ensurethecorrectownershipandaccesspermissionsforrndc.keyandrndc.conf:

chownroot.named/etc/rndc*

chmod640/etc/rndc*

4. Open/etc/named.confandaddthefollowingconfigurationsettingsaftertheclosingbraceoftheoptionsblock:

include"/etc/rndc.key";

controls{

inet127.0.0.1port953allow{127.0.0.1;}keys{

"rndc-key";};

};

5. RestartBINDfortheconfigurationchangestotakeeffect:

systemctlrestartnamed.service

6. TesttheconfigurationbyusingrndctorequestBIND'sstatus:

rndcstatus

Page 430: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...CommunicationbetweenrndcandBINDrequiresasharedkeyforauthorization.So,firstweusedrndc-confgentocreateone.Inanormaloperationwithoutarguments,theprogramgeneratesthekeyandnecessaryconfigurationfragmentsanddumpseverythingtothescreen.Youcancutandpastesectionsoftheoutputintotheappropriatefiles,butifyouonlyhaveaccesswithaterminalandkeyboardthenthiscouldprovedifficult.Instead,werantheprogramwith-aforittogeneratethekey'sdefinitionanddumpittoitsownconfigurationfileandwe'lltypetheotherconfigurationpiecesmanually.The-cargumentsimplyspecifiesourdesirednameforthekeydefinition'sfile:

rndc-confgen-a-c/etc/rndc.key

Note

Somepeoplereportthatrndc-confgenappearstocrashontheirsystem.Ifyouexperiencethis,themostlikelyreasonisthatit'swaitingforsufficientdatatogeneratethesecret,buttheentropypoolfor/dev/randomisstarvedwhichcausesrndc-confgentowait.Terminatetheprocessandtryagainusing-rtospecify/dev/urandomasanalternatesource:

rndc-confgen-a-c/etc/rndc.key-r/dev/urandom

Aquickpeekinside/etc/rndc.keyrevealsthekey'sdefinitionasfollows:

key"rndc-key"{

algorithmhmac-md5;

secret"YBmUKeobRMlAOUjCqMcb6g==";

};

rndcusesaconfigurationfileofitsown.So,nextwecreated/etc/rndc.conf:

include"/etc/rndc.key";

options{

default-key"rndc-key";

default-server127.0.0.1;

default-port953;

};

Weincludethekeydefinitionfromrndc.keyandspecifyitasthedefaultkeyforrndctouse.Wealsospecifiedthelocalloopbackaddressasthedefaultserverand953asthedefaultport.Withtheseconfigurationoptions,rndcattemptstoconnecttothelocallyrunningBINDserverwithouttheneedforustoprovideextraargumentsatthecommandline.

Last,weBINDtoallowandauthenticaterndc'sconnectionrequests.So,weagainincludethekeydefinitionandaddacontrolsblockinnamed.conf:

include"/etc/rndc.key";

controls{

inet127.0.0.1port953allow{127.0.0.1;}keys{"rndc-key";};

};

Page 431: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theinetstatementspecifieswhichaddressesareallowedtoconnectandthekeystheyneedtoauthenticate.ThefirstaddresslistswhichaddressBINDwilllistenonforconnectionrequests.Theconfigurationisintentionallyrestrictiveforthesakeofsecurityandonlyallowsustouserndclocally—BINDlistensonthelocaladdressandservicescommandssentfromthelocaladdress.

Ifyouwanttouserndcforremoteadministration,IrecommendyouagainstopeningaccessandinsteaduseSSHtologintotheremotesystemandit'scopyofrndc.BIND'scontrolchannelremainsclosedtoanyoneuptonogood,youdon'tneedtodistributecopiesofthekeyfile,andcommunicationbetweenthetwosystemsisencrypted:

ssh192.168.56.10rndcstatus

Note

Youcansavetypingbycreatinganalias:

aliasrndc-ns1="ssh192.168.56.10rndc"rndc-ns1status

Wheninvokedwithoutasubcommand,rndcdisplaysausagemessageenumeratingtheactionswecanperform.ThestatuscommandoutputsBIND'scurrentstatusincludinghowmanyzonesareconfigured,ifanyzonetransfersareinprogress,andinthecaseofaresolvingDNSserver,howmanyqueriesit'scurrentlytryingtoresolvethroughrecursion:

rndcstatus

rndcisusedtomanageBINDDNSservers

Youmayfindtheflushcommandusefulifyou'rerunningaresolvingDNSserver.ItremovesallofthecachedlookupinformationfromBIND'scache.Ifyouwanttoclearonly

Page 432: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

therecordsrelatedtoaparticulardomain,youcanuseflushname:

rndcflushnamegoogle.com

Thereloadandrefreshcommandsareusefulwithauthoritativeservers.ThereloadcommandcausesBINDtoreparsezonefilesafterthey'vebeenupdatedwithoutrestartingtheserver.Unlessaspecificzoneisgiven,allzoneswillbereloaded:

rndcreloadexample.com.

InthecaseofslaveDNSservers,wecanforceBINDtoupdateitscopyofazonefileifit'sstaleusingtherefreshcommand:

rndcrefreshexample.com.

Page 433: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonusingrndc:

Therndcmanualpage(man8rndc)RHEL7NetworkingGuide:BIND(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/sec-BIND.html)

Page 434: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter9.ManagingE-mailsThischaptercontainsthefollowingrecipes:

ConfiguringPostfixtoprovideSMTPservicesAddingSASLtoPostfixwithDovecotConfiguringPostfixtouseTLSConfiguringDovecotforsecurePOP3andIMAPaccessTargetingspamwithSpamAssassinRoutingmessageswithProcmail

Page 435: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionInthischapter,you'llfindrecipestohelpyousetupandsecuree-mailservicesforyourdomain.You'lllearnhowtosetupPostfixtorunasanSMTPserverandthenlearnhowtoconfigureittosupportSASLauthenticationandTLSencryption.Thenwe'llconfigureDovecotwhichwillprovideusersaccesstotheire-mailoverthePOP3andIMAPprotocols.Finally,you'lllearnhowtosetupSpamAssassinandProcmailtoreducetheamountofspamthatmakesitwaytoyourinbox.

Page 436: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringPostfixtoprovideSMTPservicesThisrecipeteachesyouhowtoconfigurePostfixasabasice-mailserverforyourdomain.E-mailisoneoftheoldestInternetservicesandhasbecomeoneitsmostpervasiveservices.Moreover,e-mailcanbeoneofthemostdifficultservicestomanage.

UsingtheSimpleMailTransportProtocol(SMTP),ane-mailmessagepassesthroughmanyprocessesfromitsstartingpointonitswaytoyourinbox.Whensomeonewritesyouamessage,theyuseane-mailclienttocomposethemessage.TheclientsendsthemessagetotheirmailserverwhichlooksuptheMXrecordsforyourdomainandrelaysthemessagetoyourmailserverfordelivery.Oncethemessageisreceivedbyyourmailserver,it'sdeliveredtoyourmaildirectoryontheserver.Atleastthat'sthebasicidea.Amessagecanberelayedbyanynumberofintermediateserversbetweenthesender'sserverandyourmailserver;serverscanbeconfiguredtosendmail,receivemail,orboth.Differentprotocolsareusedtoretrievethemessagesfromtheserver(POP3andIMAP)thanthoseusedtosendthem,andtryingtostayonestepaheadofspammerscanaddafairamountofcomplexity.

Note

Becauseofthecomplexityofthee-mailecosystemandbeingamailserveradministratorisoftenmorethanafull-timejob,Icanonlypresenttoyouthebasics.Laterrecipeswillteachyouhowtoaddauthenticationandencryptiontoyoursetup,therewillstillbemuchtoexploreandlearn.IstronglyrecommendthatyoutakeadvantageoftheadditionalresourcesmentionedintheSeealsosectionaftereachrecipe.

Page 437: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.You'llwanttohaveacoupleofuseraccountsavailableonthesystemfortestingpurposesaswell.

BecauseMXrecordsareusedtoresolvethemailserver'saddressduringthedeliveryprocess,it'sassumedthatyouhaveeithercompletedthepreviouschapter'srecipesorhave,otherwise,configuredyourownDNSrecords.TheIPaddress192.168.56.20isusedhereinkeepingwiththeexamplenetworkoutlinedintheConfiguringBINDasanauthoritativeDNSserverrecipeinChapter8,ManagingDomainsandDNS.

Page 438: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupPostfix:

1. UseatexteditortoopenPostfix'sconfigurationfile/etc/postfix/main.cf:

vi/etc/postfix/main.cf

2. Findtheexamplemyhostnameparameters.Deletetheleading#charactertouncommentoneoftheexamplesandupdateitsvaluewithyourqualifiedhostname:

myhostname=mail.example.com

3. Locatetheexamplemydomainparameteranduncommentandeditit,settingyourdomainnameasitsvalue:

mydomain=example.com

4. Findtheinet_interfacesparameters.Placean#infrontofthelocalhostentrytocommentitoutandthenuncommenttheallentry:

inet_interfaces=all

#inet_interfaces=$myhostname

#inet_interfaces=$myhostname,localhost

#inet_interfaces=localhost

5. Findthemydestinationparametersandcommentoutthefirstentry.Uncommenttheonethatincludes$mydomaininitslist:

#mydestination=$myhostname,localhost.$mydomain,localhost

mydestination=$myhostname,localhost.$mydomain,localhost,

$mydomain

#mydestination=$myhostname,localhost.$mydomain,localhost,

#$mydomainmail.$mydomain,www.$mydomain,ftp.$mydomain

6. Findtheexamplemynetworksparameters.Uncommentoneoftheentriesandedititsothatthevaluereflectsyournetwork:

mynetworks=192.168.56.0/24,127.0.0.0/8

7. Findtheexamplehome_mailboxparametersanduncommenttheentrywiththeMaildir/value:

home_mailbox=Maildir/

8. Saveyourchangesandclosethefile.9. StartthePostfixserverandoptionallyenableittostartautomaticallywheneverthe

systemreboots:

systemctlstartpostfix.service

systemctlenablepostfix.service

10. Openport25inthesystem'sfirewalltoallowoutsideconnectionstoPostfix:

Page 439: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

firewall-cmd--zone=public--permanent--add-service=smtp

firewall-cmd--reload

Page 440: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...CentOSsystemshavePostfixinstalledbydefault,usingitasalocalmailtransferagent.Toreconfigureittoactasourdomain'smailserver,weupdatedseveralparametersinitsconfigurationfile,/etc/postfix/main.cf.

First,weupdatedthemyhostnameparametertoprovideoursystem'squalifieddomainname(thehostnameanddomainname):

myhostname=mail.example.com

Note

CommentsintheconfigurationfilerefertoaFQDN,butweknowbetterbecauseFQDNsrequireatrailingdot.IfyoudoprovideatrueFQDNasthevalue,Postfixwillfailtostartstatingthattheparameter'svalueisbad.

ThemydomainparameterspecifiesthedomainthatthissystemisamemberofandthatPostfixishandlinge-mailfor.AlthoughPostfixwilltrytodeterminethedomainnamebasedonthesystem'squalifiedhostname,it'snotabadideatoexplicitlydefineitwithmydomaintobecertainit'scorrect:

mydomain=example.com

Theinet_interfaceparameteridentifiesthenetworkinterfacesthatPostfixwilllistenonforconnections.Theoriginalconfigurationacceptsconnectionsonlyfromthelocalhost;soweupdatedittolistenonallinterfaces,althoughyoumaywanttospecifysomethingmorespecificifyoursystemisconnectedtomultiplenetworks:

inet_interfaces=all

ThemydestinationparameterliststhezonesforwhichPostfixwillacceptmailforfinaldelivery.Wechangedtheoriginalconfigurationtoincludeourdomain:

mydestination=$myhostname,localhost.$mydomain,localhost,$mydomain

Ifnecessary,youshouldaddothervaluestothelisttoidentifyallofthesystem'shostnames,similartowhat'sshowninthelastexample,mydestination,intheset.ThisisimportanttopreventPostfixfromtryingtorelaymessagestoitself,thinkingthey'redestinedforadifferentdomainwhenthey'rereallynot:

mydestination=$myhostname,localhost.$mydomain,localhost,

$mydomain,mail.$mydomain,www.$mydomain,ftp.$mydomain

ThemynetworksparameteridentifiesthetrustednetworksPostfixcanrelaymessagesfor.ThisisthefirstlineofdefenseagainstspammersabusingyourmailserverbecausePostfixwillrefusetoacceptmessagesfordeliveryifthey'renotforourdomainandifthey'rereceivedfromasystemoutsideoneofthetrustednetworks:

Page 441: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mynetworks=192.168.56.0/24,127.0.0.0/8

Finally,wesetthemessages'deliverydestinationusingthehome_mailboxparameter:

home_mailbox=Maildir/

Messagesaretraditionallyappendedtotheuser'sfilein/var/spool/mailinwhatisknownasthemboxformat.TheMaildirformatstoresmessagesindividuallyinasubdirectoryintheuser'sMaildirdirectory.Postfixdeliversmailtothespoolbydefault.Wecanconvertmessagesbetweenthetwoformats,butchoosingMaildirnowmakesthingsabiteasierwhenweconfigureuseraccessoverIMAPinalaterrecipe.

OncePostfixisrestarted,wecansendatestmessagetoverifythattheserver'sconfigurationiscorrect.Thereareseveralwaystodothisofcourse.Theeasiestistouseacommand-linee-mailclientsuchasmailxtosendthemessage.mailxisn'tinstalledbydefaultbutisavailableviayum:

yuminstallmailx

Invokemailxtosendamessage.The-sargumentprovidesthemessage'ssubjectand-rprovidesthesender'saddress(yourowne-mailaddress).Thentherecipient'saddressfollowsafterthearguments:

[email protected]"Testemail"[email protected]

mailxreadsthemessagefromstdin.Asimple"helloworld"or"thisisatest"shouldbesufficientfortestingpurposes;whenyou'redonetyping,typeaperiodonitsownlineorpressCtrl+D:

Ifallgoeswell,mailxsendsthemailtoPostfixfordeliverywhichinturndeliversittotheuser'smaildirectoryin/home/<username>/Maildir/new.Checkthedirectoryandoutputthefile'scontentstomakesurethemessagewasdelivered:

ls/home/tboronczyk/Maildir/new

cat/home/tboronczyk/Maildir/new/146284221.Vfd00I188f5ceM9593.mail

Page 442: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Receivedmessagesaredeliveredtotheuser'sMaildirdirectory

Alternatively,wecanconnectdirectlytoPostfixusingaTelnetclient.Typingrawcommandstosendane-mailisslightlymoreinvolvedthansendingoneusingmailx,butispreferredbecauseitoffersyoumoreflexibilityandgreatervisibilityintohowPostfixresponds.Thiscanproveinvaluablewhentryingtotroubleshootaproblem.

NoTelnetclientisinstalledbydefault,sofirstyou'llneedtouseyumtoinstalltelnet:

yuminstalltelnet

Thenusetelnettoconnecttotheserveronport25,theportreservedforSMTP:

telnetmail.example.com25

TheMAILFROMcommandisusedtoprovidethesender'se-mailaddressandRCPTTOtoprovidetherecipient'saddress.Aftereachisentered,Postfixshouldrespondwitha250Okstatus:

MAILFROM:[email protected]

2502.1.0Ok

RCPTTO:[email protected]

2502.1.0Ok

DATAbeginsthemessage'scontent.Postfixacceptseverythingwetypeasthemessageuntilwe

Page 443: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

typeasingleperiodonitsownline:

DATA

352Enddatawith<CR><LF>.<CR><LF>

Subject:Testemail

Helloworld!Thisisatest.

.

2502.0.0Ok:queuedas705486E22E

Then,toclosetheconnection,typeQUIT:

QUIT

2212.0.0Bye

Connectionclosedbyforeignhost.

Page 444: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithPostfix:

RHEL7SystemAdministrator'sGuide:MailTransportAgents(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/s1-email-mta.html)RFC-5321:SimpleMailTransportProtocol(https://tools.ietf.org/html/rfc5321)MboxvsMaildir:MailStorageFormats(http://www.linuxmail.info/mbox-maildir-mail-storage-formats/)SetupaLocalMailServerinCentOS7(http://www.unixmen.com/setup-a-local-mail-server-in-centos-7)

Page 445: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AddingSASLtoPostfixwithDovecotIfamailserverrelaysamessagetoanotherdomain(thatis,therecipient'saddressisnotinourdomain)andthemessageoriginatesfromoutsideournetwork,theserverisknownasanopenrelay.Spammersareconstantlyonthelookoutforopenrelaysbecausesuchpermissivebehavioriseasytotakeadvantageof,andPostfixtriestoprotectusbydefaultbyonlyrelayingmessagesthatcomefromournetwork.Unfortunately,it'snotpracticaltorestrictlegitimateusersfromsendinge-mailthroughtheserveronlywhenthey'reonournetwork.ThisrecipeteachesyouhowtoaddSimpleAuthenticationandSecurityLayer(SASL)authenticationtoPostfix'sconfigurationusingDovecot.Postfixwillthenhappilyrelaymessagesforourusersauthenticatedusers,regardlessoftheirnetworklocation,whilestillrefusingtodosoforanyoneelse.

Page 446: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithPostfixconfiguredasdescribedinthepreviousrecipe.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 447: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosecurePostfixtoSASL:

1. Installthedovecotpackage:

yuminstalldovecot

2. Openthe/etc/dovecot/conf.d/10-master.conffilewithyourtexteditor:

vi/etc/dovecot/conf.d/10-master.conf

3. Locatetheunix_listenersectionfor/var/spool/postfix/private/auth.Uncommentthesectionbyremovingtheleading#characters:

#Postfixsmtp-auth

unix_listener/var/spool/postfix/private/auth{

mode=0666

}

4. Updatemodeto0660andaddtheparametersuserandgrouptothesectionwiththevaluepostfix:

#Postfixsmtp-auth

unix_listener/var/spool/postfix/private/auth{

mode=0660

user=postfix

group=postfix

}

5. Saveyourchangesandclosethefile.6. Openthe/etc/dovecot/conf.d/10-auth.conffilewithyourtexteditor:

vi/etc/dovecot/conf.d/10-auth.conf

7. Locatetheauth_mechanismsoptionandaddlogintoitsvalue:

auth_mechanisms=plainlogin

8. Savethechangesandclosethefile.9. StarttheDovecotserverandoptionallyenableittostartautomaticallywheneverthe

systemreboots:

systemctlstartdovecot.service

systemctlenabledovecot.service

10. Openthe/etc/postfix/main.cffilewithyourtexteditor:

vi/etc/postfix/main.cf

11. Attheendoftheconfigurationfile,addthefollowingoptionsandvalues:

smtpd_sasl_auth_enable=yes

smtpd_sasl_type=dovecot

smtpd_sasl_path=private/auth

smtpd_sasl_security_options=noanonymous

Page 448: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

12. Savethechangesandclosethefile.13. RestartPostfix:

systemctlrestartpostfix.service

Page 449: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Dovecotisaprimarilyamailretrievalserverofferingusersaccesstotheire-mailusingthePOPandIMAPprotocols,anditalsoallowsPostfixtohookintoitsSASLauthenticationmechanism.We'llneedaretrievalserverforuserstofetchtheire-mailfromthesystem,andDovecotandPostfixintegratenicely,sochoosingDovecotoverotheroptionsmakessense.

Dovecot'sconfigurationisorganizedintovariousfiles,eachfileaddressingaparticularfeatureorbitoffunctionality.Forthisrecipe,weneededtoupdatethemasterconfigurationfile/etc/dovecot/conf.d/10-master.confandtheauthenticationconfigurationfile/etc/dovecot/conf.d/10-auth.conf.

In10-master.conf,welocatedtheunix_listenerparameterthatdefinestheSMTPauthenticationservicethatwillbesharedwithPostfix.Uncommentingitwillcreatethesocketfile/var/spool/postfix/private/authoverwhichDovecotandPostfixwillcommunicate.Wethenupdatedthemodeparameterandaddedtheuserandgroupparameterstosecurethesocket'sownershipandaccesspermissions:

unix_listener/var/spool/postfix/private/auth{

mode=0660

user=postfix

group=postfix

}

In10-auth.conf,welocatedtheauth_mechanismparameterandaddedlogintoitsvalue.ThisparametersetsthelistofmechanismsDovecotuses,andloginisthemechanismusedspecificallyforSMTPauthentication:

auth_mechanisms=plainlogin

plainallowsuserstoprovidetheirusernameandpasswordinplaintext.loginisalsoconsideredaplaintextmechanism,butdon'tworry;you'lllearnhowtosecurethatinthenextrecipe.

ThefinalbitofconfigurationinvolvesaddingthenecessarySASL-relatedparameterstoPostfix'smain.cffile:

smtpd_sasl_auth_enable=yes

smtpd_sasl_type=dovecot

smtpd_sasl_path=private/auth

smtpd_sasl_security_options=noanonymous

smtpd_sasl_auth_enableenablesSASLauthenticationandsmtpd_sasl_typeinformsPostfixthatitwillbeusingDovecot'sauthenticationservice.Thesmtpd_sasl_pathparameterspecifiesthepathtothesocketfilethatisusedtocommunicatewithDovecotrelativetoPostfix'sworkingdirectory.smtpd_sasl_security_optionsprohibitsanonymousconnectionsandrequireseveryonetobeauthenticated.

Page 450: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

PostfixexpectstheusernameandpasswordtobeBase64encodedsothatweneedtoencodethembeforewecantestourconfigurationwithTelnet.base64canbeused,butbecarefulnottointroduceatrailingnewlinewhenyouprovidetheoriginalvalues.Afterinvokingbase64,youcanenteryourusernameorpasswordonstdinandimmediatelypressCtrl+Dtwice,butdonotpressEnter.Youmaywanttoredirectbase64'soutputtoaseparatefileyoucandumplatertomorereadilydistinguishtheencodedvaluefromtheoriginal,sincethey'llappeartoruntogetherintheterminalwithoutthenewline:

base64>./username

tboronczyk

base64>./password

P@$$W0rd

cat./username./password

Note

Despitethehassleof"newlinevigilance",thisapproachisbetterthanpipingthevalueasfollows:

echo-ntboronczyk|base64

Thecommand'sinvocationwillberetainedinyourshell'shistory.Whilethisisfineforusernames,sensitivedatasuchaspasswordsshouldneverbeprovidedonthecommandlineaspartofacommandforthisveryreason.

Afterconnectingtotheserverwithtelnetonport25,sendtheAUTHLOGINcommandtoinitiatetheauthentication.PostfixshouldrespondwithVXNlcm5hbWU6whichistheBase64encodedvalueforUsername::

AUTHLOGIN

334VXNlcm5hbWU6

ProvideyourencodedusernameandpressEnter.PostfixthenrespondswithUGFzc3dvcmQ6,which,asyouprobablyhavealreadyguessed,istheencodedversionofPassword:.Afteryouprovidetheencodedpassword,you'llbeinformediftheauthenticationwassuccessful:

Page 451: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheauthenticationexchangeexpectscredentialstobeBase64encoded

Page 452: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonPostfix,Dovecot,andSASL:

TheDovecotHomepage(http://www.dovecot.org/)RFC4422:SimpleAuthenticationandSecurityLayer(https://tools.ietf.org/html/rfc4422)PostfixSASLHow-To(http://www.postfix.org/SASL_README.html)25,465,587...WhatPortShouldIUse?(http://blog.mailgun.com/25-465-587-what-port-should-i-use/)

Page 453: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringPostfixtouseTLSImplementingauthenticationformailrelayingisanimportantstepinsecuringyourmailserver.Butasyoulearnedinthepreviousrecipe,theuser'snameandpasswordaresentincleartext.Base64-encodingencodesbinarydatausingonlyASCIIcharacters,whichallowsfornon-ASCIIcharactersinauser'spasswordforexample,butencodingisn'tencryption.Iftrafficbetweentheuser'smailclientandtheserverhappensoveranuntrustednetwork,amalicioususercaneasilycapturethecredentialsandmasqueradeastheuser.ThisrecipefurthersecuresPostfixbyconfiguringTransportLayerSecurity(TLS)encryptiontoprotectthecommunicationfromeavesdropping.

Page 454: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithPostfixconfiguredasdescribedinpreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 455: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigurePostfixtouseTLS:

1. Generateanewkeyfileandsecuritycertificatewithopenssl:

opensslreq-newkeyrsa:2048-nodes\

-keyout/etc/pki/tls/private/mail.example.key\

-x509-days730-subj"/CN=mail.example.com"-text\

-out/etc/pki/tls/certs/mail.example.pem

2. Useyourtexteditortoopenthe/etc/postfix/main.cffile:

vi/etc/postfix/main.cf

3. Attheendofthefile,addthefollowingoptionsandvalues:

smtpd_tls_security_level=may

smtpd_tls_cert_file=/etc/pki/tls/certs/mail.example.pem

smtpd_tls_key_file=/etc/pki/tls/private/mail.example.key

4. Saveyourchangesandclosethefile.5. RestartPostfix:

systemctlrestartpostfix.service

Page 456: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...AnencryptionkeyandasecuritycertificatethatconfirmstheownershipofthekeyareneededforSSL/TLScommunications.Aself-signedcertificateissufficientforpersonaluseorforusewithservicesonaprivatenetwork,sothisrecipeshowsushowtogeneratethisourselvesusingopenssl:

opensslreq-newkeyrsa:2048-nodes\

-keyout/etc/pki/tls/private/mail.example.key\

-x509-days730-subj"/CN=mail.example.com"-text\

-out/etc/pki/tls/certs/mail.example.pem

Thereqoptionmakesanewcertificaterequestand-newkeyasksopenssltogenerateanewprivatekeyandtousethatkeywhenitsignsthecertificate(thisiswhatwemeanwhenwesayself-signedcertificate).rsa:2048saysthekeywillbea2,048-bitRSAkey.2,048-bitkeysaregenerallyconsideredsufficientlyresistantagainstattacksuntilaroundtheyear2030basedonestimatesoftherateatwhichcomputingpowerincreases.3,072-bitkeysareconsideredsuitablebeyondthat.-nodespreventsthekeyfilefrombeingencryptedwithapassphrase.It'simportantnottoencryptthekeyfilewithapassphrasebecausePostfixneedstoaccessthekey.Ifitwereencrypted,we'dneedtoprovidethepassphrasetodecryptthekeyeverytimewestartPostfix.

-x509specifiesthatthecertificatewillbeanX.509certificate(thetypeusedbySSLandTLSconnections)and-dayssetsthecertificate'sexpirationdatetoanumberofdaysinthefuture,inthiscase730days(3years).-subjisusedtospecifythevalueforthecertificate'sCN(commonname)field,whichshouldbethehostnameortheIPaddressofthesystemthecertificateidentifies.Alternatively,youcanomittheargumentandopensslwillpromptyouinteractivelyforvaluesforanumberofotherfieldsaswell.Finally,the-textargumentspecifiesthatthecertificateshouldbeencodedastextasthisistheformatPostfixexpects:

Page 457: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Moreidentifyinginformationcanbeembeddedwithinacertificate

Aself-signedcertificatebasicallysays,here'smyencryptionkey.Youknowit'sminebecauseIsaidso.Ifyoursystem'sservicesareintendedforpublicconsumption,you'llmostlikelyneedtoinvestinacertificatesignedbyatrustedCertificateAuthority(CA).Trustedcertificatessay,youcantrustthekeyisminebecauseamutualfriendwillvouchforme.Toobtainatrustedcertificate,youneedacertificatesigningrequest(CSR):

opensslreq-new-newkeyrsa:2048-nodes\

-keyoutmail.example.key-outmail.example.csr

Then,yousendyourmoneyandtheCSRtotheCA.Afterashortwait,you'llreceiveyourcertificate.

Note

BydependingontheCAandthespecificsoftherequest,trustedcertificatescanbecomequiteexpensive.Andtrustisn'twhatitusedtobeeither.AscandaleruptedwhenitwasuncoveredthatemployeesataprominentCAweresigningforgedcertificates,reportedlyforinternaltestingpurposes.OnecanonlywonderatthelackofoversightgiventotheWeboftrust.Hopefully,theworstisbehindus.Browservendorsarestartingtopushforstricterguidelinesandmoreauditing.TherearealsoprojectssuchasLet'sEncryptwhichenablesecuretrustedcertificatestobeautomaticallygeneratedforfree.

Page 458: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Next,weaddedthenecessaryconfigurationparameterstoPostfix'smain.cffile:

smtpd_tls_security_level=may

smtpd_tls_cert_file=/etc/pki/tls/certs/mail.example.pem

smtpd_tls_key_file=/etc/pki/tls/private/mail.example.key

smtp_tls_security_levelconfiguresPostfix'senforcingbehaviorinrelationtotheencryptedconnection.mayenablesopportunisticTLS—theserveradvertisesthatencryptionandclientscantakeadvantageofitbutitsuseisnotrequired.Youmayalsosettheparametertoencrypttomaketheuseofencryptionmandatory.

smtpd_tls_cert_fileandsmtpd_tls_key_filespecifythepathstotheself-signedcertificateandtheencryptionkeywegeneratedearlier,respectively.Ifyou'reusingtrustedcertificatesthenyou'llalsoneedtoprovidethesmtpd_tls_CAfileparameterwithavaluethatidentifiesthesigningCA'spubliccertificate.

Ifyoufindthatnegotiatingthesecureconnectionisslow,thereareafewtuningparametersyoucantry.Forexample,wecanexplicitlyspecifythesourceofentropythatPostfixisusingwithtls_random_source:

tls_random_source=dev:/dev/urandom

Also,wecancachedetailsoftheencryptedsessionbetweentheserverandmailclient.Thesmtpd_tls_session_cache_databaseparameterdefinesthefileinwhichPostfixwillstorethecacheddetailsandsmtpd_tls_session_cache_timeoutspecifieshowlongthesessioncanbecached.Thisreducestheoverheadofestablishinganewsessioneachtimetheclientconnects:

smtpd_tls_session_cache_database=

btree:/var/lib/postfix/smtpd_tls_cache

smtpd_tls_session_cache_timeout=3600s

Totesttheconfiguration,youcanconnectusingtelnetandissuetheSTARTTLScommand.Postfixshouldrespondthatit'sreadytostartnegotiatingthesecureconnection:

STARTTLS

220ReadytostartTLS

Page 459: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesforworkingwithPostfixandTLS:

PostfixTLSSupport(http://www.postfix.org/TLS_README.html)Wikipedia:PublicKeyInfrastructure(https://en.wikipedia.org/wiki/Public_key_infrastructure)OpenSSLEssentials:WorkingwithSSLCertificates,PrivateKeys,andCSRs(https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)

Page 460: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringDovecotforsecurePOP3andIMAPaccessWhenyoucheckyoure-mail,thee-mailprogramconnectstoyourmailservertoseeifthereareanynewmessagesinyourmaildirectory.IfitsconfiguredtousedthePostOfficeProtocol(POP3),itdownloadsthemessageslocallyanddeletesthemfromtheserver.Ifit'sconfiguredtouseInternetMessageAccessProtocol(IMAP),themailremainsontheserverandyoumanageitremotely.

Dovecothandlesbothprotocolsoutofthebox.Sincewe'vealreadyinstalledDovecotforitsSASLfunctionality,wecouldjustopenthestandardportsforPOP3andIMAPtrafficinthesystem'sfirewallandbedone.However,theconnectionswouldbeunencryptedandinformationwouldbetransmittedacrossthenetworkinplaintext.ThisrecipeteachesyouhowtosecuretheseconnectionswithSSL.

Page 461: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithPostfixandDovecotconfiguredasdescribedinpreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 462: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconfigureaccesstoDovecot:

1. Open/etc/dovecot/dovecot.confwithyourtexteditor:

vi/etc/dovecot/dovecot.conf

2. Locatetheprotocolsparameter.Removetheleading#characterandsetitsvaluetoimapspop3s:

protocols=imapspop3s

3. Savethechangesandclosethefile.4. Open/etc/dovecot/conf.d/10-ssl.confwithyourtexteditor:

vi/etc/dovecot/conf.d/10-ssl.conf

5. Locatethesslparameterandsetitsvaluetoyes:

ssl=yes

6. Locatethessl_certandssl_keyparameters.Updatetheirvalueswiththepathstoyourcertificateandkeyfiles(notethatbothpathsareprecededwith<):

ssl_cert=</etc/pki/tls/certs/mail.example.pem

ssl_key=</etc/pki/tls/private/mail.example.key

7. Savethechangesandclosethefile.8. RestartDovecotforthechangestotakeeffect:

systemctlrestartdovecot.service

9. Openport993forIMAPoverSSLandport995forPOP3overSSLinthefirewall:

firewall-cmd--permanent--add-service=imaps\

--add-service=pop3s

firewall-cmd--reload

Page 463: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...DovecotmakesiteasytosecurethetrafficforPOP3andIMAPconnections;infact,configuringitonlytookafewseconds.Wefirsteditedtheprotocolsparameter/etc/dovecot/dovecot.conftoletDovecotknowthatwewanttheseprotocolstobesecured:

protocols=imapspop3s

Thenweupdated/etc/dovecot/conf.d/10-ssl.conftoenableSSLtousethesslparameterandtoidentifyacertificateandencryptionkeyusingssl_certandssl_key.SincePostfixandDovecotarerunningonthesamesystemandwealreadygeneratedakeyandcertificateforPostfix,wecanreferencethesamefilesinDovecot'sconfiguration.Dovecotusestheleading<infrontofthepathstospecifythatitshouldusethefile'scontentfortheparameter'svalueandnottheliteralstringitself:

ssl=yes

ssl_cert=</etc/pki/tls/certs/mail.example.pem

ssl_key=</etc/pki/tls/private/mail.example.key

Dovecotwillstillallownon-SSLaccesstoPOPandIMAP(onports110and143,respectively)fromconnectionsoriginatingfromthelocalhost,butoncewerestartitfortheconfigurationchangestotakeeffect,allotheruserswillneedtouseSSLtoaccesstheirmessages.

Wecanusemailxtotesttheconfiguration.First,we'llcheckPOP3:

mailx-fpop3s://[email protected]

The-fargumentspecifiesthedirectorythatmailxwillreadfromtoretrieveourmessages.GivenasaURI,thevalueinstructsmailxtoreadthedefaultdirectoryforouruseronthemail.example.comsystemusingPOP3overSSL(pop3s).

ThecommandisthesametocheckIMAPapartfromchangingtheURI'sprotocol:

mailx-fimaps://[email protected]

Becausewe'reusingaself-signedcertificate,mailxwillcomplainthatthecertificatehasnotbeenmarkedastrustedbytheuserandpromptuswhetherwewanttocontinue.Respondwithytothisandyou'llthenbepromptedfortheuser'spassword.mailxthendisplaystheuser'sinbox.Exittheprogrambyenteringquitattheprompt:

Page 464: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

mailxcanbeusedtotestourconfigurationofPOP3andIMAPoverSSL

Note

Ifmailxcomplainsthatit'smissingthenss-config-dirvariable,youcandefineitonthecommandlineusing-S.Thevalueshouldbeapathtothecertificatedatabasesthatmailxcanusetoverifycertificatetrust:

mailx-Snss-config-dir=/etc/pki/nssdb\

-fpop3s://[email protected]

WhenwefirstconfiguredPostfix,weadjusteditshome_mailboxparametertostoremessagesinseparatedirectories.Iacknowledgedthiswasoptionalatthattimebutitwouldmakethingseasierandcleanerwhenwesetupretrievalaccess.Ifyoudidn'tsethome_mailboxatthattime,incomingmessagesareappendedtotheuser'smailspoolfileunder/var/spool/mailandsomeadditionalconfigurationisnecessaryforDovecottoaccessthem.Thesechangescanbemadein/etc/dovecot/conf.d/10-mail.conf.

Alternatively,youcanconvertthespoolfiletoseparatemessagesinaMaildirdirectoryatthistime.First,installthemb2mdpackage:

yuminstallftp://ftp.pbone.net/mirror/atrpms.net/el7-

x86_64/atrpms/stable/mb2md-3.20-2.at.noarch.rpm

Openthe/etc/postfix/main.cffileandlocatethehome_mailboxparameter.Removetheleading#characterfromtheentrywiththevalueMaildir/:

home_mailbox=Maildir/

SaveyourchangesandthenrestartPostfixfortheupdatetotakeeffect.Then,foreachaccount,invokemb2mdtoconvertthespoolfile.Theutilityneedstoberunasthetargetuser,sousesutotemporarilyswitchtothatuser'scontext:

su-l-c"mb2md-m"tboronczyk

Page 465: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonthedifferenttopicsdiscussedinthisrecipe,includingDovecot,POP3,andIMAP.

Themailxmanualpage(man1mailx)TheDovecotHomepage(http://www.dovecot.org/)RFC3501:InternetMessageAccessProtocol(https://tools.ietf.org/html/rfc3501)RFC1939:PostOfficeProtocol(https://tools.ietf.org/html/rfc1939)ConvertingMboxMailboxestoMaildirformat(http://batleth.sapienti-sat.org/projects/mb2md/)

Page 466: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TargetingspamwithSpamAssassinSomeestimatesproposethatover90%ofalle-mailisunsolicitedadvertisements(spam)!Regardlessofwhethertheseestimatesarecorrectornot,there'snodenyingthatspamisahugeproblem.Unwantedmessagescauseextraloadonmailservers,consumestoragespace,andcanevenbeasecurityrisk.Also,whiletherehavebeenmanyattemptstolegallymanagespam,suchattemptshavelargelyfailed.

ThisrecipeteachesyouhowtosetupSpamAssassintoidentifyspammessages.SpamAssassinfiltersincomingmessagesbycheckingforvariousspamhallmarks,suchasmissingheadersandinvalidreturnaddresses,andusesheuristicstoanalyzethemessagecontent.Eachcheckcontributestothemessage'soverallspamscore,andifthisscoreexceedsthedefinedthresholdthenthemessageislabeledspam.

Page 467: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithPostfixconfiguredasdescribedinthepreviousrecipe.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 468: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoidentifyspamusingSpamAssassin:

1. Installthespamassassinpackage:

yuminstallspamassassin

2. StartSpamAssassinandoptionallyenableittostartautomaticallywheneverthesystemreboots:

systemctlstartspamassassin.service

systemctlenablespamassassin.service

3. CreateSpamAssassin'sBayesianclassifierdatabase:

sa-learn--sync

4. CreateanunprivilegedsystemuseraccountthatPostfixcanusetocommunicatewithSpamAssassin:

useradd-r-s/sbin/nologinspamd

5. OpenPostfix'smaster.cffileforediting:

vi/etc/postfix/master.cf

6. Locatethelinethatdefinesthesmtpserviceandappendthe-oargumentspecifyingspamassassinasacontentfilter:

smtpinetn-n--smtpd-ocontent_filter=spamassassin

7. Attheendoftheconfigurationfile,addthedefinitionforthespamassassinfilter:

spamassassinunix-nn--pipeuser=spamdargv=/usr/bin/spamc-e

/usr/sbin/sendmail-oi-f${sender}${recipient}

8. Saveyourchangesandclosethefile.9. RestartPostfixfortheupdatestotheconfigurationtotakeeffect:

systemctlrestartpostfix.service

Page 469: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...TheinitialinstallationofSpamAssassinisprettystraightforward.Weinstalledthespamassassinpackageandstartedandenabledthespamassassinservicewhichrunsthespamddaemon.Theclientprogramspamcisusedtocommunicatewiththedaemon,andtherestoftherecipe'sstepsfocusedonconfiguringPostfixtousespamctoscorethee-mailmessage.

WecreatedanewuseraccountnamedspamdforPostfixtousewhenitinvokesspamc.Theaccountisintendedtobeanoninteractivesystemaccount,soweprovidedthe-rargument.Thiscausesnohomedirectorytobecreatedandtheaccount'suserIDtobeassignedavaluelessthan100.The-sargumentgives/sbin/nologinastheaccount'sshelltopreventsomeonefromlogginginusingtheaccount:

useradd-r-s/sbin/nologinspamd

ForPostfixtopassmessagestoSpamAssassin,weneedtodefineanewspamassassinserviceinitsmaster.cfconfigurationfileandaskPostfixtousetheserviceasacontentfilter.Theorganizationofmaster.cfismuchdifferentfromtheconfigurationfileswe'veseenbefore—eachlinedefinesaprocessinthemaildeliverypipelineandcertainpropertiesaboutit.

Thefirstactiveentryinthefileisforthesmtpserviceandlookslikethis:

smtpinetn-n--smtpd

Thefirstcolumnisthenameoftheserviceandthesecondcolumnspecifieshowtheservicewillcommunicate.Forexample,inetsignifiesthattheprocessusesaTCP/IPsocketwhileunixsignifiesthatitusesalocalunix-domainsocket.Thenextthreecolumnsindicatewhethertheprocessisprivate(onlyaccessibletoPostfix),runswithoutadministrativeprivileges,andischrooted.Theirvaluescanbeyforyes,nforno,or-forPostfix'sdefaultvalue.Theremainingcolumnsprovideawakeuptimerforprocessesthatrunattimeintervals,thelimitforthenumberofinstancesthatcanberunningatthesametime,andthecommandthat'sinvokedtoprovidetheservice.

Tosetourspamassassinserviceasafilter,weupdatedthesmtpservice'scommandwiththe-ooptiontosetthecontent_filterparameterwiththenameofourservice:

smtpinetn-n--smtpd-ocontent_filter=spamassassin

Thenwedefinedthespamassassinserviceatthebottomofthefile:

spamassassinunix-nn--pipeuser=spamdargv=/usr/bin/spamc-e

/usr/sbin/sendmail-oi-f${sender}${recipient}

ThepipecommandispartofPostfix'sdeliverysystemwiththepurposeofpipingmessagestoexternalprocesses.Theuserargumentspecifiesthenameoftheuseraccounttheinvokedprocesswillrununderandargvisthecommandanditsargumentsthatwillberun.Ourdefinitionreferencesthespamduserwecreatedearlierandpipesthemessagetothespamc

Page 470: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

client.

Afterthemessageisreviewedbyspamd,spamcreturnsthemessagetostdoutbydefault.Toavoidlosingthemessage,wepipetheoutputtoanotherprocesstodeliverthemessage.-einstructsspamctopipetheoutputforhandling,inthiscasetoaprogramnamedsendmail.

Sendmailisanothermailserverthat'squiteolderthanPostfix.Itdominatedthee-maillandscapefordecades,andassuchmanyprogramsattempttointerfacewithittosendmail.ThisinstanceofsendmailisactuallyPostfix'sSendmailcompatibilityinterfacewhichallowsotherprocessestothinkthey'recallingSendmailwheninfactthey'rereallyworkingwithPostfix.The-oiargumentforsendmailinstructsthemailservertotreatlineswithasingledotasregularinputandnotinterpretitastheendofthemessage.The-fargumentsetsthefromaddressofthemessagetothevalueof${sender},aspecialvariablepopulatedbyPostfixwiththesender'se-mailaddress,andthemessageissentto${recipient},therecipient'se-mailaddress.

Totesttheconfiguration,wecansendane-mailmessagewiththefollowingsubject—it'saknownvaluethatSpamAssassinalwaysmarksasspam:

XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X

Ane-mailissentwithaknownsignatureinthesubjectlinetotestSpamAssassin

Whenyoucheckthemessageinyourinbox,you'llnoticethatSpamAssassinwillhaveprepended[SPAM]tothesubjectline,allowingyoutoeasilyidentifyunwantedmessages.Italsoaddsadditionalheaderstothemessagethatsummarizesitsfindingsthatleadittothe

Page 471: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

conclusionthatthemessageisspam:

SpamAssassinupdatesamessage'ssubjectlineandaddsadditionalheaderstoexplainwhyitthinksthemessageisspam

Keepinmindthattheworldofspamisconstantlyinflux;programmersareworkinghardtobuildbetterspamfilters,butspammersareworkingjustashardtofindwaystocircumventthem.Forthisreason,it'simportanttokeepSpamAssassin'sdatabaseuptodate.AcronjobisaddedwhenSpamAssassinisinstalledthatwillupdateitsdatabasedaily,butyoucanalsorunanupdatemanuallyanytimeyoulikebyrunning:

sa-update

IfSpamAssassinisfalselyidentifyingalargeamountoflegitimatemessagesasspamorviceversa,youcantrainit'sBayesianclassifiertobetteridentifyunwantedmessagesusingsa-learn.Wecanprovideacollectionofmessagesweknowarespamandidentifythemassuch

Page 472: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

withthe--spamargument,andgoodmessageswith--hamfortheprogramtostudy:

sa-learn--ham/home/tboronczyk/Maildir/cur

sa-learn--spam/home/tboronczyk/Mail/.Spam

sa-learnkeepstrackofthemessagesit'sseen.Ifyouhavepreviouslyindicatedthatamessageisspamandthenlateruseitasham,theprogramwillremoveitfromitsspamdatabase,andviceversaifyouindicateane-mailisgoodbutlaterdecideitshouldbeusedasspam.

Page 473: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithSpamAssassin:

Thesa-learnmanualpage(man1sa-learn)SpamAssassinHomePage(http://spamassassin.apache.org/)RumSpamAssassinwithPostfix(http://howto.gumph.org/content/run-spamassassin-with-postfix/)StopSpamonyourPostfixServerwithSpamAssassin(https://www.linux.com/learn/stop-spam-your-postfix-server-spamassassin)BayesTheoremExplainedLikeYou'reFive(https://www.youtube.com/watch?v=2Df1sDAyRvQ)

Page 474: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RoutingmessageswithProcmailDependingonyourpreferences,taggingmessagesasspammaynotbeenough.Maybeyou'llwanttosetuparuleinyoure-mailclientthatmovesanyunwantedmessagesfromyourinboxtoadedicatedspamdirectory.Ormaybeyouwantsuchroutingtohappenautomaticallyontheserver.WecanconfigurethisusingProcmail,amailfilteringanddeliveryagent.

Inthisrecipe,we'lllookathowtoconfigureProcmailtoroutemessages.We'llscanincomingmail,lookingforaspecialheaderthatSpamAssassinaddstomessagesifitthinksthey'respamandthendeliverthemtoaseparatedirectoryinsteadoftheinbox.

Page 475: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithPostfixconfiguredasdescribedinthepreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 476: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupProcmailtoroutemessages:

1. Createthe/etc/procmailrcfilewiththefollowingcontent:

MAILDIR=$HOME/Maildir

DEFAULT=$MAILDIR/new

INCLUDERC=/etc/mail/spamassassin/spamassassin-spamc.rc

:0

*^X-Spam-Status:Yes

.Spam

2. Createeachuser'sspamdirectory:

echoSpam>>/home/tboronczyk/Maildir/subscriptions

mkdir/home/tboronczyk/Maildir/.Spam

3. Ifyoucreatedtheuser'sspamdirectoryasroot,fixthedirectoryandsubscriptionfile'sownershipandpermissions:

chowntboronczyk/home/tboronczyk/Maildir/subscriptions

chmod0600/home/tboronczyk/Maildir/subscriptions

chowntboronczyk.tboronczyk/home/tboronczyk/Maildir/.Spam

chmod0700/home/tboronczyk/Maildir/.Spam

4. OpenPostfix'smain.cfconfigurationfilewithyoureditor:

vi/etc/postfix/main.cf

5. Locatetheexamplemailbox_commandparameters.Uncommentthesecondexampleandcorrectitspathtotheprocmailexecutable:

mailbox_command=/bin/procmail-a"$EXTENSION"

6. Savethechangesandclosethefile.7. RestartPostfixfortheupdatedconfigurationtotakeeffect:

systemctlrestartpostfix.service

Page 477: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...LikePostfix,ProcmailisinstalledbydefaultonCentOSsystems.However,weneedtocreateitsconfigurationfileforittobeusefultous.Themainconfigurationfileis/etc/procmailrcandwestartitbydefiningtheMAILDIR,DEFAULT,andINCLUDERCvariables.

MAILDIR=$HOME/Maildir

DEFAULT=$MAILDIR/new

INCLUDERC=/etc/mail/spamassassin/spamassassin-spamc.rc

MAILDIRprovidesthelocationoftheuser'smaildirectory.procmailrcisaglobalconfigurationfileandweuse$HOMEtodenotetheuser'shomedirectoryinwhichMaildirresides.DEFAULTprovidesthedefaultlocationforincomingmail,whichisthemaildirectory'snewdirectory.

INCLUDERCgivesthenameofotherfilesthatshouldbeincludedwhenProcmailprocessestheconfigurationfile.Inthiscase,SpamAssassininstallsaconfigurationfiletointegratewithProcmailwhichwereference.

Thesecondpartoftheconfigurationappearsasacrypticincantation—thedefinitionofamatchingrule.InProcmailparlance,they'recalledrecipes:

:0

*^X-Spam-Status:Yes

.Spam

Morethanonerulecanbegivenintheconfigurationfile,inwhichcasetheyareprocessedintheorderinwhichtheyappear,toptobottom.

Allrulesbeginwith:0andcontainconditionsfollowedbyanaction.Here,theconditionstartswith*tospecifyaregularexpressionpatternthatProcmailwillsearchthemessageanditsheadersfor.Theactionlinethenliststhedirectorythatmatchingmessageswillbedeliveredto.Ifit'sgivenasarelativepath,thedirectoryconsideredwillberelativeto$MAILDIR.Thus,theruleasksProcmailtorouteanymessagesflaggedwiththeX-Spam-StatusheaderbySpamAssassintotheuser'sMaildir/.Spamdirectory.

TheoriginalMaildirspecificationonlyallowsthenew,cur,andtmpdirectories,butothershaveaugmentedittosupportadditionaldirectories.Theusercaneithercreatetheirspamdirectorythroughtheire-mailclientoverIMAP,inwhichcaseallofthedetailsareworkedoutbyDovecot.Alternatively,wecancreateitfortheminthefilesystem.Whenwecreateadirectorymanually,thesubscriptionsfilemustlisttheadditionaldirectories,oneentryperline,forthemtobevisibleintheuser'smailclient.Thedirectoriesthemselvesarethennamedwithaleadingdot:

echoSpam>>/home/tboronczyk/Maildir/subscriptions

mkdir/home/tboronczyk/Maildir/.Spam

Page 478: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Procmailalsoallowsforper-useractionsaswell.Forexample,ifonlyoneuserwantstohaveflaggedmessagesmovedtotheirspamfolder,thematchingrulecanbemovedfromtheglobalconfigurationunder/etctoafilenamed.procmailrcintheirhomedirectory.It'sstillrecommendedthatyoukeepthevariabledefinitionsintheglobalconfigurationsothatthey'llbeavailabletoallusers,asProcmailexecutestheglobalfilefirstandthentheuser'slocal.procmailrcifit'savailable.

Variousflagscanbegivenafter:0thatmodifyhowProcmailbehavesorhowtheruleisinterpreted.Forexample,Procmailonlysearchthemessage'sheadersbydefault.Tosearchthemessage'sbody,weneedtoprovidetheBflag.Thefollowingruleisanexamplethatsearchesthemessage'sbodyforthetext"HelloWorld"androutesthematchingmessagesto/dev/null:

:0B

*HelloWorld

/dev/null

Someflagsyoumayfindusefulare:

H:Searchthemessage'sheadersB:Searchthemessage'sbodyD:Matchtheregularexpressioninacase-sensitivemannere:Onlyexecutetheruleiftheruleimmediatelyprecedingitwasunsuccessfulc:Createacopyofthemessageh:Onlysendthemessage'sheadertoapipedprogramb:Onlysendthemessage'sbodytoapipedprogram

Iftheactionbeginswith|thenthevalueisinterpretedasacommandandthemessageispipedtoit.Here'sanexamplethatsendsacopyofanymessagesreceivedfromthehumanresourcesdepartmenttotheprinterbypipingitthroughlpr:

:0c

*^From:[email protected]

|lpr

Iftheactionbeginswith!thenthevalueisseenasane-mailandthemessageisforwarded.Thisexampleroutesane-mailfromaknownrecipienttoapersonale-mailaccountinstead:

:0

*^From:[email protected]

[email protected]

Page 479: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonProcmail:

Theprocmailmanualpage(man1procmail)Theprocmailrcfilemanualpage(man5procmailrc)Timo'sPromailtipsandrecipes(http://www.netikka.net/tsneti/info/proctips.php)

Page 480: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter10.ManagingWebServersThischaptercontainsthefollowingrecipes:

InstallingApacheHTTPServerandPHPConfiguringname-basedvirtualhostingConfiguringApachetoservepagesoverHTTPSEnablingoverridesandperformingURLrewritingInstallingNGINXasaloadbalancer

Page 481: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionThischaptercontainsrecipesforworkingwiththeApacheHTTPServertoservewebsites.You'llfirstlearnhowtoinstalltheserveraswellasPHP,averycommonserver-sidescriptingengineusedtogeneratedynamicwebcontent.Thenyou'llseehowtoservemultiplesiteswiththesameserverinstanceusingname-basedvirtualhosting,encrypttheconnectionandservecontentoverHTTPS,andhowtorewriteincomingURLsonthefly.We'llfinishwithlookingatNGINXanditsuseasareverseproxytodecreaseloadontheserverwhileatthesametimespeedingupaccesstooursitesfortheuser.

Page 482: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingApacheHTTPServerandPHPYoumayhaveheardtheacronymLAMPwhichstandsforLinux,Apache,MySQL,andPHP.Itreferstothepopularpairingoftechnologiesforprovidingwebsitesandwebapplications.ThisrecipeteachesyouhowtoinstalltheApacheHTTPServer(Apacheforshort)andconfigureittoworkwithPHPtoservedynamicwebcontent.

Firstreleasedovertwentyyearsago,Apachewasoneofthefirstwebserversanditcontinuestobeoneofthemostpopular.ItstaskintheLAMPstackistointeractwiththeuserbyrespondingtotheirrequestsforwebresources.Perhapsoneofitssellingpointsisitsdesignthatallowsitsfunctionalitytobeexpandedwithmodules.Manymodulesexist,frommod_ssl,whichaddsHTTPSsupporttomod_rewrite,whichallowsyoutomodifytherequestURLonthefly.

PHPisascriptinglanguageforcreatingdynamicwebcontent.ItworksbehindthescenesandtheoutputofascriptisusuallyservedbyApachetosatisfyarequest.PHPwascommonlyinstalledasamodule(mod_php)thatembeddedthelanguage'sinterpreterintoApache'sprocessing,butnowadays,runningPHPasastandaloneprocessispreferred.Thisistheapproachwe'lltakeinthisrecipe.

Page 483: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatthesystemisconfiguredwiththeIPaddress192.168.56.100.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

NotethattheofficialCentOSrepositoriesinstallPHP5.4.TheRemirepositoriesoffer5.5,5.6,and7.0ifyouwanttoinstallanewerrelease.Toinstalloneofthe5.xversions,openthe/etc/yum.repos.d/remi.repofile,locatetheenabledoptioninthe[remi-php55]or[remi-php56]sectionandsetitsvalueto1.For7.0,updatetheenabledoptionfoundin/etc/yum.repos.d/remi-php70.repo.

Note

WhathappenedtoPHP6?It'salongstory....TheteamofvolunteersdevelopingPHPwasworkingonversion6,buttheinitiativefacedmanyhurdlesandwaseventuallyshelved.TopreventconfusionbetweenthelatestreleaseandanyblogpostingsthatwerewrittenaboutPHP6,itwasdecidedthatitsversionnumberwouldbebumpedto7.Inshort,PHP6didexistbutneverachievedaproperreleasestatusandmostofthecoolfeaturesplannedfor6madeitintoPHP5.3,5.4,and7.0.

Page 484: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallApacheHTTPServerandPHP:

1. Installthehttpdandphp-fpmpackages:

yuminstallhttpdphp-fpm

2. OpenApache'sconfigurationfilewithyourtexteditor:

vi/etc/httpd/conf/httpd.conf

3. LocatetheServerNameoption.Remove#appearingatthestartofthelinetouncommentitandthenchangetheoption'svaluetoreflectyourserver'shostnameorIPaddress:

ServerName192.168.56.100:80

4. FindtheDirectoryIndexoptionandaddindex.phptothelist:

<IfModuledir_module>

DirectoryIndexindex.htmlindex.php

</IfModule>

5. Attheendofthefile,addthefollowingconfiguration:

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$

fcgi://127.0.0.1:9000/var/www/html/$1

</IfModule>

6. Saveyourchangestotheconfigurationandclosethefile.7. Verifythatmod_proxy(listedasproxy_module)andmod_proxy_fcgi

(proxy_fcgi_module)extensionmodulesareenabled:

httpd-M|grepproxy

8. Bothmodulesshouldappearintheoutput.9. StartApacheandPHP'sFPMserviceandenablethemtostartautomaticallywhenyour

systemreboots:

systemctlstarthttpd.servicephp-fpm.service

systemctlenablehttpd.servicephp-fpm.service

10. Openport80inthesystem'sfirewalltoallowHTTPrequeststhrough:

firewall-cmd--zone=public--permanent--add-service=http

firewall-cmd--reload

Page 485: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThereareseveralwaystointegratePHPwithApache'sHTTPservertogeneratedynamicwebcontent.Historically,usingApache'smod_phpmodulewasthewaytogo,butnowthepreferredapproachistorunPHPasaseparateprocess,whichthewebservercommunicateswithusingtheFastCGIprotocol.So,weinstalledthehttpdpackagefortheApacheHTTPServerandthephp-fpmpackageforthePHPinterpreteranditsprocessmanager:

yuminstallhttpdphp-fpm

ThePHPFastCGIProcessManager(FPM)isincludedinthecorePHPdistributionsasofversion5.3.SeparatingPHPfromApacheencouragesamorescalablearchitecture,andusingapersistentPHPprocessreducesCPUoverheadbecauseanewinterpreterdoesn'thavetobespawnedforeachrequest.

Apache'smainconfigurationfileis/etc/httpd/conf/httpd.conf,inwhichweupdatedtheServerNameoptiontoreflectourserver'shostnameorIPaddress.Whilethisstepisn'tstrictlynecessary,ifwedon'tsettheoptionthentheserverwillwritewarningmessagestoitslogfiles.Besides,it'susefulfortheservertobeabletoidentifyitself:

ServerName192.168.56.100:80

Next,weupdatedfortheDirectoryIndexoptionbyaddingindex.phptoitslistofvalues.Whentheuserrequestsaresourcethatresolvestoadirectory,theserverwilllookinthatdirectoryforafilethatmatchesoneofthenamesintheDirectoryIndexlist.Iffound,Apachewillreturnthatfiletosatisfytherequest.Thisbehavioriswhatallowsvisitorstoaccessawebsite'shomepagewithaURLsuchaswww.example.comratherthanwww.example.com/index.html:

DirectoryIndexindex.htmlindex.php

Theorderinwhichfilesarelistedissignificant.Forexample,ifbothindex.htmlandindex.phpexistinthedirectorythenindex.htmlwillbereturnedbecauseit'slistedbeforeindex.phpintheoption'slist.

Thenwenavigatedtotheendofthefiletoaddthefollowingproxyconfiguration.IftheregularexpressionofProxyPassMatchmatchestheincomingrequestthentheserverretrievesthegivenURLandreturnsthatcontentinstead:

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$fcgi://127.0.0.1:9000/var/www/html/$1

</IfModule>

Regularexpressionsarewrittenusingaspecialnotationthatdescribeshowtomatchtext.Mostcharactersarematchedliterally,butsomehavespecialmeaning:

.:Thismatchesanycharacter.Thepatternbu.matchesagainstthetextbud,bug,bun,

Page 486: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

bus,andsoon.+:Thismatchestheprecedingelementoneormoretimes.Thepatternfe+tmatchesfet,feet,andfeeetandsoonbutnotft.*:Thisoptionallymatchestheprecedingelementanynumberoftimes.Thepatternfe*tmatchesft,fet,feet,feeet,andsoon.?:Thisoptionallymatchestheprecedingelementonce.Thepatterncolou?rmatchescolorandcolour.^:Thisanchorsthematchtothebeginningoftheline.Thepattern^abconlymatchesabcifabcappearsatthebeginningofthetext(^hasspecialsignificancewhenusedin[]).$:Thisanchorsthematchtotheendoftheline.Thepatternxyz$onlymatchesxyzifxyzappearsattheendoftheline.[]:Thismatchesanyofthecharactersgivenwithinthebrackets.Thepatternco[lr]dmatchescoldandcord.Whenthefirstcharacterin[]is^thenthelistisnegated;co[^lr]dmatchescoedbutnotcoldorcord.():Thisgroupselementsandcapturesmatches.Thepatternjump(ed)?matchesjumpandjumped.

Ifyouwantanyofthesespecialcharacterstobematchedliterallythenyoushouldescapethemwithaleadingbackslash,forexamplefoo\.htmlwillmatchfoo.htmlinsteadoffooahtml,foobhtml,andsoon.

Specialnumericvariableslike$1and$2containthevalueofanycapturedmatches.Theorderinwhichtheyarepopulatedaretheorderinwhichtheparenthesescaptureamatch,thus(foo)\.(html)sets$1tofooand$2tohtml.

Withthisunderstanding,youshouldnowbeabletodecipherthattheregularexpression^/(.*\.php)$capturesthepathandfilenameoftherequestedresourcethatendwiththeextension.php.The$1variablerepresentsthecapturedpath,soarequestfor/about/staff.phpwillbeproxiedasfcgi://127.0.0.1:9000/var/www/html/about/staff.phpwherePHP'sFast-CGIlistenerislisteningtothelocalinterfaceonport9000.

Apache'sfunctionalityisoftenextendedthroughmodules,andasasafeguardit'sagoodpracticetowrapmodule-specificconfigurationoptionsinanIfModuleblock.Theopeningofsuchblockscontainthenameofthemoduleandappearinanglebrackets<>.Theblock'sclosingappearsas</IfModule>justlikeclosinganHTMLelement.

ThedirectoryoutofwhichtheserverservesfilesfromissetbytheoptionDocumentRoot.Thedefaultvalueis/var/www/html,soanyfilesweplacethereorinasubdirectorywithinitwillbeaccessible.Asanexampletoillustratethis,thedistributionincludesasampleindex.htmlfile,whichwecanusetoverifythattheserverisrunningcorrectly;copythe/usr/share/httpd/noindex/index.htmlfileto/var/www/html:

cp/usr/share/httpd/noindex/index.html/var/www/html

Then,openyourbrowserandnavigatetothedomainorIPaddressofthesystem.Youshould

Page 487: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

seethewelcomepage:

YoucancopyApache'sdefaultindexpagetothewebdirectorytotestwhethertheserverisupandrunning

Page 488: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ForPHP,youneedtoplaceaPHPfilewhereitcanbereadbytheFast-CGIservice.TheproxyURLisfcgi://127.0.0.1:9000/var/www/html/$1,sothatwecanplaceourPHPfilesin/var/www/htmlaswell.

Createtheinfo.phpfilewiththefollowingcontent:

<?php

phpinfo();

Nowsavethefileandthennavigatetothepageinyourbrowser.YoushouldseetheoutputofPHP'sphpinfo()functionprovidingdetailedinformationonhowPHPisconfiguredandwhichofitsmodulesareavailable:

Page 489: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

PHPreportsinformationaboutitsenvironmentandtherequest

Note

Forsecuritypurposes,it'srecommendedthatyoudeletethewelcomeindex.htmlfileifyoucopieditoverandtheinfo.phpscriptafteryouverifyeverythingworks.Theinformationtheypresentcangivemalicioususersmoreinformationaboutthesetupofyourwebserver

Page 490: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

thanyou'dlikethemtohave.

Page 491: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithApacheandPHP:

ApacheHTTPServerProject(http://httpd.apache.org/)ThePHPhomepage(http://php.net/)Apachemod_proxy_fcgidocumentation(http://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html)HttpdWiki:PHP-FPM(http://wiki.apache.org/httpd/PHP-FPM)RFC-2616:HTTP/1.1(http://www.rfc-base.org/txt/rfc-2616.txt)

Page 492: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Configuringname-basedvirtualhostingAsyoumayrecallfromourdiscussionssurroundingDNSinChapter8,ManagingDomainsandDNSauser'sbrowserneedstotranslateawebsite'shostnametoitsIPaddressviaDNSlookupsbeforeitcanconnectandretrievethedesiredwebcontent.Youmayalsorecallthatthisdoesn'thavetobeaone-to-onemapping-morethanonesitecanresolvetothesameIPaddress.Apacheisflexibleenoughsothatthesameservercanservemorethanonesitebyaconfigurationknownasname-basedvirtualhosting.

Thisrecipeteachesyouhowtosetupname-basedvirtualhosting.Eachsitehasit'sownconfiguration(oftenkeptinitsownconfigurationfileforbetterorganization).Basedonthesitenamethatappearsintherequest,Apachethenselectsfromtheavailableconfigurationstoproperlyservethedesiredsite.

Page 493: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandrunningApacheasdescribedinthepreviousrecipe.Becausewe'llbeconnectingtotheserverviaadomainnameinsteadofanIPaddress,you'llneedtomakesurethenameresolvestothecorrectaddressbyupdatingyourDNSrecordsoraddingentriesto/etc/hostsfirst.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 494: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstosetupname-basedvirtualhosting:

1. OpenApache'sconfigurationfilewithyourtexteditor:

vi/etc/httpd/conf/httpd.conf

2. Atthebottomofthefile,addthefollowingIncludeoption:

Includesites/*.conf

3. Savetheupdatedconfigurationandclosethefile.4. Createthesitesdirectoryreferencedintheconfiguration:

mkdir/etc/httpd/sites

5. Createavirtualhostconfigurationfilewithinthenewsitesdirectoryforyourfirstsite:

vi/etc/httpd/sites/www.example.conf

6. Addthefollowingcodetothesite'sconfigurationfile:

<VirtualHost*:80>

ServerNamewww.example.com

DocumentRoot"/var/www/example.com/www/html"

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$

fcgi://127.0.0.1:9000/var/www/example.com/www/html/$1

</IfModule>

</VirtualHost>

7. Saveyourchangesandclosethefile.8. Createthesite'sdocumentrootreferencedintheconfigurationoptions:

mkdir-p/var/www/example.com/www/html

9. Repeatsteps4-8foreachadditionalsiteyouwillbehosting,usingthehostordomainnametocreateauniquedirectorypathforeachsite.

10. RestarttheHTTPserverfortheconfigurationchangestotakeeffect:

systemctlrestarthttpd.service

Page 495: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ConfiguringApachetoservemultipledomainsisamatterofcreatingaVirtualHostdefinitionforeachsite.Thisrecipeorganizesthedefinitionsintheirownfileunderthedirectory/etc/httpd/sitesandthenreferencestheminthemainhttpd.confconfigurationfileusinganIncludedirective:

Includesites/*.conf

Howyouorganizeyoursitesisuptoyou.Thisrecipeusesaschemewhereeachsiteisservedfromapathbasedonthedomainnamefollowedbythesubdomainrootedin/var/www.Thepath/var/www/example.com/www/htmlcontainsthefilesforthesiteatwww.example.com.Filesforthesiteatweb.example.comwouldbeplacedin/var/www/example.com/web/html.Thehtmldirectoryissimplytheweb-accessiblerootforthesite.Byincludingitinsteadofservingfilesoutofexample.com/wwwdirectly,wecanplaceanysupportingfilesoutsidetherootwhicharen'tmeantobeaccesseddirectly(forexample,ascriptwithconfigurationoptionsforaPHPwebsite),butstillkeepthemorganizedwiththerestofthesite'sfiles.

Note

Namingthepubliclyaccessibledirectoryroothtmlisaconvention,butitsonethatIfindoutdatedsincemorethanjustHTMLfilesareoftenserved.Ioftennamemyownrootdirectoriespublicorpublic_filesandupdatetheirreferencesintheconfigurationfileaccordingly.

EachdefinitionforavirtualhostiscontainedwithinaVirtualHostblock.TheopeningprovidestheIPaddressoftheinterfaceonwhichtheserverislisteningfollowedbytheportnumber.*indicatesthatthedefinitionappliestoallofthesystem'sinterfacesand80isthedefaultportforHTTPtraffic:

<VirtualHost*:80>

Optionsthatdon'tappearexplicitlyinthedefinitionareassumedtohavethesamesettingsasfoundinthemainconfiguration,soataminimum,theServerNameandDocumentRootoptionsneedtobedefinedtomakethedefinitionunique.Ifyou'reusingPHP,you'llwanttoprovidetheProxyPassMatchoptionaswellsothattherequestsaremappedtothecorrectPHPfiles:

<VirtualHost*:80>

ServerNamewww.example.com

DocumentRoot"/var/www/example.com/www/html"

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$fcgi://127.0.0.1:9000/var/www/

example.com/www/html/$1

</IfModule>

</VirtualHost>

Note

Page 496: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theorderinwhichthevirtualhostdefinitionsareloadedissomewhatimportant;thefirstoneloadedactsasthedefaultandwillhandleanyrequeststhatdonotmatchanyofthevirtualhostsdefinitions.Prefixingtheconfigurationfilesnumerically,forexample10-www.example.conf,canhelpyoucontroltheloadingorder.

Eachrequestisloggedto/var/log/httpd/access_logandanyerrorsareloggedtoerror_log.Ofcourse,thisisfineifyou'reonlyservingonesite.Butwhenservingmultiplesites,youmayfinditbeneficialtoroutelogentriestodifferentfilesfordifferentsites.TheCustomLogoptionnamesafilewheretheaccessandgeneralloggingmessagesarewrittentoandtheformatoftheentries.ErrorLogspecifiesthefilewheretheerrormessagesarewritten.Bothoftheseoptionscanappearinavirtualhost'sconfiguration:

<VirtualHost*:80>

ServerNamewww.example.com

DocumentRoot"/var/www/example.com/www/html"

CustomLog"/var/log/httpd/example.com/www/access_log""%h%u

%t"%r"%>s%b"

ErrorLog"/var/log/httpd/example.com/www/error_log"

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$fcgi://127.0.0.1:9000/var/www/

example.com/www/html/$1

</IfModule>

</VirtualHost>

ThesecondargumenttoCustomLogcanbetheformatstringitselforanaliasthatrepresentstheformatstring.Formatstringssimplydefinewhatdetailsarecontainedintheloggedmessages.

There'saslewofformatspecifiersavailablewhicharealldocumentedintheApacheHTTPdServer'sdocumentation.Here'salistofsomeofthemorecommononesyoumayuse,whileyoucanfindacompletelistonlineathttp://httpd.apache.org/docs/current/mod/mod_log_config.html#formats):

%b:Thisisthesizeoftheresponse(inbytes)servedbacktotheclient%D:Thisisthetimetakentoprocesstherequestinmilliseconds(%Trepresentsthetimetakeninseconds)%h:ThisistheIPorhostnameoftherequestingsystem%H:Thisistheprotocolusedtomaketherequest%m:Thisisthemethodusedtomaketherequest%q:ThisisthequerystringportionoftherequestedURI%r:Thisisthefirstlineoftherequest%>s:Thisistherequest'sfinalstatuscode(%srepresentstheinitialstatusforrequeststhatareredirected)%t:Thisisthetimewhentherequestwasreceived%u:Thisistheusernameforauthenticatedrequestswhentherequestwasreceived%v:Thisisthenameoftheserver(ServerName)handlingtherequest

TheLogFormatoptionnamesaformatstringwithanalias.Forexample,thehttpd.conffile

Page 497: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

usesLogFormattodefinestringsnamedascommonandcombined,whichcanbeusedelsewhere.It'sagoodideatodefineyourownaliasforyourvirtualhostloggingandusethealiasintheindividualconfigurationfilesratherthanhavingcrypticformatstringsscatteredabout.Inhttpd.conf,simplyaddyourcustomLogFormatentryinthesameareaasthecommonandcombinedentries:

LogFormat"%v%h%u%t"%r"%>s%b"vhostcommon

Then,youcanreferencethealiasinyoursites'configurationfiles:

CustomLog"/var/www/example.com/www/logs/access_log"vhostcommon

Aftermakingthechanges,restartApachefortheconfigurationtotakeeffect.

Whatevertheirdestination,makesuretheownership/permissionsyoursecuritycontextallowApacherunstowritetothelogfile.Ifthelogsresideunder/var/log/httpdthencreatingthenecessarysubdirectoriesshouldbesufficient.Theserverwillcreatethelogfilesitselfwhenitstarts:

mkidr-p/var/log/httpd/example.com/www

However,ifyouwishtokeepthelogsinanotherdirectory,perhapssuchas/var/www/example.com/www/logs,theservermaybeblockedfromwritingtothem.SELinuxisenabledregardlessofthefilesystempermissionsappearingsane.Tofixthesituation,firstverifythesecuritycontextwithls-Z:

ls-Z/var/www/example.com/www|greplogs

drwxr-xr-x.apacheapacheunconfined_u:object_r:httpd_sys_content_

t:s0logs

Inthiscase,thelogsdirectoryisownedbytheapacheuser,whichApacherunsunder,andthepermissionsonthedirectoryshouldallowtheservertocreatethelogfiles.However,wecanalsoseethatthedirectoryhasinheritedthelabelthatidentifiesitaswebcontentasindicatedbyhttpd_sys_content_t.Tofixtheproblem,weneedtorelabelthedirectoryforloggingpurposesusingchcon:

chcon-Rv--type=httpd_log_t/var/www/example.com/www/logs

Page 498: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithvirtualhosting:

ApacheVirtualHostdocumentation(http://httpd.apache.org/docs/current/vhosts/)Apachemod_log_configdocumentation(http://httpd.apache.org/docs/current/mod/mod_log_config.html)VirtualHostexamples(http://httpd.apache.org/docs/current/vhosts/examples.html)CentOSWiki:SELinuxHowTo(https://wiki.centos.org/HowTos/SELinux)

Page 499: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConfiguringApachetoservepagesoverHTTPSHTTPtrafficissentinplaintextacrossthenetwork.Inanuntrustedenvironment,amalicioususercanmonitorandcapturethetraffictospyonwhatsitesyou'revisitingandwhatcontentyou'rereading.Whilesuchsnoopingisn'tinterestingifthevictimisjustreadingthedailynewsorwatchingcatvideosonYouTube,theuser'screditcardnumber,shippingaddress,andotherdetailscouldbesnaggedifane-commercetransactionweretotakeplaceunencrypted.Tosupportencryptedtraffic,ApachesupportsHTTPS.ThisrecipewillteachyouhowtoconfigureHTTPSsupportandprotectyourusers'trafficfrompryingeyesnomatterhowbenignthecontentis.

Page 500: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatthesystemisconfiguredwiththeIPaddress192.168.56.100andisrunningApacheasdescribedinthepreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 501: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoservepagesoverHTTPS:

1. Generateanewkeyfileandsecuritycertificateusingopenssl:

opensslreq-newkeyrsa:2048-nodes\

-keyout/etc/pki/tls/private/www.example.key\

-x509-days730-subj"/CN=www.example.com"-text\

-out/etc/pki/tls/certs/www.example.pem

2. Installtheserver'sSSLmodule:

yuminstallmod_ssl

3. Openthe/etc/httpd/conf.d/ssl.conffilewithyourtexteditor:

vi/etc/httpd/conf.d/ssl.conf

4. LocatetheSSLCertificateFileoptionandupdateitsvaluetopointtotheself-signedcertificatefile:

SSLCertificateFile/etc/pki/tls/certs/www.example.pem

5. LocatetheSSLCertificateKeyFileoptionandupdateittopointtotheencryptionkey:

SSLCertificateKeyFile/etc/pki/tls/private/www.example.key

6. Saveyourchangesandclosethefile.7. Restarttheserverfortheupdatedconfigurationtotakeeffect:

systemctlrestarthttpd

8. Openport443inthefirewalltoallowHTTPStraffic:

firewall-cmd--zone=public--permanent--add-service=https

firewall-cmd--reload

Page 502: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...TheApacheHTTPServercomeswithadefaultSSL/TLSconfigurationcontainedwithinacatch-allvirtualhostdefinitionin/etc/httpd/conf.d/ssl.conf.Withmostoftheconfigurationalreadydoneforus,allthat'sleftistoinstalltheSSLmodule,generateanewkeyandcertificate,andupdatetheconfigurationtopointtoourfiles.

First,wegeneratedanewencryptionkeyandsigningcertificate.Ifyou'vealreadyreadtheConfiguringPostfixtouseTLSrecipeinChapter9,ManagingE-mails,thenyoualreadyknowthatthekeyisneededforsecuredcommunicationandthecertificateconfirmstheownershipofthekey:

opensslreq-newkeyrsa:2048-nodes\

-keyout/etc/pki/tls/private/www.example.key\

-x509-days730-subj"/CN=www.example.com"-text\

-out/etc/pki/tls/certs/www.example.pem

Therecipegeneratesaself-signedcertificatewhichissufficientforpersonaluseandintranetsites.Thereqoptioncreatesanewcertificateand-newkeygeneratesanewprivatekey.Thekeyisa2048-bitRSAkeyanditselfisnotencrypted(-nodes),sowedon'tneedtoprovideapassphrasetodecryptthekeyeverytimewestartthewebserver.ThecertificateisanX.509certificate(-x509)andisvalidfor3years(-days730).Thecertificate'sCNfieldmustmatchthedomainnameofthesiteitwillbeusedfor.

Intheconfigurationfile,theSSLCertificateFileoptionspecifiesthefilethatcontainsthecertificatefileandthekeyisidentifiedusingSSLCertificateKeyFile:

SSLCertificateFile/etc/pki/tls/certs/www.example.pem

SSLCertificateKeyFile/etc/pki/tls/private/www.example.key

Theserverdetermineswhichvirtualhostconfigurationtousetohandlearequestbylookingatthesite'snameintheincomingrequest.However,theoriginalHTTPSimplementationencryptedtherequestinitsentiretybetweenthewebclientandserver,includingthesite'shostname,whichraisedachickenandeggproblem.Theserverneededtoknowwhichcertificatetoserveandcouldn'tknowitwithoutreadingtherequest,andtheclientwantedacertificatethatmatchedthesite'sdomainbeforeitwouldevensendtherequest.ItwasimpossibletouseTLSwithname-basedvirtualhostingandanyencryptedsiterequireditsowndedicatedIPaddress.

RFC-3546(TransportLayerSecurityExtensions)modifiedtheprotocolsothatthehostnamecouldbesentunencrypted.ThisallowedtheservertoselectthecorrectcertificatetosatisfytheclientandopenedthedoorforusingTLSwithvirtualhosting.Ittookapproximatelytenyearsforthemajorbrowserstosupportthechangebutwe'reprettymuchtherenowInternetExplorerasofversion7,MozillaFirefoxasofversion2,andGoogleChromeasofversion6supportwhatisknownasServerNameIndication(SNI).

Page 503: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ToserveryourvirtualhostsoverHTTPS,eachsitewillneeditsowncertificateandkey.Then,addtheSSLEngine,SSLCertificateFile,andSSLCertificateKeyFileoptionstothehost'sconfiguration.Theportnumberalsoneedstobechangedintheconfigurationto443,thedefaultportforHTTPStraffic:

<VirtualHost*:443>

ServerNamewww.example.com

DocumentRoot"/var/www/example.com/www/html"

CustomLog"/var/log/httpd/example.com/www/access_log"common

ErrorLog"/var/log/httpd/example.com/www/error_log"

SSLEngineon

SSLCertificateFile/etc/pki/tls/certs/www.example.pem

SSLCertificateKeyFile/etc/pki/tls/private/www.example.key

<IfModuleproxy_fcgi_module>

ProxyPassMatch^/(.*\.php)$fcgi://127.0.0.1:9000/var/www/

example.com/www/html/$1

</IfModule>

</VirtualHost>

Althoughself-signedcertificatesareadequateforpersonaluseandprivatenetwork/intranetsites,mostlikelyyou'llwanttouseatrustedcertificateforsitesaccessibleonalargerscale.However,dependingontheCertificateAuthorityandthespecificsofyourrequest,purchasingatrustedcertificatecanbeexpensive.Ifyouneedonlyabasictrustedcertificate,thenyoumightwanttoinvestigatewhetherLet'sEncryptwillmeetyourneeds.Let'sEncryptisaprojectofferinganautomated,self-servicemodelforgeneratingtrustedcertificatesforfree.

TouseLet'sEncrypt,you'llneedtoinstallthecertbotpackageavailableintheEPELrepository(refertotheRegisteringtheEPELandRemirepositoriesrecipeinChapter4,SoftwareInstallationManagementifyouhaven'talreadyenabledtherepository).Thenrunthecertbotcertonlycommandandfollowthepromptstorequestyourcertificate.FullinstructionscanbefoundonlineintheLet'sEncrypt/CertbotUserGuideathttp://letsencrypt.readthedocs.io/en/latest/using.html.

Note

ThereareafewcaveatstoLet'sEncrypt.First,thecertificatesareonlyvalidforthreemonths;you'llneedtorequestanewcertificateevery90days.Italsowon'tgeneratecertificatesforIPaddresses.Also,itratelimitsrequestswhich,althoughnecessarytohelppreventabuse,causesissuesforthoseusingadynamicDNSservicesuchasDynDNSorNoIPtomaketheirsitesaccessible.ForLet'sEncrypttobeaviableoptionforyou,you'llneedaproperdomainandaccesstothewebsystemtoautomatetherenewal.Ifyou'rerunningahomeserverorusingasharedhostingprovider,thenLet'sEncryptisprobablynotforyou.

Page 504: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesforworkingwithHTTPS:

SSL/TLSStrongEncryption:How-To(http://httpd.apache.org/docs/2.4/ssl/ssl_howto.html)HowtocreateanSSLCertificateforApacheonCentOS7(http://www.digitalocean.com/community/tutorials/how-to-create-an-ssl-certificate-on-apache-for-centos-7)HowtosecureApachewithLet'sEncryptonCentOS7(https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-centos-7)

Page 505: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

EnablingoverridesandperformingURLrewritingThisrecipeteachesyouhowtousemod_rewrite.Imentionedmod_rewriteearlier;itisamoduleforApachethatallowsustomodifytheURLandresolveittodifferentresources.Therearemanyreasonsonewouldwanttodothis.Forexample,perhapsyoumovedsomefilesandtheirURLchanged,butyoudon'twantanylinksthatexistelsewherestillpointingtotheolddestinationstobebroken.YoucanwritearewriterulethatmatchestheoldlocationsandupdatestheURLontheflytosuccessfullysatisfytherequest.AnotherexampleisSEO;youmayhavelong,unfriendlycanonicalURLsforaresourcebutwantsomethingshorterandmorememorable.ThefriendlyURLscanbemappedtothecanonicalURLbehindthescenes.

Page 506: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatthesystemisconfiguredwiththeIPaddress192.168.56.100andisrunningApacheasdescribedinthepreviousrecipes.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 507: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoperformURLrewriting:

1. Openthe/etc/httpd/conf/httpd.conffilewithyourtexteditor:

vi/etc/httpd/conf/httpd.conf

2. LocatetheDirectorysectionthatdefinesvariousoptionsforyourdocumentroot.FinditsAllowOverridesoptionandupdatethevaluefromNonetoAll:

<Directory"/var/www/html">

...

AllowOverridesAll

...

</Directory>

3. Saveyourchangesandclosethefile.4. RestartApachefortheconfigurationupdatetotakeeffect:

systemctlrestarthttpd

5. Verifythatthemod_rewritemodule(identifiedasrewrite_module)isavailable:

httpd-M|greprewrite

6. Createafilenamed.htaccessinyourdocumentroot:

vi/var/www/html/.htaccess

7. Inthe.htaccessfile,addRewriteEnginetoturnontheURLrewritingengine:

RewriteEngineon

8. AddRewriterulesthatdescribethedesiredredirects.Forexample,thefollowingruleredirectsallrequestswithoutafileextensiontoaPHPfileofthegivenname:

RewriteRule^/?([A-Z]+)$$1.php[NC,L]

9. Saveandclosethefile.

Page 508: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...The.htaccessfilesaresupplementalconfigurationfilesthatresideinthesites'directorystructure.Whenconfigured,Apachesearchesforan.htaccessfileandappliestheoptionsettingsinitwhilesatisfyingarequest.Ofcourse,searchingandloadingconfigurationvaluesforeachrequestdoeshaveaslightperformanceimpact,butitstrade-offincreasesflexibility.Forexample,theserverdoesn'tneedtoberestartedforconfigurationchangesinan.htaccessfiletotakeeffect.Inashared-hostingenvironment,savvyclientscantweaktheserver'sbehaviorfortheirownsiteswithoutaskingaserveradministratororrequiringaccesstothemainconfigurationfilesin/etc/httpd(whichmaycontainsensitiveconfigurationvalues).Evenwebapplicationsthatrelyonspecificserverfeaturesmightincludean.htaccessfilewiththenecessaryconfigurationtomakeitsdeploymenteasier.

Apachedoesn'tallowtheuseofthe.htaccessfilestooverridetheserver'sconfigurationbydefault.Toenableit,weneedtoupdatetheAllowOverridesoptionintheappropriatecontextandthenrestarttheserver.Thisrecipemadethechangeinthesectionthatappliestothewebrootdirectory:

<Directory"/var/www/html">

...

AllowOverridesAll

...

</Directory>

Note

Ifyou'reusingvirtualhosting,besuretoputtheAllowOverridesoptioninyoursite'sconfigurationfile.

AvalueofNonecausestheservertoignoreany.htaccessfiles.Apartfromthat,notalloptionsareallowedinan.httaccessfile.Themostcommononesfoundinthefilespertaintorewritingrequestsordirectory-specificaccess.Thosethatcanappeararegroupedunderdifferentcategoriesandwecanspecifythecategoryofoptionsthatwillbeallowedtobeoverridden.Thepossiblegroupnamesareasfollows:

AuthConfig:Thisallowsoverridingtheauthorizationoptions(AuthUserFile,AuthDBMUserFile,andsoon)FileInfo:Thisallowsoverridingrequest-relatedoptions(ErrorDocument,Redirect,RewriteRule,andsoon)Indexes:Theseallowindex-relatedoptionstobeoverridden(DirectoryIndex,IndexOptions,andsoon)Limit:Thisallowstheaccessoptionstobeoverridden(Allow,Deny,andOrder)All:Thisallowsoverridingalloftheoptiongroups

SinceAllowOverridesappliestothedirectorylevel,it'spossibletoallowordenydifferentoverridesindifferentdirectories.Forexample,overridingcanbedisabledacrossasite,but

Page 509: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

thentheauthorizationoptionscanbeoverriddenforaprivatedirectorysothatthespecificauthorizationdatabasescanbespecified:

<Directory"/var/www/html">

AllowOverridesNone

</Directory>

<Directory"/var/www/html/priv">

AllowOverridesAuthConfig

</Directory>

Note

EvenifyouhavefullcontroloverApacheandyouwanttoplaceeverythinginthemainhttpd.conffilesforperformancereasons,allowingrewriteoptionstobeoverriddenwithFileInfoletsyoudeviseandtroubleshootyourruleswithoutrestartingtheserveraftereachchange.Youcanthenmigratetherulestothemainconfigurationfileonceyou'recertainthey'recorrect,andturnoffoverrides.

rewrite_moduleinjectsitselfintotheserver'srequesthandlingworkflowandcanchangewhattherequestedURLlookslikeonthefly,givenwhatweprovideinourruleset.Althoughthemoduleisinstalledbydefault,westillneedtoexplicitlyenableURLrewritingwithRewriteEngineon.Beyondthat,thetwomostimportantrewriteoptionsareRewriteRuleandRewriteCond.

TheRewriteRuleoptionspecifiesaregularexpressionagainstwhichtheURLiscompared.Ifitmatches,thenthegivensubstitutiontakesplace.Positionalvariablessuchas$1canbeusedinthesubstitutiontoreferencecapturedpatternmatches.Inourrecipe,therulematchesthepath(suchas/aboutor/contactus)andrewritesittodirecttheusertoaPHPscriptofthesamename(about.phporcontact.php),thushidingthefactthatwe'reusingPHPfromourusers:

RewriteRule^/?([A-Z]+)$$1.php[NC,L]

Wealsocanprovideflagsthataffecthowtherequestisreturned.TheNCflag,forexample,performsthepatternmatchingcaseinsensitively.TheLflagstopstheengineandreturnstheURLwithoutanyfurtherruleprocessing.AlsocommonareR,whichforcesaredirect(anHTTPstatuscodeisusuallygiven,forexampleR=301),andQSA,whichappendsthequerystringfromtheoriginalURLtothenewURL.

TheRewriteCondoptiongivesaconditionthatmustpassbeforeevaluatingaRewriteRule.Theconditionisamixofregularexpressionmatching,variables,andtestoperators.SpecialvariablesareavailablewhichwecanusetoreferencepiecesoftheURL,suchasthehostname(%{HTTP_HOST}),therequestedfile(%{REQUEST_FILENAME}),andthequerystring(%{QUERY_STRING}),ordetailsabouttheenvironment/request,suchascookies(%{HTTP_COOKIE})anduseragentstrings(%{HTTP_USER_AGENT}).The-doperatortestswhetherthepathisadirectory,-ftestswhetherthepathisafile,and!negatesthematch.RewriteCond

Page 510: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

canalsoacceptahandfulofflags,suchasNCflagtomakecomparisonwithoutregardtocasesensitivityandtheORflagtojoinmultipleoptionsinanorrelationship(multipleoptionsareimplicitlytreatedasand).

AverycommonrewritethatusesbothRewriteCondandRewriteRuleisonethatdirectstheusertoamainindex.phpfilewhentherequestdoesn'tmatchanexistingfileordirectory.Thisisusedalotwithwebapplicationsthatrouteallrequeststhroughacentralcontrolpoint:

RewriteCond%{REQUEST_FILENAME}!-f

RewriteCond%{REQUEST_FILENAME}!-d

RewriteRule^(.*)index.php[L,QSA]

ThefirstRewriteCondoptioncheckswhethertherequestisforanexistingfileandthesecondchecksthesameforanexistingdirectory.Iftherequestisneitherforafilenoradirectory,thentheRewriteRuleoptionmapstherequesttoindex.php.Anyquerystringthatmaybepresentisincludedandit'smarkedasthelastaction,sonofurtherrewritingwillbeperformed.

Manypeoplejokinglyrefertorewritingasblackmagic.Indeed,it'simpressivehowpowerfulmod_rewriteisandhowittransformsrequests,anditcanbefrustratingwhenyoucan'tseemtofigureouttheproperincantationtomakeyourruleworkasdesired.Inthiscase,youmaywanttoturnonloggingtogaininsightintohowtheengineviewstherequest.Toenablelogging,usetheRewriteLogoptiontospecifyalogfilewheremessagescanbewrittento,anduseRewriteLogLeveltospecifytheverbosity.Typically,avalueof5forRewriteLogLevelissufficient.Theycanbeaddedtoyour.htaccessfileandremovedlaterafteryou'reconfidentthatyourrulesarecorrect:

RewriteLog/var/log/httpd/rewrite_log

RewriteLogLevel5

Page 511: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonrewritingURLs:

Apachemod_rewritedocumentation(http://httpd.apache.org/docs/current/mod/mod_rewrite.html)URLrewritingguide(http://httpd.apache.org/docs/2.0/misc/rewriteguide.html)URLrewritingforthefearful(https://24ways.org/2013/url-rewriting-for-the-fearful)

Page 512: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

InstallingNGINXasaloadbalancerHightrafficwebsitescanbedistributedtodifferentservers,eithertobetterspreadouttheworkloadortoachieveredundancy.Eachserverintheclusterofsystemswouldhavetheirowncopyofthewebsiteorwebapplication'sfilesandbecapableofsatisfyingtheuser'srequest.Thetrickthenistoroutetheuser'srequesttooneoftheseserversinanorderlyfashion.Therearedifferentapproachestothis,butacommononeistosetupaloadbalancerorreverseproxyserver.

NGINXissomewhatnewertothescenethanApache;writtenalittleoveradecadeagospecificallytohandlehigh-loadconnections,itcanfunctionasawebserver,proxy,cache,andload-balancer.Inthisrecipe,we'llseehowtosetupNGINXasaloadbalancertoproxyrequestsbetweentheclientandaclusterofApacheservers.

Page 513: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ItassumesthatyouhaveothersystemsconfiguredwithApachetoserveawebsiteasdescribedintheearlierrecipes;we'llrefertothesesystemsusingtheIPaddresses192.168.56.20and192.168.56.30.ThepackageforNGINXishostedbytheEPELrepository;iftherepositoryisnotalreadyregistered,refertotheRegisteringtheEPELandRemirepositoriesrecipeinChapter4,SoftwareInstallationManagement.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 514: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstosetupreverseproxyusingNGINX:

1. InstallthenginxpackagefromtheEPELrepository:

yuminstallnginx

2. OpentheNGINXserver'sconfigurationfilewithyourtexteditor:

vi/etc/nginx/nginx.conf

3. Withinthehttpblock,addanewupstreamblocktoidentifytheserversinyourcluster:

upstreamcluster{

server192.168.56.20;

server192.168.56.30;

}

4. Findthelocationblockandaddaproxy_passoptionthatreferencestheupstreamblock:

location/{

proxy_passhttp://cluster;

}

5. Saveyourchangestotheconfigurationandclosethefile.6. Starttheserverandenableittostartautomaticallywhenyoursystemreboots:

systemctlstartnginx.service

systemctlenablenginx.service

7. Openport80inthesystem'sfirewalltoallowHTTPrequeststhrough:

firewall-cmd--zone=public--permanent--add-service=http

firewall-cmd--reload

Page 515: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Asusual,webeganbyinstallingtheprogram'spackage,thistimenginx.ThepackageisavailableintheEPELrepository.Onceinstalled,weupdateditsconfiguration,identifyingtheserversinourclusterandthenproxyingrequests.First,weaddedanupstreamblock:

upstreamcluster{

server192.168.56.20;

server192.168.56.30;

}

clusterissimplyanameweassignedtothisgroupofserverssothatwecanrefertothegroupbyname.Youcanhavemultipleupstreamblocksifyouarebalancingmultipleclusters.EachserverentrywithinitgivestheIPaddressorhostnameofoneofthesystemsrunningthesite.

Next,wefoundthemainlocationblockandaddedaproxy_passparameter.proxy_passwillforwardtheincomingrequesttooneofthesystemsinourclustergroupandreturntheresponsetosatisfytherequest:

location/{

proxy_passhttp://cluster;

}

CommunicationbetweenNGINXandthehostingwebserversisdoneoverhttpsincethat'stheprotocolspecifiedinthevalueforproxy_pass.Thisisfinebecausetheclusteredsystemswouldberunningbehindtheloadbalanceronatrustednetwork.IfyoursiteistobeservedoverHTTPS,it'sNGINXthatwillneedtohandletheTLSnegotiationasit'sthepublicserverpointseenbytheclient;theclientisunawareofanythingbehindthebalancer.

ToconfigureNGINXtohandleHTTPSrequests,withintheserverblockupdatethelistenoptionstolistenonport443.Thenaddentrieswiththessl_certificateandssl_certificate_keyoptionstoidentifythecertificateandkey,respectively:

server{

#listen80default_server;

#listen[::]:80default_server;

listen443ssldefault_server;

listen[::]:443ssldefault_server;

ssl_certificate/etc/pki/tls/certs/www.example.pem;

ssl_certificate_key/etc/pki/tls/private/www.example.key;

...

}

Oncethechangesaremadeandtheconfigurationfileissaved,openport443inyourfirewallandrestartNGINX:

Page 516: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

firewall-cmd--zone=public--permanent--add-service=https

firewall-cmd--reload

systemctctlrestartnginx.service

Round-robinisthedefaultapproachforloadbalancing.Thismeansthefirstrequestisproxiedtothefirstserverinthecluster,thennexttothesecondserver,andsoon.WhenNGINXreachestheendofthelist,itstartsagainfromthetopofthelist,proxyingthenextrequesttothefirstserver.Thereareotherstrategieswecanuse,forexample,weightedbalancing.

Toperformweightedbalancing,weassignaweighttoanyoftheserversanditwillhandlethatnumberofrequestsperiteration.Here,thefirstserverwillhandlefiverequestsbeforeNGINXproxiesanythingtothesecondserver:

upstreamcluster{

server192.168.56.20weight=5;

server192.168.56.30;

}

Whenusingloadbalancing,rememberthatanyonewebserverisn'tguaranteedtoreceivethenextrequestsentbyauser.Ifyou'rebalancingaccesstoawebapplicationthatusessessions,thiscanbeproblematic.Youmaywanttoconsiderstoringsessiondataonacentralsystemthateachwebserverhasaccessto,perhapsusingadatabasesuchasRedisorMemcache.

Note

Irecommendthatyouavoidanybalancingstrategythatreliesonsessionpersistence.Thepostathttp://www.chaosincomputing.com/2012/05/sticky-sessions-are-eviloffersagoodoverviewoftheirproblems.

Page 517: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithNGINXandloadbalancing:

TheNGINXwebsite(https://www.nginx.com/)HowtoinstallNGINXonCentOS7(https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-centos-7)ConfiguringHTTPSservers(http://nginx.org/en/docs/http/configuring_https_servers.html)UsingNGINXasaloadbalancer(http://nginx.org/en/docs/http/load_balancing.html)HowtostorePHPsessionsinMemcache(http://www.scalescale.com/tips/nginx/store-php-sessions-memcached)

Page 518: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter11.SafeguardingAgainstThreatsThischaptercontainsthefollowingrecipes:

SendingmessagestoSyslogRotatinglogfileswithlogrotateUsingTripwiretodetectmodifiedfilesUsingClamAVtofightvirusesCheckingforrootkitswithchkrootkitUsingBaculafornetworkbackups

Page 519: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionFromloggingyoursystem'sactivitiestosniffingoutrootkits,thischapterpresentsrecipestohelpprotecttheinvestmentyou'vemadeinyoursystemanditsdataagainstvariousthreats.First,you'lllearnhowtosetupacentrallogserverusingSyslog,andthen,howtorotatelogfilestomakesurethattheydon'tgrowoutofcontrol.Then,we'lllookathowTripwireisusedtodetectsystemintrusionbycheckingifchangeshavebeenmadetoimportantsystemfiles.ThischapteralsocontainsrecipesforsettingupClamAVandchkrootkittokeepyoursystemfreeofviruses,Trojans,rootkits,andothermalware.We'llfinishwithhowtosetupacentralizedbackupserverusingBaculatosafeguardyourdatafromeverydaythreatssuchasaccidentaldeletionandhardwarefailures.

Page 520: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SendingmessagestoSyslogSyslogisaprocessthatlistensformessagesfromotherapplicationsandwritesthemtoitslogfiles,providingacommonservicetohandleallloggingactivity.MessagescanalsobesenttoarunninginstanceofSyslogonaremotesystemactingasacentralizedlogserverforyourentirenetwork.Apartfromconvenience,centralizedloggingcanbeusefulforsecurityreasonsandalsobecauseit'sharderforanattackertocovertheirtrackswhenit'sloggedtoasecondsystem.Inthisrecipe,you'lllearnhowtoconfigurelocalandremoteinstancesofSyslogtorunyourownlogserver.

Page 521: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequirestwoCentOSsystemswithworkingnetworkconnections.TherecipewillrefertothefirstsystemasthelocalsystemandassumethatitisconfiguredwiththeIPaddress192.168.56.100andthehostnamebenito.Thesecondsystem,referredtoastheremotesystem,isassumedtohavetheaddress192.168.56.35andthehostnamelogs.Thesystemsshouldbeabletoaccesseachotherbythehostnames;so,youwillneedtoaddtheappropriateDNSrecordsoroverrideentriesinthesystems'/etc/hostsfiles.Administrativeprivilegesarealsorequiredeitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 522: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Toforwardlogmessagesfromthelocalsystemtotheremotesystem,performthefollowingstepsonthelocalsystem:

1. OpenSyslog'sconfigurationfileusingyourtexteditor:

vi/etc/rsyslog.conf

2. Attheendofthefile,addthefollowingrule:

*.*@logs.example.com

3. Savethechangeandclosetheconfigurationfile.4. RestartSyslogfortheupdatedconfigurationtotakeeffect:

systemctlrestartrsyslog

Then,toacceptincominglogmessages,performthefollowingstepsontheremotesystem:

1. OpenSyslog'sconfigurationfileusingyourtexteditor:

vi/etc/rsyslog.conf

2. Locatethe$ModLoaddirectiveresponsibleforloadingtheimudpmoduleanduncommentitbyremovingtheleading#character.Uncommentthe$UDPServerRundirectivethatimmediatelyfollowsitaswell:

$ModLoadimudp

$UDPServerRun514

3. Savethechangesandclosetheconfigurationfile.4. RestartSyslogfortheupdatedconfigurationtotakeeffect:

systemctlrestartrsyslog

5. OpenthefirewalltoUDPtrafficonport514:

firewall-cmd--zone=public--permanent--add-port=514/udp

firewall-cmd--reload

Page 523: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Syslogreceivesmessagesthroughseveralloggingfacilities,andeachmessagehasanassignedpriority/severity.Messagescanbefilteredbasedontheirfacilityandprioritysothatthedesiredmessagesarerelayedwhiletherestarediscarded.AlistoffacilitiesandprioritiesarebothoutlinedinRFC-5424(theSyslogprotocol),andRsyslog(theversionofSyslogavailableinCentOS)implementsmostofthem.

Facilitiesofferabroadcategorizationdesignedtoorganizemessagesbythetypeofservicethatgeneratesthem.Youcanthinkofthemaschannels,whereamessagethatlogsauser'sfailedloginattemptcanbesentovertheauthchannelseparatefrommessagesloggingtherestartofaservicesentoverthedaemonchannel.Rsyslog'sfacilitiesarethefollowing:

auth:Securityandauthorization-relatedmessagescron:Messagesfromcrondaemon:Messagesfromsystemdaemonskern:MessagesfromtheLinuxkernellpr:Messagesfromthesystem'sprinterservicesmail:Messagesfromthesystem'smailservicesnews:MessagesfromNTTPservicessyslog:MessagesgeneratedbySyslogitselfuser:User-levelmessagesuucp:MessagesfromUUCPserviceslocal0-local7:User-levelfacilitiesformessagesthataren'thandledbytheotherfacilities

Prioritiesindicatetheseverityofthemessage,forexample,asituationthatgeneratesanerrormessageismoreseverethanonegeneratinganinformationalordebuggingmessage.Rsyslog'sprioritiesareasfollows:

emerg,panic:Thesystemisunusablealert:Immediateactionisrequiredcrit:Acriticaleventhappenederr,error:Anerrorhappenedwarn,warning:Asignificantconditionisencounterednotice:Noticemessagesinfo:Informationalmessagesdebug:Debuggingmessages

TherulesinSyslog'sconfigurationfilespecifywherealogiswrittentoandtheyaremadeupoftwoparts—thefirstpartisapatternthatidentifiesafacilityandpriority.Itconsistsofboththefacilityandprioritynamesseparatedbyadot,forexample,auth.warnorlocal2.debug.Morethanonefacilitycanbeseparatedbycommas,asinauth,daemon,cron.warn.Additionally,*canbeusedasawildcardtomatchallfacilitiesorpriorities.auth.*representsmessagescomingthroughtheauthfacilityofanypriority,*.warnrepresentsmessageswitha

Page 524: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

priorityofwarnorabovefromanyfacility,and*.*representsallmessagesregardlessoffacilityorpriority.

Messagesthatmatchthepatternareprocessedbytherule'ssecondpart,theaction.Usually,theactionisthelocationofafilethatthemessageiswrittento,butitcanalsodiscardthemessage(use~asthelocation),sendthemessagetoanamedpipetobehandledbyanexternalprocess(prefixthelocationwith|),orforwardthemessagetoanothersystem(giveahostnameasthelocationprefixedwith@).

SinceRsyslogisinstalled,theservice'sconfigurationfileis/etc/rsyslogd.conf.Onthelocalsystemweaddedthefollowingrule:

*.*@logs.example.com

Thisrulematchesallmessagesandsendsthemtotheserverlogs.example.com.One@meansmessageswillbesentusingUDPwhiletwomeanstheywillbesentusingTCP:

*.*@@archive.example.com

Then,weuncommentedthefollowingconfigurationontheremotesystem:

$ModLoadimudp

$UDPServerRun514

$ModLoadloadsaSyslogmodule,inthiscaseimudp,whichhandlesincomingmessagesoverUDP.The$UDPServerRundirectivespecifiestheportwhichthemodulelistenstoforthemessages.Traditionally,Syslogmessagesaresenttoport514.

Note

SyslogcanbeconfiguredtotransmitmessagesusingTCP,butunlessyouhavespecificneedtodoso,IrecommendthatyouuseUDP.UDPislessreliable,butTCPentailsmoreoverheadandcanresultinmoreseverenetworkcongestionduringheavyloggingevents.

Page 525: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Theconfigurationfilecontainsrulestodirectmessagestodifferentfilesbasedontheirfacilityandpriorities

ManyapplicationsarecapableofsendingmessagestoSyslog,eveniftheywritetotheirownlogfilesbydefault.Someprogramsdosowhengivenanappropriateargumentonthecommandline,forexample,MySQLacceptsthe--syslogargument.Others,suchasBINDandApache,requirechangesintheirconfigurationfiles.EventheshellscriptsyouwritecansendmessagestoSyslogusingtheloggercommandasfollows:

logger-nlogs.example.com-puser.notice"Testnotice"

loggeracceptsseveralargumentsandthenthelogmessage.-nspecifiestheserverwherethemessageissent(messagesaresenttothelocalsystem'sSysloginstancewhennotprovided)and-pspecifiesthefacilityandpriorityforthemessage.

Page 526: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithSyslog:

TheRsyslogwebsite(http://www.rsyslog.com/)BasicconfigurationofRsyslog(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/s1-basic_configuration_of_rsyslog.html)RFC5424:TheSyslogprotocol(http://www.rfc-base.org/txt/rfc-5424.txt)

Page 527: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

RotatinglogfileswithlogrotateLogfilesareimportantbecausetheyprovidebetterinsightintowhatishappeningonasystem.Thedebugginganderrormessagesinalogcanbeusedtotrackdownthesourceofaproblemandresolveitquickly.Authenticationmessagesmaintainarecordofwhoaccessedthesystemandwhen,andrepeatedauthenticationfailurescanbeasignthatanattackeristryingtogainunauthorizedaccess.However,theusefulnessoflogstypicallydiminisheswithage,andchattyapplicationsthatgeneratealotoflogentriescould,ifleftunchecked,easilyconsumeallofthesystem'sstorageresources.Thisrecipewillshowyouhowtorotatethelogfilestopreventthefilesfromgrowingoutofcontrolandstalelogsfromwastingspace.

Page 528: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequiredeitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 529: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoconfigurelogfilerotationusinglogrotate:

1. Createthe/etc/logrotate.d/examplefile:

vi/etc/logrotate.d/example

2. Writethefollowingcontentstothefile:

/var/log/example.log{

monthly

rotate4

missingok

notifempty

create0600rootroot

postrotate

kill-HUP$(cat/var/run/example.pid)

endscript

}

3. Saveyourupdateandclosethefile.

Page 530: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...logrotaterotatesthelogfilesbyrenamingthemassequentialbackupsandcreatinganewfilefortheapplicationtowriteto.Whilerotatingexample.log,itrenamesexample.logtoexample.log.1.Ifexample.log.1exists,itrenamesthatfiletoexample.log.2first(andsoonfortheotherenumeratedfiles).

Forthesakeofthisexample,thisrecipecreatedanewconfigurationtorotatethe/var/log/example.logfile.Themainconfigurationfileoflogrotateis/etc/logrotate.conf,whileadditionalfilescanbeplacedinthe/etc/logrotate.ddirectory.You'llwanttochecklogrotate.dtoseeifrotationfortheapplication'slogsyouwanttomanageisalreadyconfigured(manypackageswilldropaconfigurationfilethereasacourtesy).Youcanthenupdatetheconfigurationifthepackagemaintainer'sconfigurationdoesn'tsuityourneeds.Directivesinthemainfilesettheglobalbehavior,whichisoverriddenonaper-configurationbasisbytheadditionalfilesinlogrotate.d.

Theconfigurationsuppliesthenameofthetargetedlogfilefollowedbyabracedsetofdirectivesthatspecifieshowlogrotateshouldmanagethefile.*canbeusedasawildcardtomatchmultiplefileswhichisusefulwhenanapplicationwritestomorethanonelogfile.Forexample,theApacheHTTPserverlogsmessagestoaccess_loganderror_login/var/log/http.Soit'sconfigurationtargetsthelogfilesasfollows:

/var/log/http/*log{

...

}

Themonthlydirectiveinstructslogrotatetorotatethefilesonamonthlybasis.Otheroptionsaredaily,weekly,andyearly.Alternatively,youcaninstructlogrotatetomanagefilesbasedontheirsize—thesizedirectivespecifiesasizeandlogrotatewillrotatethosefilesthatarelargerthanthat.

size30k

Ifavalueisgivenwithoutaunit,thegivenvalueisunderstoodasbytes.logrotatealsosupportskforkilobytes,Mformegabytes,andGforgigabytes.

Therotatedirectivespecifieshowmanylogfilestokeepintherotation.Inourscenario,fourfilesareallowed;so,example.log.3overwritesexample.log.4andthereisnoexample.log.5.Themissingokdirectiveletslogrotateknowthatit'sokaytogoonifalogfiledoesn'texist(itsdefaultbehavioristoraiseanerror).Also,thenotifemptydirectiveinstructslogrotatetoskiprotatingifthefileisempty.Thecreatedirectiveinstructslogrotatetocreateanewlogfileafterrenamingtheoriginalandsuppliesthemode,user,andgroupforthenewfile:

rotate4

missingok

notifempty

Page 531: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

create0600rootroot

Rotatedlogfilesarenumberedinsequence

Note

Thecontentoftheoriginalexample.log.4filedoesn'thavetobelost.Oneoptionistousethemaildirectivetoinstructlogrotatetoe-mailitscontentstoyoubeforeoverwritingit.

[email protected]

Personallythough,Irecommendusingmailonlyifthefileisrelativelysmallsincesendingalargefilecancauseunduestrainonthemailserver.Also,alogfilethatcontainssensitiveinformationshouldn'tbetransmittedbye-mail.Forsensitivelogsandlargerfiles,Irecommendusingprerotatetoinvokescporanotherutilitytocopythefileelsewherebeforetherotation.

prerotate

scp/var/log/[email protected]:example.log-$(date

+%F)

endscript

Wecanspecifyexternalactionstobeperformedbeforeandafterthelogfilesarerotated.Theprerotatedirectivesuppliesasetofshellcommandsthatwillbeexecutedbeforetherotationprocessbegins,andthepostrotatedirectivesuppliescommandsthatwillberunafterrotation.Bothdirectivesuseendscripttomarktheendofthecommandsetasshownintheprecedingtipandintherecipe'sconfiguration.Theconfigurationinvokeskilltosendthehang-upsignal(HUP)totheexampleprocesswhichwouldreloadthatdaemon.Someprogramsmightbeconfusedifthelogfilethey'rewritingtoismovedandrecreated,andreloadingitcausestheprogramtoreopenitsconnectiontothelogfilesothatitcancontinuelogging:

postrotate

kill-HUP$(cat/var/run/example.pid)

endscript

logrotateisrundailyviacron,soonceyou'vecreated/adjustedyourrotation'sconfigurationyoushouldbefinished.Thenexttimelogrotateruns,itwillpickuptheupdateasitre-reads

Page 532: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

alloftheconfigurationfiles.

Page 533: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithlogrotate:

Thelogrotatemanualpage(man8logrotate)ManageLinuxlogfileswithLogrotate(http://www.techrepublic.com/article/manage-linux-log-files-with-logrotate)Howtomanagesystemlogs(http://www.tecmint.com/manage-linux-system-logs-using-rsyslogd-and-logrotate/)

Page 534: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

UsingTripwiretodetectmodifiedfilesThisrecipeshowsyouhowtosetupTripwire,anauditingtoolfordetectingchangesmadetofilesonyoursystem.Mostoften,Tripwireispositionedasanintrusiondetectionsystembecausetheunexpectedmodificationofimportantconfigurationfilesisusuallyasignofintrusionormaliciousactivity.Beingabletomonitorforsuchchangesgivesyoutheabilitytodetectandputastoptomaliciousactivityinatimelymannershoulditoccur.

Page 535: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.ThetripwirepackageisfoundintheEPELrepository,sotherepositorymustberegisteredasdiscussedinChapter4,SoftwareInstallationManagement.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 536: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstomonitorforsystemintrusionsusingTripwire:

1. InstallthetripwirepackagefromtheEPELrepository:

yuminstalltripwire

2. Runtripwire-setup-keyfilestogenerateTripwire'skeyfilesandconfigurationandpolicyfiles:

tripwire-setup-keyfiles

Youwillbepromptedtoprovideapassphraseforthesitekeyfileandlocalkeyfilesandthentogivethesitepassphraseagaintosigntheconfigurationandpolicyfilesthataregenerated.

3. InitializeTripwire'sdatabase.Youwillbepromptedtoprovideyourlocalpassphrase:

tripwire--init2>output.txt

4. Reviewwarningsintheoutputtoidentifyfilesthataredefinedinthepolicybutdonotexistonyoursystem:

catoutput.txt

5. Commentouttheentriesin/etc/tripwire/twpol.txtthatreferencethenonexistingfilesinoutput.txt.Ifallofthewarningsinoutput.txtwerecausedbynonexistingfiles,thenyoucanautomatethisstepasfollows:

forfin$(grep"Filename:"output.txt|cut-f2-d:);do

sed-i"s|\($f\)|#\\1|g"/etc/tripwire/twpol.txt

done

6. Regeneratethesignedpolicyfile.Providethepasswordforthesitekeyfilewhenprompted:

twadmin--create-polfile-S/etc/tripwire/site.key

/etc/tripwire/twpol.txt

7. Deletetheoriginaldatabaseandinitializeanewone.Thistime,theprocessshouldfinishwithoutgeneratinganywarnings:

rm/var/lib/tripwire/benito.twd

tripwire--init

Page 537: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Tripwireauditsyoursystemtodetectwhichfileshavechanged.Theideabehindthisis,ifanattackergainsaccesstoyoursystem,they'llinevitablycreateormodifykeyfilestosecuretheirpresence.However,itwouldbetrivialforanattackertomodifyTripwire'spolicyfilestocreatetheillusionthatnothinghaschanged;so,theconfigurationandpolicyfilesaresignedwithakeyfile.Theconfigurationfile,policyfile,andthekeyfileareallgeneratedwhenwerun:

tripwire-setup-keyfiles

Becausethedefaultpolicytriestobeascomprehensiveaspossibleformostusers,therewillbeentriesthataren'tapplicabletoourCentOSsystem.IfweweretorunwiththeunmodifieddefaultsthenTripwirewouldreportthemissingfiles,andsiftingthroughthelistoffalsepositiveswouldmakeitmoredifficulttoidentifyifsomeonedeletedafileoflegitimateconcern.Ratherthanreviewingthepolicyfilemanually,especiallyifyou'renotanexpertandfamiliarwithsomeofthefiles,thebestapproachistorunaninitialscanonasystemthatisknowntobecleanandthenletTripwirereportthenonexistentfiles.Thiswillhelpsavetimeaswetrytotailorthepolicytooursystem.

InitializingTripwire'sdatabaseisdoneusingtripwire--init.Theprogramwillscanthesystem,comparingthefilesystemwithwhatitknowsaboutinthepolicyfileandcollectstatisticsonthefilesthatdoexist.ThesestatisticsarestoredinthedatabaseasabaselinemetricforcomparisonthenexttimeTripwirerunstoseeiftherehavebeenchanges.Thereciperedirectedtheerroroutputcontainingthelistofmissingfilestoaseparatetextfilefortworeasons:thelistwillbelengthyandit'ssometimeseasiertopagethroughafilethanscrolltheterminalsession,andwecanscripttheprocessofcustomizingthepolicybasedonthatoutput:

tripwire--init2>output.txt

sedisthetraditionalsearch-and-replaceworkhorseandgrepisgreatforfindingandextractinglinesofinterest,sowecanusethesetwotoolstoupdatethepolicy/etc/tripwire/twpol.txt.First,weneedtoknowwhatthemessagesinoutput.txtlooklike:

catoutput.txt

NonexistentfilesgenerateawarningwheninitializingtheTripwiredatabase

Page 538: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Note

Ifallofthewarningsintheoutputfilearerelatedtononexistentfilesthenit'ssafetoautomateupdatingthepolicy.Thisiswhywethencarefullyreviewedthecontentsbeforecontinuing.

WeusegreptotargetthelinescontainingFilename:andthenusecuttosplitthelineonthecolonandcapturethesecondpart—thenameofthenonexistentfile.Theforloopcaptureseachfilenameandassignsittothevariablef,whichwecanthenreferenceinourpatterntosed.Thepatternperformsaglobalsearchandreplace,usingcapturingparenthesesandnumericbackreferencestooverwritethefilenamewithaleading#:

forfin$(grep"Filename:"output.txt|cut-f2-d:);do

sed-i"s|\($f\)|#\\1|g"/etc/tripwire/twpol.txt;

done

Note

It'simportantthereisaspaceinthesearchspaceafterthefilenametomakesureweonlymatchtheentirefile.Forexample,wewanttoavoidascenariowhere/etc/rc.dwillalsomatch/etc/rc.d/initbecauseofthecommonprefix.

Anunsigned,plain-textcopyofthepolicyisstoredat/etc/tripwire/twpol.txt.Afterwemakeourchanges,wewanttocreateasignedpolicyfilewhichisusedbyTripwireforthesecurityreasonsmentionedearlier.Thisisdonewithtwadminandthe--create-policyargument.The-Sargumentprovidesthecommandwiththepathtooursigningkeyandthenwesupplytheplain-textedcopyofthepolicyastheinput:

twadmin--create-polfile-S/etc/tripwire/site.key

/etc/tripwire/twpol.txt

twadminwillsignthepolicyandwritetheresultto/etc/tripwire/tw.pol.Afterthepolicyfilehasbeenmodifiedwecanthenreinitializethedatabase.Infact,anytimethepolicyfileisupdatedyoushouldregeneratethedatabase,whichisstoredin/var/lib/tripwireandisnamedusingthesystem'shostname:

rm/var/lib/tripwire/benito.twd

tripwire--init

Toscanthesystemforviolations,runTripwirewiththe--checkoption:

tripwire--check

Page 539: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Tripwirereportsitsfindingsafterascanisperformed

Page 540: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Ofcourse,tobeeffective,ascanmustbeperformedatleastonceaday.Forthisreason,acronjobisinstalledin/etc/cron.dailybythetripwirepackagewhichrunsaTripwirescan.Dependingonhowcronisconfigured,theoutputofthescanwillprobablybee-mailedbycrontothesystem'srootuser(andwillmostlikelyendupin/var/spool/mail/root).Youcanedit/etc/cron.daily/tripwire-checksothattheoutputise-mailedtoyouinstead:

test-f/etc/tripwire/tw.cfg&&/usr/sbin/tripwire--check|

/bin/mailx-s"TripwireReport"[email protected]>&1

YoucanalsoconfigureTripwiretosende-mailsitselfifyouprefer.First,you'llwanttoensurethatTripwirecansendmailtoyouraddress.Issuethefollowingtosendatestmessageandthenchecktomakesureitarrivesinyourinbox:

[email protected]

Note

Youcanusesupplythe--email-reportoptionwhenrunningamanualscantohaveTripwiresenditsresultstoyoure-mail.

tripwire--check--email-report

Bydefault,Tripwirewillattempttosendthee-mailviasendmail(orPostfix'ssendmailinterface).IfyouneedtosendthemailthroughanSMTPserverinstead,reviewtheEmailNotificationVariablessectioninman4twconfig.

Specifyingthedestinatione-mailaddressisabitmoreinvolvedinTripwire'sconfiguration.ThetestsdefinedintheTripwirepolicyfilearegroupedintorulesets,whichallowsfilestobegroupedtogetherinalogicalfashion.Forexample,thereisarulesetthatteststheintegrityoftheTripwirebinariesthemselves,whichisseparatefromtherulesetthattestssystemadministrationprograms.Eachrulesetcanhaveadefinede-mailaddresstosendnotificationsto,whichisgreatforflexibilitywhereoneadministratorshouldbenotifiedofmodificationstoonesetoffilesandanotheradminshouldbenotifiedaboutothers:

(

rulename="TripwireBinaries",

[email protected],

severity=$(SIG_HI)

)

Ifyou'retheonlyadministrator,repeatedlyspecifyingthesameaddresscanbetedious.Abetterapproachwoulddefinethee-mailaddressasaglobalvariableandthenletthecreativeuseofsedcometotherescue.

First,edittwpol.txttoincludethevariableassignmentforyoure-mailaddressintheglobalvariabledefinitionssection:

@@sectionGLOBAL

TWROOT=/usr/sbin;

Page 541: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TWBIN=/usr/sbin;

TWPOL=/"/etc/tripwire";

TWD="/var/lib/tripwire";

TWSKEY="/etc/tripwire";

TWLKEY="/etc/tripwire";

TWREPORT="/var/lib/tripwire/report";

HOSTNAME=benito;

EMAILADDR="[email protected]";

Savethechangeandclosethefile.Then,knowingeachrulesetcontainsaseveritydirective,wecanuseareplacementpatterntoinsertthemailtodirective:

sed-i"s|\(\+\)\(severity=\)|\\1mailto=\$(EMAILADDR),\n\\1\\2|g"

/etc/tripwire/twpol.txt

Theendresultshouldincludetheemailtodirectiveineachruleset'sdefinition:

(

rulename="TripwireBinaries",

emailto=$(EMAILADDR),

severity=$(SIG_HI)

)

Afteryouinspecttheresults,resignthepolicyfileandreinitializethedatabase.

Page 542: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithTripwire:

IntroductiontoTripwire(man8twintro)Tripwireconfigurationmanualpage(man4twconfig)Tripwirepolicymanualpage(man4twpolicy)IntrusiondetectionwithTripwire(http://www.akadia.com/services/tripwire.html)HowtosetupanduseTripwire(http://www.linuxjournal.com/article/8758)

Page 543: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

UsingClamAVtofightvirusesThethreatfromviruses,Trojans,andotherformsofmalwareisreal.Theyhavegrownexponentiallyinbothquantityandinsophistication,andantivirussoftwarehavehadtoadoptsophisticateddetectionmethods.Whilethere'snoguaranteethatyoursystemwillnotfallvictimtotheseunwantedbitsofcode,remainingmindfulwhenusingtheInternetandsharingfiles,implementingcommon-sensesecuritypolicies,andusinganup-to-dateantivirusprogramcangoalongwayinprotectingyou.ThisrecipewillshowyouhowtoinstallClamAV,theprofessional-gradeopen-sourceantivirusprogram,keepitsthreatdatabaseuptodate,andscanyoursystem.

Page 544: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.TheClamAVpackagescanbefoundintheEPELrepository,sotherepositorymustberegisteredasdiscussedinChapter4,SoftwareInstallationManagement.Administrativeprivilegesarealsorequiredeitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 545: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoinstallClamAVandscanforvirusesandTrojans:

1. Installtheclamavandclamav-updatepackagesfromtheEPELrepository:

yuminstallclamavclamav-update

2. Openthefreshclamconfigurationfilewithyourtexteditor:

vi/etc/freshclam.conf

3. LocatetheExamplelineandaddan#tothestartofitslinetocommentitout:

#Commentorremovethelinebelow

#Example

4. Savetheupdateandclosethefile.5. Runfreshclamtoupdatethescanner'sthreatdatabase:

freshclam

6. Createasystemdservicefiletomanagethefreshclamdaemonforautomateupdates:

vi/lib/systemd/system/freshclam.service

7. Usethefollowingforthefile'scontent:

[Unit]

Description=freshclamdaemontoupdateclamav

After=network.target

[Service]

Type=forking

ExecStart=/usr/bin/freshclam-d

Restart=on-failure

[Install]

WantedBy=multi-user.target

8. Forcesystemdtoreloaditsservices:

systemctldaemon-reload

9. Startthenewfreshclamserviceandenableittostartwhenthesystemreboots:

systemctlstartfreshclam.service

systemctlenablefreshclam.service

10. Scanthefilesinyourhomedirectoryforthreatsusingclamscan:

clamscan-ir/home/tboronczyk

Page 546: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...First,weinstalledtheclamavandclamav-updatepackages.Theclamavpackagecontainsthevirusscannerwhileclamav-updatecontainsthefreshclamprogram,whichupdatesClamAV'svirusdefinitionstokeepituptodate:

yuminstallclamavclamav-update

freshclamreadsitsconfigurationfrom/etc/freshclam.conf.ThefilecontainsalinewiththewordExampletopreventusersfromusingthedefaultsblindlyandwemustremoveitorcommentitoutbeforewecanusefreshclam.Thedefaultssettingsarefineforourpurposesandthisismoreofanannoyancethananythingelse,butitdoesforceustolookatthefileandseewhatbehaviorcanbetweaked.Eachdirectiveiscommentedwithanexplanationandwhatthedefaultbehavioris.

Then,weranfreshclamtoupdatethescanner'sdatabases:

freshclam

Note

Theprocessoutputsitsprogresstotheterminalandyoumayseeseveralerrormessages.Forexample,itmayreportthatitwasunabletodownloadadailyfile.Don'tpanic;freshclamwilltryseveralmirrors.Aslongasitreportsthatmain.cvd,daily.cvd,andbytecode.cvdareuptodatewhenit'sfinishedyouknowyouhavethelatestdefinitions.

Wecanrunfreshclamanytimewewanttomakesurethedefinitiondatabasesareuptodate,butitwouldbeinconvenienttohavetoalwaysrunitmanually.Whenlaunchedwiththe-dargument,freshclamwillruninthedaemonmodeandperiodicallycheckforupdatesthroughouttheday(everytwohoursbydefault).Tokeepthingsclean,wecreatedaservicefiletorunfreshclamandregistereditwithsystemd:

[Unit]

Description=freshclamclamavupdatedaemon

After=network.target

[Service]

Type=forking

ExecStart=/usr/bin/freshclam-d

Restart=on-failure

[Install]

WantedBy=multi-user.target

The[Unit]sectiondefinesthebasicattributesoftheservice,suchasitsdescriptionandthatitreliesonanetworkconnection.The[Service]sectiondefinestheserviceitself,ExecStartwillrunfreshclamwiththe-dargument,Typeletssystemdknowthattheprocesswillforkandruninthebackgroundasadaemon,andRestartwillhavesystemdmonitortheserviceandrestartitautomaticallyifitcrashes.The[Install]sectiondefineshowitwillbelinkedwhenwerunsystemctlenable.

Page 547: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Note

Thesystemfile'scontentisprettybasicandcanbeusedasastartingpointforothercustomservicesyouwrite.

Scanningfilesforthreatsisdonewithclamscan:

clamscan-ir/home/tboronczyk

The-iargumentinstructsthescannertoonlyoutputinfectedfilesasopposedtothenameofeveryfileitscans.-rtriggersarecursivescan,descendingintosubdirectories.Thepathgivencanbeanindividualfiletoscanoradirectory,inthiscase,ourhomedirectory:

ClamAVprovidesasummaryofitsscanresults

Note

YoucanuseEICAR'stestfilesfromhttp://www.eicar.org/85-0-Download.htmltoverifyifClamAVisworking.Readtheirintendedusepageformoreinformationathttp://www.eicar.org/86-0-Intended-use.html.

ClamAVisgenerallyusedintwoways—asascannertoexamineexistingfilestodetectthreatsorasafiltertodetectthreatsinastreamofdatainrealtime.Theeasiestwaytoscheduleareoccurringscanisbysettingupacronjob.

Tocreateapersonalcronjobthatrunsclamavtoscanyourhomedirectory,usecrontab:

crontab-e

crontabwilllaunchyourdefaulteditorforyoutoenterthejobschedule.Thencrontabwillautomaticallyactivatethejobafteryousavethescheduleandclosethefile.

Anexampleschedulethatrunsclamscaneverydayat3:00a.m.mightlookasfollows:

Page 548: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

03***clamscan>>$HOME/clamscan.log

Thefirstfivecolumnsspecifythetimewhenthejobshouldrun.Thefirstcolumnisthetime'sminutes,thesecondishours,thethirdisthedayofthemonth,thefourthisthemonth,andlastisthedayoftheweekwhenthejobwillrun.*isusedasashorthandtoindicatetheentirerange,thustheexamplewillruneverydayofeverymonth.Moreinformationcanbefoundinthemanpageoutliningtheformatofthecrontabfile(man5crontab).

Onaserversystem,ClamAVisoftenrunasareal-timescannerasamailfilter.Messagesarereceivedbythemailserver,forexamplePostfix,andpassedofftoClamAVforscanning.Assumingthatyou'rerunningPostfix,asdiscussedinChapter9,ManagingE-mails,here'swhatyou'llneedtodotosetupClamAVandPostfixtoworktogether.

First,weneedtoinstallsomeadditionalpackages.Theclamav-scanner-systemdpackagewillinstallthefunctionalityweneedtorunclamscanasadaemonsothatit'salwaysavailableandtheclamav-milter-systemdpackageinstallsamailfilterthatactsasaproxybetweenPostfixandthescanner:

yuminstallclamav-scanner-systemdclamav-milter-systemd

Then,edittheconfigurationfile/etc/clamd.d/scan.conf.CommentouttheExamplelineanduncommenttheLocalSocketoption:

LocalSocket/var/run/clamd.scan/clamd.sock

ThevaluegivenwithLocalSocketisthesocketfileusedbythescannerdaemonforcommunicatingwithoutsideprocesses.

Next,editthe/etc/mail/clamav-milter.conffile,whichistheconfigurationfilefortheclamav-miltermailfilter.CommentouttheExampleline,uncommentthefirstMilterSocketdirective,andaddtheClamdSocketdirective.ThevalueforClamdSocketshouldbethesameastheLocalSocketinscan.confbutprefixedwithunix:todenotethatit'saUnixsocket:

MilterSocket/var/run/clamav-milter/clamav.socket

ClamdSocketunix:/var/run/clamd.scan/clamd.sock

Startandenablethescannerdaemonandthefilterservices:

[email protected]

[email protected]

Finally,open/etc/postfix/main.cnfandaddansmtpd_miltersentrywhichletsPostfixknowaboutthefilter:

smtpd_milters=unix:/var/run/clamav-milter/clamav.socket

Don'tforgettorestartPostfixafterupdatingitsconfiguration:

systemctlrestartpostfix.service

Page 549: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithClamAV:

ClamAVdocumentation(http://www.clamav.net/documents/installing-clamav)EuropeanInstituteforComputerAnti-VirusResearch(http://www.eicar.org/)

Page 550: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CheckingforrootkitswithchkrootkitIntheunfortunateeventthatanattackergainsaccesstoyoursystem,oneofthefirstthingsthey'lldoistrytohidetheirintrusionwhilepreservingaccessforaslongaspossible,perhapsbyinstallingarootkit.Arootkitisaprogramthatrunsstealthilyandgivestheattackeradministratoraccess.TheyembedthemselvesintheLinuxkerneltopreventdetection,andthereareevenrootkitsthatcanhideinasystemfirmware'sdedicatedmemoryallowinganattackertocontrolthesystemevenwhenit'spowereddown.Thisrecipeshowsyouhowtocheckyoursystemforrootkitsusingchkrootkit.

Page 551: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 552: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstousechkrootkittocheckforrootkits:

1. Installthegccandglibc-staticpackagesthatareneededtocompilechkrootkitbinaries:

yuminstallgccglibc-static

2. Downloadchkrootkitsourcecode:

curl-Oftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz

3. Extractthedownloadedsourcecodearchiveandenterintothecode'sdirectory:

tarxzvfchkrootkit.tar.gz

cdchkrootkit-0.50

4. Runmaketocompilechkrootkit'sbinarycomponents:

make

5. chkrootkitrequiresnetstattoconductitsnetworktestswhichisavailableinthenet-toolspackage:

yuminstallnet-tools

6. Runchkrootkittoscanforrootkits:

./chkrootkit

Page 553: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...chkrootkitconsistsofashellscriptandasmallcollectionofcompiledutilitiesdistributedassourcecodesoweneedtocompileit.Thismeansyou'llneedacompilerinstalledonyoursystem.Minimally,gccwillsuffice.Also,weneedtoinstalltheglibc-staticpackagebecausetheproject'sMakefilebuildsastaticallycompiledbinary—allofthebinaries'dependenciesarecompiledin;itdoesn'tdynamicallyreferencethecopyofthesystem'ssharedlibraries:

yuminstallgccglibc-static

Thesourcecodeforchkrootkitisavailableontheproject'swebsite.Thelinkusedintherecipeisadirectlinktothelatestsourcearchiveandisdownloadedusingcurl:

curl-Oftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz

Oncethedownloadiscomplete,buildingchkrootkit'sisamatterofextractingthearchive,enteringintothenewlycreateddirectory,andrunningmake:

make

WhenyoulearnedhowtocompileaprogramfromsourcecodeintheCompilingaprogramfromsourcerecipeofChapter4,SoftwareInstallationManagement,youusedthecommonconfigure,make,andmakeinstallapproach.However,chkrootkitdoesn'tshipwithaconfigurescriptanditsMakefiledoesn'tcontainaninstalltarget.Allweneedtodoheretokickoffthecompilationprocessisinvokemakeitself.

chkrootkitrunsaseriesofteststocheckforknownrootkitsignatures.Someofthesetestsuseitscompiledutilitieswhileothersusecommonsystemutilities.Oneofitsnetworktestscheckswhichportsareopenusingnetstat,whichisnotinstalledbydefaultonCentOSbutisavailableinthenet-toolspackage.So,beforewecanusechkrootkit,weneedtoinstallthisdependency:

yuminstallnet-tools

Onceeverythingisinstalled,wecanexecutethechkrootkitscript.Whenrunwithoutanyarguments,chkrootkitexecutesallofitstests.Otherwise,wecanspecifyoneormoretestsandonlythosewillrun.The-l(lowercaseL)argumentwilldisplayalistofpossibletests:

./chkrootkit-l

Page 554: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithchkrootkit:

Thechkrootkitwebsite(http://www.chkrootkit.org)Chkrootkit:checkyoursystemforhiddenrootkits(https://www.youtube.com/watch?v=IdvdUv0Nsq4)

Page 555: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

UsingBaculafornetworkbackupsThefactofthematteristhatwearelivinginaworldthatisbecomingincreasinglydependentondata.Also,fromaccidentaldeletiontoacatastrophicharddrivefailure,therearemanythreatstothesafetyofyourdata.Themoreimportantyourdataisandthemoredifficultitistorecreateifitwerelost,themoreimportantitistohavebackups.So,thisrecipeshowsyouhowyoucansetupabackupserverusingBaculaandhowtoconfigureothersystemsonyournetworktobackuptheirdatatoit.

Page 556: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresatleasttwoCentOSsystemswithworkingnetworkconnections.Thefirstsystemisthelocalsystemwhichwe'llassumehasthehostnamebenitoandtheIPaddress192.168.56.41.Thesecondsystemisthebackupserver.You'llneedadministrativeaccessonbothsystems,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 557: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...PerformthefollowingstepsonyourlocalsystemtoinstallandconfiguretheBaculafiledaemon:

1. Installthebacula-clientpackage:

yuminstallbacula-client

2. Openthefiledaemon'sconfigurationfilewithyourtexteditor:

vi/etc/bacula/bacula-fd.conf

3. IntheFileDaemonresource,updatethevalueoftheNamedirectivetoreflectthesystem'shostnamewiththesuffix-fd:

FileDaemon{

Name=benito-fd

...

}

4. Savethechangesandclosethefile.5. Startthefiledaemonandenableittostartwhenthesystemreboots:

systemctlstartbacula-fd.service

systemctlenablebacula-fd.service

6. OpenthefirewalltoallowTCPtrafficthroughtoport9102:

firewall-cmd--zone=public--permanent--add-port=9102/tcp

firewall-cmd--reload

7. Repeatsteps1-6oneachsystemthatwillbebackedup.

PerformthefollowingstepsonthesystemdesignatedasthebackupservertoinstallandconfiguretheBaculadirector,storage,andfiledaemons.

1. Installthebacula-console,bacula-director,bacula-storage,andbacula-clientpackages:

yuminstallbacula-consolebacula-directorbacula-storage

bacula-client

2. Re-linkthecataloglibrarytouseSQLitedatabasestorage:

alternatives--configlibbaccats.so

3. Type2whenaskedtoprovidetheselectionnumber.4. CreatetheSQLitedatabasefileandimportthetableschema:

/usr/libexec/bacula/create_sqlite3_database

/usr/libexec/bacula/make_sqlite3_tables

Page 558: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

5. Openthedirector'sconfigurationfilewithyourtexteditor:

vi/etc/bacula/bacula-dir.conf

6. IntheJobresourcewhereNamehasthevalueBackupClient1,changethevalueoftheNamedirectivetoreflectoneofthelocalsystems.ThenaddaClientdirectivewithavaluethatmatchesthatsystem'sFileDaemonName:

Job{

Name="BackupBenito"

Client=benito-fd

JobDefs="DefaultJob"

}

7. DuplicatetheJobresourceandupdateitsdirectivevaluesasnecessarysothatthereisaJobresourcedefinedforeachsystemtobebackedup.

8. Foreachsystemthatwillbebackedup,duplicatetheClientresourcewheretheNamedirectiveissettobacula-fd.Inthecopiedresource,updatetheNameandAddressdirectivestoidentifythatsystem:

Client{

Name=bacula-fd

Address=localhost

...

}

Client{

Name=benito-fd

Address=192.168.56.41

...

}

Client{

Name=javier-fd

Address=192.168.56.42

...

}

9. Saveyourchangesandclosethefile.10. Openthestoragedaemon'sconfigurationfile:

vi/etc/bacula/bacula-sd.conf

11. IntheDeviceresourcewhereNamehasthevalueFileStorage,changethevalueoftheArchiveDevicedirectiveto/bacula:

Device{

Name=FileStorage

MediaType=File

ArchiveDevice=/bacula

...

12. Savetheupdateandclosethefile.13. Createthe/baculadirectoryandassignittheproperownership:

mkdir/bacula

Page 559: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

chownbacula:bacula/bacula

14. IfyouhaveSELinuxenabled,resetthesecuritycontextonthenewdirectory:

restorecon-Rv/bacula

15. Startthedirectorandstoragedaemonsandenablethemtostartwhenthesystemreboots:

systemctlstartbacula-dir.servicebacula-sd.service

bacula-fd.service

systemctlenablebacula-dir.servicebacula-sd.service

bacula-fd.service

16. OpenthefirewalltoallowTCPtrafficthroughtoports9101-9103:

firewall-cmd--zone=public--permanent--add-port=9101-9103/tcp

firewall-cmd-reload

17. LaunchBacula'sconsoleinterface:

bconsole

18. Enterlabeltocreateadestinationforthebackup.Whenpromptedforthevolumename,useVolume0001orasimilarvalue.Whenpromptedforthepool,selecttheFilepool:

label

19. Enterquittoleavetheconsoleinterface.

Page 560: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

HowitworksConfiguringBaculacanbeadauntingtaskforthemostpartbecauseofthesuite'sdistributedarchitectureandthelevelofflexibilityitoffersinorganizingandschedulingbackupandrestorejobs.However,onceeverythingisupandrunning,I'msureyou'llhavepeaceofmindknowingthatyourdataissafefromaccidentsanddisasters.

Baculaismadeupofseveralcomponents.Inthisrecipe,oureffortswerecenteredonthreedaemons—thedirector,thefiledaemon,andthestoragedaemon.Thefiledaemonisinstalledoneachoftheclientsystemstobebackedupandlistensforconnectionsfromthedirector.Thedirectorconnectstoeachfiledaemonasscheduledandtellsitwhichfilestobackupandwheretocopythemto(thestoragedaemon).Thestoragedaemonreceivesthebackedupdataandwritesittothebackupmedium,forexample,thediskortapedrive.

First,weinstalledthefiledaemonwiththebacula-clientpackageonourclientsystems.Thenweeditedthefiledaemon'sconfigurationfilefoundat/etc/bacula/bacula-fd.conftospecifythenameoftheprocess.Theconventionistoaddthesuffix-fdtothesystem'shostname:

FileDaemon{

Name=benito-fd

FDPort=9102

WorkingDirectory=/var/spool/bacula

PidDirectory=/var/run

MaximumConcurrentJobs=20

}

Aftertheupdateismadetotheconfiguration,westartedtheserviceandopenedtheappropriateportinthesystemfirewall.Thefiledaemonisnowlistening,waitingforthedirectortoconnectandtellitwhatitneedstodo.

Onthebackupserver,weinstalledthebacula-director,bacula-storage,andbacula-clientpackages.Thisgivesusthedirectorandstoragedaemon,andanotherfiledaemon.Thefiledaemon'spurposehereonthebackupserveristobackupBacula'scatalog:

Page 561: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ThisimagereproducedfromBacula'sdocumentationshowshowthedifferentapplicationsrelatetooneanother

Baculamaintainsadatabaseofmetadataaboutpreviousbackupjobscalledthecatalog,whichcanbemanagedbyMySQL,PostgreSQL,orSQLite.SQLiteisanembeddeddatabaselibrary,meaningtheprogramusingitlinksagainsttheSQLitelibraryandmanagesitsowndatabasefiles.Tosupportmultipledatabases,Bacula'scodeiswrittensothatallthedatabaseaccessroutinesarecontainedinseparatesharedlibrarieswithadifferentlibraryforeachdatabase.Then,whenBaculawantstointeractwithadatabase,itdoessothroughlibbaccats.so,afake

Page 562: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

librarythatisnothingmorethanasymboliclinkpointingtooneofthespecificdatabaselibraries.Thislet'sBaculasupportdifferentdatabaseswithoutrequiringustorecompileitssourcecode.

Tocreatethesymboliclink,weusedalternativesandselectthereallibrarythatwewanttouse:

alternatives--configlibbaccats.so

Then,weinitializedthedatabase'sschemausingthescriptsthatcomewithBacula:

/usr/libexec/bacula/create_sqlite3_database

/usr/libexec/bacula/make_sqlite3_tables

Baculasupportsmultipledatabaseswithoutrecompiling

Note

ThisrecipetookadvantageofBacula'sSQLitesupportbecauseit'sconvenientanddoesn'trequireadditionalefforttosetup.IfyouwanttouseMySQL,installMySQLasdiscussedinChapter7,WorkingwithDatabases,createadedicatedMySQLuserforBaculatouse,andtheninitializetheschemawiththefollowingscripts:

/usr/libexec/bacula/grant_mysql_privileges

/usr/libexec/bacula/create_mysql_database

/usr/libexec/bacula/make_mysql_tables

You'llalsoneedtoreviewBacula'sconfigurationfilestoprovideBaculawiththerequiredMySQLcredentials.

Differentresourcesaredefinedinthedirector'sconfigurationfileat/etc/bacula/bacula-dir.conf,manyofwhichconsistnotonlyoftheirownvaluesbutalsoreferencetootherresources.Forexample,theFileSetresourcespecifieswhichfilesareincludedorexcludedinbackupsandrestores,whileaScheduleresourcespecifieswhenbackupsshouldbemade.AJobDefresourcecancontainvariousconfigurationdirectivesthatarecommontomultiple

Page 563: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

backupjobsandalsoreferenceparticularFileSetandScheduleresources.Clientresourcesidentifythenamesandaddressesofsystemsrunningfiledaemons,andaJobresourcewillpulltogetheraJobDefandClientresourcetodefinethebackuporrestoretaskforaparticularsystem.Someresourcesdefinethingsatamoregranularlevelandareusedasbuildingblockstodefineotherresources,creatingcomplexdefinitionsinaflexiblemanner.

Tip

Thedefaultresourcedefinitionsdefinebasicbackupandrestorejobssufficientforthisrecipe.You'llwanttostudytheconfigurationandseehowthedifferentresourcesfittogethersoyoucantweakthemtobettersuityourbackupneeds.

Page 564: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thisimage,reproducedfromBacula'sdocumentationshows,howthedifferentresourcesrelatetooneanother

Togetstarted,wecustomizedtheexistingbackupJobbychangingitsnameandclient.ThenwecustomizedtheexistingClientresourcebychangingitsnameandaddresstopointtoaspecificsystemrunningafiledaemon.ThepairofJobandClientresourceswereduplicated,apairforeachsystemwe'rebackingup.NoticethatwealsoleftadefaultClientresourcethatdefinesbacula-fdforthelocalhost.Thisisthefiledaemonthat'slocaltothebackupserverandwillbethetargetforthingssuchasrestorejobsandcatalogbackups:

Job{

Name="BackupBenito"

Client=benito-fd

JobDefs="DefaultJob"

}

Job{

Name="BackupJavier"

Client=javier-fd

JobDefs="DefaultJob"

}

Client{

Name=bacula-fd

Address=localhost

...

}

Client{

Name=benito-fd

Address=192.168.56.100

...

}

Client{

Name=javier-fd

Address=192.168.56.100

...

}

Tip

Ifyouhavealotofclientsystemsoralotofjobdefinitions,youcanstaybetterorganizedbydefiningtheseresourcesintheirownfilesandreadthemintobacula-dir.conf.Createthedirectory/etc/bacula/config.d,andplacetheindividualconfigurationfilesthere.Thenaddthefollowinglinetobacula-dir.conftoreadthem:

@|"find/etc/bacula/config.d-name'*.conf'f-exececho@{}\;"

Tocompletethesetup,weneedtolabelabackupvolume.Thistask,aswithmostothers,is

Page 565: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

performedthroughbconsole,aconsoleinterfacetotheBaculadirector.

Weusedthelabelcommandtodefinealabelforthebackupvolume,andwhenpromptedforthepool,weassignedthelabeledvolumetotheFilepool.Inawayverysimilartohowlogicalvolumeswork(refertoChapter5,ManagingFilesystemsandStorage),anindividualdeviceorstorageunitisallocatedasavolumeandthevolumesaregroupedintostoragepools.Ifapoolcontainstwovolumesbackedbytapedrivesforexample,andoneofthedrivesisfull,thestoragedaemonwillwritethebackupdatatothetapethathasspaceavailable.Eventhoughinourconfigurationwe'restoringthebackuptodisk,westillneedtocreateavolumeasthedestinationfordatatobewrittento.

Atthispoint,youshouldconsiderwhichbackupstrategyworksbestforyou.Afullbackupisacompletecopyofyourdata,adifferentialbackupcapturesonlythefilesthathavechangedsincethelastfullbackup,andanincrementalbackupcopiesthefilesthathavechangedsincethelastbackup(regardlessofthetypeofbackup).Commonly,administratorsemployacombinationofthese,perhapsmakingafullbackupatthestartoftheweekandthendifferentialorincrementalbackupseachdaythereafter.Thissavesstoragespacebecausethedifferentialandincrementalbackupsaresmallerandalsoconvenientwhentheneedtorestoreafilearises,becausealimitednumberofbackupsneedtobesearchedforthefile.

Anotherconsiderationistheexpectedsizeofeachbackupandhowlongitwilltakeforthebackuptoruntocompletion.Fullbackupsobviouslytakelongertorun,andinanofficewith9-5workinghours,MondaythroughFriday,itmaynotbepossibletorunafullbackupduringtheevenings.PerformingafullbackuponFridaysgivesthebackuptimeovertheweekendtorun.Smaller,incrementalbackupscanbeperformedontheotherdayswhentimeislesser.

Stillanotherpointthatisimportantinyourbackupstrategyishowlongthebackupswillbekeptandwheretheywillbekept.Thistouchesonalargerissue,disasterrecovery.Ifyourofficeburnsdown,ayear'sworthofbackupswillbeofnouseiftheyweresittingintheoffice'sITcloset.Atoneemployer,wekeptthelastfullbackupandlastday'sincrementalonadiskonsite.Thesewerethenduplicatedtotapeandshippedoffsite.

Regardlessofthestrategyyouchoosetoimplement,yourbackupsareonlyasgoodasyourabilitytorestoredatafromthem.Youshouldperiodicallytestyourbackupstomakesureyoucanrestoreyourfiles.

Torunabackupjobondemand,enterruninbconsole.You'llbepromptedwithamenutoselectoneofthecurrentconfiguredjobs.You'llthenbepresentedwiththejob'soptions,suchaswhatlevelofbackupwillbeperformed(full,incremental,ordifferential),it'spriority,andwhenitwillrun.Youcantypeyesornotoacceptorcancelitormodtomodifyaparameter.Onceaccepted,thejobwillbequeuedandassignedajobID.

Torestorefilesfromabackup,usetherestorecommand.You'llbepresentedwithalistofoptionsallowingyoutospecifywhichbackupthedesiredfileswillberetrievedfrom.

Page 566: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Dependingonyourselection,thepromptswillbedifferent.Bacula'spromptsareratherclear,soreadthemcarefullyanditwillguideyouthroughtheprocess.

Apartfromtherunandrestorecommands,anotherusefulcommandisstatus.ItwillallowyoutoseethecurrentstatusoftheBaculacomponents,ifthereareanyjobscurrentlyrunning,andwhichjobshavecompleted.Afulllistofcommandscanberetrievedbytypinghelpinbconsole.

bconsoleisaconsoleinterfacetotheBaculadirector

Page 567: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithBacula:

Baculadocumentation(http://blog.bacula.org/documentation/)HowtouseBaculaonCentOS7(https://www.digitalocean.com/community/tutorial_series/how-to-use-bacula-on-centos-7)Bacula-Web(aweb-basedreportingandmonitoringtoolforBacula)(http://www.bacula-web.org/)

Page 568: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Chapter12.VirtualizationThischaptercontainsthefollowingrecipes:

CreatinganewvirtualmachineCloningavirtualmachineAddingstoragetoavirtualmachineConnectingUSBperipheralstoaguestsystemConfiguringaguest'snetworkinterface

Page 569: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

IntroductionTherecipesinthischapterfocusonrunningasecondoperatingsystemasaguestusingvirtualizationonyourCentOSsystem.You'lllearnhowtosetupthevirtualmachinetoinstallaguestoperatingsystem,properlycreateacopyofthemachinethroughcloning,andaddadditionalstorageresources.You'llalsolearnhowtoshareaccesstoUSBperipheralsattachedtothehostsystemandconfiguretheguest'svirtualnetworkinterfacetoaccessthenetwork.

Page 570: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CreatinganewvirtualmachineThisrecipeteachesyouhowtoinstalltheKVMvirtualizationsoftwareandcreateanewvirtualmachine.Virtualizationallowsustotakeadvantageofthehardwareresourcesavailabletousbyrunningmultipleoperatingsystemsonthesamephysicalsystem.Theprimaryoperatingsystemisinstalled"bare-metal"andisknownasthehostOS.Then,specialsoftwareisinstalledthatallowsthehosttoprovideemulationordirectaccesstohardwareresources.Theresourcesarepartitionedasvirtualmachinesandseveralguestoperatingsystemscanthenbeinstalledandrunontopofthehost,eachintheirownvirtualmachine.

Page 571: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnectionandagraphicaluserinterfaceinstalled(refertotheInstallingtheGNOMEdesktopandInstallingtheKDEPlasmadesktoprecipesinChapter1,GettingStartedwithCentOS).Administrativeprivilegesarealsorequired,eitherbylogginginwiththerootaccountorthroughtheuseofsudo.

Page 572: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoinstallaguestoperatingsystem:

1. Installthenecessaryvirtualizationpackagesusingpackagegroups:

yumgroupinstall"VirtualizationPlatform"

"VirtualizationClient""VirtualizationTools"

2. LaunchtheVirtualMachineManagerapplication:

virt-manager

3. CreateanewvirtualmachinebyselectingNewVirtualMachinefromtheFilemenu.ThisopenstheNewVMwizard.

4. SelectthedesiredinstallationmethodandclickonForward.Forthisrecipe,we'llchoosetheLocalinstallmediaoption:

Page 573: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheNewVMwizardcollectsthenecessarydetailstocreateanewmachine

5. Selectthemediasource.IfthemediaisaCDorDVD,selecttheUseCDROMorDVDoption.IfthemediaisanISOfile,selecttheUseISOimageoptionandspecifythepathtotheimagefile.Then,clickonForward:

Page 574: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ThenewmachinewilluseanISOfileasitsinstallationmedia

6. SettheamountofRAMandthenumberofCPUsthatyouwanttoallocatetothevirtualmachineandthenclickonForward:

Page 575: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

1GBofRAMand1CPUareallocatedtothevirtualmachine

7. SpecifythestoragecapacitythatwillbeallocatedtothemachineandthenclickonForward:

Page 576: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Themachineissetupwith8GBofstorage

8. ProvideanametoidentifythevirtualmachineandclickonFinish:

Page 577: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Thewizardisreadytocreatethevirtualmachineandboottheinstallationmedia

9. Thevirtualmachinewillautomaticallystartandbootfromthespecifiedinstallation

Page 578: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

media.Youcannowproceedwithinstallingyourguestoperatingsysteminthemachineasifitwereaphysicalsystem:

Anoperatingsystemcanbeinstalledonthevirtualmachinethesamewayasaphysicalsystem

Page 579: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thenecessarysoftwareisinstalledbyinstallingthreepackagegroups;theVirtualizationPlatformgroupinstallsthebasevirtualizationlibraries,theVirtualizationClientpackageinstallsclientprogramsforcreatingandmanagingvirtualmachines,andtheVirtualizationToolspackageinstallsutilitiesformaintainingthemachines:

yumgroupinstall"VirtualizationPlatform"

"VirtualizationClient""VirtualizationTools"

Afterinstallingthesoftware,weusedtheVirtualMachineManagertocreateamachine.Themachinedefinesavirtualsystem,specifyingwhatresourcesareavailabletotheguestandhowtheguestmayaccessthem.UndertheGNOMEdesktopenvironment,themanagerislaunchedfromtheSystemToolscategoryoftheApplicationsmenu.InKDE,it'sfoundviatheKickoffApplicationLauncherunderApplications|SystemTools.Themanagercanalsobelaunchedfromthecommandlinewithvirt-manager:

virt-manager

Note

Anewvirtualmachinecanbecreatedonthecommandlineaswell,usingvirt-installandspecifyingtheresourceallocationsasarguments.Thisisespeciallyusefulifyouwanttoscripttheprocessofspinningupnewguests.

Themanager'snewVMmakesiteasytocreateanewvirtualmachinedefinitionbypromptingusforthenecessaryresourceallocations.Forinstance,we'reaskedtoprovidetheamountofRAM,thenumberofCPUs,andtheamountofstoragespacetomakeavailabletotheguest.Afterweprovidethevalues,itcreatesthemachineandstartsit,bootingfromthespecifiedinstallationmediatoinstalltheguestoperatingsystem.Fromthere,installingtheoperatingsystemisthesameasifyouwereinstallingitonaphysicalsystem.

Tobootavirtualmachine,selectthedesiredmachinefromtheavailablelistsothatit'shighlightedandthenclickontheplayarrowiconinthemanager'stoolbar.Alternatively,right-clickonthelistentryandselectRunfromthecontextmenu.ThispowersonthemachineanditsstatuschangestoRunning.Whenyou'refinished,youcanpowerthemachineoffbyclickingonthepowerswitchiconinthetoolbarorononeoftheShutDownoptionsfromthecontextmenu.Themachine'sstatuschangestoShutoff.Tointeractwiththeguestwhileit'srunning,double-clickontheentryorhighlightitandthenclickontheOpeniconinthemanager'stoolbar.

Note

Scrollbarswillappearonthesideandbottomofthewindowiftheguest'sdisplayistoolargetoshowinitsentirety.Scalingittofitwithinthewindowcanimproveyourexperience.Toadjustthedisplay'spresentation,selectDisplayfromView.

Page 580: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithvirtualmachines:

Thevirt-installmanualpage(man1virt-install)TheKVMwebsite(http://www.linux-kvm.org/page/Main_Page)RHEL7VirtualizationDeploymentandAdministrationGuide(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Virtualization_Deployment_and_Administration_Guide/BestpracticesforKVM(http://www.ibm.com/support/knowledgecenter/linuxonibm/liaat/liaatbpkickoff.htm)

Page 581: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

CloningavirtualmachineSinceavirtualmachineisultimatelynothingmorethandatafiles,thesecaneasilybecopiedandshared.Thisisusefulbecauseyoucansetupagoldserverexactlyhowyouwantitandthenmakecopiesthatareusedfordifferentpurposes.However,usingthecpcommandisn'tthewaytogoaboutit.Thisrecipeshowsyouthecorrectwaytoduplicateamachinewithaprocesscalledcloning.

Page 582: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresavirtualmachinesetupasdescribedinthepreviousrecipe.Whilethecloningprocessdoesn'trequireadministrativeprivilegesperse,privilegesmaybeneededtoaccessthemachine'sfilesdependingonwheretheyarelocated.Bydefault,thefilesarestoredat/var/lib/libvirt/images,whichrequiresadministrativeaccess.

Page 583: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstocloneavirtualmachine:

1. Makesurethemachineyouwanttocloneisnotrunning.2. InVirtualMachineManager,right-clickonthedesiredmachineinthelistofavailable

machinesandselectClonefromthecontextmenu.ThisopenstheCloneVirtualMachinedialog:

Page 584: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

TheCloneVirtualMachinedialogmakesiteasytocloneamachineimage

Page 585: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

3. SpecifyauniquenameforthenewimageandclickontheClonebutton.Thiswillcreateastandalonecopyofthevirtualmachineandselectedstorage.

Page 586: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...ThisrecipeusedVirtualMachineManagertocreateacopyofamachineknownasaclone.Themachineshouldbeclonedinthismannerinsteadofsimplycopyingtheunderlyingfiles,becausethecloningprocessalsoupdatesvariousidentifiersthatshouldbeuniquebetweenmachines,suchastheMACaddressofthenetworkinterface.

Note

Thevirt-clonecommandcanbeusedtocloneaguestonthecommand-line.Formoreinformation,refertotheprogram'smanpageusingman1virt-clone.

Ifyouwanttoupdatevariousaspectsoftheclonedmachinebeforebootingit,youcanusetoolssuchasvirt-sysprepandvirt-configure.Theseprogramsmountthemachine'sdiskimageinachrootedenvironment,performtherequestedmodifications,andthenunmounttheimage.virt-sysprepisinstalledvialibguestfs-tools-c:

yuminstalllibguestfs-tools-c

Toviewalistoftheavailablemaintenanceactionsvirt-sysprepcanperform,invoketheprogramusing--list-operations.Eachoptionwillbedisplayedalongwithabriefdescriptionofwhatitdoes.Toperformanoperation,usethe--operationargumentfollowedbyoneormoreoftheoperationlabels,separatedbycommas.Forexample,thefollowingcommandclearsthebashhistoryforanyaccountsonthesystemanddeletesanyfilesthatmaybein/tmp.The-aargumentprovidesthepathtothemachine'sdiskimage:

virt-sysprep-a/var/lib/virt/images/Ubuntu-clone.qcow2

--operationsbash-history,tmp-files

Dependingonwhattheoriginalmachineimagewasusedfor,youmayfindthefollowingcleanupoperationsusefulaswell:

ca-certificates:ThisdeletesanyCAcertificateslogfiles:Thisdeleteslogfilesssh-hostkeys:ThisdeletestheSSHhostkeysssh-userdir:Thisdeletestheusers'.sshdirectoriesuser-account:Thisdeletesalluseraccountsexceptforroot

Thereissomeoverlapinthefunctionalityofvirt-sysprepandvirt-customize;however,virt-customizeperformsmoregeneralcustomizationoperations,whilevirt-sysprep'sactionsfocusmoreoncleaningupanimage.virt-customizecandothingslikemoveandsetthesystem'shostname,resetpasswords,andinstallanduninstallpackages.

Toresetthesystem'shostname,usethe--hostnameargumentandprovidethedesiredname:

virt-customize-a/var/lib/virt/images/Ubuntu-clone.qcow2

--hostnameubuntu2

Page 587: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

The--installand--uninstallargumentsaddandremovepackagesandspecifyoneormorepackagenamesseparatedbycommas:

virt-customize-a/var/lib/virt/images/Ubuntu-clone.qcow2

--installbuild-essential

Someargumentsyoumayfindusefulforvirt-customizeareasfollows:

--chmod:Thischangesfilepermissions--copy:Thiscreatesacopyofafileordirectory--delete:Thisremovesafileordirectory--mkdir:Thiscreatesanewdirectory--move:Thismovesafileordirectorytoanewdestination--password:Thisupdatesauser'spassword--run-command:Thisrunsacommandontheimage

Page 588: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationoncloningandcustomizingvirtualmachines:

Thevirt-clonemanualpage(man1virt-clone)Thevirt-configuremanualpage(man1virt-configure)Thevirt-sysprepmanualpage(man1virt-sysprep)HowtocloneaKVMvirtualmachineandresettheVM(http://www.unixarena.com/2015/12/how-to-clone-a-kvm-virtual-machines-and-reset-the-vm.html)

Page 589: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

AddingstoragetoavirtualmachineEvenifyou'renotadatahoarder,thetimewillprobablycomewhenyouneedtoaddadditionalstoragetoaguestsystem.Noworries!Thisiseasytodo!Thisrecipeteachesyouhowtoaddandmodifythevirtualhardwareattachedtoamachine.

Page 590: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresavirtualmachinesetupasdescribedinthepreviousrecipes.

Page 591: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoaddstoragetoavirtualmachine:

1. Makesurethevirtualmachineyouwanttomodifyisnotrunning.2. Openthevirtualmachinebydouble-clickingonthedesiredentryinthelistofavailable

machines.3. EitherclickonthelightbulbiconinthemenubarorselectDetailsfromViewtoshowthe

virtualmachine'shardwaredetails:

Themachine'svirtualhardwareisdisplayedandresourcescanbeadded,modified,andremoved

4. ClickontheAddHardwarebuttoninthebottom-leftcornerofthewindowtoopentheAddNewVirtualHardwarewindow.

5. SelectStoragefromthelistofpossibleresources.SpecifythedesiredstoragespacetoallocateforthenewdiskandclickonFinish:

Page 592: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Avirtual8GBstoragedriveisaddedtothemachine

6. LeavethehardwareviewbyeitherclickingonthecomputericoninthemenubarorselectingConsolefromView.

Page 593: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Thisrecipeshowedyouwheretoconfigurethevirtualhardwaredefinitionsassociatedwithamachine.Toincreasethestorageavailabletoaguestoperatingsystem,wenavigatedtothisviewandaddedanewvirtualdrive.Thestoragedevicecanbecreatedthroughtheinterface,asshownintherecipe,oranexistingdrivefilecanbeselectedandattachedtothesystem.

Note

Ifyouarecreatinganewdisk,youwillwanttopartition,format,andmountthestoragesoitcanbeused.YoumayfindtherecipesdiscussedinChapter5,ManagingFilesystemsandStoragehelpful.

Otherhardwarecanbemanagedviathehardwareviewaswell.Mostnotably,youcanaddandconfigurenewnetworkinterfacesandallocateadditionalRAMandCPUresources.IncreasingtheRAM/CPUmightbedonetorunresource-intensiveprocessesonthesystem—it'sbettertoallocateasmalleramountfirstandthenincreasetheresourceswhentheneedarises.

Anotherusefulconfigurationistochangethedisplayserver.Bydefault,thedisplayisconfiguredtouseSPICE,amorerobustprotocolthanVNC.ASPICEserverisbuiltintothevirtualizationplatformsothatyoucanconnecttothevirtualmachineusingaSPICEclienttoaccessitsdisplay,eveniftheguestisonlyrunningaconsoledisplay(refertohttps://www.spice-space.org/tofindaSPICEclient).IfyouwanttoconnectusingVNCinstead,selecttheDisplaySpiceentryinthehardwarelistandsetitsTypetoVNCserver.ChangetheAddressvaluetoAllinterfacestoacceptconnectionsfromoutsidethelocalhost,specifyaconnectionpassword,andthenclickontheApplybutton.

Thedisplay'slabelinthehardwarelistwillchangetoDisplayVNC:

Page 594: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Userscanconnecttoavirtualsystem'sdisplayusingaSPICEorVNCclient

Page 595: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonworkingwithvirtualhardware:

RHEL7VirtualizationDeploymentandAdministrationGuide:StoragePools(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Virtualization_Deployment_and_Administration_Guide/chap-Storage_pools.html)Storagemanagement(http://libvirt.org/storage.html)

Page 596: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

ConnectingUSBperipheralstoaguestsystemThisrecipeteachesyouhowtosharetheUSBdevicesthatareconnectedtothehostsystemwithavirtualmachine.ThismeansyoucanuseyourUSBprinters,webcams,andstoragedevicesfromyourguestoperatingsystem.

Page 597: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresavirtualmachinesetupasdescribedinthepreviousrecipes.

Page 598: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...FollowthesestepstoconnectUSBperipheralstoaguestsystem:

1. Makesurethevirtualmachineyouwanttomodifyisnotrunning.2. AttachtheUSBdevicetothephysicalsystem.3. Openthevirtualmachinebydouble-clickingonthedesiredentryinthelistofavailable

machines.4. Showthevirtualmachine'shardwaredetailsbyclickingonthelightbulbiconinthemenu

barorselectingDetailsfromView.5. ClickontheAddHardwarebuttontoopentheAddNewVirtualHardwarewindow.6. SelectUSBHOSTDevicefromthelistofresources.7. SelectthedesiredUSBdeviceandthenclickontheFinishbutton:

USBdevicesattachedtothehostsystemcanbeassignedtothevirtualmachines

Page 599: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

8. LeavethehardwareviewbyeitherclickingonthecomputericoninthemenubarorselectingConsolefromView.

9. StartthevirtualmachineandverifythattheUSBdeviceisavailable.

Page 600: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...USBdevicesattachedtothehostsystemcanbeallocatedtoavirtualmachinethroughthehardwaredetails.WeselectedtheUSBHostDevicecategory,whichdisplayedallofthedevicescurrentlyregisteredwiththehostfromwhichwecanmakeourselection.ThereareacoupleofitemstobeawareofwhenusingUSBdevicesinyourguestsystem.First,onlytheUSB1.1protocolissupported.Thisisn'tanissueformostperipherals,suchaswebcams,printers,andUSBmicrophones,wheretransferspeedisn'tmuchofaconcern.ItmaybeaconcernifyouintendtoattachaUSBstoragedeviceandtransferlargeamountsofdata.Second,thedevicemustbepluggedinandaccessiblebythehostbeforestartingthevirtualmachine.Thisisbecausethevirtualizationplatformrunningonthehostisresponsibleforprovisioningaccesstotheguest.

Note

ThisrecipeshowedyouhowtoassignaUSBdeviceconnectedtothehostsystemtoaguest.Ifyou'reaccessingyourvirtualmachineremotelywithaSPICEclient,youcanpluginUSBdevicestoyourlocalmachineandredirectthemtotheremoteguestusingUSBredirection.MoreinformationcanbefoundintheRHEL7VirtualizationDeploymentandAdministrationGuide.

Page 601: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonsharingUSBdevices:

RHEL7VirtualizationDeploymentandAdministrationGuide:USBDevices(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Virtualization_Deployment_and_Administration_Guide/sect-Guest_virtual_machine_device_configuration-USB_devices.html)USBpass-throughwithlibvirtandKVM(https://david.wragg.org/blog/2009/03/usb-pass-through-with-libvirt-and-kvm.html)

Page 602: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Configuringaguest'snetworkinterfaceThisrecipeteachesyouhowtoconfigurethevirtualnetworkinterface'sbehavior.Bychangingtheinterface'sbehavior,youcanprovidetheguestdirectaccessorfilteredaccesstothenetwork,andevensetupalocalnetworkvisibleonlytothehostsystemandotherguests.

Page 603: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

GettingreadyThisreciperequiresaCentOSsystemwithaworkingnetworkconnection.Italsorequiresavirtualmachinesetupasdescribedinthepreviousrecipes.

Page 604: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howtodoit...Followthesestepstoconfigureaguest'snetworkinterface:

1. Makesurethatthevirtualmachineyouwanttomodifyisnotrunning.2. Openthevirtualmachinebydouble-clickingonthedesiredentryinthelistofavailable

machines.3. Viewthevirtualmachine'shardwaredetailsbyclickingonthelightbulbiconinthemenu

barorselectingDetailsfromView.4. SpecifythedesiredNetworksource(NATorHostdevice).5. Ifselectingahostdevice,specifythedesiredmode(Bridged,VEPA,Private,or

Passthrough):

Thevirtualnetworkinterfacecanbeconfiguredtohandletheguest'strafficindifferentways

6. ClickontheApplybuttontosaveyourconfiguration.

Page 605: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

7. LeavethehardwareviewbyeitherclickingonthecomputericoninthemenubarorselectingConsolefromView.

8. Startthevirtualmachineandproceedtoconfiguringtheguest'snetworkingasnecessary.

Page 606: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

Howitworks...Managingaguest'snetworkconnectivityisamatterofspecifyingthebehaviorofthevirtualmachine'snetworkadaptor.Todothiscorrectly,weneedtofirstunderstandwhatthebehaviorsarefromtheoptionsthatareavailabletous.

ThefirstoptionisNetworkAddressTranslation(NAT)andthatisthedefaultfornewvirtualmachines.Thevirtualizationplatformprovidesavirtualnetworkinterfacetotheguestandhandlesallofitstraffic.Theplatformmarshalsthetrafficthroughthehost'sphysicalinterface,actingverymuchlikearouterbetweentheguestandhost.

Thesecondoptionistotiethevirtualinterfacedirectlytothehost'sphysicalinterface.Therearefoursharingmodes,whichareasfollows:

Bridged:Thevirtualizationplatformconnectstheguestandhostinterfaces,givingtheguestdirectaccesstotheInternet.TheguestneedstoobtainitsownIPaddressandhasfullaccesstothenetwork.VEPA:ThisisforusewithVEPA-capablenetworkdevices(specialhardwarerequirementsmustbemet).Private:Theplatformcreatesprivatenetwork,routingpacketssothatvirtualmachinesonthesamehostcancommunicatewithoneanotherandtheexternalnetwork,butconnectionscominginfromthenetworkcan'treachthevirtualmachines.Passthrough:Thehost'sinterfaceisshareddirectly(additionaltechnicalrequirementsmustbemet).

Thedocumentationandterminologyarequitetechnical,giventhenatureofthesubject.Moreover,manypeoplewhoarenotnetworkingexpertsoftenhavetroubledecidingthecorrectconfiguration.Inmyexperience,there'retwocommonscenariosinwhichnon-networkersusevirtualization-localvirtualizationtoprovideanalternateenvironmentandvirtualizationtoprovisionmultipleserversystems.Ifyou'reusingyourvirtualmachineasatypicaldesktopsystemwhereusersneedInternetaccesstoreade-mailandsurftheWeb,useNATnetworkingandconfiguretheguesttouseDHCP.Ifyou'rerunningthemachinesasservers,sharethehost'sadaptorintheBridgedmodeandconfiguretheguestwithastaticIPaddress.

Page 607: CentOS 7 Server Deployment Cookbook · 2019. 6. 12. · CentOS Linux guides and How to articles covering all sorts of topics appropriate for beginners and advanced users. He wrote

SeealsoRefertothefollowingresourcesformoreinformationonconfiguringthevirtualnetworkinterface:

libvirtVirtualizationAPI:Networking(http://wiki.libvirt.org/page/Networking)RHEL7VirtualizationDeploymentandAdministrationGuide:NetworkConfiguration(https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Virtualization_Deployment_and_Administration_Guide/chap-Network_configuration.html)