sendmail.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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 void send_r_n(const char *s)
  99. {
  100. if (verbose)
  101. bb_error_msg("send:'%s'", s);
  102. printf("%s\r\n", s);
  103. }
  104. static int smtp_checkp(const char *fmt, const char *param, int code)
  105. {
  106. char *answer;
  107. char *msg = send_mail_command(fmt, param);
  108. // read stdin
  109. // if the string has a form NNN- -- read next string. E.g. EHLO response
  110. // parse first bytes to a number
  111. // if code = -1 then just return this number
  112. // if code != -1 then checks whether the number equals the code
  113. // if not equal -> die saying msg
  114. while ((answer = xmalloc_fgetline(stdin)) != NULL) {
  115. if (verbose)
  116. bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
  117. if (strlen(answer) <= 3 || '-' != answer[3])
  118. break;
  119. free(answer);
  120. }
  121. if (answer) {
  122. int n = atoi(answer);
  123. if (timeout)
  124. alarm(0);
  125. free(answer);
  126. if (-1 == code || n == code) {
  127. free(msg);
  128. return n;
  129. }
  130. }
  131. bb_error_msg_and_die("%s failed", msg);
  132. }
  133. static int smtp_check(const char *fmt, int code)
  134. {
  135. return smtp_checkp(fmt, NULL, code);
  136. }
  137. // strip argument of bad chars
  138. static char *sane_address(char *str)
  139. {
  140. char *s;
  141. trim(str);
  142. s = str;
  143. while (*s) {
  144. /* Standard allows these chars in username without quoting:
  145. * /!#$%&'*+-=?^_`{|}~
  146. * and allows dot (.) with some restrictions.
  147. * I chose to only allow a saner subset.
  148. * I propose to expand it only on user's request.
  149. */
  150. if (!isalnum(*s) && !strchr("=+_-.@", *s)) {
  151. bb_error_msg("bad address '%s'", str);
  152. /* returning "": */
  153. str[0] = '\0';
  154. return str;
  155. }
  156. s++;
  157. }
  158. return str;
  159. }
  160. // check for an address inside angle brackets, if not found fall back to normal
  161. static char *angle_address(char *str)
  162. {
  163. char *s, *e;
  164. e = trim(str);
  165. if (e != str && *--e == '>') {
  166. s = strrchr(str, '<');
  167. if (s) {
  168. *e = '\0';
  169. str = s + 1;
  170. }
  171. }
  172. return sane_address(str);
  173. }
  174. static void rcptto(const char *s)
  175. {
  176. if (!*s)
  177. return;
  178. // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
  179. if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
  180. bb_error_msg("Bad recipient: <%s>", s);
  181. }
  182. // send to a list of comma separated addresses
  183. static void rcptto_list(const char *list)
  184. {
  185. char *free_me = xstrdup(list);
  186. char *str = free_me;
  187. char *s = free_me;
  188. char prev = 0;
  189. int in_quote = 0;
  190. while (*s) {
  191. char ch = *s++;
  192. if (ch == '"' && prev != '\\') {
  193. in_quote = !in_quote;
  194. } else if (!in_quote && ch == ',') {
  195. s[-1] = '\0';
  196. rcptto(angle_address(str));
  197. str = s;
  198. }
  199. prev = ch;
  200. }
  201. if (prev != ',')
  202. rcptto(angle_address(str));
  203. free(free_me);
  204. }
  205. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  206. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  207. {
  208. char *opt_connect;
  209. char *opt_from = NULL;
  210. char *s;
  211. llist_t *list = NULL;
  212. char *host = sane_address(safe_gethostname());
  213. unsigned nheaders = 0;
  214. int code;
  215. enum {
  216. HDR_OTHER = 0,
  217. HDR_TOCC,
  218. HDR_BCC,
  219. } last_hdr = 0;
  220. int check_hdr;
  221. int has_to = 0;
  222. enum {
  223. //--- standard options
  224. OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
  225. OPT_f = 1 << 1, // sender address
  226. OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
  227. OPT_i = 1 << 3, // IMPLIED!
  228. //--- BB specific options
  229. OPT_w = 1 << 4, // network timeout
  230. OPT_H = 1 << 5, // use external connection helper
  231. OPT_S = 1 << 6, // specify connection string
  232. OPT_a = 1 << 7, // authentication tokens
  233. OPT_v = 1 << 8, // verbosity
  234. //--- for -amMETHOD
  235. OPT_am_plain = 1 << 9, // AUTH PLAIN
  236. };
  237. // init global variables
  238. INIT_G();
  239. // default HOST[:PORT] is $SMTPHOST, or localhost
  240. opt_connect = getenv("SMTPHOST");
  241. if (!opt_connect)
  242. opt_connect = (char *)"127.0.0.1";
  243. // save initial stdin since body is piped!
  244. xdup2(STDIN_FILENO, 3);
  245. G.fp0 = xfdopen_for_read(3);
  246. // parse options
  247. // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
  248. // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
  249. // it is still under development.
  250. opts = getopt32(argv, "^"
  251. "tf:o:iw:+H:S:a:*:v"
  252. "\0"
  253. // -v is a counter, -H and -S are mutually exclusive, -a is a list
  254. "vv:H--S:S--H",
  255. &opt_from, NULL,
  256. &timeout, &opt_connect, &opt_connect, &list, &verbose
  257. );
  258. //argc -= optind;
  259. argv += optind;
  260. // process -a[upm]<token> options
  261. if ((opts & OPT_a) && !list)
  262. bb_show_usage();
  263. while (list) {
  264. char *a = (char *) llist_pop(&list);
  265. if ('u' == a[0])
  266. G.user = xstrdup(a+1);
  267. if ('p' == a[0])
  268. G.pass = xstrdup(a+1);
  269. if ('m' == a[0]) {
  270. if ((a[1] | 0x20) == 'p') // PLAIN
  271. opts |= OPT_am_plain;
  272. else if ((a[1] | 0x20) == 'l') // LOGIN
  273. ; /* do nothing (this is the default) */
  274. else
  275. bb_error_msg_and_die("unsupported AUTH method %s", a+1);
  276. }
  277. }
  278. // N.B. list == NULL here
  279. //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
  280. // connect to server
  281. // connection helper ordered? ->
  282. if (opts & OPT_H) {
  283. const char *delay;
  284. const char *args[] = { "sh", "-c", opt_connect, NULL };
  285. // plug it in
  286. launch_helper(args);
  287. // Now:
  288. // our stdout will go to helper's stdin,
  289. // helper's stdout will be available on our stdin.
  290. // Wait for initial server message.
  291. // If helper (such as openssl) invokes STARTTLS, the initial 220
  292. // is swallowed by helper (and not repeated after TLS is initiated).
  293. // We will send NOOP cmd to server and check the response.
  294. // We should get 220+250 on plain connection, 250 on STARTTLSed session.
  295. //
  296. // The problem here is some servers delay initial 220 message,
  297. // and consider client to be a spammer if it starts sending cmds
  298. // before 220 reached it. The code below is unsafe in this regard:
  299. // in non-STARTTLSed case, we potentially send NOOP before 220
  300. // is sent by server.
  301. //
  302. // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
  303. //
  304. delay = getenv("SMTP_ANTISPAM_DELAY");
  305. if (delay)
  306. sleep(atoi(delay));
  307. code = smtp_check("NOOP", -1);
  308. if (code == 220)
  309. // we got 220 - this is not STARTTLSed connection,
  310. // eat 250 response to our NOOP
  311. smtp_check(NULL, 250);
  312. else
  313. if (code != 250)
  314. bb_error_msg_and_die("SMTP init failed");
  315. } else {
  316. // vanilla connection
  317. int fd;
  318. fd = create_and_connect_stream_or_die(opt_connect, 25);
  319. // and make ourselves a simple IO filter
  320. xmove_fd(fd, STDIN_FILENO);
  321. xdup2(STDIN_FILENO, STDOUT_FILENO);
  322. // Wait for initial server 220 message
  323. smtp_check(NULL, 220);
  324. }
  325. // we should start with modern EHLO
  326. if (250 != smtp_checkp("EHLO %s", host, -1))
  327. smtp_checkp("HELO %s", host, 250);
  328. // perform authentication
  329. if (opts & OPT_a) {
  330. // read credentials unless they are given via -a[up] options
  331. if (!G.user || !G.pass)
  332. get_cred_or_die(4);
  333. if (opts & OPT_am_plain) {
  334. // C: AUTH PLAIN
  335. // S: 334
  336. // C: base64encoded(auth<NUL>user<NUL>pass)
  337. // S: 235 2.7.0 Authentication successful
  338. //Note: a shorter format is allowed:
  339. // C: AUTH PLAIN base64encoded(auth<NUL>user<NUL>pass)
  340. // S: 235 2.7.0 Authentication successful
  341. smtp_check("AUTH PLAIN", 334);
  342. {
  343. unsigned user_len = strlen(G.user);
  344. unsigned pass_len = strlen(G.pass);
  345. unsigned sz = 1 + user_len + 1 + pass_len;
  346. char plain_auth[sz + 1];
  347. // the format is:
  348. // "authorization identity<NUL>username<NUL>password"
  349. // authorization identity is empty.
  350. plain_auth[0] = '\0';
  351. strcpy(stpcpy(plain_auth + 1, G.user) + 1, G.pass);
  352. printbuf_base64(plain_auth, sz);
  353. }
  354. } else {
  355. // C: AUTH LOGIN
  356. // S: 334 VXNlcm5hbWU6
  357. // ^^^^^^^^^^^^ server says "Username:"
  358. // C: base64encoded(user)
  359. // S: 334 UGFzc3dvcmQ6
  360. // ^^^^^^^^^^^^ server says "Password:"
  361. // C: base64encoded(pass)
  362. // S: 235 2.7.0 Authentication successful
  363. smtp_check("AUTH LOGIN", 334);
  364. printstr_base64(G.user);
  365. smtp_check("", 334);
  366. printstr_base64(G.pass);
  367. }
  368. smtp_check("", 235);
  369. }
  370. // set sender
  371. // N.B. we have here a very loosely defined algorythm
  372. // since sendmail historically offers no means to specify secrets on cmdline.
  373. // 1) server can require no authentication ->
  374. // we must just provide a (possibly fake) reply address.
  375. // 2) server can require AUTH ->
  376. // we must provide valid username and password along with a (possibly fake) reply address.
  377. // For the sake of security username and password are to be read either from console or from a secured file.
  378. // Since reading from console may defeat usability, the solution is either to read from a predefined
  379. // file descriptor (e.g. 4), or again from a secured file.
  380. // got no sender address? use auth name, then UID username as a last resort
  381. if (!opt_from) {
  382. opt_from = xasprintf("%s@%s",
  383. G.user ? G.user : xuid2uname(getuid()),
  384. xgethostbyname(host)->h_name);
  385. }
  386. free(host);
  387. smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
  388. // process message
  389. // read recipients from message and add them to those given on cmdline.
  390. // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
  391. // and then use the rest of stdin as message body
  392. code = 0; // set "analyze headers" mode
  393. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  394. dump:
  395. // put message lines doubling leading dots
  396. if (code) {
  397. // escape leading dots
  398. // N.B. this feature is implied even if no -i (-oi) switch given
  399. // N.B. we need to escape the leading dot regardless of
  400. // whether it is single or not character on the line
  401. if ('.' == s[0] /*&& '\0' == s[1] */)
  402. bb_putchar('.');
  403. // dump read line
  404. send_r_n(s);
  405. free(s);
  406. continue;
  407. }
  408. // analyze headers
  409. // To: or Cc: headers add recipients
  410. check_hdr = (0 == strncasecmp("To:", s, 3));
  411. has_to |= check_hdr;
  412. if (opts & OPT_t) {
  413. if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
  414. rcptto_list(s+3);
  415. last_hdr = HDR_TOCC;
  416. goto addheader;
  417. }
  418. // Bcc: header adds blind copy (hidden) recipient
  419. if (0 == strncasecmp("Bcc:", s, 4)) {
  420. rcptto_list(s+4);
  421. free(s);
  422. last_hdr = HDR_BCC;
  423. continue; // N.B. Bcc: vanishes from headers!
  424. }
  425. }
  426. check_hdr = (list && isspace(s[0]));
  427. if (strchr(s, ':') || check_hdr) {
  428. // other headers go verbatim
  429. // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
  430. // Continuation is denoted by prefixing additional lines with whitespace(s).
  431. // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
  432. if (check_hdr && last_hdr != HDR_OTHER) {
  433. rcptto_list(s+1);
  434. if (last_hdr == HDR_BCC)
  435. continue;
  436. // N.B. Bcc: vanishes from headers!
  437. } else {
  438. last_hdr = HDR_OTHER;
  439. }
  440. addheader:
  441. // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
  442. if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  443. goto bail;
  444. llist_add_to_end(&list, s);
  445. } else {
  446. // a line without ":" (an empty line too, by definition) doesn't look like a valid header
  447. // so stop "analyze headers" mode
  448. reenter:
  449. // put recipients specified on cmdline
  450. check_hdr = 1;
  451. while (*argv) {
  452. char *t = sane_address(*argv);
  453. rcptto(t);
  454. //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  455. // goto bail;
  456. if (!has_to) {
  457. const char *hdr;
  458. if (check_hdr && argv[1])
  459. hdr = "To: %s,";
  460. else if (check_hdr)
  461. hdr = "To: %s";
  462. else if (argv[1])
  463. hdr = "To: %s," + 3;
  464. else
  465. hdr = "To: %s" + 3;
  466. llist_add_to_end(&list,
  467. xasprintf(hdr, t));
  468. check_hdr = 0;
  469. }
  470. argv++;
  471. }
  472. // enter "put message" mode
  473. // N.B. DATA fails iff no recipients were accepted (or even provided)
  474. // in this case just bail out gracefully
  475. if (354 != smtp_check("DATA", -1))
  476. goto bail;
  477. // dump the headers
  478. while (list) {
  479. send_r_n((char *) llist_pop(&list));
  480. }
  481. // stop analyzing headers
  482. code++;
  483. // N.B. !s means: we read nothing, and nothing to be read in the future.
  484. // just dump empty line and break the loop
  485. if (!s) {
  486. send_r_n("");
  487. break;
  488. }
  489. // go dump message body
  490. // N.B. "s" already contains the first non-header line, so pretend we read it from input
  491. goto dump;
  492. }
  493. }
  494. // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
  495. // N.B. after reenter code will be > 0
  496. if (!code)
  497. goto reenter;
  498. // finalize the message
  499. smtp_check(".", 250);
  500. bail:
  501. // ... and say goodbye
  502. smtp_check("QUIT", 221);
  503. // cleanup
  504. if (ENABLE_FEATURE_CLEAN_UP)
  505. fclose(G.fp0);
  506. return EXIT_SUCCESS;
  507. }