Debian Codegraph @

sshsendmail.py

raw symbols SCIP
1 #!/usr/bin/python3
2 # coding: utf-8
3
4 """A safer sendmail command"""
5
6 # Copyright (C) 2017 Antoine Beaupré <[email protected]>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
17 #
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 from __future__ import division, absolute_import
22 from __future__ import print_function, unicode_literals
23
24 import argparse
25 import copy
26 import logging
27 import logging.handlers
28 import os
29 import subprocess
30 import sys
31
32 __description__ = """nullmailer-rsendmail compatibility shim."""
33
34
35 def parse_args():
36 parser = argparse.ArgumentParser(description=__doc__, epilog=__description__)
37 parser.add_argument(
38 "--loglevel",
39 dest="loglevel",
40 default="WARNING",
41 help="level should be sent to syslog (default: %(default)s)",
42 )
43 default_mta = "postfix"
44 if "nullmailer" in os.path.realpath(sys.argv[0]):
45 default_mta = "nullmailer"
46 parser.add_argument(
47 "--mta",
48 choices=["postfix", "nullmailer"],
49 default=default_mta,
50 help="communication interface with parent MTA (default: %(default)s)",
51 )
52 parser.add_argument("--identity", help="path to SSH private key")
53 parser.add_argument("--user", help="username for the SSH host")
54 parser.add_argument("--host", help="remote email gateway running rsendmail")
55 parser.add_argument("-f", dest="sender", help="enveloper sender")
56 parser.add_argument(
57 "-d",
58 "-s",
59 dest="nullmailer1",
60 action="store_true",
61 help="arguments passed by nullmailer1, triggers an exception",
62 )
63 parser.add_argument(
64 "recipients",
65 nargs="*",
66 help="who to send the email to, may be parsed from MTA-specific headers instead",
67 )
68 args = parser.parse_args()
69 if args.mta != "nullmailer" and not args.host:
70 parser.error("a remote host should be provided as --host")
71 if args.nullmailer1:
72 parser.error("nullmailer 1 flags detected, aborting")
73 return args
74
75
76 def setupLogging(syslog):
77 logger = logging.getLogger("")
78 # disable the base filter, each stream has its own filter
79 logger.setLevel("DEBUG")
80 sl = logging.handlers.SysLogHandler(address="/dev/log", facility="mail")
81 sl.setFormatter(
82 logging.Formatter(sys.argv[0] + "[%(process)d]: %(levelname)s: %(message)s")
83 )
84 # convert syslog argument to a numeric value
85 sl.setLevel(syslog.upper())
86 logger.addHandler(sl)
87
88
89 def readNullMailer2Options(args, stream):
90 """read nullmailer configuration
91
92 nullmailer sends its configuration on stdin with one option per
93 line, in key=value pairs separated by equal signs. we parse from
94 the ``stream`` argument to facilitate tests.
95
96 store the resulting config in the ``args`` namespace.
97 """
98 for line in stream:
99 # this block ends on an empty line
100 line = line.strip()
101 logging.debug("got config from nullmailer: %s", line)
102 if line == "":
103 break
104 if "=" in line:
105 name, val = line.split("=", 1)
106 setattr(args, name, val)
107 else:
108 logging.warning("unexpected config syntax from nullmailer: %s", line)
109
110
111 def readNullMailer2Envelope(stream):
112 """read envelope information from nullmailer
113
114 nullmailer sends addresses one per line. the first address is the
115 "envelope sender address", who to send errors to and equivalent to
116 the `-f` sendmail flag. then the remaining lines are recipients.
117
118 extract the sender and recipients, which are return as a tuple.
119 """
120 sender = None
121 recipients = []
122 try:
123 for line in stream:
124 line = line.strip()
125 logging.debug("got envelope from nullmailer: %s", line)
126 # the envelope block ends on an empty line
127 if line == b"":
128 break
129 assert (
130 len(line) > 3
131 ), "sanity check: emails are generally longer than three characters"
132
133 if not sender:
134 # first the sender...
135 sender = line.decode(errors="backslashreplace")
136 else:
137 # ... then the recipients
138 recipients.append(line.decode(errors="backslashreplace"))
139 except OSError as e:
140 # this error was triggered when called with nullmailer 1.
141 # this should not happen anymore as nullmailer 1 passes the -d
142 # or -s flags which we abort on since 743e584 but checking
143 # anyways shouldn't hurt
144 if "read() should have returned a bytes object, not 'NoneType'" in str(e):
145 logging.error(
146 "cannot open file descriptor 3, are you running nullmailer 2.x?"
147 )
148 return sender, recipients
149
150
151 # map error codes from sendmail to nullmailer
152 nullmailer_sysexits_map = {
153 os.EX_OK: "EX_OK", # Successful completion on all addresses.
154 # ssh returns the remote command status code, unless the command
155 # cannot be ran, in which case it returns this:
156 255: "ERR_CONN_FAILED",
157 # those are defined in sendmail(8) manpage (v8.15.2)
158 os.EX_NOUSER: "ERR_MSG_REFUSED", # User name not recognized.
159 os.EX_UNAVAILABLE: "ERR_EXEC_FAILED", # Catchall meaning necessary resources were not available.
160 # not in Python or Debian
161 # os.EX_SYNTAX: 'ERR_MSG_REFUSED', # Syntax error in address.
162 os.EX_SOFTWARE: "ERR_USAGE", # Internal software error, including bad arguments.
163 os.EX_OSERR: "ERR_EXEC_FAILED", # Temporary operating system error, such as ``cannot fork''.
164 os.EX_NOHOST: "ERR_NO_ADDRESS", # Host name not recognized.
165 # os.EX_TEMPFAIL is ignored for sendmail, because it is "Message
166 # could not be sent immediately, but was queued." That is nuts:
167 # this is not an error, it is what mail servers do. They queue up
168 # mail. Leave room for reasonable mail server errors and ignore
169 # old sendmail here.
170 #
171 # postfix exit codes, as read in the sendmail.c source code in
172 # Postfix 3.3.0
173 1: "ERR_USAGE", # 1: if daemon mode fails
174 os.EX_TEMPFAIL: "ERR_MSG_TEMPFAIL", # failed to write queue file, etc
175 os.EX_NOPERM: "ERR_MSG_REFUSED", # User %s(%ld) is not allowed to submit mail
176 os.EX_USAGE: "ERR_USAGE", # problem with the arguments passed to Postfix
177 os.EX_DATAERR: "ERR_USAGE", # unable to extract recipients, error reading input
178 # already covered above:
179 # EX_OSERR: no login name found for user ID, fail to open /dev/null
180 # EX_UNAVAILABLE: can't exec postdrop, can't fork, can't chdir, etc
181 # EX_SOFTWARE
182 #
183 # Exim returns 0 or 1 (so always temporary), covered above.
184 #
185 # opensmtpd also uses EX_* macros, all covered above
186 #
187 # qmail
188 100: "ERR_USAGE", # newaliases, usage
189 111: "ERR_EXEC_FAILED", # can't run some part of qmail
190 }
191
192 # python version of `lib/errcodes.h` from nullmailer 2.1
193 nullmailer_error_table = {
194 # not part of nullmailer, but should be.
195 "EX_OK": os.EX_OK,
196 # temporary errors are < 32
197 "ERR_USAGE": 1, # Invalid command-line arguments
198 "ERR_HOST_NOT_FOUND": 2, # gethostbyname failed with HOST_NOT_FOUND
199 "ERR_NO_ADDRESS": 3, # gethostbyname failed with NO_ADDRESS
200 "ERR_GHBN_TEMP": 5, # gethostbyname failed with TRY_AGAIN
201 "ERR_SOCKET": 6, # socket failed
202 "ERR_CONN_REFUSED": 7, # connect failed with ECONNREFUSED
203 "ERR_CONN_TIMEDOUT": 8, # connect failed with ETIMEDOUT
204 "ERR_CONN_UNREACHABLE": 9, # connect failed with ENETUNREACH
205 "ERR_CONN_FAILED": 10, # connect failed
206 "ERR_PROTO": 11, # unexpected result from server
207 "ERR_MSG_OPEN": 12, # could not open the message
208 "ERR_MSG_READ": 13, # reading the message failed
209 "ERR_MSG_WRITE": 14, # writing the message failed
210 "ERR_EXEC_FAILED": 15, # executing a program failed
211 "ERR_MSG_TEMPFAIL": 16, # server temporarily failed to receive
212 "ERR_UNKNOWN": 17, # Arbitrary error code
213 "ERR_CONFIG": 18, # Error reading a config file
214 "ERR_BIND_FAILED": 19, # Failed to bind source address
215 # Permanent errors are >= 32
216 "ERR_PERMANENT_FLAG": 32,
217 "ERR_GHBN_FATAL": 33, # gethostbyname failed with NO_RECOVERY
218 "ERR_MSG_REFUSED": 34, # server refused the message
219 "ERR_MSG_PERMFAIL": 35, # server permanently failed to receive
220 }
221
222
223 def main():
224 argv = copy.copy(sys.argv)
225 args = parse_args()
226 setupLogging(args.loglevel)
227
228 logging.debug("config: %s", args)
229 if args.mta == "nullmailer":
230 logging.debug("argv: %s", argv)
231 readNullMailer2Options(args, sys.stdin)
232 logging.debug("modified config: %s", args)
233
234 # need unbuffered I/O otherwise parts of the message will be
235 # swallowed before being passed to the subprocess
236 message = open(3, mode="rb", buffering=0)
237 args.sender, args.recipients = readNullMailer2Envelope(message)
238 elif args.mta == "postfix":
239 message = sys.stdin
240 else:
241 # should not happen
242 logging.error("unsupported MTA: %s", args.mta)
243 return 1
244
245 # compose base command
246 command = ["ssh", args.host]
247 if args.identity:
248 command += ["-i", args.identity]
249 if args.user:
250 command += ["-l", args.user]
251
252 # remote command
253 remote_command = ["rsendmail"]
254 if args.sender:
255 remote_command += ["-f", args.sender]
256 if args.recipients:
257 remote_command += args.recipients
258 command.append(" ".join(remote_command))
259
260 logging.info("sending email through %s", command)
261 process = subprocess.Popen(command, shell=False, close_fds=False, stdin=message)
262 status = process.wait()
263 if status != 0:
264 logging.error("command failed with exit status %d: %s", status, command)
265
266 if args.mta == "nullmailer":
267 # map rsendmail error codes to nullmailer. default to temporary.
268 return nullmailer_error_table[
269 nullmailer_sysexits_map.get(status, "ERR_UNKNOWN")
270 ]
271 elif args.mta == "postfix":
272 # SSH will return code 255 on *any* failure, treat those as temporary
273 if status == 255:
274 return os.EX_TEMPFAIL
275 # otherwise error codes are from rsendmail, which passes them
276 # from sendmail, so this should be in sysexits.h and processed
277 # properly by Postfix, as per
278 # postfix-3.3.0/src/global/pipe_command.c
279 else:
280 return status
281 else:
282 # NOTREACHED
283 return os.EX_SOFTWARE
284
285
286 if __name__ == "__main__":
287 try:
288 sys.exit(main())
289 except Exception as e:
290 logging.exception("got exception %s", e)
291 sys.exit(1)