Sunteți pe pagina 1din 20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

HomePurchasePDFsForumsAbout

QuickHOWTO:Ch21:ConfiguringLinuxMailServers
FromLinuxHomeNetworking

Contents
1Introduction 2Debian/UbuntuDifferences 3ConfiguringSendmail 3.1HowSendmailWorks 3.1.1IncomingMail 3.1.2OutgoingMail 3.1.3SendmailMacros 3.2InstallingSendmail 3.3ManagingthesendmailServer 3.4HowToRestartSendmailAfterEditingYourConfigurationFiles 3.5The/etc/mail/sendmail.mcFile 3.5.1HowtoPutCommentsinsendmal.mc 3.6ConfiguringDNSforsendmail 3.6.1ConfigureYourMailServer'sNameInDNS 3.6.2ConfigureThe/etc/resolv.confFile 3.6.3The/etc/hostsFile 3.7HowToConfigureLinuxSendmailClients 3.8ConvertingFromaMailClienttoaMailServer 3.8.1AGeneralGuideToUsingThesendmail.mcFile 3.8.2The/etc/mail/relaydomainsFile 3.9The/etc/mail/accessFile 3.9.1The/etc/mail/localhostnamesFile 3.10WhichUserShouldReallyReceiveTheMail? 3.10.1The/etc/mail/virtusertablefile 3.10.2The/etc/aliasesFile 3.11SendmailMasqueradingExplained 3.11.1Configuringmasquerading 3.11.2TestingMasquerading 3.11.3OtherMasqueradingNotes 3.12UsingSendmailtoChangetheSender'sEmailAddress 3.13TroubleshootingSendmail 3.13.1TestingTCPconnectivity 3.13.2FurtherTestingofTCPconnectivity 3.13.3The/var/log/maillogFile 3.13.4CommonErrorsDueToIncompleteRPMInstallation 3.13.5IncorrectlyConfigured/etc/hostsFiles 4FightingSPAM 4.1UsingPublicSPAMBlacklistsWithSendmail 4.2Spamassassin 4.2.1DownloadingAndInstallingSpamassassin 4.2.2ManagingthespamassassinServer 4.2.3Configuringprocmailforspamassassin 4.2.4ConfiguringSpamassassin 4.2.5Testingspamassassin 4.2.6Tuningspamassassin 4.2.7UpdatingSpamassassinsBuiltinRules 4.3UsingGreylisting 4.3.1DownloadingandInstallingmiltergreylist 4.3.2Configuringmiltergreylist 4.3.3Configuringmiltergreylist 4.4ASimplePERLScriptToHelpStopSPAM 5ConfiguringYourDovecotPOP/IMAPMailServer 5.1InstallingDovecot 5.2StartingDovecot 5.3DovecotConfigurationFiles 5.4ChoiceofProtocols 5.4.1Version1.x

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

1/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

5.4.2Version2.xandNewer 5.5VerifiyingWhetherDovecotisListening 5.6ConfiguringSSLCertificatesforPOP3SandIMAPS 5.6.1ConfiguringSSLCertificatesforPOP3SandIMAPS 5.7DovecotMailboxes 5.7.1ConfiguringDovecotformbox 5.7.2ConfiguringDovecotformaildir 5.8ConfiguringYourMailClients 5.9Howtohandleoverlappingemailaddresses. 5.10TroubleshootingDovecotMail 5.10.1AlwaysStartwithLogging 6Conclusion

Introduction

EmailisanimportantpartofanyWebsiteyoucreate.Inahomeenvironment,afreewebbasedemailservicemaybesufficient,butifyouarerunningabusiness,thenadedicatedm probablyberequired.

Thischapterwillshowyouhowtousesendmailtocreateamailserverthatwillrelayyourmailtoaremoteuser'smailboxorincomingmailtoalocalmailbox.You'llalsolearnho sendmailviayourmailserverusingawithmailclientsuchasOutlookExpressorEvolution.

Debian/UbuntuDifferences

ThischapterfocusesonFedora/CentOS/RedHatforsimplicityofexplanation.WheneverthereisadifferenceintherequiredcommandsforDebian/UbuntuvariationsofLinux

TheuniversaldifferenceisthatthecommandsshownaredonebytheFedora/CentOS/RedHatrootuser.WithDebian/Ubuntuyouwilleitherhavetobecomerootusingthe"su oryoucantemporarilyincreaseyourprivilegeleveltorootusingthe"sudo<command>"command. Hereisanexampleofhowtopermanentlybecomeroot:


user@ubuntu:~$sudosu [sudo]passwordforpeter: root@ubuntu:~#

Hereisanexampleofhowtotemporarilybecomeroottorunaspecificcommand.Thefirstattempttogetadirectorylistingfailsduetoinsufficientprivileges.Thesecondattempts sudokeywordisinsertedbeforethecommand.
user@ubuntu:~$lsl/var/lib/mysql/mysql ls:cannotaccess/var/lib/mysql/mysql:Permissiondenied user@ubuntu:~$sudolsl/var/lib/mysql/mysql [sudo]passwordforpeter: total964 rwrw1mysqlmysql88202010121923:09columns_priv.frm rwrw1mysqlmysql02010121923:09columns_priv.MYD rwrw1mysqlmysql40962010121923:09columns_priv.MYI rwrw1mysqlmysql95822010121923:09db.frm ... ... ... user@ubuntu:~$

Nowthatyouhavegotthisstraight,letscontinuewiththediscussion.

ConfiguringSendmail

OneofthetasksinsettingupDNSforyourdomain(mysite.com)istousetheMXrecordintheconfigurationzonefiletostatethehostnameoftheserverthatwillhandlethemail mostpopularUnixmailtransportagentissendmail,butothers,suchaspostfixandqmail,arealsogainingpopularitywithLinux.ThestepsusedtoconvertaLinuxboxintoasendm beexplainedhere.

HowSendmailWorks
Asstatedbefore,sendmailcanhandlebothincomingandoutgoingmailforyourdomain.Takeacloserlook.

IncomingMail

UsuallyeachuserinyourhomehasaregularLinuxaccountonyourmailserver.Mailsenttoeachoftheseusers(username@mysite.com)eventuallyarrivesatyourmailserveran processesitanddepositsitinthemailboxfileoftheuser'sLinuxaccount.

Mailisn'tactuallysentdirectlytotheuser'sPC.Usersretrievetheirmailfromthemailserverusingclientsoftware,suchasMicrosoft'sOutlookorOutlookExpress,thatsupportsei IMAPmailretrievalprotocols.

Linuxusersloggedintothemailservercanreadtheirmaildirectlyusingatextbasedclient,suchasmail,oraGUIclient,suchasEvolution.Linuxworkstationuserscanusethesa accesstheirmailremotely.

OutgoingMail

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

2/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Theprocessisdifferentwhensendingmailviathemailserver.PCandLinuxworkstationusersconfiguretheiremailsoftwaretomakethemailservertheiroutboundSMTPmails

Ifthemailisdestinedforalocaluserinthemysite.comdomain,thensendmailplacesthemessageinthatperson'smailboxsothattheycanretrieveitusingoneofthemethodsabov

Ifthemailisbeingsenttoanotherdomain,sendmailfirstusesDNStogettheMXrecordfortheotherdomain.Itthenattemptstorelaythemailtotheappropriatedestinationmails SimpleMailTransportProtocol(SMTP).OneofthemainadvantagesofmailrelayingisthatwhenaPCuserAsendsmailtouserBontheInternet,thePCofuserAcandelegate processingtothemailserver. Note:Ifmailrelayingisnotconfiguredproperly,thenyourmailservercouldbecommandeeredtorelayspam.Simplesendmailsecuritywillbecoveredlater.

SendmailMacros

Whenmailpassesthroughasendmailserverthemailroutinginformationinitsheaderisanalyzed,andsometimesmodified,accordingtothedesiresofthesystemsadministrator.U highlycomplicatedregularexpressionslistedinthe/etc/mail/sendmail.cffile,sendmailinspectsthisheaderandthenactsaccordingly.

Inrecognitionofthecomplexityofthe/etc/mail/sendmail.cffile,amuchsimplerfilenamed/etc/sendmail.mcwascreated,anditcontainsmoreunderstandableinstructionsforsystem use.Thesearetheninterpretedbyanumberofmacroroutinestocreatethesendmail.cffile.Aftereditingsendmail.mc,youmustalwaysrunthemacrosandrestartsendmailforthe effect. Eachsendmail.mcdirectivestartswithakeyword,suchasDOMAIN,FEATURE,orOSTYPE,followedbyasubdirectiveandinsomecasesarguments.Atypicalexampleis. Asstatedbefore,sendmailcanhandlebothincomingandoutgoingmailforyourdomain.Takeacloserlook.


