| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""A safer sendmail command""" |
| 5 |
|
| 6 |
> |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
if status == 0: |
| 157 |
logging.info("2.0.0 message sent through command: %s", command) |
| 158 |
else: |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 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()) |