/usr/bin/dkim-milter.py is in dkim-milter-python 0.9-1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | #!/usr/bin/python
# A simple DKIM milter.
# You must install pydkim/dkimpy for this to work.
# http://www.sendmail.org/doc/sendmail-current/libmilter/docs/installation.html
# Author: Stuart D. Gathman <stuart@bmsi.com>
# Copyright 2007 Business Management Systems, Inc.
# This code is under GPL. See COPYING for details.
import sys
import Milter
import dkim
from dkim.dnsplug import get_txt
from dkim.util import parse_tag_value
import authres
import logging
import logging.config
import os
import os.path
import tempfile
import StringIO
import re
from Milter.config import MilterConfigParser
from Milter.utils import iniplist,parse_addr,parseaddr
class Config(object):
"Hold configuration options."
pass
def read_config(list):
"Return new config object."
for fn in list:
if os.access(fn,os.R_OK):
logging.config.fileConfig(fn)
break
cp = MilterConfigParser()
cp.read(list)
if cp.has_option('milter','datadir'):
os.chdir(cp.get('milter','datadir'))
conf = Config()
conf.log = logging.getLogger('dkim-milter')
conf.log.info('logging started')
conf.socketname = cp.getdefault('milter','socketname', '/tmp/dkimmiltersock')
conf.miltername = cp.getdefault('milter','name','pydkimfilter')
conf.internal_connect = cp.getlist('milter','internal_connect')
# DKIM section
if cp.has_option('dkim','privkey'):
conf.keyfile = cp.getdefault('dkim','privkey')
conf.selector = cp.getdefault('dkim','selector','default')
conf.domain = cp.getdefault('dkim','domain')
conf.reject = cp.getdefault('dkim','reject')
if conf.keyfile and conf.domain:
try:
with open(conf.keyfile,'r') as kf:
conf.key = kf.read()
except:
conf.log.error('Unable to read: %s',conf.keyfile)
return conf
FWS = re.compile(r'\r?\n[ \t]+')
class dkimMilter(Milter.Base):
"Milter to check and sign DKIM. Each connection gets its own instance."
def log(self,*msg):
self.conf.log.info('[%d] %s' % (self.id,' '.join([str(m) for m in msg])))
def __init__(self):
self.mailfrom = None
self.id = Milter.uniqueID()
# we don't want config used to change during a connection
self.conf = config
self.fp = None
@Milter.noreply
def connect(self,hostname,unused,hostaddr):
self.internal_connection = False
self.hello_name = None
# sometimes people put extra space in sendmail config, so we strip
self.receiver = self.getsymval('j').strip()
if hostaddr and len(hostaddr) > 0:
ipaddr = hostaddr[0]
if iniplist(ipaddr,self.conf.internal_connect):
self.internal_connection = True
else: ipaddr = ''
self.connectip = ipaddr
if self.internal_connection:
connecttype = 'INTERNAL'
else:
connecttype = 'EXTERNAL'
self.log("connect from %s at %s %s" % (hostname,hostaddr,connecttype))
return Milter.CONTINUE
# multiple messages can be received on a single connection
# envfrom (MAIL FROM in the SMTP protocol) seems to mark the start
# of each message.
@Milter.noreply
def envfrom(self,f,*str):
self.log("mail from",f,str)
self.fp = StringIO.StringIO()
self.mailfrom = f
t = parse_addr(f)
if len(t) == 2: t[1] = t[1].lower()
self.canon_from = '@'.join(t)
self.user = self.getsymval('{auth_authen}')
self.has_dkim = False
self.author = None
self.arheaders = []
self.arresults = []
if self.user:
# Very simple SMTP AUTH policy by default:
# any successful authentication is considered INTERNAL
self.internal_connection = True
auth_type = self.getsymval('{auth_type}')
ssl_bits = self.getsymval('{cipher_bits}')
self.log(
"SMTP AUTH:",self.user,"sslbits =",ssl_bits, auth_type,
"ssf =",self.getsymval('{auth_ssf}'), "INTERNAL"
)
# Detailed authorization policy is configured in the access file below.
self.arresults.append(
authres.SMTPAUTHAuthenticationResult(result = 'pass',
result_comment = auth_type+' sslbits='+ssl_bits, smtp_auth = self.user)
)
return Milter.CONTINUE
@Milter.noreply
def header(self,name,val):
lname = name.lower()
if not self.has_dkim and lname == 'dkim-signature':
self.log("%s: %s" % (name,val))
self.has_dkim = True
if lname == 'from':
fname,self.author = parseaddr(val)
self.log("%s: %s" % (name,val))
elif lname == 'authentication-results':
self.arheaders.append(val)
if self.fp:
self.fp.write("%s: %s\n" % (name,val))
return Milter.CONTINUE
@Milter.noreply
def eoh(self):
if self.fp:
self.fp.write("\n") # terminate headers
self.bodysize = 0
return Milter.CONTINUE
@Milter.noreply
def body(self,chunk): # copy body to temp file
if self.fp:
self.fp.write(chunk) # IOError causes TEMPFAIL in milter
self.bodysize += len(chunk)
return Milter.CONTINUE
def eom(self):
if not self.fp:
return Milter.ACCEPT # no message collected - so no eom processing
# lookup Author Domain Signing Policy, if any
adsp = { 'dkim': 'unknown' }
if self.author:
author_domain = self.author.split('@',1)[-1]
s = get_txt('_adsp._domainkey.'+author_domain)
if s:
m = parse_tag_value(s)
if m.has_key('dkim'):
self.log(s)
adsp = m
# Remove existing Authentication-Results headers for our authserv_id
for i,val in enumerate(self.arheaders,1):
# FIXME: don't delete A-R headers from trusted MTAs
ar = authres.AuthenticationResultsHeader.parse_value(FWS.sub('',val))
if ar.authserv_id == self.receiver:
self.chgheader('authentication-results',i,'')
self.log('REMOVE: ',val)
# Check or sign DKIM
self.fp.seek(0)
if self.internal_connection:
txt = self.fp.read()
self.sign_dkim(txt)
result = None
elif self.has_dkim:
txt = self.fp.read()
if self.check_dkim(txt):
result = 'pass'
else:
result = 'fail'
self.arresults.append(
authres.DKIMAuthenticationResult(result=result,
header_i = self.header_i, header_d = self.header_d,
result_comment = self.dkim_comment)
)
else:
result = 'none'
# Check if local reject policy and ADSP indicate message should be rejected
lp = self.conf.reject # local policy
if lp and result and result != 'pass':
p = adsp['dkim'] # author domain policy
if lp == p or p == 'discardable' and lp == 'all':
if result == 'none':
t = 'Missing'
else:
t = 'Invalid'
self.setreply('550','5.7.1',
'%s DKIM signature for %s with ADSP dkim=%s'%(t,self.author,p))
self.log('REJECT: %s DKIM signature'%t)
return Milter.REJECT
if self.arresults:
h = authres.AuthenticationResultsHeader(authserv_id = self.receiver,
results=self.arresults)
self.log(h)
name,val = str(h).split(': ',1)
self.addheader(name,val,0)
return Milter.CONTINUE
def sign_dkim(self,txt):
conf = self.conf
try:
d = dkim.DKIM(txt,logger=conf.log)
h = d.sign(conf.selector,conf.domain,conf.key,
canonicalize=('relaxed','simple'))
name,val = h.split(': ',1)
self.addheader(name,val.strip().replace('\r\n','\n'),0)
except dkim.DKIMException as x:
self.log('DKIM: %s'%x)
except Exception as x:
conf.log.error("sign_dkim: %s",x,exc_info=True)
def check_dkim(self,txt):
res = False
conf = self.conf
d = dkim.DKIM(txt,logger=conf.log)
try:
res = d.verify()
if res:
self.dkim_comment = 'Good %d bit signature.' % d.keysize
else:
self.dkim_comment = 'Bad %d bit signature.' % d.keysize
except dkim.DKIMException as x:
self.dkim_comment = str(x)
#self.log('DKIM: %s'%x)
except Exception as x:
self.dkim_comment = str(x)
conf.log.error("check_dkim: %s",x,exc_info=True)
self.header_i = d.signature_fields.get(b'i')
self.header_d = d.signature_fields.get(b'd')
if res:
#self.log('DKIM: Pass (%s)'%d.domain)
self.dkim_domain = d.domain
else:
fd,fname = tempfile.mkstemp(".dkim")
with os.fdopen(fd,"w+b") as fp:
fp.write(txt)
self.log('DKIM: Fail (saved as %s)'%fname)
return res
if __name__ == "__main__":
Milter.factory = dkimMilter
Milter.set_flags(Milter.CHGHDRS + Milter.ADDHDRS)
global config
config = read_config(['dkim-milter.cfg','/etc/dkim-milter-python/dkim-milter.cfg'])
miltername = config.miltername
socketname = config.socketname
ownpid = os.getpid()
if not os.path.isfile('/var/run/dkim-milter-python/dkim-milter.pid'):
pidfile = open('/var/run/dkim-milter-python/dkim-milter.pid',mode='w+')
pidfile.write(ownpid)
pidfile.flush()
pidfile.close()
sys.stdout.flush()
Milter.runmilter(miltername,socketname,240)
|