FEATURE(`virtusertable',`hasho/etc/mail/virtusertable.db')dnl

Thekeywordsusuallydefineasubdirectoryof/usr/share/sendmailcfinwhichthemacromaybefoundandthesubdirectiveisusuallythenameofthemacrofileitself.Sointheex nameis/usr/share/sendmailcf/feature/virtusertable.m4,andtheinstruction`\hasho/etc/mail/virtusertable.db'isbeingpassedtoit. Noticethatsendmailissensitivetothequotationmarksusedinthem4macrodirectives.Theyopenwithagravemarkandendwithasinglequote.


FEATURE(`masquerade_envelope')dnl

Somekeywords,suchasdefineforthedefinitionofcertainsendmailvariablesandMASQUERADE_DOMAIN,havenocorrespondingdirectorieswithmatchingmacrofiles.The /usr/share/sendmailcf/m4directorydealwiththese. Onceyoufinisheditingthesendmail.mcfile,youcanthenexecutethemakecommandwhileinthe/etc/maildirectorytoregeneratethenewsendmail.cffile.


[root@bigboytmp]#cd/etc/mail [root@bigboymail]#make

Iftherehavebeennochangestothefilesin/etc/mailsincethelasttimemakewasrun,thenyou'llgetanerrorlikethis:
[root@bigboymail]#make make:Nothingtobedonefor`all'. [root@bigboymail]#

Themakecommandactuallygeneratesthesendmail.cffileusingthem4command.Them4usageissimple,youjustspecifythenameofthemacrofileastheargument,inthiscase redirecttheoutput,whichwouldnormallygotothescreen,tothesendmail.cffilewiththe">"redirectorsymbol.
[root@bigboytmp]#m4/etc/mail/sendmail.mc>/etc/mail/sendmail.cf

I'lldiscussmanyofthefeaturesofthesendmail.mcfilelaterinthechapter.

InstallingSendmail

MostRedHatandFedoraLinuxsoftwareproductpackagesareavailableintheRPMformat,whereasDebianandUbuntuLinuxuseDEBformatinstallationfiles.Whensearching rememberthatthefilenameusuallystartswiththesoftwarepackagenameandisfollowedbyaversionnumber,asinsendmail8.12.101.1.1.i386.rpm.(Forhelpondownloadinga requiredpackages,seeChapter6,InstallingLinuxSoftware). Note:Youwillneedtomakesurethatthesendmail,sendmailcf,andm4packagesareinstalled.

ManagingthesendmailServer
Managingthesendmaildaemoniseasytodo,buttheprocedurediffersbetweenLinuxdistributions.Herearesomethingstokeepinmind.

1. Firstly,differentLinuxdistributionsusedifferentdaemonmanagementsystems.Eachsystemhasitsownsetofcommandstodosimilaroperations.Themostcommonlyused managementsystemsareSysVandSystemd. 2. Secondly,thedaemonnameneedstobeknown.Inthiscasethenameofthedaemonissendmail. Armedwiththisinformationyoucanknowhowto: 1. Startyourdaemonsautomaticallyonbooting 2. Stop,startandrestartthemlateronduringtroubleshootingorwhenaconfigurationfilechangeneedstobeapplied. Formoredetailsonthis,pleasetakealookatthe"ManagingDaemons"sectionofChapter6"InstallingLinuxSoftware"

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

3/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Note:Remembertoconfigureyourdaemontostartautomaticallyuponyournextreboot.

HowToRestartSendmailAfterEditingYourConfigurationFiles

Inthischapter,you'llseethatsendmailusesavarietyofconfigurationfilesthatrequiredifferenttreatmentsfortheircommandstotakeeffect.Thislittleactivatesendmail.shscripten requiredpostconfigurationsteps.
# #Script:/usr/local/bin/activatesendmail.sh # #!/bin/bash cd/etc/mail /usr/bin/make /usr/bin/newaliases systemctlrestartsendmail.service systemctlrestartspamassassin.service

Itfirstrunsthemakecommand,whichcreatesanewsendmail.cffilefromthesendmail.mcfileandcompilessupportingconfigurationfilesinthe/etc/maildirectoryaccordingtothe file/etc/mail/Makefile.Itthengeneratesnewemailaliaseswiththenewaliasescommand,(thiswillbecoveredlater),andthenrestartssendmail. Thescriptalsorestartsspamassassin,apackagethatwillbediscussedlater. Usethiscommandtomakethescriptexecutable.


[root@bigboytmp]#chmod700/usr/local/bin/activatesendmail.sh

You'llneedtorunthescripteachtimeyouchangeanyofthesendmailconfigurationfilesdescribedinthesectionstofollow.
[root@bigboytmp]#/usr/local/bin/activatesendmail.sh

Inaproductionsystemyoumaywanttobemoreselectiveandonlyrestartthespecificapplicationsonwhichyouareworking.Iincludedalloftheminthescriptsoyoudon'tforge

The/etc/mail/sendmail.mcFile

Youcandefinemostofsendmail'sconfigurationparametersinthe/etc/mail/sendmail.mcfile,whichisthenusedbythem4macrostocreatethe/etc/mail/sendmail.cffile.Configura sendmail.mcfileismuchsimplerthanconfigurationofsendmail.cf,butitisstilloftenviewedasanintimidatingtaskwithitsseriesofstructureddirectivestatementsthatgetthejob inmostcasesyouwon'thavetoeditthisfileveryoften.

HowtoPutCommentsinsendmal.mc
InmostLinuxconfigurationfilesa#symbolisusedatthebeginningofalineconvertitintoacommentlineortodeactivateanycommandsthatmayresideonthatline.

Thesendmail.mcfiledoesn'tusethischaracterforcommenting,butinsteadusesthestring"dnl".Herearesomevalidexamplesofcommentsusedwiththesendmail.mcconfigurati Thesestatementsaredisabledbydnlcommenting.
dnlDAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1,Name=MTA') dnl#DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1,Name=MTA')

Thisstatementisincorrectlydisabled:
#DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1,Name=MTA')

Thisstatementisactive:
DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1,Name=MTA')

Note:Remembertoruntheactivatesendmail.shscripttoactivateanyconfigurationchanges.

ConfiguringDNSforsendmail

RememberthatyouwillneverreceivemailunlessyouhaveconfiguredDNSforyourdomaintomakeyournewLinuxboxmailserverthetargetoftheDNSdomain'sMXrecord. 18,"ConfiguringDNS",orChapter19,"DynamicDNS",fordetailsonhowtodothis.

ConfigureYourMailServer'sNameInDNS

Youfirstneedtomakesurethatyourmailserver'snameresolvesinDNScorrectly.Forexample,ifyourmailserver'snameisbigboyandityouintendforittomostlyhandlemailf site.com,thenbigboy.mysite.commustcorrectlyresolvetotheIPaddressofoneofthemailserver'sinterfaces.Youcantestthisusingthehostcommand:
[root@smallfrytmp]#hostbigboy.mysite.com bigboy.mysite.comhasaddress192.168.1.100 [root@smallfrytmp]#

YouwillneedtofixyourDNSserver'sentriesiftheresolutionisn'tcorrect.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

4/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

ConfigureThe/etc/resolv.confFile
ThesendmailprogramexpectsDNStobeconfiguredcorrectlyontheDNSserver.TheMXrecordforyourdomainmustpointtotheIPaddressofthemailserver.

Theprogramalsoexpectsthefilesusedbythemailserver'sDNSclienttobeconfiguredcorrectly.Thefirstoneisthe/etc/resolv.conffileinwhichtheremustbeadomaindirective thedomainsthemailserverisexpectedtohandlemailfor. Finally,sendmailexpectsanameserverdirectivethatpointstotheIPaddressoftheDNSserverthemailservershouldusetogetitsDNSinformation. Forexample,ifthemailserverishandlingmailformysite.comandtheIPaddressoftheDNSserveris192.168.1.100,theremustbedirectivesthatlooklikethis:


domainmysite.com nameserver192.168.1.100

Anincorrectlyconfiguredresolv.conffilecanleadtoerrorswhenrunningthem4commandtoprocesstheinformationinyoursendmail.mcfile.
WARNING:localhostname(smallfry)isnotqualifiedfix$jinconfigfile

The/etc/hostsFile
The/etc/hostsfilealsoisusedbyDNSclientsandalsoneedstobecorrectlyconfigured.Hereisabriefexampleofthefirstlineyoushouldexpecttoseeinit:
127.0.0.1bigboy.mysite.comlocalhost.localdomainlocalhostbigboy

Theentryfor127.0.0.1mustalwaysbefollowedbythefullyqualifieddomainname(FQDN)oftheserver.Inthecaseaboveitwouldbebigboy.mysite.com.Thenyoumusthave localhostandlocalhost.localdomain.Linuxdoesnotfunctionproperlyifthe127.0.0.1entryin/etc/hostsdoesn'talsoincludelocalhostandlocalhost.localdomain.Finallyyoucanad yourhostmayhavetotheendoftheline.

HowToConfigureLinuxSendmailClients

AllLinuxmailclientsinyourhomeorcompanyneedtoknowwhichserveristhemailserver.Thisisconfiguredinthesendmail.mcfilebysettingtheSMART_HOSTstatementto server.Intheexamplebelow,themailserverhasbeensettomail.mysite.com,themailserverforthemysite.comdomain.
define(`SMART_HOST',`mail.mysite.com')

Ifyoudon'thaveamailserveronyournetwork,youcaneithercreateone,orusetheoneofferedbyyourISP. Oncethisisdone,youneedtoprocessthesendmail.mcfileandrestartsendmail.Todothis,runtherestartingscriptwefromearlierinthechapter. IfthesendmailserverisaLinuxserver,thenthe/etc/hostsfilewillalsohavetobecorrectlyconfiguredtoo. Note:Remembertoruntheactivatesendmail.shscriptshownatthebeginningofthechaptertoactivateanyconfigurationchanges.

ConvertingFromaMailClienttoaMailServer

AllLinuxsystemshaveavirtualloopbackinterfacethatlivesonlyinmemorywithanIPaddressof127.0.0.1.AsmailmustbesenttoatargetIPaddressevenwhenthereisnoNIC sendmailthereforeusestheloopbackaddresstosendmailbetweenusersonthesameLinuxserver.Tobecomeamailserver,andnotamailclient,sendmailneedstobeconfigured messagesonNICinterfacesaswell.

1)DeterminewhichNICssendmailisrunningon.Youcanseetheinterfacesonwhichsendmailislisteningwiththenetstatcommand.BecausesendmaillistensonTCPport25,yo grepfor25toseeadefaultconfigurationlisteningonlyonIPaddress127.0.0.1(loopback):
[root@bigboytmp]#netstatan|grep:25|greptcp tcp00127.0.0.1:250.0.0.0:*LISTEN [root@bigboytmp]#

2)Editsendmail.mctomakesendmaillistenonallinterfaces.Ifsendmailislisteningontheloopbackinterfaceonly,youshouldcommentoutthedaemon_optionslineinthe/etc/ma withdnlstatements.Itisalsogoodpracticetotakeprecautionsagainstspambynotacceptingmailfromdomainsthatdon'texistbycommentingouttheaccept_unresolvable_domai thefourthandnexttolastlinesintheexample.


dnl dnlThischangessendmailtoonlylistenontheloopback dnldevice127.0.0.1andnotonanyothernetwork dnldevices.Commentthisoutifyouwant dnltoacceptemailoverthenetwork. dnlDAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1,Name=MTA') dnl ... ... ... dnl dnlWestronglyrecommendtocommentthisoneoutifyouwant dnltoprotectyourselffromspam.However,thelaptopand dnlusersoncomputersthatdo dnlnothave24x7DNSdoneedthis. dnlFEATURE(`accept_unresolvable_domains')dnl dnlFEATURE(`relay_based_on_MX')dnl dnl

Note:Youneedtobecarefulwiththeaccept_unresolvable_namesfeature.Inthesamplenetwork,bigboythemailserverdoesnotacceptemailrelayedfromanyoftheotherPCs theyarenotinDNS.Chapter18,"ConfiguringDNS",showshowtocreateyourowninternaldomainjustforthispurpose.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

5/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Note:IfyourserverhasmultipleNICsandyouwantittolistentooneofthem,thenyoucanuncommentthelocalhostDAEMON_OPTIONSentryandaddanotheronefortheIP onwhichtowishtoacceptSMTPtraffic.

3)CommentouttheSMART_HOSTEntryinsendmal.mc.Themailserverdoesn'tneedaSMART_HOSTentryinitssendmail.mcfile.Commentthisoutwithadnlatthebeginn
dnldefine(`SMART_HOST',`mail.mysite.com')

4)Regeneratethesendmail.cffile,andrestartsendmail.Again,youcandothiswiththeactivatesendmail.shscriptfromthebeginningofthechapter. 5)Makesuresendmailislisteningonallinterfaces(0.0.0.0).
[root@bigboytmp]#netstatan|grep:25|greptcp tcp000.0.0.0:250.0.0.0:*LISTEN [root@bigboytmp]#

