Configuring Linux Mail Servers
Configuring Linux Mail Servers
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
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
HowSendmailWorks
Asstatedbefore,sendmailcanhandlebothincomingandoutgoingmailforyourdomain.Takeacloserlook.
IncomingMail
UsuallyeachuserinyourhomehasaregularLinuxaccountonyourmailserver.Mailsenttoeachoftheseusers([email protected])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
SendmailMacros
Whenmailpassesthroughasendmailserverthemailroutinginformationinitsheaderisanalyzed,andsometimesmodified,accordingtothedesiresofthesystemsadministrator.U highlycomplicatedregularexpressionslistedinthe/etc/mail/sendmail.cffile,sendmailinspectsthisheaderandthenactsaccordingly.
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
ManagingthesendmailServer
Managingthesendmaildaemoniseasytodo,buttheprocedurediffersbetweenLinuxdistributions.Herearesomethingstokeepinmind.
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
You'llneedtorunthescripteachtimeyouchangeanyofthesendmailconfigurationfilesdescribedinthesectionstofollow.
[root@bigboytmp]#/usr/local/bin/activatesendmail.sh
Inaproductionsystemyoumaywanttobemoreselectiveandonlyrestartthespecificapplicationsonwhichyouareworking.Iincludedalloftheminthescriptsoyoudon'tforge
The/etc/mail/sendmail.mcFile
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.
Anincorrectlyconfiguredresolv.conffilecanleadtoerrorswhenrunningthem4commandtoprocesstheinformationinyoursendmail.mcfile.
WARNING:localhostname(smallfry)isnotqualifiedfix$jinconfigfile
The/etc/hostsFile
The/etc/hostsfilealsoisusedbyDNSclientsandalsoneedstobecorrectlyconfigured.Hereisabriefexampleofthefirstlineyoushouldexpecttoseeinit:
127.0.0.1bigboy.mysite.comlocalhost.localdomainlocalhostbigboy
HowToConfigureLinuxSendmailClients
AllLinuxmailclientsinyourhomeorcompanyneedtoknowwhichserveristhemailserver.Thisisconfiguredinthesendmail.mcfilebysettingtheSMART_HOSTstatementto server.Intheexamplebelow,themailserverhasbeensettomail.mysite.com,themailserverforthemysite.comdomain.
define(`SMART_HOST',`mail.mysite.com')
ConvertingFromaMailClienttoaMailServer
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]#
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
The/etc/mail/accessFile
Ifyoudon'ttaketheprecautionofusingthisfeature,youmayfindyourserverbeingusedtorelaymailforspamemailsites.Configuringthe/etc/mail/accessfilewillnotstopspam onlyspamflowingthroughyou.
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/aliasesFile
Youcanthinkofthe/etc/aliasesfileasamailinglistfile.Thefirstcolumnhasthemailinglistname(sometimescalledavirtualmailbox),andthesecondcolumnhasthemembersof separatedbycommas.
Tostart,sendmailsearchesthefirstcolumnofthefileforamatch.Ifthereisnomatch,thensendmailassumestherecipientisaregularuseronthelocalserveranddepositsthemail
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,[email protected]
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
Mailsentto"[email protected]"goestousers"grandma","brother"and"sister"
#Myfamily family:grandma,brother,sister
Mailsenttoadminlistgetssenttoalltheuserslistedinthefile/home/mailings/adminlist.
#Mymailinglistfile adminlist:":include:/home/mailings/adminlist"
Note:Besuretorunthenewaliasescommandforthesechangestotakeeffect.
SendmailMasqueradingExplained
[email protected]@bigboy.mysite.com,thenyouhavetwochoices: Configureyouremailclient,suchasOutlookExpress,[email protected].(I'llexplainthisinthe"ConfiguringYourPOPMailServer"section.). Setupmasqueradingtomodifythedomainnameofalltrafficoriginatingfromandpassingtroughyourmailserver.
Configuringmasquerading
Theresultisthat:
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.
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
[email protected]
Youremailsfromlinuxusernameshouldnowappeartocomefromusername@newdomain.com. Herearesomeotherexamples:
[email protected] [email protected] [email protected]
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
FurtherTestingofTCPconnectivity
3)InformthemailserverfromwhichthetestmessageiscomingwiththeMAILFROM:statement.
MAILFROM:[email protected] [email protected]
4)Tellthemailservertowhomthetestmessageisgoingwiththe"RCPTTO:"statement.
RCPTTO:[email protected] [email protected]
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]#[email protected] 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:<[email protected]> 250<[email protected]>...SenderOk >>>RCPTTo:<[email protected]> 250<[email protected]>...RecipientOk >>>DATA 354Entermail,endwith"."onalinebyitself >>>. 250Messageacceptedfordelivery [email protected](Messageacceptedfordelivery) Closingconnectiontomail.anothersite.com. >>>QUIT [root@bigboytmp]#
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
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
Spamassassin
Oncesendmailreceivesanemailmessage,ithandsthemessageovertoprocmail,whichistheapplicationthatactuallyplacestheemailinusermailboxesonthemailserver.You temporarilyhandovercontroltoanotherprogram,suchasaspamfilter.Themostcommonlyusedfilterisspamassassin.
spamassassindoesn'tdeletespam,itmerelyaddstheword"spam"tothebeginningofthesubjectlineofsuspectedspamemails.YoucanthenconfiguretheemailfilterrulesinOu anyothermailclienttoeitherdeletethesuspectmessageorstoreitinaspecialSpamfolder.
DownloadingAndInstallingSpamassassin
ManagingthespamassassinServer
Managingthespamassassindaemoniseasytodo,buttheprocedurediffersbetweenLinuxdistributions.Herearesomethingstokeepinmind.
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
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
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=<[email protected]>, reject=4514.7.1Greylistinginaction,pleasecomebackin00:05:00 Dec2320:40:21bigboymiltergreylist:jBO4eF2m027418:addr211.115.216.225from <[email protected]>rcpt<[email protected]>:autowhitelistedfor24:00:00
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
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
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
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.
linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers
16/20
9/12/12
Quick HOWTO : Ch21 : Configuring Linux Mail Servers - Linux Home Networking
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 } }
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
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 [email protected]
Thenextstepistotunthemkcert.shscriptandmakesurethekeysareintherightlocation.
[root@bigboytmp]#/usr/libexec/dovecot/mkcert.sh Generatinga1024bitRSAprivatekey ...........++++++ ......................++++++ writingnewprivatekeyto'/etc/pki/dovecot/private/dovecot.pem' subject=/OU=MySiteITDepartment/CN=mail.mysite.com/[email protected] SHA1Fingerprint=A0:F9:95:1B:90:21:B9:B2:45:5B:CC:DF:20:2C:9E:25:74:69:F1:DD [root@bigboytmp]#
Nowthatyourcertificateshavebeencreatedyoushouldbereadytostartservingsecureemailtoyourusers.
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
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
Howtohandleoverlappingemailaddresses.
Ifyouhaveuseroverlap,suchasJohnSmith([email protected])andJohnBrown([email protected]),bothuserswillgetsenttotheLinuxuseraccountjohnbydefault.Yo forasolution:
TroubleshootingDovecotMail
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]#
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.
linuxhomenetworking.com//Quick_HOWTO_:_Ch21_:_Configuring_Linux_Mail_Servers
20/20