Debian Codegraph @

rsendmail.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 logging
26 import logging.handlers
27 import os
28 import shlex
29 import subprocess
30 import sys
31
32 __description__ = """A wrapper for the sendmail command which allows calling sendmail
33 without allowing side effects traditionnally allowed by sendmail
34 binaries (like flushing the queue or reloading the alias files). This
35 is designed to be ran from an SSH command and be safely assigned
36 as a authorized_keys `command=` parameter."""
37
38
39 def parse_args():
40 parser = argparse.ArgumentParser(description=__doc__, epilog=__description__)
41 parser.add_argument(
42 "--loglevel",
43 dest="loglevel",
44 default="INFO",
45 help="level should be sent to syslog (default: %(default)s)",
46 )
47 parser.add_argument(
48 "-oi",
49 dest="passthrough",
50 action=StoreFlagAction,
51 help="(Ignored) When reading a message from standard input, don´t treat a"
52 "line with only a . character as the end of input.",
53 )
54 parser.add_argument(
55 "-f",
56 dest="passthrough",
57 action=StoreFlagAction,
58 nargs=1,
59 help="Set the envelope sender address. This is the address where"
60 "delivery problems are sent to. Passed to sendmail.",
61 )
62 # XXX: would be better to have a "passthru" action or something
63 parser.add_argument(
64 "-t",
65 dest="passthrough",
66 action=StoreFlagAction,
67 help="Extract recipients from message headers. These are added to any"
68 "recipients specified on the command line. Passed to sendmail, no"
69 "processing is done by rsendmail.",
70 )
71 parser.add_argument("recipient", nargs="*", help="recipients of the message")
72 argv = os.environ.get("SSH_ORIGINAL_COMMAND", None)
73 if argv:
74 argv = shlex.split(argv)[1:]
75 return parser.parse_args(argv)
76
77
78 class StoreFlagAction(argparse.Action):
79 """store the provided flag in the destination
80
81 >>> parser = argparse.ArgumentParser()
82 >>> parser.add_argument('-t', dest='p', action=StoreFlagAction) # doctest: +ELLIPSIS
83 StoreFlagAction(...)
84 >>> parser.add_argument('-f', dest='p', nargs=1, action=StoreFlagAction) # doctest: +ELLIPSIS
85 StoreFlagAction(...)
86 >>> parser.parse_args([])
87 Namespace(p=[])
88 >>> parser.parse_args(['-t'])
89 Namespace(p=['-t'])
90 >>> parser.parse_args(['-t', '-f', 'foo'])
91 Namespace(p=['-t', '-f', 'foo'])
92 """
93
94 def __init__(self, *args, **kwargs):
95 kwargs["nargs"] = kwargs.get("nargs", 0)
96 super().__init__(*args, default=[], **kwargs)
97
98 def __call__(self, parser, namespace, values, option_string=None):
99 if option_string:
100 items = getattr(namespace, self.dest, [])
101 if not items:
102 items = []
103 items.append(option_string)
104 if values:
105 items += values
106 setattr(namespace, self.dest, items)
107
108
109 def filter_args(args):
110 """find arguments in list that have possibly nasty side effects
111
112 >>> list(filter_args(['-f', 'foo']))
113 ['-f']
114 """
115 for arg in args:
116 if arg.startswith("-") or " " in arg:
117 yield arg
118
119
120 def setupLogging(loglevel):
121 logger = logging.getLogger("")
122 # disable the base filter, each stream has its own filter
123 logger.setLevel(loglevel)
124 sl = logging.handlers.SysLogHandler(address="/dev/log", facility="mail")
125 sl.setFormatter(
126 logging.Formatter(sys.argv[0] + "[%(process)d]: %(levelname)s: %(message)s")
127 )
128 logger.addHandler(sl)
129 st = logging.StreamHandler()
130 logger.addHandler(st)
131
132
133 def main():
134 args = parse_args()
135 setupLogging(args.loglevel)
136
137 bad = list(filter_args(args.recipient))
138 if bad:
139 logging.error(
140 'email addresses cannot start with a dash ("-") or contain spaces: %s', bad
141 )
142 return 1
143 # make sure we also look in /usr/sbin as it is often where sendmail is located
144 if "/usr/sbin" not in os.get_exec_path():
145 os.environ["PATH"] += ":/usr/sbin"
146 command = ["sendmail"] + args.passthrough + args.recipient
147 logging.debug("sending message through command: %s", command)
148 process = subprocess.Popen(command, shell=False, stdin=sys.stdin, close_fds=True)
149 status = process.wait()
150 # those statuses and come from the SMTP standard, RFC 3463. They
151 # are used liberally here, as a fallback when the `sshsendmail`
152 # command isn't used on the other end, in which case Postfix will
153 # parse the first line of the output looking for such an "enhanced
154 # status code". Those are also useful for debugging as they will
155 # show up in mail logs.
156 if status == 0:
157 logging.info("2.0.0 message sent through command: %s", command)
158 else:
159 # 4 means temporary, 3.5 means "The system is not configured
160 # in a manner that will permit it to accept this message." It
161 # is a generic error that was picked because it is otherwise
162 # not possible to determine the actual error from the sendmail
163 # return codes, or, more exactly, we already do that level of
164 # parsing in sshsendmail and do not want to duplicate that
165 # here.
166 logging.error(
167 "4.3.5 failed to send message with status code %d through command: %s",
168 status,
169 command,
170 )
171 return status
172
173
174 if __name__ == "__main__":
175 sys.exit(main())