YouhavenowcompletedthefirstphaseofconvertingyourLinuxserverintoasendmailserverbyenablingittolistentoSMTPtrafficonitsinterfaces.Thefollowingsectionswill definewhattypeofmailitshouldhandleandthevariouswaysthismailcanbeprocessed.

AGeneralGuideToUsingThesendmail.mcFile
Thesendmail.mcfilecanseemjumbled.TomakeitlessclutteredIusuallycreatetwoeasilyidentifiablesectionsinitwithallthecustomcommandsI'veeveradded. ThefirstsectionisnearthetopwheretheFEATUREstatementsusuallyare,andthesecondsectionisattheverybottom.

Sometimessendmailwillarchivethisfilewhenyoudoaversionupgrade.Havingeasilyidentifiablemodificationsinthefilewillmakepostupgradereconfigurationmucheasier.H
dnl*****Customisedsection1start***** dnl dnl FEATURE(delay_checks)dnl FEATURE(masquerade_envelope)dnl FEATURE(allmasquerade)dnl FEATURE(masquerade_entire_domain)dnl dnl dnl dnl*****Customisedsection1end*****

The/etc/mail/relaydomainsFile

The/etc/mail/relaydomainsfileisusedtodeterminedomainsfromwhichitwillrelaymail.Thecontentsoftherelaydomainsfileshouldbelimitedtothosedomainsthatcanbetru spam.Bydefault,thisfiledoesnotexistinastandardRedHat/Fedorainstall.Inthiscase,allmailsentfrommysuperdupersite.comandnotdestinedforthismailserverwillbefo
mysuperdupersite.com

Onedisadvantageofthisfileisthatcontrolsmailbasedonthesourcedomainonly,andsourcedomainscanbespoofedbyspamemailservers.The/etc/mail/accessfilehasmoreca restrictingrelayingbyIPaddressornetworkrangeandismorecommonlyused.Ifyoudelete/etc/mail/relaydomains,thenrelayaccessisfullydeterminedbythe/etc/mail/accessfi Note:Besuretorunactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

The/etc/mail/accessFile

YoucanmakesurethatonlytrustedPCsonyournetworkhavetheabilitytorelaymailviayourmailserverbyusingthe/etc/mail/accessfile.Thatistosay,themailserverwillrela thosePCsonyournetworkthathavetheiremailclientsconfiguredtousethemailserverastheiroutgoingSMTPmailserver.(InOutlookExpress,yousetthisusing: Tools>Accounts>Properties>Servers)

Ifyoudon'ttaketheprecautionofusingthisfeature,youmayfindyourserverbeingusedtorelaymailforspamemailsites.Configuringthe/etc/mail/accessfilewillnotstopspam onlyspamflowingthroughyou.

The/etc/mail/accessfilehastwocolumns.ThefirstlistsIPaddressesanddomainsfromwhichthemailiscomingorgoing.Thesecondliststhetypeofactiontobetakenwhenmai ordestinationsisreceived.KeywordsincludeRELAY,REJECT,OK(notACCEPT),andDISCARD.ThereisnothirdcolumntostatewhethertheIPaddressordomainistheso ofthemail,sendmailassumesitcouldbeeitherandtriestomatchboth.Allotherattemptedrelayedmailthatdoesn'tmatchanyoftheentriesinthe/etc/mail/accessfile,sendmailwi this,myexperiencehasbeenthatcontrolonaperemailaddressbasisismuchmoreintuitiveviathe/etc/mail/virtusertablefile.

Thesamplefilethatfollowsallowsrelayingforonlytheserveritself(127.0.0.1,localhost),twoclientPCsonyourhome192.168.1.Xnetwork,everyoneonyour192.168.2.Xnetw passingemailthroughthemailserverfromserversbelongingtomysite.com.Rememberthataserverwillbeconsideredapartofmysite.comonlyifitsIPaddresscanbefoundin zonefile:


localhost.localdomainRELAY localhostRELAY 127.0.0.1RELAY 192.168.1.16RELAY 192.168.1.17RELAY 192.168.2RELAY mysite.comRELAY

Note:You'llnowhavetoconvertthistextfileintoasendmailreadabledatabasefilenamed/etc/mail/access.db.Theactivatesendmail.shscriptweconfiguredatthebeginningofth foryoutoo.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

6/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Rememberthattherelaysecurityfeaturesofthisfilemaynotworkifyoudon'thaveacorrectlyconfigured/etc/hostsfile.

The/etc/mail/localhostnamesFile

Whensendmailreceivesmail,itneedsawayofdeterminingwhetheritisresponsibleforthemailitreceives.Itusesthe/etc/mail/localhostnamesfiletodothis.Thisfilehasalisto domainsforwhichsendmailacceptsresponsibility.Forexample,ifthismailserverwastoacceptmailforthedomainsmysite.comandanothersitethenthefilewouldlooklikethis
mysite.com anothersite.com

Inthiscase,remembertomodifytheMXrecordoftheanothersite.comDNSzonefilepointtomysite.com.Hereisanexample(Remembereach"."isimportant):
PrimaryMailExchangerforanothersite.com anothersite.com.MX10mail.mysite.com.

Note:Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

WhichUserShouldReallyReceiveTheMail?
Aftercheckingthecontentsofthevirtusertable,sendmailchecksthealiasesfilestodeterminetheultimaterecipientofmail.

The/etc/mail/virtusertablefile

The/etc/mail/virtusertablefilecontainsasetofsimpleinstructionsonwhattodowithreceivedmail.Thefirstcolumnliststhetargetemailaddressandthesecondcolumnliststhelo aremoteemailaddress,oramailinglistentryinthe/etc/aliasesfiletowhichtheemailshouldbeforwarded. Ifthereisnomatchinthevirtusertablefile,sendmailchecksforthefullemailaddressinthe/etc/aliasesfile.


webmaster@anothersite.comwebmasters @anothersite.commarc sales@mysite.comsales@anothersite.com paul@mysite.compaul finance@mysite.compaul @mysite.comerror:nouserUserunknown

Inthisexample,mailsentto: webmaster@anothersite.comwillgotolocaluser(ormailinglist)webmasters,allothermailtoanothersite.comwillgotolocalusermarc. salesatmysite.comwillgotothesalesdepartmentatmyothersite.com. paulandfinanceatmysite.comgoestolocaluser(ormailinglist)paul Allotherusersatmysite.comreceiveabouncebackmessagestating"Userunknown". Note:Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

The/etc/aliasesFile

Youcanthinkofthe/etc/aliasesfileasamailinglistfile.Thefirstcolumnhasthemailinglistname(sometimescalledavirtualmailbox),andthesecondcolumnhasthemembersof separatedbycommas.

Tostart,sendmailsearchesthefirstcolumnofthefileforamatch.Ifthereisnomatch,thensendmailassumestherecipientisaregularuseronthelocalserveranddepositsthemail

Ifitfindsamatchinthefirstcolumn,sendmailnotesthenicknameentryinthesecondcolumn.Itthensearchesforthenicknameagaininthefirstcolumntoseeiftherecipientisn't mailinglist. Ifsendmaildoesn'tfindaduplicate,itassumestherecipientisaregularuseronthelocalserveranddepositsthemailintheirmailbox.

Iftherecipientisamailinglist,thensendmailgoesthroughtheprocessalloveragaintodetermineifanyofthemembersisonyetanotherlist,andwhenitisallfinished,theyallge mailmessage.

Intheexamplethatfollows,youcanseethatmailsenttousersbin,daemon,lp,shutdown,apache,named,andsoonbysystemprocesseswillallbesenttouser(ormailinglist)roo isactuallyanaliasforamailinglistconsistingofusermarcandwebmaster@mysite.com.
#BasicsystemaliasestheseMUSTbepresent. mailerdaemon:postmaster postmaster:root #Generalredirectionsforpseudoaccounts. bin:root daemon:root ... ... abuse:root #trapdecodetocatchsecurityattacks decode:root #Personwhoshouldgetroot'smail root:marc,webmaster@mysite.com

Noticethattherearenospacesbetweenthemailinglistentriesforroot:Youwillgeterrorsifyouaddspaces.

Note:Thedefault/etc/aliasesfileinstalledwithRedHat/Fedorahasthelastlineofthissamplecommentedoutwitha#,youmaywanttodeletethecommentandchangeusermarc

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

7/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Alsoaftereditingthisfile,you'llhavetoconvertitintoasendmailreadabledatabasefilenamed/etc/aliases.db.Hereisthecommandtodothat:
[root@bigboytmp]#newaliases

Inthissimplemailinglistexample,mailsenttorootactuallygoestouseraccountmarcandwebmaster@mysite.com.Becausealiasescanbeveryuseful,hereareafewmorelistex /etc/aliasesfile. Mailto"directors@mysite.com"goestousers"peter","paul"and"mary".


#DirectorsofmySOHOcompany directors:peter,paul,mary

Mailsentto"family@mysite.com"goestousers"grandma","brother"and"sister"
#Myfamily family:grandma,brother,sister

Mailsenttoadminlistgetssenttoalltheuserslistedinthefile/home/mailings/adminlist.
#Mymailinglistfile adminlist:":include:/home/mailings/adminlist"

Theadvantageofusingmailinglistfilesisthattheadminlistfilecanbeafilethattrusteduserscanedit,userrootisonlyneededtoupdatethealiasesfile.Despitethis,therearesom mailreflectors.Oneisthatbouncemessagesfromfailedattemptstobroadcastgotoallusers.Anotheristhatallsubscriptionsandunsubscriptionshavetobedonemanuallybythem administrator.Ifeitheroftheseareaproblemforyou,thenconsiderusingamailinglistmanager,suchasmajordomo.

Oneimportantnoteaboutthe/etc/aliasesfile:Bydefaultyoursystemusessendmailtomailsystemmessagestolocaluserroot.Whensendmailsendsemailtoalocaluser,themail mailheader.IfyouthenuseamailclientwithaspammailfilteringruletorejectmailwithnoTo:intheheader,suchasOutlookExpressorEvolution,youmayfindyourselfdump Togetaroundthis,trymakingroothaveanaliasforauserwithafullyqualifieddomainname,thisforcessendmailtoinsertthecorrectfieldsintheheaderforexample:


#Personwhoshouldgetroot'smail root:webmaster@mysite.com

Note:Besuretorunthenewaliasescommandforthesechangestotakeeffect.

