sendmail.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * bare bones sendmail
  4. *
  5. * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. //config:config SENDMAIL
  10. //config: bool "sendmail (14 kb)"
  11. //config: default y
  12. //config: help
  13. //config: Barebones sendmail.
  14. //applet:IF_SENDMAIL(APPLET(sendmail, BB_DIR_USR_SBIN, BB_SUID_DROP))
  15. //kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
  16. //usage:#define sendmail_trivial_usage
  17. //usage: "[-tv] [-f SENDER] [-amLOGIN 4<user_pass.txt | -auUSER -apPASS]"
  18. //usage: "\n [-w SECS] [-H 'PROG ARGS' | -S HOST] [RECIPIENT_EMAIL]..."
  19. //usage:#define sendmail_full_usage "\n\n"
  20. //usage: "Read email from stdin and send it\n"
  21. //usage: "\nStandard options:"
  22. //usage: "\n -t Read additional recipients from message body"
  23. //usage: "\n -f SENDER For use in MAIL FROM:<sender>. Can be empty string"
  24. //usage: "\n Default: -auUSER, or username of current UID"
  25. //usage: "\n -o OPTIONS Various options. -oi implied, others are ignored"
  26. //usage: "\n -i -oi synonym, implied and ignored"
  27. //usage: "\n"
  28. //usage: "\nBusybox specific options:"
  29. //usage: "\n -v Verbose"
  30. //usage: "\n -w SECS Network timeout"
  31. //usage: "\n -H 'PROG ARGS' Run connection helper. Examples:"
  32. //usage: "\n openssl s_client -quiet -tls1 -starttls smtp -connect smtp.gmail.com:25"
  33. //usage: "\n openssl s_client -quiet -tls1 -connect smtp.gmail.com:465"
  34. //usage: "\n $SMTP_ANTISPAM_DELAY: seconds to wait after helper connect"
  35. //usage: "\n -S HOST[:PORT] Server (default $SMTPHOST or 127.0.0.1)"
  36. //usage: "\n -amLOGIN Log in using AUTH LOGIN"
  37. //usage: "\n -amPLAIN or AUTH PLAIN"
  38. //usage: "\n (-amCRAM-MD5 not supported)"
  39. //usage: "\n -auUSER Username for AUTH"
  40. //usage: "\n -apPASS Password for AUTH"
  41. //usage: "\n"
  42. //usage: "\nIf no -a options are given, authentication is not done."
  43. //usage: "\nIf -amLOGIN is given but no -au/-ap, user/password is read from fd #4."
  44. //usage: "\nOther options are silently ignored; -oi is implied."
  45. //usage: IF_MAKEMIME(
  46. //usage: "\nUse makemime to create emails with attachments."
  47. //usage: )
  48. /* Currently we don't sanitize or escape user-supplied SENDER and RECIPIENT_EMAILs.
  49. * We may need to do so. For one, '.' in usernames seems to require escaping!
  50. *
  51. * From http://cr.yp.to/smtp/address.html:
  52. *
  53. * SMTP offers three ways to encode a character inside an address:
  54. *
  55. * "safe": the character, if it is not <>()[].,;:@, backslash,
  56. * double-quote, space, or an ASCII control character;
  57. * "quoted": the character, if it is not \012, \015, backslash,
  58. * or double-quote; or
  59. * "slashed": backslash followed by the character.
  60. *
  61. * An encoded box part is either (1) a sequence of one or more slashed
  62. * or safe characters or (2) a double quote, a sequence of zero or more
  63. * slashed or quoted characters, and a double quote. It represents
  64. * the concatenation of the characters encoded inside it.
  65. *
  66. * For example, the encoded box parts
  67. * angels
  68. * \a\n\g\e\l\s
  69. * "\a\n\g\e\l\s"
  70. * "angels"
  71. * "ang\els"
  72. * all represent the 6-byte string "angels", and the encoded box parts
  73. * a\,comma
  74. * \a\,\c\o\m\m\a
  75. * "a,comma"
  76. * all represent the 7-byte string "a,comma".
  77. *
  78. * An encoded address contains
  79. * the byte <;
  80. * optionally, a route followed by a colon;
  81. * an encoded box part, the byte @, and a domain; and
  82. * the byte >.
  83. *
  84. * It represents an Internet mail address, given by concatenating
  85. * the string represented by the encoded box part, the byte @,
  86. * and the domain. For example, the encoded addresses
  87. * <God@heaven.af.mil>
  88. * <\God@heaven.af.mil>
  89. * <"God"@heaven.af.mil>
  90. * <@gateway.af.mil,@uucp.local:"\G\o\d"@heaven.af.mil>
  91. * all represent the Internet mail address "God@heaven.af.mil".
  92. */
  93. #include "libbb.h"
  94. #include "mail.h"
  95. // limit maximum allowed number of headers to prevent overflows.
  96. // set to 0 to not limit
  97. #define MAX_HEADERS 256
  98. static int smtp_checkp(const char *fmt, const char *param, int code)
  99. {
  100. char *answer;
  101. char *msg = send_mail_command(fmt, param);
  102. // read stdin
  103. // if the string has a form NNN- -- read next string. E.g. EHLO response
  104. // parse first bytes to a number
  105. // if code = -1 then just return this number
  106. // if code != -1 then checks whether the number equals the code
  107. // if not equal -> die saying msg
  108. //FIXME: limit max len!!!
  109. while ((answer = xmalloc_fgetline(stdin)) != NULL) {
  110. if (G.verbose)
  111. bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
  112. if (strlen(answer) <= 3 || '-' != answer[3])
  113. break;
  114. free(answer);
  115. }
  116. if (answer) {
  117. int n = atoi(answer);
  118. if (G.timeout)
  119. alarm(0);
  120. free(answer);
  121. if (-1 == code || n == code) {
  122. free(msg);
  123. return n;
  124. }
  125. }
  126. bb_error_msg_and_die("%s failed", msg);
  127. }
  128. static int smtp_check(const char *fmt, int code)
  129. {
  130. return smtp_checkp(fmt, NULL, code);
  131. }
  132. // strip argument of bad chars
  133. static char *sane_address(char *str)
  134. {
  135. char *s;
  136. trim(str);
  137. s = str;
  138. while (*s) {
  139. /* Standard allows these chars in username without quoting:
  140. * /!#$%&'*+-=?^_`{|}~
  141. * and allows dot (.) with some restrictions.
  142. * I chose to only allow a saner subset.
  143. * I propose to expand it only on user's request.
  144. */
  145. if (!isalnum(*s) && !strchr("=+_-.@", *s)) {
  146. bb_error_msg("bad address '%s'", str);
  147. /* returning "": */
  148. str[0] = '\0';
  149. return str;
  150. }
  151. s++;
  152. }
  153. return str;
  154. }
  155. // check for an address inside angle brackets, if not found fall back to normal
  156. static char *angle_address(char *str)
  157. {
  158. char *s, *e;
  159. e = trim(str);
  160. if (e != str && *--e == '>') {
  161. s = strrchr(str, '<');
  162. if (s) {
  163. *e = '\0';
  164. str = s + 1;
  165. }
  166. }
  167. return sane_address(str);
  168. }
  169. static void rcptto(const char *s)
  170. {
  171. if (!*s)
  172. return;
  173. // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
  174. if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
  175. bb_error_msg("Bad recipient: <%s>", s);
  176. }
  177. // send to a list of comma separated addresses
  178. static void rcptto_list(const char *list)
  179. {
  180. char *free_me = xstrdup(list);
  181. char *str = free_me;
  182. char *s = free_me;
  183. char prev = 0;
  184. int in_quote = 0;
  185. while (*s) {
  186. char ch = *s++;
  187. if (ch == '"' && prev != '\\') {
  188. in_quote = !in_quote;
  189. } else if (!in_quote && ch == ',') {
  190. s[-1] = '\0';
  191. rcptto(angle_address(str));
  192. str = s;
  193. }
  194. prev = ch;
  195. }
  196. if (prev != ',')
  197. rcptto(angle_address(str));
  198. free(free_me);
  199. }
  200. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  201. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  202. {
  203. unsigned opts;
  204. char *opt_connect;
  205. char *opt_from = NULL;
  206. char *s;
  207. llist_t *list = NULL;
  208. char *host = sane_address(safe_gethostname());
  209. unsigned nheaders = 0;
  210. int code;
  211. enum {
  212. HDR_OTHER = 0,
  213. HDR_TOCC,
  214. HDR_BCC,
  215. } last_hdr = 0;
  216. int check_hdr;
  217. int has_to = 0;
  218. enum {
  219. //--- standard options
  220. OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
  221. OPT_f = 1 << 1, // sender address
  222. OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
  223. OPT_i = 1 << 3, // IMPLIED!
  224. //--- BB specific options
  225. OPT_w = 1 << 4, // network timeout
  226. OPT_H = 1 << 5, // use external connection helper
  227. OPT_S = 1 << 6, // specify connection string
  228. OPT_a = 1 << 7, // authentication tokens
  229. OPT_v = 1 << 8, // verbosity
  230. //--- for -amMETHOD
  231. OPT_am_plain = 1 << 9, // AUTH PLAIN
  232. };
  233. // init global variables
  234. INIT_G();
  235. // default HOST[:PORT] is $SMTPHOST, or localhost
  236. opt_connect = getenv("SMTPHOST");
  237. if (!opt_connect)
  238. opt_connect = (char *)"127.0.0.1";
  239. // save initial stdin since body is piped!
  240. xdup2(STDIN_FILENO, 3);
  241. G.fp0 = xfdopen_for_read(3);
  242. // parse options
  243. // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
  244. // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
  245. // it is still under development.
  246. opts = getopt32(argv, "^"
  247. "tf:o:iw:+H:S:a:*:v"
  248. "\0"
  249. // -v is a counter, -H and -S are mutually exclusive, -a is a list
  250. "vv:H--S:S--H",
  251. &opt_from, NULL,
  252. &G.timeout, &opt_connect, &opt_connect, &list, &G.verbose
  253. );
  254. //argc -= optind;
  255. argv += optind;
  256. // process -a[upm]<token> options
  257. if ((opts & OPT_a) && !list)
  258. bb_show_usage();
  259. while (list) {
  260. char *a = (char *) llist_pop(&list);
  261. if ('u' == a[0])
  262. G.user = xstrdup(a+1);
  263. if ('p' == a[0])
  264. G.pass = xstrdup(a+1);
  265. if ('m' == a[0]) {
  266. if ((a[1] | 0x20) == 'p') // PLAIN
  267. opts |= OPT_am_plain;
  268. else if ((a[1] | 0x20) == 'l') // LOGIN
  269. ; /* do nothing (this is the default) */
  270. else
  271. bb_error_msg_and_die("unsupported AUTH method %s", a+1);
  272. }
  273. }
  274. // N.B. list == NULL here
  275. //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
  276. // connect to server
  277. // connection helper ordered? ->
  278. if (opts & OPT_H) {
  279. const char *delay;
  280. const char *args[] = { "sh", "-c", opt_connect, NULL };
  281. // plug it in
  282. launch_helper(args);
  283. // Now:
  284. // our stdout will go to helper's stdin,
  285. // helper's stdout will be available on our stdin.
  286. // Wait for initial server message.
  287. // If helper (such as openssl) invokes STARTTLS, the initial 220
  288. // is swallowed by helper (and not repeated after TLS is initiated).
  289. // We will send NOOP cmd to server and check the response.
  290. // We should get 220+250 on plain connection, 250 on STARTTLSed session.
  291. //
  292. // The problem here is some servers delay initial 220 message,
  293. // and consider client to be a spammer if it starts sending cmds
  294. // before 220 reached it. The code below is unsafe in this regard:
  295. // in non-STARTTLSed case, we potentially send NOOP before 220
  296. // is sent by server.
  297. //
  298. // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
  299. //
  300. delay = getenv("SMTP_ANTISPAM_DELAY");
  301. if (delay)
  302. sleep(atoi(delay));
  303. code = smtp_check("NOOP", -1);
  304. if (code == 220)
  305. // we got 220 - this is not STARTTLSed connection,
  306. // eat 250 response to our NOOP
  307. smtp_check(NULL, 250);
  308. else
  309. if (code != 250)
  310. bb_simple_error_msg_and_die("SMTP init failed");
  311. } else {
  312. // vanilla connection
  313. int fd;
  314. fd = create_and_connect_stream_or_die(opt_connect, 25);
  315. // and make ourselves a simple IO filter
  316. xmove_fd(fd, STDIN_FILENO);
  317. xdup2(STDIN_FILENO, STDOUT_FILENO);
  318. // Wait for initial server 220 message
  319. smtp_check(NULL, 220);
  320. }
  321. // we should start with modern EHLO
  322. if (250 != smtp_checkp("EHLO %s", host, -1))
  323. smtp_checkp("HELO %s", host, 250);
  324. // perform authentication
  325. if (opts & OPT_a) {
  326. // read credentials unless they are given via -a[up] options
  327. if (!G.user || !G.pass)
  328. get_cred_or_die(4);
  329. if (opts & OPT_am_plain) {
  330. // C: AUTH PLAIN
  331. // S: 334
  332. // C: base64encoded(auth<NUL>user<NUL>pass)
  333. // S: 235 2.7.0 Authentication successful
  334. //Note: a shorter format is allowed:
  335. // C: AUTH PLAIN base64encoded(auth<NUL>user<NUL>pass)
  336. // S: 235 2.7.0 Authentication successful
  337. smtp_check("AUTH PLAIN", 334);
  338. {
  339. unsigned user_len = strlen(G.user);
  340. unsigned pass_len = strlen(G.pass);
  341. unsigned sz = 1 + user_len + 1 + pass_len;
  342. char plain_auth[sz + 1];
  343. // the format is:
  344. // "authorization identity<NUL>username<NUL>password"
  345. // authorization identity is empty.
  346. plain_auth[0] = '\0';
  347. strcpy(stpcpy(plain_auth + 1, G.user) + 1, G.pass);
  348. printbuf_base64(plain_auth, sz);
  349. }
  350. } else {
  351. // C: AUTH LOGIN
  352. // S: 334 VXNlcm5hbWU6
  353. // ^^^^^^^^^^^^ server says "Username:"
  354. // C: base64encoded(user)
  355. // S: 334 UGFzc3dvcmQ6
  356. // ^^^^^^^^^^^^ server says "Password:"
  357. // C: base64encoded(pass)
  358. // S: 235 2.7.0 Authentication successful
  359. smtp_check("AUTH LOGIN", 334);
  360. printstr_base64(G.user);
  361. smtp_check("", 334);
  362. printstr_base64(G.pass);
  363. }
  364. smtp_check("", 235);
  365. }
  366. // set sender
  367. // N.B. we have here a very loosely defined algorythm
  368. // since sendmail historically offers no means to specify secrets on cmdline.
  369. // 1) server can require no authentication ->
  370. // we must just provide a (possibly fake) reply address.
  371. // 2) server can require AUTH ->
  372. // we must provide valid username and password along with a (possibly fake) reply address.
  373. // For the sake of security username and password are to be read either from console or from a secured file.
  374. // Since reading from console may defeat usability, the solution is either to read from a predefined
  375. // file descriptor (e.g. 4), or again from a secured file.
  376. // got no sender address? use auth name, then UID username as a last resort
  377. if (!opt_from) {
  378. opt_from = xasprintf("%s@%s",
  379. G.user ? G.user : xuid2uname(getuid()),
  380. xgethostbyname(host)->h_name);
  381. }
  382. free(host);
  383. smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
  384. // process message
  385. // read recipients from message and add them to those given on cmdline.
  386. // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
  387. // and then use the rest of stdin as message body
  388. code = 0; // set "analyze headers" mode
  389. //FIXME: limit max len!!!
  390. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  391. dump:
  392. // put message lines doubling leading dots
  393. if (code) {
  394. // escape leading dots
  395. // N.B. this feature is implied even if no -i (-oi) switch given
  396. // N.B. we need to escape the leading dot regardless of
  397. // whether it is single or not character on the line
  398. if ('.' == s[0] /*&& '\0' == s[1] */)
  399. bb_putchar('.');
  400. // dump read line
  401. send_r_n(s);
  402. free(s);
  403. continue;
  404. }
  405. // analyze headers
  406. // To: or Cc: headers add recipients
  407. check_hdr = (0 == strncasecmp("To:", s, 3));
  408. has_to |= check_hdr;
  409. if (opts & OPT_t) {
  410. if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
  411. rcptto_list(s+3);
  412. last_hdr = HDR_TOCC;
  413. goto addheader;
  414. }
  415. // Bcc: header adds blind copy (hidden) recipient
  416. if (0 == strncasecmp("Bcc:", s, 4)) {
  417. rcptto_list(s+4);
  418. free(s);
  419. last_hdr = HDR_BCC;
  420. continue; // N.B. Bcc: vanishes from headers!
  421. }
  422. }
  423. check_hdr = (list && isspace(s[0]));
  424. if (strchr(s, ':') || check_hdr) {
  425. // other headers go verbatim
  426. // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
  427. // Continuation is denoted by prefixing additional lines with whitespace(s).
  428. // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
  429. if (check_hdr && last_hdr != HDR_OTHER) {
  430. rcptto_list(s+1);
  431. if (last_hdr == HDR_BCC)
  432. continue;
  433. // N.B. Bcc: vanishes from headers!
  434. } else {
  435. last_hdr = HDR_OTHER;
  436. }
  437. addheader:
  438. // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
  439. if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  440. goto bail;
  441. llist_add_to_end(&list, s);
  442. } else {
  443. // a line without ":" (an empty line too, by definition) doesn't look like a valid header
  444. // so stop "analyze headers" mode
  445. reenter:
  446. // put recipients specified on cmdline
  447. check_hdr = 1;
  448. while (*argv) {
  449. char *t = sane_address(*argv);
  450. rcptto(t);
  451. //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  452. // goto bail;
  453. if (!has_to) {
  454. const char *hdr;
  455. if (check_hdr && argv[1])
  456. hdr = "To: %s,";
  457. else if (check_hdr)
  458. hdr = "To: %s";
  459. else if (argv[1])
  460. hdr = "To: %s," + 3;
  461. else
  462. hdr = "To: %s" + 3;
  463. llist_add_to_end(&list,
  464. xasprintf(hdr, t));
  465. check_hdr = 0;
  466. }
  467. argv++;
  468. }
  469. // enter "put message" mode
  470. // N.B. DATA fails iff no recipients were accepted (or even provided)
  471. // in this case just bail out gracefully
  472. if (354 != smtp_check("DATA", -1))
  473. goto bail;
  474. // dump the headers
  475. while (list) {
  476. send_r_n((char *) llist_pop(&list));
  477. }
  478. // stop analyzing headers
  479. code++;
  480. // N.B. !s means: we read nothing, and nothing to be read in the future.
  481. // just dump empty line and break the loop
  482. if (!s) {
  483. send_r_n("");
  484. break;
  485. }
  486. // go dump message body
  487. // N.B. "s" already contains the first non-header line, so pretend we read it from input
  488. goto dump;
  489. }
  490. }
  491. // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
  492. // N.B. after reenter code will be > 0
  493. if (!code)
  494. goto reenter;
  495. // finalize the message
  496. smtp_check(".", 250);
  497. bail:
  498. // ... and say goodbye
  499. smtp_check("QUIT", 221);
  500. // cleanup
  501. if (ENABLE_FEATURE_CLEAN_UP)
  502. fclose(G.fp0);
  503. return EXIT_SUCCESS;
  504. }