You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

received.cxx 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /*-
  2. * Copyright 2021 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "libserver/url.h"
  18. #include "lua/lua_common.h"
  19. #include "libserver/cfg_file.h"
  20. #include "libserver/mempool_vars_internal.h"
  21. #include "mime_string.hxx"
  22. #include "smtp_parsers.h"
  23. #include "message.h"
  24. #include "received.hxx"
  25. #include "frozen/string.h"
  26. #include "frozen/unordered_map.h"
  27. namespace rspamd::mime {
  28. enum class received_part_type {
  29. RSPAMD_RECEIVED_PART_FROM,
  30. RSPAMD_RECEIVED_PART_BY,
  31. RSPAMD_RECEIVED_PART_FOR,
  32. RSPAMD_RECEIVED_PART_WITH,
  33. RSPAMD_RECEIVED_PART_ID,
  34. RSPAMD_RECEIVED_PART_UNKNOWN,
  35. };
  36. struct received_part {
  37. received_part_type type;
  38. mime_string data;
  39. std::vector<mime_string> comments;
  40. explicit received_part(received_part_type t)
  41. : type(t),
  42. data(received_char_filter)
  43. {
  44. }
  45. };
  46. static inline auto
  47. received_part_set_or_append(const char *begin,
  48. gsize len,
  49. mime_string &dest) -> void
  50. {
  51. if (len == 0) {
  52. return;
  53. }
  54. dest.append(begin, len);
  55. dest.trim(" \t");
  56. }
  57. static auto
  58. received_process_part(const std::string_view &data,
  59. received_part_type type,
  60. std::ptrdiff_t &last,
  61. received_part &npart) -> bool
  62. {
  63. auto obraces = 0, ebraces = 0;
  64. auto seen_tcpinfo = false;
  65. enum _parse_state {
  66. skip_spaces,
  67. in_comment,
  68. read_data,
  69. read_tcpinfo,
  70. all_done
  71. } state,
  72. next_state;
  73. /* In this function, we just process comments and data separately */
  74. const auto *p = data.data();
  75. const auto *end = p + data.size();
  76. const auto *c = p;
  77. state = skip_spaces;
  78. next_state = read_data;
  79. while (p < end) {
  80. switch (state) {
  81. case skip_spaces:
  82. if (!g_ascii_isspace(*p)) {
  83. c = p;
  84. state = next_state;
  85. }
  86. else {
  87. p++;
  88. }
  89. break;
  90. case in_comment:
  91. if (*p == '(') {
  92. obraces++;
  93. }
  94. else if (*p == ')') {
  95. ebraces++;
  96. if (ebraces >= obraces) {
  97. if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) {
  98. if (p > c) {
  99. npart.comments.emplace_back(received_char_filter);
  100. auto &comment = npart.comments.back();
  101. received_part_set_or_append(c, p - c,
  102. comment);
  103. }
  104. }
  105. p++;
  106. c = p;
  107. state = skip_spaces;
  108. next_state = read_data;
  109. continue;
  110. }
  111. }
  112. p++;
  113. break;
  114. case read_data:
  115. if (*p == '(') {
  116. if (p > c) {
  117. if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) {
  118. received_part_set_or_append(c, p - c,
  119. npart.data);
  120. }
  121. }
  122. state = in_comment;
  123. obraces = 1;
  124. ebraces = 0;
  125. p++;
  126. c = p;
  127. }
  128. else if (g_ascii_isspace(*p)) {
  129. if (p > c) {
  130. if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) {
  131. received_part_set_or_append(c, p - c,
  132. npart.data);
  133. }
  134. }
  135. state = skip_spaces;
  136. next_state = read_data;
  137. c = p;
  138. }
  139. else if (*p == ';') {
  140. /* It is actually delimiter of date part if not in the comments */
  141. if (p > c) {
  142. if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) {
  143. received_part_set_or_append(c, p - c,
  144. npart.data);
  145. }
  146. }
  147. state = all_done;
  148. continue;
  149. }
  150. else if (npart.data.size() > 0) {
  151. /* We have already received data and find something with no ( */
  152. if (!seen_tcpinfo && type == received_part_type::RSPAMD_RECEIVED_PART_FROM) {
  153. /* Check if we have something special here, such as TCPinfo */
  154. if (*c == '[') {
  155. state = read_tcpinfo;
  156. p++;
  157. }
  158. else {
  159. state = all_done;
  160. continue;
  161. }
  162. }
  163. else {
  164. state = all_done;
  165. continue;
  166. }
  167. }
  168. else {
  169. p++;
  170. }
  171. break;
  172. case read_tcpinfo:
  173. if (*p == ']') {
  174. received_part_set_or_append(c, p - c + 1,
  175. npart.data);
  176. seen_tcpinfo = TRUE;
  177. state = skip_spaces;
  178. next_state = read_data;
  179. c = p;
  180. }
  181. p++;
  182. break;
  183. case all_done:
  184. if (p > data.data()) {
  185. last = p - data.data();
  186. return true;
  187. }
  188. else {
  189. /* Empty element */
  190. return false;
  191. }
  192. break;
  193. }
  194. }
  195. /* Leftover */
  196. switch (state) {
  197. case read_data:
  198. if (p > c) {
  199. if (type != received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN) {
  200. received_part_set_or_append(c, p - c,
  201. npart.data);
  202. }
  203. last = p - data.data();
  204. return true;
  205. }
  206. break;
  207. case skip_spaces:
  208. if (p > data.data()) {
  209. last = p - data.data();
  210. return true;
  211. }
  212. default:
  213. break;
  214. }
  215. return false;
  216. }
  217. template<std::size_t N>
  218. constexpr auto lit_compare_lowercase(const char lit[N], const char *in) -> bool
  219. {
  220. for (auto i = 0; i < N; i++) {
  221. if (lc_map[(unsigned char) in[i]] != lit[i]) {
  222. return false;
  223. }
  224. }
  225. return true;
  226. }
  227. static auto
  228. received_spill(const std::string_view &in,
  229. std::ptrdiff_t &date_pos) -> std::vector<received_part>
  230. {
  231. std::vector<received_part> parts;
  232. std::ptrdiff_t pos = 0;
  233. auto seen_from = false, seen_by = false;
  234. const auto *p = in.data();
  235. const auto *end = p + in.size();
  236. auto skip_spaces = [&p, end]() {
  237. while (p < end && g_ascii_isspace(*p)) {
  238. p++;
  239. }
  240. };
  241. skip_spaces();
  242. /* Skip SMTP comments */
  243. if (*p == '(') {
  244. auto obraces = 0, ebraces = 0;
  245. while (p < end) {
  246. if (*p == ')') {
  247. ebraces++;
  248. }
  249. else if (*p == '(') {
  250. obraces++;
  251. }
  252. p++;
  253. if (obraces == ebraces) {
  254. /* Skip spaces after */
  255. skip_spaces();
  256. break;
  257. }
  258. }
  259. }
  260. auto len = end - p;
  261. if (len == 0) {
  262. return parts;
  263. }
  264. auto maybe_process_part = [&](received_part_type what) -> bool {
  265. parts.emplace_back(what);
  266. auto &rcvd_part = parts.back();
  267. auto chunk = std::string_view{p, (std::size_t)(end - p)};
  268. if (!received_process_part(chunk, what, pos, rcvd_part)) {
  269. parts.pop_back();
  270. return false;
  271. }
  272. return true;
  273. };
  274. if (len > 4 && lit_compare_lowercase<4>("from", p)) {
  275. p += sizeof("from") - 1;
  276. /* We can now store from part */
  277. if (!maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_FROM)) {
  278. /* Do not accept malformed from */
  279. return {};
  280. }
  281. g_assert(pos != 0);
  282. p += pos;
  283. len = end > p ? end - p : 0;
  284. seen_from = true;
  285. }
  286. if (len > 2 && lit_compare_lowercase<2>("by", p)) {
  287. p += sizeof("by") - 1;
  288. if (!maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_BY)) {
  289. return {};
  290. }
  291. g_assert(pos != 0);
  292. p += pos;
  293. len = end > p ? end - p : 0;
  294. seen_by = true;
  295. }
  296. if (!seen_from && !seen_by) {
  297. /* Useless received */
  298. return {};
  299. }
  300. while (p < end) {
  301. bool got_part = false;
  302. if (*p == ';') {
  303. /* We are at the date separator, stop here */
  304. date_pos = p - in.data() + 1;
  305. break;
  306. }
  307. else {
  308. if (len > sizeof("with") && lit_compare_lowercase<4>("with", p)) {
  309. p += sizeof("with") - 1;
  310. got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_WITH);
  311. }
  312. else if (len > sizeof("for") && lit_compare_lowercase<3>("for", p)) {
  313. p += sizeof("for") - 1;
  314. got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_FOR);
  315. }
  316. else if (len > sizeof("id") && lit_compare_lowercase<2>("id", p)) {
  317. p += sizeof("id") - 1;
  318. got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_ID);
  319. }
  320. else {
  321. while (p < end) {
  322. if (!(g_ascii_isspace(*p) || *p == '(' || *p == ';')) {
  323. p++;
  324. }
  325. else {
  326. break;
  327. }
  328. }
  329. if (p == end) {
  330. return {};
  331. }
  332. else if (*p == ';') {
  333. date_pos = p - in.data() + 1;
  334. break;
  335. }
  336. else {
  337. got_part = maybe_process_part(received_part_type::RSPAMD_RECEIVED_PART_UNKNOWN);
  338. }
  339. }
  340. if (!got_part) {
  341. p++;
  342. len = end > p ? end - p : 0;
  343. }
  344. else {
  345. g_assert(pos != 0);
  346. p += pos;
  347. len = end > p ? end - p : 0;
  348. }
  349. }
  350. }
  351. return parts;
  352. }
  353. #define RSPAMD_INET_ADDRESS_PARSE_RECEIVED \
  354. (rspamd_inet_address_parse_flags)(RSPAMD_INET_ADDRESS_PARSE_REMOTE | RSPAMD_INET_ADDRESS_PARSE_NO_UNIX)
  355. static auto
  356. received_process_rdns(rspamd_mempool_t *pool,
  357. const std::string_view &in,
  358. mime_string &dest) -> bool
  359. {
  360. auto seen_dot = false;
  361. const auto *p = in.data();
  362. const auto *end = p + in.size();
  363. if (in.empty()) {
  364. return false;
  365. }
  366. if (*p == '[' && *(end - 1) == ']' && in.size() > 2) {
  367. /* We have enclosed ip address */
  368. auto *addr = rspamd_parse_inet_address_pool(p + 1,
  369. (end - p) - 2,
  370. pool,
  371. RSPAMD_INET_ADDRESS_PARSE_RECEIVED);
  372. if (addr) {
  373. const char *addr_str;
  374. if (rspamd_inet_address_get_port(addr) != 0) {
  375. addr_str = rspamd_inet_address_to_string_pretty(addr);
  376. }
  377. else {
  378. addr_str = rspamd_inet_address_to_string(addr);
  379. }
  380. dest.assign_copy(std::string_view{addr_str});
  381. return true;
  382. }
  383. }
  384. auto hlen = 0u;
  385. while (p < end) {
  386. if (!g_ascii_isspace(*p) && rspamd_url_is_domain(*p)) {
  387. if (*p == '.') {
  388. seen_dot = true;
  389. }
  390. hlen++;
  391. }
  392. else {
  393. break;
  394. }
  395. p++;
  396. }
  397. if (hlen > 0) {
  398. if (p == end || (seen_dot && (g_ascii_isspace(*p) || *p == '[' || *p == '('))) {
  399. /* All data looks like a hostname */
  400. dest.assign_copy(std::string_view{in.data(), hlen});
  401. return true;
  402. }
  403. }
  404. return false;
  405. }
  406. static auto
  407. received_process_host_tcpinfo(rspamd_mempool_t *pool,
  408. received_header &rh,
  409. const std::string_view &in) -> bool
  410. {
  411. rspamd_inet_addr_t *addr = nullptr;
  412. auto ret = false;
  413. if (in.empty()) {
  414. return false;
  415. }
  416. if (in[0] == '[') {
  417. /* Likely Exim version */
  418. auto brace_pos = in.find(']');
  419. if (brace_pos != std::string_view::npos) {
  420. auto substr_addr = in.substr(1, brace_pos - 1);
  421. addr = rspamd_parse_inet_address_pool(substr_addr.data(),
  422. substr_addr.size(),
  423. pool,
  424. RSPAMD_INET_ADDRESS_PARSE_RECEIVED);
  425. if (addr) {
  426. rh.addr = addr;
  427. rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr)));
  428. }
  429. }
  430. }
  431. else {
  432. if (g_ascii_isxdigit(in[0])) {
  433. /* Try to parse IP address */
  434. addr = rspamd_parse_inet_address_pool(in.data(),
  435. in.size(), pool, RSPAMD_INET_ADDRESS_PARSE_RECEIVED);
  436. if (addr) {
  437. rh.addr = addr;
  438. rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr)));
  439. }
  440. }
  441. if (!addr) {
  442. /* Try canonical Postfix version: rdns [ip] */
  443. auto obrace_pos = in.find('[');
  444. if (obrace_pos != std::string_view::npos) {
  445. auto ebrace_pos = in.rfind(']');
  446. if (ebrace_pos != std::string_view::npos && ebrace_pos > obrace_pos) {
  447. auto substr_addr = in.substr(obrace_pos + 1,
  448. ebrace_pos - obrace_pos - 1);
  449. addr = rspamd_parse_inet_address_pool(substr_addr.data(),
  450. substr_addr.size(),
  451. pool,
  452. RSPAMD_INET_ADDRESS_PARSE_RECEIVED);
  453. if (addr) {
  454. rh.addr = addr;
  455. rh.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(addr)));
  456. /* Process with rDNS */
  457. auto rdns_substr = in.substr(0, obrace_pos);
  458. if (received_process_rdns(pool, rdns_substr, rh.real_hostname)) {
  459. ret = true;
  460. }
  461. }
  462. }
  463. }
  464. else {
  465. /* Hostname or some crap, sigh... */
  466. if (received_process_rdns(pool, in, rh.real_hostname)) {
  467. ret = true;
  468. }
  469. }
  470. }
  471. }
  472. return ret;
  473. }
  474. static void
  475. received_process_from(rspamd_mempool_t *pool,
  476. const received_part &rpart,
  477. received_header &rh)
  478. {
  479. if (rpart.data.size() > 0) {
  480. /* We have seen multiple cases:
  481. * - [ip] (hostname/unknown [real_ip])
  482. * - helo (hostname/unknown [real_ip])
  483. * - [ip]
  484. * - hostname
  485. * - hostname ([ip]:port helo=xxx)
  486. * Maybe more...
  487. */
  488. auto seen_ip_in_data = false;
  489. if (!rpart.comments.empty()) {
  490. /* We can have info within comment as part of RFC */
  491. received_process_host_tcpinfo(
  492. pool, rh,
  493. rpart.comments[0].as_view());
  494. }
  495. if (rh.real_ip.size() == 0) {
  496. /* Try to do the same with data */
  497. if (received_process_host_tcpinfo(
  498. pool, rh,
  499. rpart.data.as_view())) {
  500. seen_ip_in_data = true;
  501. }
  502. }
  503. if (!seen_ip_in_data) {
  504. if (rh.real_ip.size() != 0) {
  505. /* Get announced hostname (usually helo) */
  506. received_process_rdns(pool,
  507. rpart.data.as_view(),
  508. rh.from_hostname);
  509. }
  510. else {
  511. received_process_host_tcpinfo(pool,
  512. rh, rpart.data.as_view());
  513. }
  514. }
  515. }
  516. else {
  517. /* rpart->dlen = 0 */
  518. if (!rpart.comments.empty()) {
  519. received_process_host_tcpinfo(
  520. pool, rh,
  521. rpart.comments[0].as_view());
  522. }
  523. }
  524. }
  525. static auto
  526. received_header_parse(received_header_chain &chain, rspamd_mempool_t *pool,
  527. const std::string_view &in,
  528. struct rspamd_mime_header *hdr) -> bool
  529. {
  530. std::ptrdiff_t date_pos = -1;
  531. static constexpr const auto protos_map = frozen::make_unordered_map<frozen::string, received_flags>({{"smtp", received_flags::SMTP},
  532. {"esmtp", received_flags::ESMTP},
  533. {"esmtpa", received_flags::ESMTPA |
  534. received_flags::AUTHENTICATED},
  535. {"esmtpsa", received_flags::ESMTPSA |
  536. received_flags::SSL |
  537. received_flags::AUTHENTICATED},
  538. {"esmtps", received_flags::ESMTPS |
  539. received_flags::SSL},
  540. {"lmtp", received_flags::LMTP},
  541. {"imap", received_flags::IMAP},
  542. {"imaps", received_flags::IMAP |
  543. received_flags::SSL},
  544. {"http", received_flags::HTTP},
  545. {"https", received_flags::HTTP |
  546. received_flags::SSL},
  547. {"local", received_flags::LOCAL}});
  548. auto parts = received_spill(in, date_pos);
  549. if (parts.empty()) {
  550. return false;
  551. }
  552. auto &rh = chain.new_received();
  553. rh.flags = received_flags::UNKNOWN;
  554. rh.hdr = hdr;
  555. for (const auto &part: parts) {
  556. switch (part.type) {
  557. case received_part_type::RSPAMD_RECEIVED_PART_FROM:
  558. received_process_from(pool, part, rh);
  559. break;
  560. case received_part_type::RSPAMD_RECEIVED_PART_BY:
  561. received_process_rdns(pool,
  562. part.data.as_view(),
  563. rh.by_hostname);
  564. break;
  565. case received_part_type::RSPAMD_RECEIVED_PART_WITH:
  566. if (part.data.size() > 0) {
  567. auto proto_flag_it = protos_map.find(part.data.as_view());
  568. if (proto_flag_it != protos_map.end()) {
  569. rh.flags = proto_flag_it->second;
  570. }
  571. }
  572. break;
  573. case received_part_type::RSPAMD_RECEIVED_PART_FOR:
  574. rh.for_mbox.assign_copy(part.data);
  575. rh.for_addr = rspamd_email_address_from_smtp(rh.for_mbox.data(),
  576. rh.for_mbox.size());
  577. break;
  578. default:
  579. /* Do nothing */
  580. break;
  581. }
  582. }
  583. if (!rh.real_hostname.empty() && rh.from_hostname.empty()) {
  584. rh.from_hostname.assign_copy(rh.real_hostname);
  585. }
  586. if (date_pos > 0 && date_pos < in.size()) {
  587. auto date_sub = in.substr(date_pos);
  588. rh.timestamp = rspamd_parse_smtp_date((const unsigned char *) date_sub.data(),
  589. date_sub.size(), nullptr);
  590. }
  591. return true;
  592. }
  593. static auto
  594. received_maybe_fix_task(struct rspamd_task *task) -> bool
  595. {
  596. auto *recv_chain_ptr = static_cast<received_header_chain *>(MESSAGE_FIELD(task, received_headers));
  597. if (recv_chain_ptr) {
  598. auto need_recv_correction = false;
  599. auto top_recv_maybe = recv_chain_ptr->get_received(0);
  600. if (top_recv_maybe.has_value()) {
  601. auto &top_recv = top_recv_maybe.value().get();
  602. const auto *raddr = top_recv.addr;
  603. if (top_recv.real_ip.size() == 0 || (task->cfg && task->cfg->ignore_received)) {
  604. need_recv_correction = true;
  605. }
  606. else if (!(task->flags & RSPAMD_TASK_FLAG_NO_IP) && task->from_addr) {
  607. if (!raddr) {
  608. need_recv_correction = true;
  609. }
  610. else {
  611. if (rspamd_inet_address_compare(raddr, task->from_addr, FALSE) != 0) {
  612. need_recv_correction = true;
  613. }
  614. }
  615. }
  616. if (need_recv_correction && !(task->flags & RSPAMD_TASK_FLAG_NO_IP) && task->from_addr) {
  617. msg_debug_task("the first received seems to be"
  618. " not ours, prepend it with fake one");
  619. auto &trecv = recv_chain_ptr->new_received(received_header_chain::append_type::append_head);
  620. trecv.flags |= received_flags::ARTIFICIAL;
  621. if (task->flags & RSPAMD_TASK_FLAG_SSL) {
  622. trecv.flags |= received_flags::SSL;
  623. }
  624. if (task->auth_user) {
  625. trecv.flags |= received_flags::AUTHENTICATED;
  626. }
  627. trecv.real_ip.assign_copy(std::string_view(rspamd_inet_address_to_string(task->from_addr)));
  628. const auto *mta_name = (const char *) rspamd_mempool_get_variable(task->task_pool,
  629. RSPAMD_MEMPOOL_MTA_NAME);
  630. if (mta_name) {
  631. trecv.by_hostname.assign_copy(std::string_view(mta_name));
  632. }
  633. trecv.addr = rspamd_inet_address_copy(task->from_addr,
  634. task->task_pool);
  635. if (task->hostname) {
  636. trecv.real_hostname.assign_copy(std::string_view(task->hostname));
  637. trecv.from_hostname.assign_copy(trecv.real_hostname);
  638. }
  639. return true;
  640. }
  641. /* Extract data from received header if we were not given IP */
  642. if (!need_recv_correction && (task->flags & RSPAMD_TASK_FLAG_NO_IP) &&
  643. (task->cfg && !task->cfg->ignore_received)) {
  644. if (!top_recv.real_ip.empty()) {
  645. if (!rspamd_parse_inet_address(&task->from_addr,
  646. top_recv.real_ip.data(),
  647. top_recv.real_ip.size(),
  648. RSPAMD_INET_ADDRESS_PARSE_NO_UNIX)) {
  649. msg_warn_task("cannot get IP from received header: '%s'",
  650. top_recv.real_ip.data());
  651. task->from_addr = nullptr;
  652. }
  653. }
  654. if (!top_recv.real_hostname.empty()) {
  655. task->hostname = top_recv.real_hostname.data();
  656. }
  657. return true;
  658. }
  659. }
  660. }
  661. return false;
  662. }
  663. static auto
  664. received_export_to_lua(received_header_chain *chain, lua_State *L) -> bool
  665. {
  666. if (chain == nullptr) {
  667. return false;
  668. }
  669. lua_createtable(L, chain->size(), 0);
  670. auto push_flag = [L](const received_header &rh, received_flags fl, const char *name) {
  671. lua_pushboolean(L, !!(rh.flags & fl));
  672. lua_setfield(L, -2, name);
  673. };
  674. auto i = 1;
  675. for (const auto &rh: chain->as_vector()) {
  676. lua_createtable(L, 0, 10);
  677. if (rh.hdr && rh.hdr->decoded) {
  678. rspamd_lua_table_set(L, "raw", rh.hdr->decoded);
  679. }
  680. lua_createtable(L, 0, 3);
  681. push_flag(rh, received_flags::ARTIFICIAL, "artificial");
  682. push_flag(rh, received_flags::AUTHENTICATED, "authenticated");
  683. push_flag(rh, received_flags::SSL, "ssl");
  684. lua_setfield(L, -2, "flags");
  685. auto push_nullable_string = [L](const mime_string &st, const char *field) {
  686. if (st.empty()) {
  687. lua_pushnil(L);
  688. }
  689. else {
  690. lua_pushlstring(L, st.data(), st.size());
  691. }
  692. lua_setfield(L, -2, field);
  693. };
  694. push_nullable_string(rh.from_hostname, "from_hostname");
  695. push_nullable_string(rh.real_hostname, "real_hostname");
  696. push_nullable_string(rh.real_ip, "from_ip");
  697. push_nullable_string(rh.by_hostname, "by_hostname");
  698. push_nullable_string(rh.for_mbox, "for");
  699. if (rh.addr) {
  700. rspamd_lua_ip_push(L, rh.addr);
  701. }
  702. else {
  703. lua_pushnil(L);
  704. }
  705. lua_setfield(L, -2, "real_ip");
  706. lua_pushstring(L, received_protocol_to_string(rh.flags));
  707. lua_setfield(L, -2, "proto");
  708. lua_pushinteger(L, rh.timestamp);
  709. lua_setfield(L, -2, "timestamp");
  710. lua_rawseti(L, -2, i++);
  711. }
  712. return true;
  713. }
  714. }// namespace rspamd::mime
  715. bool rspamd_received_header_parse(struct rspamd_task *task,
  716. const char *data, size_t sz,
  717. struct rspamd_mime_header *hdr)
  718. {
  719. auto *recv_chain_ptr = static_cast<rspamd::mime::received_header_chain *>(MESSAGE_FIELD(task, received_headers));
  720. if (recv_chain_ptr == nullptr) {
  721. /* This constructor automatically registers dtor in mempool */
  722. recv_chain_ptr = new rspamd::mime::received_header_chain(task);
  723. MESSAGE_FIELD(task, received_headers) = (void *) recv_chain_ptr;
  724. }
  725. return rspamd::mime::received_header_parse(*recv_chain_ptr, task->task_pool,
  726. std::string_view{data, sz}, hdr);
  727. }
  728. bool rspamd_received_maybe_fix_task(struct rspamd_task *task)
  729. {
  730. return rspamd::mime::received_maybe_fix_task(task);
  731. }
  732. bool rspamd_received_export_to_lua(struct rspamd_task *task, lua_State *L)
  733. {
  734. return rspamd::mime::received_export_to_lua(
  735. static_cast<rspamd::mime::received_header_chain *>(MESSAGE_FIELD(task, received_headers)),
  736. L);
  737. }
  738. /* Tests part */
  739. #define DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL
  740. #include "doctest/doctest.h"
  741. TEST_SUITE("received")
  742. {
  743. TEST_CASE("parse received")
  744. {
  745. using namespace std::string_view_literals;
  746. using map_type = ankerl::unordered_dense::map<std::string_view, std::string_view>;
  747. std::vector<std::pair<std::string_view, map_type>> cases{
  748. // Simple received
  749. {"from smtp11.mailtrack.pl (smtp11.mailtrack.pl [185.243.30.90])"sv,
  750. {{"real_ip", "185.243.30.90"},
  751. {"real_hostname", "smtp11.mailtrack.pl"},
  752. {"from_hostname", "smtp11.mailtrack.pl"}}},
  753. // Real Postfix IPv6 received
  754. {"from server.chat-met-vreemden.nl (unknown [IPv6:2a01:7c8:aab6:26d:5054:ff:fed1:1da2])\n"
  755. "\t(using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits))\n"
  756. "\t(Client did not present a certificate)\n"
  757. "\tby mx1.freebsd.org (Postfix) with ESMTPS id CF0171862\n"
  758. "\tfor <test@example.com>; Mon, 6 Jul 2015 09:01:20 +0000 (UTC)\n"
  759. "\t(envelope-from upwest201diana@outlook.com)"sv,
  760. {{"real_ip", "2a01:7c8:aab6:26d:5054:ff:fed1:1da2"},
  761. {"from_hostname", "server.chat-met-vreemden.nl"},
  762. {"by_hostname", "mx1.freebsd.org"},
  763. {"for_mbox", "<test@example.com>"}}},
  764. // Exim IPv4 received
  765. {"from localhost ([127.0.0.1]:49019 helo=hummus.csx.cam.ac.uk)\n"
  766. " by hummus.csx.cam.ac.uk with esmtp (Exim 4.91-pdpfix1)\n"
  767. " (envelope-from <exim-dev-bounces@exim.org>)\n"
  768. " id 1fZ55o-0006DP-3H\n"
  769. " for <xxx@xxx.xxx>; Sat, 30 Jun 2018 02:54:28 +0100"sv,
  770. {
  771. {"from_hostname", "localhost"},
  772. {"real_ip", "127.0.0.1"},
  773. {"for_mbox", "<xxx@xxx.xxx>"},
  774. {"by_hostname", "hummus.csx.cam.ac.uk"},
  775. }},
  776. // Exim IPv6 received
  777. {"from smtp.spodhuis.org ([2a02:898:31:0:48:4558:736d:7470]:38689\n"
  778. " helo=mx.spodhuis.org)\n"
  779. " by hummus.csx.cam.ac.uk with esmtpsa (TLSv1.3:TLS_AES_256_GCM_SHA384:256)\n"
  780. " (Exim 4.91-pdpfix1+cc) (envelope-from <xxx@exim.org>)\n"
  781. " id 1fZ55k-0006CO-9M\n"
  782. " for exim-dev@exim.org; Sat, 30 Jun 2018 02:54:24 +0100"sv,
  783. {
  784. {"from_hostname", "smtp.spodhuis.org"},
  785. {"real_ip", "2a02:898:31:0:48:4558:736d:7470"},
  786. {"for_mbox", "exim-dev@exim.org"},
  787. {"by_hostname", "hummus.csx.cam.ac.uk"},
  788. }},
  789. // Haraka received
  790. {"from aaa.cn ([1.1.1.1]) by localhost.localdomain (Haraka/2.8.18) with "
  791. "ESMTPA id 349C9C2B-491A-4925-A687-3EF14038C344.1 envelope-from <huxin@xxx.com> "
  792. "(authenticated bits=0); Tue, 03 Jul 2018 14:18:13 +0200"sv,
  793. {
  794. {"from_hostname", "aaa.cn"},
  795. {"real_ip", "1.1.1.1"},
  796. {"by_hostname", "localhost.localdomain"},
  797. }},
  798. // Invalid by
  799. {"from [192.83.172.101] (HELLO 148.251.238.35) (148.251.238.35) "
  800. "by guovswzqkvry051@sohu.com with gg login "
  801. "by AOL 6.0 for Windows US sub 008 SMTP ; Tue, 03 Jul 2018 09:01:47 -0300"sv,
  802. {
  803. {"from_hostname", "192.83.172.101"},
  804. {"real_ip", "192.83.172.101"},
  805. }},
  806. // Invalid hostinfo
  807. {"from example.com ([]) by example.com with ESMTP id 2019091111 ;"
  808. " Thu, 26 Sep 2019 11:19:07 +0200"sv,
  809. {
  810. {"by_hostname", "example.com"},
  811. {"from_hostname", "example.com"},
  812. {"real_hostname", "example.com"},
  813. }},
  814. // Different real and announced hostnames + broken crap
  815. {"from 171-29.br (1-1-1-1.z.com.br [1.1.1.1]) by x.com.br (Postfix) "
  816. "with;ESMTP id 44QShF6xj4z1X for <hey@y.br>; Thu, 21 Mar 2019 23:45:46 -0300 "
  817. ": <g @yi.br>"sv,
  818. {
  819. {"real_ip", "1.1.1.1"},
  820. {"from_hostname", "171-29.br"},
  821. {"real_hostname", "1-1-1-1.z.com.br"},
  822. {"by_hostname", "x.com.br"},
  823. }},
  824. // Different real and announced ips + no hostname
  825. {"from [127.0.0.1] ([127.0.0.2]) by smtp.gmail.com with ESMTPSA id xxxololo"sv,
  826. {
  827. {"real_ip", "127.0.0.2"},
  828. {"from_hostname", "127.0.0.1"},
  829. {"by_hostname", "smtp.gmail.com"},
  830. }},
  831. // Different real and hostanes
  832. {"from 185.118.166.127 (steven2.zhou01.pserver.ru [185.118.166.127]) "
  833. "by mail.832zsu.cn (Postfix) with ESMTPA id AAD722133E34"sv,
  834. {
  835. {"real_ip", "185.118.166.127"},
  836. {"from_hostname", "185.118.166.127"},
  837. {"real_hostname", "steven2.zhou01.pserver.ru"},
  838. {"by_hostname", "mail.832zsu.cn"},
  839. }},
  840. // \0 in received must be filtered
  841. {"from smtp11.mailt\0rack.pl (smtp11.mail\0track.pl [1\085.243.30.90])"sv,
  842. {{"real_ip", "185.243.30.90"},
  843. {"real_hostname", "smtp11.mailtrack.pl"},
  844. {"from_hostname", "smtp11.mailtrack.pl"}}},
  845. // No from part
  846. {"by mail.832zsu.cn (Postfix) with ESMTPA id AAD722133E34"sv,
  847. {
  848. {"by_hostname", "mail.832zsu.cn"},
  849. }},
  850. // From part is in the comment
  851. {"(from asterisk@localhost)\n"
  852. " by pbx.xxx.com (8.14.7/8.14.7/Submit) id 076Go4wD014562;\n"
  853. " Thu, 6 Aug 2020 11:50:04 -0500"sv,
  854. {
  855. {"by_hostname", "pbx.xxx.com"},
  856. }},
  857. };
  858. rspamd_mempool_t *pool = rspamd_mempool_new_default("rcvd test", 0);
  859. for (auto &&c: cases) {
  860. SUBCASE(c.first.data())
  861. {
  862. rspamd::mime::received_header_chain chain;
  863. auto ret = rspamd::mime::received_header_parse(chain, pool,
  864. c.first, nullptr);
  865. CHECK(ret == true);
  866. auto &&rh = chain.get_received(0);
  867. CHECK(rh.has_value());
  868. auto res = rh.value().get().as_map();
  869. for (const auto &expected: c.second) {
  870. CHECK_MESSAGE(res.contains(expected.first), expected.first.data());
  871. CHECK(res[expected.first] == expected.second);
  872. }
  873. for (const auto &existing: res) {
  874. CHECK_MESSAGE(c.second.contains(existing.first), existing.first.data());
  875. CHECK(c.second[existing.first] == existing.second);
  876. }
  877. }
  878. }
  879. rspamd_mempool_delete(pool);
  880. }
  881. }