SendmailMasqueradingExplained
Ifyouwantyourmailtoappeartocomefromuser@mysite.comandnotuser@bigboy.mysite.com,thenyouhavetwochoices: Configureyouremailclient,suchasOutlookExpress,tosetyouremailaddresstouser@mysite.com.(I'llexplainthisinthe"ConfiguringYourPOPMailServer"section.). Setupmasqueradingtomodifythedomainnameofalltrafficoriginatingfromandpassingtroughyourmailserver.

Configuringmasquerading

IntheDNSconfiguration,youmadebigboythemailserverforthedomainmysite.com.Younowhavetotellbigboyinthesendmailconfigurationfilesendmail.mcthatalloutgoin onbigboyshouldappeartobecomingfrommysite.comifnot,basedonoursettingsinthe/etc/hostsfile,mailwillappeartocomefrommail.mysite.com.Thisisn'tterrible,butyo yourWebsitetoberememberedwiththeword"mail"infrontofit.Inotherwordsyoumaywantyourmailservertohandleallemailbyassigningaconsistentreturnaddresstoall matterwhichserveroriginatedtheemail. Youcansolvethisbyeditingyoursendmail.mcconfigurationfileandaddingsomemasqueradingcommandsanddirectives:


FEATURE(always_add_domain)dnl FEATURE(`masquerade_entire_domain')dnl FEATURE(`masquerade_envelope')dnl FEATURE(`allmasquerade')dnl MASQUERADE_AS(`mysite.com')dnl MASQUERADE_DOMAIN(`mysite.com.')dnl MASQUERADE_DOMAIN(localhost)dnl MASQUERADE_DOMAIN(localhost.localdomain)dnl

Theresultisthat:

TheMASQUERADE_ASdirectivemakesallmailoriginatingonbigboyappeartocomefromaserverwithinthedomainmysite.combyrewritingtheemailheader. TheMASQUERADE_DOMAINdirectivemakesmailrelayedviabigboyfromallmachinesintheanothersite.comandlocaldomaindomainsappeartocomefromtheMAS domainofmysite.com.UsingDNS,sendmailchecksthedomainnameassociatedwiththeIPaddressofthemailrelayclientsendingthemailtohelpitdeterminewhetherit masqueradingornot. FEATUREmasquerade_entire_domainmakessendmailmasqueradeserversnamed*mysite.com,and*anothersite.comasmysite.com.Inotherwords,mailfromsales.my masqueradedasmysite.com.Ifthiswasn'tselected,thenonlyserversnamedmysite.comandmyothersite.comwouldbemasqueraded.Usethiswithcautionwhenyouare necessaryauthoritytodothis. FEATUREallmasquerademakessendmailrewritebothrecipientaddressesandsenderaddressesrelativetothelocalmachine.Ifyoucc:yourselfonanoutgoingmail,theoth cc:toanaddressheknowsinsteadofoneonlocalhost.localdomain.

Note:UseFEATUREallmasqueradewithcautionifyourmailserverhandlesemailformanydifferentdomainsandthemailboxesfortheusersinthesedomainsresideonth allmasqueradestatementcausesallmaildestinedforthesemailboxestoappeartobedestinedforusersinthedomaindefinedintheMASQUERADE_ASstatement.Inother MASQUERADE_ASismysite.comandyouuseallmasquerade,thenmailforpeter@anothersite.comentersthecorrectmailboxbutsendmailrewritestheTo:,makingthe senttopeter@myste.comoriginally.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

8/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

FEATUREalways_add_domainalwaysmasqueradesemailaddresses,evenifthemailissentfromauseronthemailservertoanotheruseronthesamemailserver. FEATUREmasquerade_enveloperewritestheemailenvelopejustasMASQUERADE_ASrewrotetheheader.

Masqueradingisanimportantpartofanymailserverconfigurationasitenablessystemsadministratorstousemultipleoutboundmailservers,eachprovidingonlytheglobaldomain companyandnotthefullyqualifieddomainnameoftheserveritself.Allemailcorrespondencethenhasauniformemailaddressformatthatcomplieswiththecompany'sbrandma

Note:Emailclients,suchasOutlookExpress,considertheTo:andFrom:statementsastheemailheader.WhenyouchooseReplyorReplyAllinOutlookExpress,theprogram theTo:andFrom:intheheader.Itiseasytofaketheheader,asspammersoftendoitisdetrimentaltoemaildelivery,however,tofaketheenvelope.

TheemailenvelopecontainstheTo:andFrom:usedbymailserversforprotocolnegotiation.Itistheenvelope'sFrom:thatisusedwhenemailrejectionmessagesaresentbetween Note:Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

TestingMasquerading

ThebestwayoftestingmasqueradingfromtheLinuxcommandlineistousethe"mailvusername"command.Ihavenoticedthat"sendmailvusername"ignoresmasqueradinga shouldalsotailthe/var/log/maillogfiletoverifythatthemasqueradingisoperatingcorrectlyandchecktheenvelopeandheaderoftestemailreceivedbytestemailaccounts.

OtherMasqueradingNotes
Bydefault,user"root"willnotbemasqueraded.Toremovethisrestrictionuse:
EXPOSED_USER(`root')dnl

commandin/etc/mail/sendmail.mc.Youcancommentthisoutifyoulikewitha"dnl"atthebeginningofthelineandrunningthesendmailstartscript.

UsingSendmailtoChangetheSender'sEmailAddress

Sometimesmasqueradingisn'tenough.Attimesyoumayneedtochangenotonlythedomainofthesenderbutalsotheusernameportionofthesender'semailaddress.Forexamp boughtaprogramforyourSOHOofficethatsendsoutnotificationstoyourstaff,buttheprograminsertsitsownaddressassender'saddress,notthatoftheITperson.

WebbasedCGIscriptstendtorunasuserapacheand,therefore,sendmailasuserapachetoo.Oftenyouwon'twantthis,notonlybecauseapache'semailaddressmaynotbeasu becausesomeantispamprogramschecktoensurethattheFrom:,orsourceemailaddress,actuallyexistsasarealuser.Ifyourvirtusertablefileallowsemailtoonlypredefinedus abouttheapacheuserwillfail,andyourvalidemailmaybeclassifiedasbeingspam. Withsendmail,youcanchangeboththedomainandusernameonacasebycasebasisusingthegenericstablefeature: 1)Addthesestatementstoyour/etc/mail/sendmail.mcfiletoactivatethefeature:


FEATURE(`genericstable',`hasho/etc/mail/genericstable.db')dnl GENERICS_DOMAIN_FILE(`/etc/mail/genericsdomains')dnl

2)Createa/etc/mail/genericsdomainsfilethatisjustalistofallthedomainsthatshouldbeinspected.Makesurethefileincludesyourserver'scanonicaldomainname,whichyou command:
sendmailbtd0.1</dev/null

Hereisasample/etc/mail/genericsdomainsfile:
mysite.com anothersite.com bigboy.mysite.com

3)Createyour/etc/mail/genericstablefile.Firstsendmailsearchesthe/etc/mail/genericsdomainsfileforalistofdomainstoreversemap.Itthenlooksatthe/etc/mail/genericstablef emailaddressfromamatchingdomain.Theformatofthefileis
linuxusernameusername@newdomain.com

Youremailsfromlinuxusernameshouldnowappeartocomefromusername@newdomain.com. Herearesomeotherexamples:
alertsecurityalert@mysite.com peterurgentmessage@mysite.com apachemailer@mysite.com

Note:Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

TroubleshootingSendmail
Thereareanumberofwaystotestsendmailwhenitdoesn'tappeartoworkcorrectly.Hereareafewmethodsyoucanusetofixsomeofthemostcommonproblems.

TestingTCPconnectivity

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

9/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

TheveryfirststepistodeterminewhetheryourmailserverisaccessibleonthesendmailSMTPTCPport25.Lackofconnectivitycouldbecausedbyafirewallwithincorrectperm forwardingrulestoyourmailserver.Failurecouldalsobecausedbythesendmailprocessbeingstopped.ItisbesttotestthisfrombothinsideyournetworkandfromtheInternet. Chapter4,"SimpleNetworkTroubleshooting",coverstroubleshootingwithTELNET.

FurtherTestingofTCPconnectivity

YoucanalsomimicafullmailsessionusingTELNETtomakesureeverythingisworkingcorrectly.Ifyougeta"500Commandnotrecognized"errormessagealongtheway,the typographicalerror.Followthesestepscarefully. 1)Telnettothemailserveronport25.Youshouldgetaresponsewitha220statuscode.


[root@bigboytmp]#telnetmail.mysite.com25 Tryingmail.mysite.com... Connectedtomail.mysite.com. Escapecharacteris'^]'. 220mail.mysite.comESMTPserverready

Ifthisbasicstepfails,youprobablyhaveaconnectionproblemthatcouldbetheresultoftypicalnetworkissuesoutlinedinChapter4,"SimpleNetworkTroubleshooting".Review findyourselfhavingproblemsrelatedtobasicconnectivity. 2)Usethehellocommandtotellthemailserverthedomainyoubelongto.Youshouldreceiveamessagewithasuccessfulstatus250codeatthebeginningoftheresponse.


heloanotherwebsite.org 250mail.mysite.comHelloc24497110.client.comcast.net[24.4.97.110],pleasedtomeetyou.

3)InformthemailserverfromwhichthetestmessageiscomingwiththeMAILFROM:statement.
MAILFROM:sender@anotherwebsite.org 2502.1.0sender@anotherwebsite.org...Senderok

4)Tellthemailservertowhomthetestmessageisgoingwiththe"RCPTTO:"statement.
RCPTTO:user@mysite.com 2502.1.5user@mysite.com...Recipientok

5)PreparethemailservertoreceivedatawiththeDATAstatement
DATA 354Entermail,endwith"."onalinebyitself

6)Typethestring"subject:"thentypeasubject.Typeinyourtextmessage,endingitwithasingleperiodonthelastline.Forexample.
Subject:TestMessage Testingsendmailinteractively . 2502.0.0iA75r9si017840Messageacceptedfordelivery

7)UsetheQUITcommandtoendthesession.
QUIT 2212.0.0mail.mysite.comclosingconnection Connectionclosedbyforeignhost. [root@bigboytmp]#

Nowverifythattheintendedrecipientreceivedthemessage,andcheckthesystemlogsforanymailapplicationerrors.

The/var/log/maillogFile

Becausesendmailwritesallitsstatusmessagesinthe/var/log/maillogfile,alwaysmonitorthisfilewheneveryouaredoingchanges.OpentwoTELNET,SSH,orconsolewindow themandmonitorthesendmailstatusoutputintheotherusingthecommand
[root@bigboytmp]#tailf/var/log/maillog

Thistacticwillmakeitmucheasiertotroubleshootanyissuesyoumayfindinsendmail.

CommonErrorsDueToIncompleteRPMInstallation

Boththenewaliasesandm4commandsrequirethesendmailcfandm4RPMpackages.Thesemustbeinstalled.Iftheyarenot,you'llgeterrorswhenrunningvarioussendmailrela SampleErrorswhenrunningnewaliases
[root@bigboymail]#newaliases Warning:.cffileisoutofdate:sendmail8.12.5supportsversion10,.cffileisversion0 Nolocalmailerdefined QueueDirectory(Q)optionmustbeset [root@bigboymail]#

Sampleerrorswhenprocessingthesendmail.mcfile
[root@bigboymail]#m4/etc/mail/sendmail.mc>/etc/mail/sendmail.cf

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

10/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

/etc/mail/sendmail.mc:8:m4:Cannotopen/usr/share/sendmailcf/m4/cf.m4:Nosuchfileordirectory [root@bigboymail]#

Sampleerrorswhenrestartingsendmail
[root@bigboymail]#systemctlrestartsendmail.service Shuttingdownsendmail:[OK] Shuttingdownsmclient:[FAILED] Startingsendmail:5545.0.0Nolocalmailerdefined 5545.0.0QueueDirectory(Q)optionmustbeset [FAILED] Startingsmclient:[OK] [root@bigboymail]#

Iftheseerrorsoccur,makesureyourm4,sendmailandsenmailcfRPMpackagesareinstalledcorrectly.

IncorrectlyConfigured/etc/hostsFiles
Bydefault,Fedorainsertsthehostnameoftheserverbetweenthe127.0.0.1andthelocalhostentriesin/etc/hostslikethis:
127.0.0.1bigboylocalhost.localdomainlocalhost

Unfortunatelyinthisconfiguration,sendmailwillthinkthattheserver'sFQDNisbigboy,whichitwillidentifyasbeinginvalidbecausethereisnoextensionattheend,suchas.co thendefaulttosendingemailsinwhichthedomainislocalhost.localdomain.

The/etc/hostsfileisalsoimportantforconfiguringmailrelay.YoucancreateproblemsifyoufailtoplacetheservernameintheFDQNfor127.0.0.1entry.Heresendmailthinkst FDQNwasmysiteandthatthedomainwasallof.com.
127.0.0.1mysite.comlocalhost.localdomainlocalhost#(Wrong!!!)

Theserverwouldthereforebeopentorelayallmailfromany.comdomainandwouldignorethesecurityfeaturesoftheaccessandrelaydomainsfilesI'lldescribelater.

Asmentioned,apoorlyconfigured/etc/hostsfilecanmakemailsentfromyourservertotheoutsideworldappearasifitcamefromusersatlocalhost.localdomainandnotbigboy.m

Usethesendmailprogramtosendasampleemailtosomeoneinverbosemode.Entersometextafterissuingthecommandandendyourmessagewithasingleperiodallbyitselfo example:
[root@bigboytmp]#sendmailvexample@anothersite.com testtext testtext . example@anothersite.com...Connectingtomail.anothersite.com.viaesmtp... 220ltmail.anothersite.comLiteMailv3.02(BFLITEMAIL4A)Sat,05Oct200206:48:440400 >>>EHLOlocalhost.localdomain 250mx.anothersite.comHello[67.120.221.106],pleasedtomeetyou 250HELP >>>MAILFrom:<root@localhost.localdomain> 250<root@localhost.localdomain>...SenderOk >>>RCPTTo:<example@anothersite.com> 250<example@anothersite.com>...RecipientOk >>>DATA 354Entermail,endwith"."onalinebyitself >>>. 250Messageacceptedfordelivery example@anothersite.com...Sent(Messageacceptedfordelivery) Closingconnectiontomail.anothersite.com. >>>QUIT [root@bigboytmp]#

localhost.localdomainisthedomainthatallcomputersusetorefertothemselves,itisthereforeanillegalInternetdomain.Consideranexample:MailsentfromcomputerPC1toPC fromauseratlocalhost.localdomainonPC1andisrejected.Therejectedemailisreturnedtolocalhost.localdomain.PC2seesthatthemailoriginatedfromlocalhost.localdomaina rejectedemailshouldbesenttoauseronPC2thatmaynotexist.Youendupwithanerrorin/var/log/maillog:


Oct1610:20:04bigboysendmail[2500]:g9GHK3iQ002500:SYSERR(root):savemail:cannotsaverejectedemailanywhere Oct1610:20:04bigboysendmail[2500]:g9GHK3iQ002500:Losing./qfg9GHK3iQ002500:savemailpanic

Youmayalsogetthiserrorifyouareusingaspampreventionprogram,suchasascriptbasedonthePERLmoduleMail::Audit.Anerrorinthescriptcouldcausethistypeofmess

Anothersetoftelltaleerrorscausedbythesameproblemcanbegeneratedwhentryingtosendmailtoauser(theexampleusesroot)orcreatinganewaliasdatabasefile.(I'llexpla commandlater.)
[root@bigboytmp]#sendmailvroot WARNING:localhostname(bigboy)isnotqualifiedfix$jinconfigfile [root@bigboytmp]#newaliases WARNING:localhostname(bigboy)isnotqualifiedfix$jinconfigfile [root@bigboytmp]#

Anaccompanyingerrorin/var/log/mailloglogfilelookslikethis:
Oct1610:23:58bigboysendmail[2582]:Myunqualifiedhostname(bigboy)unknownsleepingforretry

Whenyouhavegotsendmailfinallyworkingitwillbetimetofocusyourattentiononfightingunwantedemail,orSPAM.Thiswillbecoverednext.

FightingSPAM

UnsolicitedCommercialEmail(UCEorSPAM)canbeannoying,timeconsumingtodeleteandinsomecasesdangerouswhentheycontainvirusesandworms.Fortunatelytherea

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

11/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

useyourmailservertocombatSPAM.

UsingPublicSPAMBlacklistsWithSendmail

TherearemanypubliclyavailablelistsofknownopenmailrelayserversandspamgeneratingmailserversontheInternet.Somearemaintainedbyvolunteers,othersaremanagedb companies,butinallcasestheyrelyheavilyoncomplaintsfromspamvictims.SomespamblacklistssimplytrytodeterminewhethertheemailiscomingfromalegitimateIPaddre

TheIPaddressesofoffendersusuallyremainonthelistforsixmonthstotwoyears.Insomecases,toprovideadditionalpressureonthespammers,theblacklistsincludenotonlyth addressbutalsotheentiresubnetornetworkblocktowhichitbelongs.Thispreventsthespammersfromeasilyswitchingtheirservers'IPaddressestothenextavailableonesonth ifthespammerusesapublicdatacenter,itispossiblethattheiractivitiescouldalsocausetheIPaddressesoflegitimateemailerstobeblacklistedtoo.Itishopedthattheselegitima pressurethedatacenter'smanagementtoevictthespammingcustomer.

Youcanconfiguresendmailtouseitsdnsblfeaturetobothquerytheselistsandrejectthemailifamatchisfound.Herearesomesampleentriesyoucanaddtoyour/etc/sendmail.m allbeononeline. RFCIgnorant:AvalidIPaddresschecker.


FEATURE(`dnsbl',`ipwhois.rfcignorant.org',`"550Mailfrom"$&{client_addr}"refused.RejectedforbadWHOISinfoonIPofyourSMTPserverseehttp://www.rfcignorant.org/"')

Easynet:Anopenproxylist.
FEATURE(`dnsbl',`proxies.blackholes.easynet.nl',`"5505.7.1ACCESSDENIEDtoOPENPROXYSERVER"$&{client_name}"byeasynet.nlDNSBL(http://proxies.blackholes.easynet.nl/errors.html

Spamcop:Aspammerblacklist.
FEATURE(`dnsbl',`bl.spamcop.net',`"450Mailfrom"$`'&{client_addr}"refusedseehttp://spamcop.net/bl.shtml"')

Spamhaus:Aspammerblacklist.
FEATURE(`dnsbl',`sbl.spamhaus.org',`Rejectedseehttp://spamhaus.org/')dnl

Note: VisittheURLslistedineachFEATUREcommandtolearnmoreabouttheindividualservices. Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

Spamassassin

Oncesendmailreceivesanemailmessage,ithandsthemessageovertoprocmail,whichistheapplicationthatactuallyplacestheemailinusermailboxesonthemailserver.You temporarilyhandovercontroltoanotherprogram,suchasaspamfilter.Themostcommonlyusedfilterisspamassassin.

spamassassindoesn'tdeletespam,itmerelyaddstheword"spam"tothebeginningofthesubjectlineofsuspectedspamemails.YoucanthenconfiguretheemailfilterrulesinOu anyothermailclienttoeitherdeletethesuspectmessageorstoreitinaspecialSpamfolder.

DownloadingAndInstallingSpamassassin

MostRedHatandFedoraLinuxsoftwareproductpackagesareavailableintheRPMformat,whereasDebianandUbuntuLinuxuseDEBformatinstallationfiles.Whensearching rememberthatthefilenameusuallystartswiththesoftwarepackagenameandisfollowedbyaversionnumber,asinspamassassin2.602.i386.rpm.(Forhelpdownloading,seeCh RPMSoftware").

ManagingthespamassassinServer
Managingthespamassassindaemoniseasytodo,buttheprocedurediffersbetweenLinuxdistributions.Herearesomethingstokeepinmind.

1. Firstly,differentLinuxdistributionsusedifferentdaemonmanagementsystems.Eachsystemhasitsownsetofcommandstodosimilaroperations.Themostcommonlyused managementsystemsareSysVandSystemd. 2. Secondly,thedaemonnameneedstobeknown.Inthiscasethenameofthedaemonisspamassassin. Armedwiththisinformationyoucanknowhowto: 1. Startyourdaemonsautomaticallyonbooting 2. Stop,startandrestartthemlateronduringtroubleshootingorwhenaconfigurationfilechangeneedstobeapplied. Formoredetailsonthis,pleasetakealookatthe"ManagingDaemons"sectionofChapter6"InstallingLinuxSoftware" Note:Remembertoconfigureyourdaemontostartautomaticallyuponyournextreboot.

Configuringprocmailforspamassassin
The/etc/procmailrcfileisusedbyprocmailtodeterminetheprocmailhelperprogramsthatshouldbeusedtofiltermail.Thisfileisn'tcreatedbydefault. spamassassinhasatemplateyoucanusecalled/etc/mail/spamassassin/spamassassinspamc.rc.Copythetemplatetothe/etcdirectory.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

12/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

[root@bigboytmp]#cp/etc/mail/spamassassin/spamassassinspamc.rc/etc/procmailrc

Thiswillactivatespamassassinforallyourmailusers.

ConfiguringSpamassassin

Thespamassassinconfigurationfileisnamed/etc/mail/spamassassin/local.cf.Afulllistingofalltheoptionsavailableinthelocal.cffilecanbefoundintheLinuxmanpagesusingt command:
[root@bigboytmp]#manMail::SpamAssassin::Conf

Youcancustomizethisfullycommentedsampleconfigurationfiletomeetyourneeds.
################################################################### #See'perldocMail::SpamAssassin::Conf'for #detailsofwhatcanbeadjusted. ################################################################### # #Thesevaluescanbeoverriddenbyediting #~/.spamassassin/user_prefs.cf(seespamassassin(1)fordetails) # #Howmanyhitsbeforeamessageisconsideredspam.Thelowerthe #numberthemoresensitiveitis. required_hits5.0 #Whethertochangethesubjectofsuspectedspam(1=Yes,0=No) rewrite_subject1 #Texttoprependtosubjectifrewrite_subjectisused subject_tag*****SPAM***** #Encapsulatespaminanattachment(1=Yes,0=No) report_safe1 #Useterseversionofthespamreport(1=Yes,0=No) use_terse_report0 #EnabletheBayessystem(1=Yes,0=No) use_bayes1 #EnableBayesautolearning(1=Yes,0=No) auto_learn1 #Enableordisablenetworkchecks(1=Yes,0=No) skip_rbl_checks0 use_razor21 use_dcc1 use_pyzor1 #Mailusinglanguagesusedinthesecountrycodeswillnotbemarked #asbeingpossiblyspaminaforeignlanguage. #english ok_languagesen #Mailusinglocalesusedinthesecountrycodeswillnotbemarked #asbeingpossiblyspaminaforeignlanguage. ok_localesen

Note:Besuretoruntheactivatesendmail.shscriptfromthebeginningofthechapterforthesechangestotakeeffect.

Testingspamassassin

Youcantestthevalidityofyourlocal.cffilebyusingthespamassassincommandwiththelintoption.Thiswilllistanysyntaxproblemsthatmayexist.Inthisexampletwoerrors correctedbeforethecommandwasrunagain.
[root@bigboytmp]#spamassassindlint Createduserpreferencesfile:/root/.spamassassin/user_prefs config:SpamAssassinfailedtoparseline,skipping:use_terse_report0 config:SpamAssassinfailedtoparseline,skipping:auto_learn1 lint:2issuesdetected.pleasererunwithdebugenabledformoreinformation. [root@bigboytmp]#vi/etc/mail/spamassassin/local.cf ... ... ... [root@bigboytmp]#spamassassindlint [root@bigboytmp]

Tuningspamassassin

Youcantunethesensitivityofspamassassintothetypeofspamyoureceivebyadjustingtherequired_hitsvalueinthelocal.cffile.Thiscanbemadeeasierbyviewingthescoresp amessageinitsheader.InmostGUIbasedemailclientsthiscanbedonebylookingattheemail'sproperties.Inthiscase,aNigerianemailscamspamwasdetectedandgivenasco markedasspam.


XSpamStatus:Yes,score=20.1required=2.1tests=DEAR_FRIEND, DNS_FROM_RFC_POST,FROM_ENDS_IN_NUMS,MSGID_FROM_MTA_HEADER,NA_DOLLARS, NIGERIAN_BODY1,NIGERIAN_BODY2,NIGERIAN_BODY3,NIGERIAN_BODY4,

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

13/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

RCVD_IN_BL_SPAMCOP_NET,RCVD_IN_SBL,RISK_FREE,SARE_FRAUD_X3, SARE_FRAUD_X4,SARE_FRAUD_X5,US_DOLLARS_3autolearn=failed version=3.0.4 XSpamReport: *0.5FROM_ENDS_IN_NUMSFrom:endsinnumbers *0.2RISK_FREEBODY:Riskfree.Suuurreeee.... *0.4US_DOLLARS_3BODY:Mentionsmillionsof$($NN,NNN,NNN.NN) *0.8DEAR_FRIENDBODY:DearFriend?That'snotverydear! *2.2NA_DOLLARSBODY:TalksaboutamillionNorthAmericandollars *1.8RCVD_IN_BL_SPAMCOP_NETRBL:Receivedviaarelayinbl.spamcop.net *[Blockedsee<http://www.spamcop.net/bl.shtml?213.185.106.3>] *1.1RCVD_IN_SBLRBL:ReceivedviaarelayinSpamhausSBL *[213.185.106.3listedinsblxbl.spamhaus.org] *1.4DNS_FROM_RFC_POSTRBL:Envelopesenderinpostmaster.rfcignorant.org *1.9NIGERIAN_BODY3MessagebodylookslikeaNigerianspammessage3+ *2.9NIGERIAN_BODY1MessagebodylookslikeaNigerianspammessage1+ *1.4NIGERIAN_BODY4MessagebodylookslikeaNigerianspammessage4+ *1.7SARE_FRAUD_X5Matches5+phrasescommonlyusedinfraudspam *0.5NIGERIAN_BODY2MessagebodylookslikeaNigerianspammessage2+ *1.7SARE_FRAUD_X3Matches3+phrasescommonlyusedinfraudspam *1.7SARE_FRAUD_X4Matches4+phrasescommonlyusedinfraudspam *0.0MSGID_FROM_MTA_HEADERMessageIdwasaddedbyarelay

IfSPAMslipsthroughyourspamassassinsystem,youcanusethismethodtoadjustyourrulestoreducetheriskinfuture.

UpdatingSpamassassinsBuiltinRules

Thespamassassinpackagecomeswithafile,/etc/cron.d/saupdate,whichupdatestherulefilesinthe/etc/mail/spamassassin/directoryeachday.Thismakestheadministrationofy easier.

Limitingyourspamfightingeffortstotherequired_hitsvalueisn'tusuallyadequate.Youwillprobablyneedadditionalspamassassintoolstobemoreselectiveandaccurateinyour coverednext.

UsingGreylisting

Tomaximizetheeffectoftheirefforts,spammerstrytosendemailasquicklyaspossible.Theytakenoteoftheemailsthatbounce,sothattheyknowwhichaddressestoremovefr maketheirnextmailingmoreefficient.

Whenmailserversreceivemailtoorapidlyforthemtohandle,theycanaskthesendertotryagainlater.Spammersoftenviewresendingemailstovalidaddressesasawasteofcom couldbeusedtosendmailtobrandnewaddressesthatbelongtofastermailservers.Emailsthatneedtoberesentareusuallyabandoned.

Someemailsneedreliabledeliverytobeeffectiveandthesendersofthesetypesofmessagesarewillingtoresend.Theseincludebankstatementnotifications,ecommercepurchase subscriptionnewsletters.

Inaprevioussectionwesawwherespamassassinalwaysrejectsemailsfromblacklistedsources.Withgreylisting,sourcesarejustaskedtoresend.Oneofthemostpopulargreylist productsisthemiltergreylistpackagewhichalsoworksseamlesslywithspamassassin.ItiseasytouseandIlldiscusshowcanbeconfiguredonyourmailserver.

DownloadingandInstallingmiltergreylist

MostRedHatandFedoraLinuxsoftwareproductpackagesareavailableintheRPMformat,whereasDebianandUbuntuLinuxuseDEBformatinstallationfiles.Whensearching rememberthatthefilenameusuallystartswiththesoftwarepackagenameandisfollowedbyaversionnumber,asinmiltergreylist4.2.61400.fc14.x86_64.rpm.(Forhelpondow installingtherequiredpackages,seeChapter6,InstallingLinuxSoftware). Note:Themiltergreylistpackageisasendmailaddonanddoesnotrunasadaemon.Youdohavetorestartsendmailforthesettingstotakeeffect.

Configuringmiltergreylist
Configuringmiltergreylistrequiresthesefourquicksteps: 1.AddthemiltergreyliststatementslistedintheREADMEfiletoyour/etc/mail/sendmail.mcfile:
INPUT_MAIL_FILTER(`greylist',`S=local:/var/miltergreylist/miltergreylist.sock') define(`confMILTER_MACROS_CONNECT',`j,{if_addr}') define(`confMILTER_MACROS_HELO',`{verify},{cert_subject}') define(`confMILTER_MACROS_ENVFROM',`i,{auth_authen}') define(`confMILTER_MACROS_ENVRCPT',`{greylist}')

2.Thepreviousstepreferencedthefile/var/miltergreylist/miltergreylist.sockwhichnowhastobecreatedandownedbythegrmilteruser.Youcandothisbyfirstsearchingforth /etc/passwd,todoublecheckthattheuserfirstexistsandthatthedirectoryisownedbythisuseralso.Nextcreatethefileandchangeitsownership.Themethodcanbeseenhere.
[root@bigboytmp]#grepgrey/etc/passwd grmilter:x:495:494:Greylistmilteruser:/var/lib/miltergreylist:/sbin/nologin [root@bigboytmp]#touch/var/lib/miltergreylist/miltergreylist.sock [root@bigboytmp]#chowngrmilter:grmilter\ /var/lib/miltergreylist/miltergreylist.sock [root@bigboytmp]#ll/var/lib/miltergreylist/miltergreylist.sock rwrr1grmiltergrmilter0Dec1200:26/var/lib/miltergreylist/miltergreylist.sock [root@bigboytmp]#

3.ConfigureGreylisttostartautomaticallyonreboot.Fedora/CentOS/RedHat
[root@bigboytmp]#chkconfigspamassassinon

Ubuntu/Debian
user@ubuntu:~$sudosysvrcconfspamassassinon

4.Editthe/etc/mail/greylist.confconfigurationfile.Herewesetthetryagainlatertofiveminutesandusethewhitelistcommandtodeactivatethetimerfortrustednetworkssotha

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

14/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

immediately.
# #File:/etc/mail/greylist.conf # #Howlongaclienthastowaitbeforeweaccept #themessagesitretriestosend.Here,1hour. # greylist5m # #Whitelistaddresseswithinmyownhome/officenetwork # aclwhitelistaddr192.168.0.0/16

5.Runtheactivatesendmail.shscriptforthenewsettingstotakeeffect. Yournewspammitigationtoolshouldnowbefullyfunctional.Youarereadytogo!

Configuringmiltergreylist

Nowthatwehavemiltergreylistinstalled,weneedtobeabletodosomebasictroubleshooting.The/var/log/maillogfileshouldbeusedtodeterminewhatishappeningtoyourma samplesofwhattoexpect:
Dec2400:32:31bigboysendmail[28847]:jBO8WVnG028847:Milter:to=<spamvictim@mywebsite.org>, reject=4514.7.1Greylistinginaction,pleasecomebackin00:05:00 Dec2320:40:21bigboymiltergreylist:jBO4eF2m027418:addr211.115.216.225from <slashdot@slashdot.org>rcpt<spamvictim@mywebsite.org>:autowhitelistedfor24:00:00

Inthefirstentry,theemailreceivedisgivenatag(jBO8WVnG028847)basedonkeycharacteristicsinthemailheaderandarequestissenttothesendertoresendtheemailinfive thatisreceivedwiththesamecalculatedkeywithintheautowhiteperiodconfiguredinthegreylist.conffilewillthenbeautomaticallyacceptedwithoutdelay.Inthesecondentry,t resentandimmediatelyaccepted.Anyotheremailfromthatsourcewithinthenext24hourswillbeacceptedwithoutdelay.

Note:Greylistingisveryeffective,butyouwillhavetotneitsoperationtomakesurecriticalemailsarenotdelayedatall.Onesolutonistosettheautowhiteperiodin/etc/mail/grey morethan24hoursespeciallyifyougetmailfromcertainrecipients,suchasnewsletters,onadailybasis.Thismakesthemarrivewithoutinterruption.

ASimplePERLScriptToHelpStopSPAM
Blacklistswon'tstopeverything,butyoucanlimittheamountofunsolicitedspamyoureceivebywritingasmallscripttointerceptyourmailbeforeitiswrittentoyourmailbox.

Thisisfairlysimpletodo,becausesendmailalwayschecksthe.forwardfileinyourhomedirectoryforthenameofthisscript.Thesendmailprogramthenlooksforthefilenamein /etc/smrshandexecutesit.

Bydefault,PERLdoesn'tcomewithmodulesthatareabletocheckemailheadersandenvelopessoyouhavetodownloadthemfromCPAN(www.cpan.org).Themostimportan MailTools IOStringy MIMEtools MailAudit Ihavewrittenascriptcalledmailfilter.plthateffectivelyfiltersoutspamemailformyhomesystem.Afewstepsarerequiredtomakethescriptwork: 1. InstallPERLandthePERLmodulesyoudownloadedfromCPAN. 2. Placeanexecutableversionofthescriptinyourhomedirectoryandmodifythescript's$FILEPATHvariablepointtoyourhomedirectory. 3. Updatefilemailfilter.accept,whichspecifiesthesubjectsandemailaddressestoaccept,andfilemailfilter.reject,whichspecifiesthosetoreject. 4. Updateyour.forwardfileandplaceanentryin/etc/smrsh. Mailfilterfirstrejectsallemailbasedontherejectfileandthenacceptsallmailfoundintheacceptfile.Itthendenieseverythingelse. ForasimplescriptwithinstructionsonhowtoinstallthePERLmodules,seeAppendixII,"Codes,Scripts,andConfigurations".

ConfiguringYourDovecotPOP/IMAPMailServer
LinuxcomeswiththeeasytousedovecotIMAP/POPserverpackagewhichrequiresverylittleconfigurationafterinstallation.

EachuseronyourLinuxboxwillgetmailsenttotheiraccount'smailfolder,butsendmailjusthandlesmailsenttoyourmysite.comdomain.Ifyouwanttoretrievethemailfromy useraccountusingamailclientsuchasEvolution,MicrosoftOutlookorOutlookExpress,thenyouhaveafewmoresteps.You'llalsohavetomakeyourLinuxboxaPOPmailse

InstallingDovecot

MostRedHatandFedoraLinuxsoftwareproductpackagesareavailableintheRPMformat,whereasDebianandUbuntuLinuxuseDEBformatinstallationfiles.Whensearching rememberthatthefilenameusuallystartswiththesoftwarepackagenameandisfollowedbyaversionnumber,asindovecot0.99.111.FC3.4.i386.rpm.(Forhelpondownloading requiredpackages,seeChapter6,InstallingLinuxSoftware).

StartingDovecot
ThemethodologiesvarydependingonthevariantofLinuxyouareusingasyoullseenext. Fedora/CentOS/RedHat

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

15/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

WiththeseflavorsofLinuxyoucanusethechkconfigcommandtogetdovecotconfiguredtostartatboot:
[root@bigboytmp]#chkconfigdovecoton

Tostart,stop,andrestartdovecotafterbootingusetheservicecommand:
[root@bigboytmp]#servicedovecotstart [root@bigboytmp]#servicedovecotstop [root@bigboytmp]#servicedovecotrestart

Todeterminewhetherdovecotisrunningyoucanissueeitherofthesetwocommands.Thefirstwillgiveastatusmessage.ThesecondwillreturntheprocessIDnumbersofthedo
[root@bigboytmp]#servicedovecotstatus [root@bigboytmp]#pgrepspam

Note:Remembertorunthechkconfigcommandatleastoncetoensuredovecotstartsautomaticallyonyournextreboot. Ubuntu/Debian

WiththeseflavorsofLinuxthecommandsaredifferent.TryinstallingthesysvrcconfandsysvinitutilsDEBpackagesastheyprovidecommandsthatsimplifytheprocess.(Forh andinstallingthepackages,seeChapter6,InstallingLinuxSoftware) Youcanusethesysvrcconfcommandtogetdovecotconfiguredtostartatboot:


user@ubuntu:~$sudosysvrcconfdovecoton

Tostart,stop,andrestartdovecotafterbootingtheservicecommandisthesame:
user@ubuntu:~$sudoservicedovecotstart user@ubuntu:~$sudoservicedovecotstop user@ubuntu:~$sudoservicedovecotrestart

Todeterminewhetherdovecotisrunningyoucanissueeitherofthesetwocommands.Thefirstwillgiveastatusmessage.ThesecondwillreturntheprocessIDnumbersofthedo
user@ubuntu:~$sudoservicedovecotstatus user@ubuntu:~$pgrepdovecot

Note:Remembertorunthesysvrcconfcommandatleastoncetoensuredovecotstartsautomaticallyonyournextreboot.

DovecotConfigurationFiles
RemembertorestartDovecotafteryoumakeanychangestoyourconfigurationfiles.Thisistheonlywaytoactivatethenewsettings.

YoucandefinemostofDovecot'sconfigurationparametersinthedovecot.conffilewhichmaybelocatedineitherthe/etcor/etc/dovecotdirectorydependingonyourversionofL

ChoiceofProtocols

YoucanselectoneoftwoprotocolsinyourDovecotconfiguration:IMAPandPOP3.WithPOP3yourmailisdownloadedtoyourcomputersothatyoucanworkwithitoffline.I replytoPOP3mailfromdifferentcomputersitwillbedifficulttogetacompletepictureofsomethreadsastherepliessentononecomputerwontbevisibleontheother.WithIMA alwaysremainsonyourmailserverwhicheliminatesthisproblem.Italsoallowsyoutocreatefoldersforyouremailwhichmakesiteasytoorganizeyouremailandaccessitfrom EachoftheseprotocolsoperateonadifferentTCPportasshowninTable211.

Protocol TCPPort POP POPS IMAP IMAPS 110 995 143 993

Thisinformationwillberequiredforyourconfigurationfileasyouwillsoonsee.Youshouldalsomakesureyourfirewallrulesallowtraffictoaccessyourserverontheseports.

Version1.x

Inthisversion,DovecotwouldbydefaultactasaserverforIMAP,secureencryptedIMAP(IMAPS),POPandsecureencryptedPOP(POPS).Youcouldlimitthislistbyediting the/etc/dovecot.conffileandthenrestartingdovecotforthechangetotakeeffect.IntheexamplebelowdovecotisconfiguredtoserveonlyPOP3.

Note:UnfortunatelythePOP3andIMAPprotocolssendyourusernameandpasswordunencryptedwhichexposesyouruserstoattacks.Dovecotexpectsyoutousethemoresecu IMAPSmethodsandthereforedisablestheuseofplaintextpasswordsbydefault.Toenabletheacceptanceofplaintextauthenticationthedisable_plaintext_authcommandneedst theexamplealsoshows.


# #File/etc/dovecot.confsample #

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

16/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

#Protocolswewanttobeservingimapimapspop3pop3s #protocols=imapimapspop3pop3s protocols=pop3 disable_plaintext_auth=no

YoushouldalwaystrytousesecurePOP3SorIMAPSforbetterpeaceofmind.MoredetailsonhowtodothiswithnewerversionsofDovecotwillbecoverednext.

Version2.xandNewer
Inmorerecentversions,thesyntaxofthedovecot.confstatementsusedtodefineprotocolshaschanged. BothPOP3andIMAPsettingsareconfiguredinaservicesectionandyoucandefinetheIPaddresseseachshoulduseandtheTCPportsonwhichtheyshouldlisten.

Inthisexample,wehavedisabledIMAPSandPOP3bysettingtheirinet_listenerportstozero.POP3Sisworkingonaddress192.168.1.100whileIMAPworksonthelocalhostad BothPOP3SandIMAPlistenontheirrespectiveTCPports.
#RequiredtomakePOPS/IMAPStoworkwithcertificates ssl=yes

servicepop3login{ inet_listenerpop3{ port=0 } inet_listenerpop3s{ port=995 address=192.168.1.100 } } serviceimaplogin{ inet_listenerimap{ address=127.0.0.1 port=143 } inet_listenerimaps{ port=0 } }

IMAPSandPOP3ScommonlyrelyontheuseofSSLcertificatesforencryption.YoumakeDovecotawarethatyouintendtousethismethodwiththesslcommand.Thisisalsosh example.Itisanimportantstep. Note:AlwaysremembertorestartDovecotinorderforthesesettingstotakeeffect.

VerifiyingWhetherDovecotisListening

Youcanthenusethenetstatcommandtodoasimplepreliminarytesttomakesuredovecotislisteningonthecorrectports.InthisexampleweseethatIMAPislisteningonlocalho listeningontheNICIPaddressofserverbigboy.Itproofthatourconfigurationworks.
[root@bigboytmp]#netstatta|egrepi'pop|imap' tcp00localhost:imap*:*LISTEN tcp00bigboy:pop3s*:*LISTEN [root@bigboytmp]#

Itisofteninsufficienttousethisasyouronlytest.Tryusingthetelnetcommandfromanotherlocationtoverifythatremoteclientcancontactyourmailserveronthecorrectports.I mayhavearoutingorfirewallissue,ordovecotmaynotberunning.InthisexamplewearetestingonthePOPSport,995.
[root@bigboytmp]#telnetmail.mysite.com995 Trying192.168.1.100... Connectedtomail.simiya.com. Escapecharacteris'^]'. ^] telnet>quit Connectionclosed. [root@bigboytmp]#

ConnectionproblemscouldalsobetheresultoftypicalnetworkissuesoutlinedinChapter4,"SimpleNetworkTroubleshooting".Reviewthischapterifyoufindyourselfhavingp basicconnectivity.

ConfiguringSSLCertificatesforPOP3SandIMAPS

Asmentionedpreviously,whenconfiguringPOP3SandIMAPSyouneedtoletDovecotknowwhereyourcertificatesare.Bydefaultthecertificatesarenameddovecot.pemandr shouldbefoundinyourdovecot.conffileoroneofitsdaughterconfigurationfilesinthe/etc/dovecot/conf.ddirectory.Theconfigurationshouldlooklikethis.
ssl_cert=</etc/pki/dovecot/certs/dovecot.pem ssl_key=</etc/pki/dovecot/private/dovecot.pem

YoucanverifythesecommandsarelistedinyourDovecotconfigurationfiletree.Thiscanbedonewithasimplerecursivegrepcommandwhichsearches/etc/dovecotanditssubd withthestringdovecot.peminthem.Inthiscasethestatementsarefoundinthe10ssl.conffileinthe/etc/dovecot/conf.ddirectory.
[root@bigboytmp]#grepirdovecot.pem/etc/dovecot/ /etc/dovecot/conf.d/10ssl.conf:ssl_cert=</etc/pki/dovecot/certs/dovecot.pem /etc/dovecot/conf.d/10ssl.conf:ssl_key=</etc/pki/dovecot/private/dovecot.pem [root@bigboytmp]#

Afterfindingthereferencesyoushouldverifythatthefilesexist.Thiscanbedonewiththelocatecommand.Hereweseethefilelocationspreviouslylistedintheconfigurationfile actuallyresideinthefilesystem.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

17/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

[root@bigboytmp]#locatedovecot.pem /etc/pki/dovecot/certs/dovecot.pem /etc/pki/dovecot/private/dovecot.pem [root@bigboytmp]#

Whatdoyoudoifyoudonthavethesefiles?Dontworry,youcaneasilycreatethemandthiswillbecoverednext.

ConfiguringSSLCertificatesforPOP3SandIMAPS

Whatdoyoudoifyoudonthavethesefiles?Dontworry,youcaneasilycreatethemandthiswillbecoverednext.Themkcert.shfilewillgenerateyourDovecotcertificatesfory configuredinthedovecotopenssl.cnffile.Youcanusethelocatecommandtofindbothfiles.
[root@bigboytmp]#locatemkcert.sh /usr/libexec/dovecot/mkcert.sh [root@bigboytmp]#locatedovecotopenssl.cnf /etc/pki/dovecot/dovecotopenssl.cnf [root@bigboytmp]#

Thoughthecontentsofthedovecotopenssl.cnffilewillbesufficienttogenteratetheSSLcertificates,youmaywanttocustomizeittomeettheneedsofyourorganizationasseenh
# #File:dovecotopenssl.cnf # [req_dn] #country(2lettercode) C=US #StateorProvinceName(fullname) ST=California #LocalityName(eg.city) L=SanFrancisco #Organization(eg.company) O=MySiteInc #OrganizationalUnitName(eg.section) OU=MySiteITDepartment #CommonName(*.example.comisalsopossible) CN=mail.mysite.com #Emailcontact emailAddress=postmaster@mysite.com

Thenextstepistotunthemkcert.shscriptandmakesurethekeysareintherightlocation.
[root@bigboytmp]#/usr/libexec/dovecot/mkcert.sh Generatinga1024bitRSAprivatekey ...........++++++ ......................++++++ writingnewprivatekeyto'/etc/pki/dovecot/private/dovecot.pem' subject=/OU=MySiteITDepartment/CN=mail.mysite.com/emailAddress=postmaster@mysite.com SHA1Fingerprint=A0:F9:95:1B:90:21:B9:B2:45:5B:CC:DF:20:2C:9E:25:74:69:F1:DD [root@bigboytmp]#

Nowthatyourcertificateshavebeencreatedyoushouldbereadytostartservingsecureemailtoyourusers.

Dovecotusesitsowncertificatesandthemethoddescribedhereshowsyouhowtocreateyourown.Ifyouarepartofanenterprisewithitsowndomain,youshouldinvestingettin certificatescreatedbyanofficialcertificateauthoritylikeVerisign.AllemailclientsrecognizeorganizationsliketheseandwilloperateusingPOPSandIMAPSwithoutdisplaying statingthatthecertificatecomesfromanuntrustedsource.

ForadditionalsecurityyoucaninstallaseparatecertificateonalltheclientcomputersandconfigureDovecottoonlyinteractwithclientstheseknowncredentials.Howdothisisbe thisbook,butshouldbeinvestigatedtoreduceyoursecurityrisk.

DovecotMailboxes
Thoughsendmailsendsyouremailtoalocaluseraccount,Linuxmaystorethecontentofthemailinoneofmanyformats.Twocommonmethodsaremboxandmaildir.

Dovecotusesthemail_locationdirectivetodefinethetypeofmailformatandthelocationofitsfiles.Thisdirectivemaybefoundineitheryourdovecot.conffileoroneofitsdaugh filesinthe/etc/dovecot/conf.ddirectory.Itmayalsobecommentedout.

VerifythatthesedirectivesarelistedinyourDovecotconfigurationfiletree.Thiscanbedonewithasimplerecursivegrepcommandwhichsearches/etc/dovecotanditssubdirecto thestringmail_locationinthem.Inthiscasethestatementsarefoundinthe10mail.conffileinthe/etc/dovecot/conf.ddirectory.
[root@bigboytmp]#grepirmail_location/etc/dovecot /etc/dovecot/conf.d/10mail.conf:#mail_location=maildir:~/Maildir /etc/dovecot/conf.d/10mail.conf:#mail_location=mbox:~/mail:INBOX=/var/mail/%u /etc/dovecot/conf.d/10mail.conf:#mail_location=mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n /etc/dovecot/conf.d/10mail.conf:#mail_location= /etc/dovecot/conf.d/10mail.conf:#mail_location=mbox:~/mail:INBOX=/var/mail/%u [root@bigboytmp]#

Ifyoulookclosely,youwillnoticethatthereferencesareallcommentedout.Thefollowingsectionswillshowyouhowtodeterminewhichmethodtouse.Ifyouselecttheincorre youwontbeabletodownloadyourmail,becauseDovecotwillbelookingforitinthewronglocation!

ConfiguringDovecotformbox

Mboxmailisstoredinthedirectory/var/mail.EachuserisassignedasinglefilethatcontainsalltheirmailandthefilenameisthesameasLinuxusername.Iftherearefilesin/var/m youaremostlikelyusingthemboxmethod.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

18/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

[root@bigboytmp]#ls/var/mail/ user1user2user3user4user5user6user7user8user9 [root@bigboytmp]#

Theconfigurationformboxrequirestheadditionofthislinetoyourdovecot.conffile,orasinourcase,uncommentingasimilarlinefromthe10mail.conffile.Eithermethodwillw
mail_location=mbox:~/mail:INBOX=/var/mail/%u

Note:RemembertorestartDovecotforthissettingtobeactivated. Nowitistimetotakealookatthemaildirmethod.

ConfiguringDovecotformaildir
Maildirmailsarealmostalwaysstoredina~/Maildir/directoryintheusershomedirectory.Unlikethemboxmethod,withmaildireachmailisstoredinaseparatefile. ToconfigureDovecotforyourmaildirmail,usethisdirective:
mail_location=maildir:~/Maildir

Note:RemembertorestartDovecotforthissettingtobeactivated. Youaredone!Thatwaseasy.

DifferentdistributionsofLinuxusedifferingmethodsofstoringemail.IfneithermboxormaildirseemstobethemethodyoursystemisusingthenchecktheDovecotwebsiteatdo furtherdetails.

ConfiguringYourMailClients

BydefaultyourPOP/IMAPemailaccountswillbetheregularLinuxuseraccountsinwhichsendmailhasdepositedmail.Youcannowconfigureyouremailclienttouseyouru serverquiteeasily.ForexampletoconfigurePOPSMail,setyourPOPSmailserverintheclientprogramtobetheIPaddressofyourLinuxmailserver.UseyourLinuxuserusern whenprompted. IfyouareusingaselfsignedSSLcertificate,yourmailclientwillgiveawarninganaskwhetherthecertificateshouldbeaccepted.Youwillhavetosayyes. Next,setyourSMTPmailservertobetheIPaddress/domainnameofyourLinuxmailserver.

Howtohandleoverlappingemailaddresses.

Ifyouhaveuseroverlap,suchasJohnSmith(john@mysite.com)andJohnBrown(john@anothersite.com),bothuserswillgetsenttotheLinuxuseraccountjohnbydefault.Yo forasolution:

Maketheuserpartoftheemailaddressdifferent,john1@mysite.comandjohn2@anothersite.comforexample,andcreateLinuxaccountsjohn1andjohn2.Iftheusersinsis names,thenyoumayneedtomodifyyourvirtusertablefile. Createtheuseraccountsjohn1andjohn2andpointvirtusertableentriesforjohn@mysite.comtoaccountjohn1andpointjohn@anothersite.comentriestoaccountjohn2.T configurationinOutlookExpressforeachusershouldretrievetheirmailviaPOPusingjohn1andjohn2,respectively. Withthistrickyou'llbeabletohandlemanyusersbelongingtomultipledomainswithoutmanyaddressoverlapproblems.

TroubleshootingDovecotMail

TheveryfirsttroubleshootingstepistodeterminewhetheryourserverisaccessibleonthecorrectTCPports.Forexample,withPOPuseTCPport110orforPOPSuseportof99 connectivitycouldbecausedbyafirewallwithincorrectpermit,NAT,orportforwardingrulestoyourserver.TestthisfrombothinsideyournetworkandfromtheInternet.(Trou withTELNETiscoveredinChapter4,"SimpleNetworkTroubleshooting")

AlwaysStartwithLogging

WheneveryouareindoubtturnonDovecotsdebuggingfeaturestorevealmoreaboutwhatishappening.InmorerecentversionsofDovecot,theloggingsectionsindovecot.conf toaloggingconfigurationfileinthe/etc/dovecot/conf.ddirectory.Inthisexamplethefileisnamed10logging.conf.
[root@bigboytmp]#ls/etc/dovecot/conf.d/*log* /etc/dovecot/conf.d/10logging.conf [root@bigboytmp]#

Thefilehasmanysectionsthatallowyoutoturnonveryverbosedebugginglevelmessagesforauthentication,SSL,andgeneralmessaging.Itisaninvaluablesourceoftroublesho Dovecotlogstothe/var/log/maillogfile.FordetailsonsettingupLinuxloggingrefertoChapter5,"Troubleshootingwithsyslog."Herearesomegoodexamples: InthiscasetheMaildirmail_locationmethodwasincorrectlychosenandtheexpectedmailfileswerenotfound


Dec520:49:47bigboydovecot:pop3(mailuser1):Debug:maildir:access(/home/users/mailuser1/Maildir,rwx):failed:Nosuchfileordirectory Dec520:49:47bigboydovecot:pop3(mailuser1):Debug:maildir:couldn'tfindrootdir

InthiscaseDovecotsautodetectionmethodfailedtodeterminethecorrectmail_location.Thedirectivehadtobemanuallyadded.

Dec509:10:26bigboydovecot:pop3(mailuser2):Error:userlhnmail:Initializationfailed:mail_locationnotsetandautodetectionfailed:Mailstorageautodetectionfailedwithhome=/

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

19/20

9/12/12

Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking

Wheneverthereisanydoubt,lookfortheerrormessageinthelogfile,trytounderstandwhatitmeansandwhatcouldbedonetofixtheproblem.Remember,findinghelpforyour Internetwillbemucheasierifyousearchforkeypartsofyourlogmessage.

Conclusion

EmailisanimportantpartofanyWebsite,andyouneedtoplanitsconfigurationcarefullytomakeitaseamlesspartoftheWebexperienceofyourvisitors.Withoutit,yourWeb complete.

AfullyfunctioningWebsiteisjustthebeginning.Itneedstobemaintainedtoreducetheriskoffailureandmonitoredtohelpdetectpotentialproblems.Chapter22,"MonitoringS Performance",discussesmanyLinuxbasedtoolsthatyoucanbeusetotrackthehealthofyourLinuxserver. Retrievedfrom"http://www.linuxhomenetworking.com/wiki/index.php?title=Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers&oldid=4331" Thispagewaslastmodifiedon9August2012,at23:29. ContentisavailableunderAttributionNonCommercialNoDerivs2.5.

linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers

20/20

S-ar putea să vă placă și