forked from OISF/suricata
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app-layer-smtp.c
5211 lines (4657 loc) · 175 KB
/
app-layer-smtp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2007-2012 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Anoop Saldanha <anoopsaldanha@gmail.com>
*/
#include "suricata.h"
#include "suricata-common.h"
#include "debug.h"
#include "decode.h"
#include "threads.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream.h"
#include "app-layer.h"
#include "app-layer-detect-proto.h"
#include "app-layer-protos.h"
#include "app-layer-parser.h"
#include "app-layer-smtp.h"
#include "util-mpm.h"
#include "util-debug.h"
#include "util-byte.h"
#include "util-unittest.h"
#include "util-unittest-helper.h"
#include "util-memcmp.h"
#include "flow-util.h"
#include "detect-engine.h"
#include "detect-engine-state.h"
#include "detect-parse.h"
#include "decode-events.h"
#include "conf.h"
#include "util-mem.h"
#include "util-misc.h"
/* content-limit default value */
#define FILEDATA_CONTENT_LIMIT 100000
/* content-inspect-min-size default value */
#define FILEDATA_CONTENT_INSPECT_MIN_SIZE 32768
/* content-inspect-window default value */
#define FILEDATA_CONTENT_INSPECT_WINDOW 4096
#define SMTP_MAX_REQUEST_AND_REPLY_LINE_LENGTH 510
#define SMTP_COMMAND_BUFFER_STEPS 5
/* we are in process of parsing a fresh command. Just a placeholder. If we
* are not in STATE_COMMAND_DATA_MODE, we have to be in this mode */
#define SMTP_PARSER_STATE_COMMAND_MODE 0x00
/* we are in mode of parsing a command's data. Used when we are parsing tls
* or accepting the rfc 2822 mail after DATA command */
#define SMTP_PARSER_STATE_COMMAND_DATA_MODE 0x01
/* Used when we are still in the process of parsing a server command. Used
* with multi-line replies and the stream is fragmented before all the lines
* for a response is seen */
#define SMTP_PARSER_STATE_PARSING_SERVER_RESPONSE 0x02
/* Used to indicate that the parser has seen the first reply */
#define SMTP_PARSER_STATE_FIRST_REPLY_SEEN 0x04
/* Used to indicate that the parser is parsing a multiline reply */
#define SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY 0x08
/* Used to indicate that the server supports pipelining */
#define SMTP_PARSER_STATE_PIPELINING_SERVER 0x10
/* Various SMTP commands
* We currently have var-ified just STARTTLS and DATA, since we need to them
* for state transitions. The rest are just indicate as OTHER_CMD. Other
* commands would be introduced as and when needed */
#define SMTP_COMMAND_STARTTLS 1
#define SMTP_COMMAND_DATA 2
#define SMTP_COMMAND_BDAT 3
/* not an actual command per se, but the mode where we accept the mail after
* DATA has it's own reply code for completion, from the server. We give this
* stage a pseudo command of it's own, so that we can add this to the command
* buffer to match with the reply */
#define SMTP_COMMAND_DATA_MODE 4
/* All other commands are represented by this var */
#define SMTP_COMMAND_OTHER_CMD 5
/* Different EHLO extensions. Not used now. */
#define SMTP_EHLO_EXTENSION_PIPELINING
#define SMTP_EHLO_EXTENSION_SIZE
#define SMTP_EHLO_EXTENSION_DSN
#define SMTP_EHLO_EXTENSION_STARTTLS
#define SMTP_EHLO_EXTENSION_8BITMIME
SCEnumCharMap smtp_decoder_event_table[ ] = {
{ "INVALID_REPLY", SMTP_DECODER_EVENT_INVALID_REPLY },
{ "UNABLE_TO_MATCH_REPLY_WITH_REQUEST",
SMTP_DECODER_EVENT_UNABLE_TO_MATCH_REPLY_WITH_REQUEST },
{ "MAX_COMMAND_LINE_LEN_EXCEEDED",
SMTP_DECODER_EVENT_MAX_COMMAND_LINE_LEN_EXCEEDED },
{ "MAX_REPLY_LINE_LEN_EXCEEDED",
SMTP_DECODER_EVENT_MAX_REPLY_LINE_LEN_EXCEEDED },
{ "INVALID_PIPELINED_SEQUENCE",
SMTP_DECODER_EVENT_INVALID_PIPELINED_SEQUENCE },
{ "BDAT_CHUNK_LEN_EXCEEDED",
SMTP_DECODER_EVENT_BDAT_CHUNK_LEN_EXCEEDED },
{ "NO_SERVER_WELCOME_MESSAGE",
SMTP_DECODER_EVENT_NO_SERVER_WELCOME_MESSAGE },
{ "TLS_REJECTED",
SMTP_DECODER_EVENT_TLS_REJECTED },
{ "DATA_COMMAND_REJECTED",
SMTP_DECODER_EVENT_DATA_COMMAND_REJECTED },
/* MIME Events */
{ "MIME_PARSE_FAILED",
SMTP_DECODER_EVENT_MIME_PARSE_FAILED },
{ "MIME_MALFORMED_MSG",
SMTP_DECODER_EVENT_MIME_MALFORMED_MSG },
{ "MIME_INVALID_BASE64",
SMTP_DECODER_EVENT_MIME_INVALID_BASE64 },
{ "MIME_INVALID_QP",
SMTP_DECODER_EVENT_MIME_INVALID_QP },
{ "MIME_LONG_LINE",
SMTP_DECODER_EVENT_MIME_LONG_LINE },
{ "MIME_LONG_ENC_LINE",
SMTP_DECODER_EVENT_MIME_LONG_ENC_LINE },
{ "MIME_LONG_HEADER_NAME",
SMTP_DECODER_EVENT_MIME_LONG_HEADER_NAME },
{ "MIME_LONG_HEADER_VALUE",
SMTP_DECODER_EVENT_MIME_LONG_HEADER_VALUE },
{ "MIME_LONG_BOUNDARY",
SMTP_DECODER_EVENT_MIME_BOUNDARY_TOO_LONG },
/* Invalid behavior or content */
{ "DUPLICATE_FIELDS",
SMTP_DECODER_EVENT_DUPLICATE_FIELDS },
{ "UNPARSABLE_CONTENT",
SMTP_DECODER_EVENT_UNPARSABLE_CONTENT },
{ NULL, -1 },
};
typedef struct SMTPThreadCtx_ {
MpmThreadCtx *smtp_mpm_thread_ctx;
PrefilterRuleStore *pmq;
} SMTPThreadCtx;
#define SMTP_MPM mpm_default_matcher
static MpmCtx *smtp_mpm_ctx = NULL;
/* smtp reply codes. If an entry is made here, please make a simultaneous
* entry in smtp_reply_map */
enum {
SMTP_REPLY_211,
SMTP_REPLY_214,
SMTP_REPLY_220,
SMTP_REPLY_221,
SMTP_REPLY_235,
SMTP_REPLY_250,
SMTP_REPLY_251,
SMTP_REPLY_252,
SMTP_REPLY_334,
SMTP_REPLY_354,
SMTP_REPLY_421,
SMTP_REPLY_450,
SMTP_REPLY_451,
SMTP_REPLY_452,
SMTP_REPLY_455,
SMTP_REPLY_500,
SMTP_REPLY_501,
SMTP_REPLY_502,
SMTP_REPLY_503,
SMTP_REPLY_504,
SMTP_REPLY_550,
SMTP_REPLY_551,
SMTP_REPLY_552,
SMTP_REPLY_553,
SMTP_REPLY_554,
SMTP_REPLY_555,
};
SCEnumCharMap smtp_reply_map[ ] = {
{ "211", SMTP_REPLY_211 },
{ "214", SMTP_REPLY_214 },
{ "220", SMTP_REPLY_220 },
{ "221", SMTP_REPLY_221 },
{ "235", SMTP_REPLY_235 },
{ "250", SMTP_REPLY_250 },
{ "251", SMTP_REPLY_251 },
{ "252", SMTP_REPLY_252 },
{ "334", SMTP_REPLY_334 },
{ "354", SMTP_REPLY_354 },
{ "421", SMTP_REPLY_421 },
{ "450", SMTP_REPLY_450 },
{ "451", SMTP_REPLY_451 },
{ "452", SMTP_REPLY_452 },
{ "455", SMTP_REPLY_455 },
{ "500", SMTP_REPLY_500 },
{ "501", SMTP_REPLY_501 },
{ "502", SMTP_REPLY_502 },
{ "503", SMTP_REPLY_503 },
{ "504", SMTP_REPLY_504 },
{ "550", SMTP_REPLY_550 },
{ "551", SMTP_REPLY_551 },
{ "552", SMTP_REPLY_552 },
{ "553", SMTP_REPLY_553 },
{ "554", SMTP_REPLY_554 },
{ "555", SMTP_REPLY_555 },
{ NULL, -1 },
};
/* Create SMTP config structure */
SMTPConfig smtp_config = { 0, { 0, 0, 0, 0, 0 }, 0, 0, 0, STREAMING_BUFFER_CONFIG_INITIALIZER};
static SMTPString *SMTPStringAlloc(void);
/**
* \brief Configure SMTP Mime Decoder by parsing out mime section of YAML
* config file
*
* \return none
*/
static void SMTPConfigure(void) {
SCEnter();
int ret = 0, val;
intmax_t imval;
uint32_t content_limit = 0;
uint32_t content_inspect_min_size = 0;
uint32_t content_inspect_window = 0;
ConfNode *config = ConfGetNode("app-layer.protocols.smtp.mime");
if (config != NULL) {
ret = ConfGetChildValueBool(config, "decode-mime", &val);
if (ret) {
smtp_config.decode_mime = val;
}
ret = ConfGetChildValueBool(config, "decode-base64", &val);
if (ret) {
smtp_config.mime_config.decode_base64 = val;
}
ret = ConfGetChildValueBool(config, "decode-quoted-printable", &val);
if (ret) {
smtp_config.mime_config.decode_quoted_printable = val;
}
ret = ConfGetChildValueInt(config, "header-value-depth", &imval);
if (ret) {
smtp_config.mime_config.header_value_depth = (uint32_t) imval;
}
ret = ConfGetChildValueBool(config, "extract-urls", &val);
if (ret) {
smtp_config.mime_config.extract_urls = val;
}
ret = ConfGetChildValueBool(config, "body-md5", &val);
if (ret) {
smtp_config.mime_config.body_md5 = val;
}
}
/* Pass mime config data to MimeDec API */
MimeDecSetConfig(&smtp_config.mime_config);
smtp_config.content_limit = FILEDATA_CONTENT_LIMIT;
smtp_config.content_inspect_window = FILEDATA_CONTENT_INSPECT_WINDOW;
smtp_config.content_inspect_min_size = FILEDATA_CONTENT_INSPECT_MIN_SIZE;
ConfNode *t = ConfGetNode("app-layer.protocols.smtp.inspected-tracker");
ConfNode *p = NULL;
if (t != NULL) {
TAILQ_FOREACH(p, &t->head, next) {
if (strcasecmp("content-limit", p->name) == 0) {
if (ParseSizeStringU32(p->val, &content_limit) < 0) {
SCLogWarning(SC_ERR_SIZE_PARSE,
"parsing content-limit %s failed", p->val);
content_limit = FILEDATA_CONTENT_LIMIT;
}
smtp_config.content_limit = content_limit;
}
if (strcasecmp("content-inspect-min-size", p->name) == 0) {
if (ParseSizeStringU32(p->val, &content_inspect_min_size) < 0) {
SCLogWarning(SC_ERR_SIZE_PARSE,
"parsing content-inspect-min-size %s failed", p->val);
content_inspect_min_size = FILEDATA_CONTENT_INSPECT_MIN_SIZE;
}
smtp_config.content_inspect_min_size = content_inspect_min_size;
}
if (strcasecmp("content-inspect-window", p->name) == 0) {
if (ParseSizeStringU32(p->val, &content_inspect_window) < 0) {
SCLogWarning(SC_ERR_SIZE_PARSE,
"parsing content-inspect-window %s failed", p->val);
content_inspect_window = FILEDATA_CONTENT_INSPECT_WINDOW;
}
smtp_config.content_inspect_window = content_inspect_window;
}
}
}
smtp_config.sbcfg.buf_size = content_limit ? content_limit : 256;
SCReturn;
}
static void SMTPSetEvent(SMTPState *s, uint8_t e)
{
SCLogDebug("setting event %u", e);
if (s->curr_tx != NULL) {
AppLayerDecoderEventsSetEventRaw(&s->curr_tx->decoder_events, e);
// s->events++;
return;
}
SCLogDebug("couldn't set event %u", e);
}
static SMTPTransaction *SMTPTransactionCreate(void)
{
SMTPTransaction *tx = SCCalloc(1, sizeof(*tx));
if (tx == NULL) {
return NULL;
}
TAILQ_INIT(&tx->rcpt_to_list);
tx->mime_state = NULL;
return tx;
}
/** \internal
* \brief update inspected tracker if it gets to far behind
*
* As smtp uses the FILE_USE_DETECT flag in the file API, we are responsible
* for making sure that File::content_inspected is not getting too far
* behind.
*/
static void SMTPPruneFiles(FileContainer *files)
{
SCLogDebug("cfg: win %"PRIu32" min_size %"PRIu32,
smtp_config.content_inspect_window, smtp_config.content_inspect_min_size);
File *file = files->head;
while (file) {
SCLogDebug("file %p", file);
uint32_t window = smtp_config.content_inspect_window;
if (file->sb->stream_offset == 0)
window = MAX(window, smtp_config.content_inspect_min_size);
uint64_t file_size = FileDataSize(file);
uint64_t data_size = file_size - file->sb->stream_offset;
SCLogDebug("window %"PRIu32", file_size %"PRIu64", data_size %"PRIu64,
window, file_size, data_size);
if (data_size > (window * 3)) {
uint64_t left_edge = file_size - window;
SCLogDebug("file->content_inspected now %"PRIu64, left_edge);
file->content_inspected = left_edge;
}
file = file->next;
}
}
static void FlagDetectStateNewFile(SMTPTransaction *tx)
{
if (tx && tx->de_state) {
SCLogDebug("DETECT_ENGINE_STATE_FLAG_FILE_TS_NEW set");
tx->de_state->dir_state[0].flags |= DETECT_ENGINE_STATE_FLAG_FILE_TS_NEW;
} else if (tx == NULL) {
SCLogDebug("DETECT_ENGINE_STATE_FLAG_FILE_TS_NEW NOT set, no TX");
} else if (tx->de_state == NULL) {
SCLogDebug("DETECT_ENGINE_STATE_FLAG_FILE_TS_NEW NOT set, no TX DESTATE");
}
}
int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len,
MimeDecParseState *state)
{
SCEnter();
int ret = MIME_DEC_OK;
Flow *flow = (Flow *) state->data;
SMTPState *smtp_state = (SMTPState *) flow->alstate;
MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data;
FileContainer *files = NULL;
uint16_t flags = FileFlowToFlags(flow, STREAM_TOSERVER);
/* we depend on detection engine for file pruning */
flags |= FILE_USE_DETECT;
/* Find file */
if (entity->ctnt_flags & CTNT_IS_ATTACHMENT) {
/* Make sure file container allocated */
if (smtp_state->files_ts == NULL) {
smtp_state->files_ts = FileContainerAlloc();
if (smtp_state->files_ts == NULL) {
ret = MIME_DEC_ERR_MEM;
SCLogError(SC_ERR_MEM_ALLOC, "Could not create file container");
SCReturnInt(ret);
}
}
files = smtp_state->files_ts;
/* Open file if necessary */
if (state->body_begin) {
if (SCLogDebugEnabled()) {
SCLogDebug("Opening file...%u bytes", len);
printf("File - ");
for (uint32_t i = 0; i < entity->filename_len; i++) {
printf("%c", entity->filename[i]);
}
printf("\n");
}
/* Set storage flag if applicable since only the first file in the
* flow seems to be processed by the 'filestore' detector */
if (files->head != NULL && (files->head->flags & FILE_STORE)) {
flags |= FILE_STORE;
}
if (FileOpenFile(files, &smtp_config.sbcfg, (uint8_t *) entity->filename, entity->filename_len,
(uint8_t *) chunk, len, flags) == NULL) {
ret = MIME_DEC_ERR_DATA;
SCLogDebug("FileOpenFile() failed");
}
FlagDetectStateNewFile(smtp_state->curr_tx);
/* If close in the same chunk, then pass in empty bytes */
if (state->body_end) {
SCLogDebug("Closing file...%u bytes", len);
if (files->tail->state == FILE_STATE_OPENED) {
ret = FileCloseFile(files, (uint8_t *) NULL, 0, flags);
if (ret != 0) {
SCLogDebug("FileCloseFile() failed: %d", ret);
ret = MIME_DEC_ERR_DATA;
}
} else {
SCLogDebug("File already closed");
}
}
} else if (state->body_end) {
/* Close file */
SCLogDebug("Closing file...%u bytes", len);
if (files && files->tail && files->tail->state == FILE_STATE_OPENED) {
ret = FileCloseFile(files, (uint8_t *) chunk, len, flags);
if (ret != 0) {
SCLogDebug("FileCloseFile() failed: %d", ret);
ret = MIME_DEC_ERR_DATA;
}
} else {
SCLogDebug("File already closed");
}
} else {
/* Append data chunk to file */
SCLogDebug("Appending file...%u bytes", len);
/* 0 is ok, -2 is not stored, -1 is error */
ret = FileAppendData(files, (uint8_t *) chunk, len);
if (ret == -2) {
ret = 0;
SCLogDebug("FileAppendData() - file no longer being extracted");
} else if (ret < 0) {
SCLogDebug("FileAppendData() failed: %d", ret);
ret = MIME_DEC_ERR_DATA;
}
}
if (ret == 0) {
SCLogDebug("Successfully processed file data!");
}
} else {
SCLogDebug("Body not a Ctnt_attachment");
}
if (files != NULL) {
SMTPPruneFiles(files);
FilePrune(files);
}
SCReturnInt(ret);
}
/**
* \internal
* \brief Get the next line from input. It doesn't do any length validation.
*
* \param state The smtp state.
*
* \retval 0 On suceess.
* \retval -1 Either when we don't have any new lines to supply anymore or
* on failure.
*/
static int SMTPGetLine(SMTPState *state)
{
SCEnter();
void *ptmp;
/* we have run out of input */
if (state->input_len <= 0)
return -1;
/* toserver */
if (state->direction == 0) {
if (state->ts_current_line_lf_seen == 1) {
/* we have seen the lf for the previous line. Clear the parser
* details to parse new line */
state->ts_current_line_lf_seen = 0;
if (state->ts_current_line_db == 1) {
state->ts_current_line_db = 0;
SCFree(state->ts_db);
state->ts_db = NULL;
state->ts_db_len = 0;
state->current_line = NULL;
state->current_line_len = 0;
}
}
uint8_t *lf_idx = memchr(state->input, 0x0a, state->input_len);
if (lf_idx == NULL) {
/* fragmented lines. Decoder event for special cases. Not all
* fragmented lines should be treated as a possible evasion
* attempt. With multi payload smtp chunks we can have valid
* cases of fragmentation. But within the same segment chunk
* if we see fragmentation then it's definitely something you
* should alert about */
if (state->ts_current_line_db == 0) {
state->ts_db = SCMalloc(state->input_len);
if (state->ts_db == NULL) {
return -1;
}
state->ts_current_line_db = 1;
memcpy(state->ts_db, state->input, state->input_len);
state->ts_db_len = state->input_len;
} else {
ptmp = SCRealloc(state->ts_db,
(state->ts_db_len + state->input_len));
if (ptmp == NULL) {
SCFree(state->ts_db);
state->ts_db = NULL;
state->ts_db_len = 0;
return -1;
}
state->ts_db = ptmp;
memcpy(state->ts_db + state->ts_db_len,
state->input, state->input_len);
state->ts_db_len += state->input_len;
} /* else */
state->input += state->input_len;
state->input_len = 0;
return -1;
} else {
state->ts_current_line_lf_seen = 1;
if (state->ts_current_line_db == 1) {
ptmp = SCRealloc(state->ts_db,
(state->ts_db_len + (lf_idx + 1 - state->input)));
if (ptmp == NULL) {
SCFree(state->ts_db);
state->ts_db = NULL;
state->ts_db_len = 0;
return -1;
}
state->ts_db = ptmp;
memcpy(state->ts_db + state->ts_db_len,
state->input, (lf_idx + 1 - state->input));
state->ts_db_len += (lf_idx + 1 - state->input);
if (state->ts_db_len > 1 &&
state->ts_db[state->ts_db_len - 2] == 0x0D) {
state->ts_db_len -= 2;
state->current_line_delimiter_len = 2;
} else {
state->ts_db_len -= 1;
state->current_line_delimiter_len = 1;
}
state->current_line = state->ts_db;
state->current_line_len = state->ts_db_len;
} else {
state->current_line = state->input;
state->current_line_len = lf_idx - state->input;
if (state->input != lf_idx &&
*(lf_idx - 1) == 0x0D) {
state->current_line_len--;
state->current_line_delimiter_len = 2;
} else {
state->current_line_delimiter_len = 1;
}
}
state->input_len -= (lf_idx - state->input) + 1;
state->input = (lf_idx + 1);
return 0;
}
/* toclient */
} else {
if (state->tc_current_line_lf_seen == 1) {
/* we have seen the lf for the previous line. Clear the parser
* details to parse new line */
state->tc_current_line_lf_seen = 0;
if (state->tc_current_line_db == 1) {
state->tc_current_line_db = 0;
SCFree(state->tc_db);
state->tc_db = NULL;
state->tc_db_len = 0;
state->current_line = NULL;
state->current_line_len = 0;
}
}
uint8_t *lf_idx = memchr(state->input, 0x0a, state->input_len);
if (lf_idx == NULL) {
/* fragmented lines. Decoder event for special cases. Not all
* fragmented lines should be treated as a possible evasion
* attempt. With multi payload smtp chunks we can have valid
* cases of fragmentation. But within the same segment chunk
* if we see fragmentation then it's definitely something you
* should alert about */
if (state->tc_current_line_db == 0) {
state->tc_db = SCMalloc(state->input_len);
if (state->tc_db == NULL) {
return -1;
}
state->tc_current_line_db = 1;
memcpy(state->tc_db, state->input, state->input_len);
state->tc_db_len = state->input_len;
} else {
ptmp = SCRealloc(state->tc_db,
(state->tc_db_len + state->input_len));
if (ptmp == NULL) {
SCFree(state->tc_db);
state->tc_db = NULL;
state->tc_db_len = 0;
return -1;
}
state->tc_db = ptmp;
memcpy(state->tc_db + state->tc_db_len,
state->input, state->input_len);
state->tc_db_len += state->input_len;
} /* else */
state->input += state->input_len;
state->input_len = 0;
return -1;
} else {
state->tc_current_line_lf_seen = 1;
if (state->tc_current_line_db == 1) {
ptmp = SCRealloc(state->tc_db,
(state->tc_db_len + (lf_idx + 1 - state->input)));
if (ptmp == NULL) {
SCFree(state->tc_db);
state->tc_db = NULL;
state->tc_db_len = 0;
return -1;
}
state->tc_db = ptmp;
memcpy(state->tc_db + state->tc_db_len,
state->input, (lf_idx + 1 - state->input));
state->tc_db_len += (lf_idx + 1 - state->input);
if (state->tc_db_len > 1 &&
state->tc_db[state->tc_db_len - 2] == 0x0D) {
state->tc_db_len -= 2;
state->current_line_delimiter_len = 2;
} else {
state->tc_db_len -= 1;
state->current_line_delimiter_len = 1;
}
state->current_line = state->tc_db;
state->current_line_len = state->tc_db_len;
} else {
state->current_line = state->input;
state->current_line_len = lf_idx - state->input;
if (state->input != lf_idx &&
*(lf_idx - 1) == 0x0D) {
state->current_line_len--;
state->current_line_delimiter_len = 2;
} else {
state->current_line_delimiter_len = 1;
}
}
state->input_len -= (lf_idx - state->input) + 1;
state->input = (lf_idx + 1);
return 0;
} /* else - if (lf_idx == NULL) */
}
}
static int SMTPInsertCommandIntoCommandBuffer(uint8_t command, SMTPState *state, Flow *f)
{
SCEnter();
void *ptmp;
if (state->cmds_cnt >= state->cmds_buffer_len) {
int increment = SMTP_COMMAND_BUFFER_STEPS;
if ((int)(state->cmds_buffer_len + SMTP_COMMAND_BUFFER_STEPS) > (int)USHRT_MAX) {
increment = USHRT_MAX - state->cmds_buffer_len;
}
ptmp = SCRealloc(state->cmds,
sizeof(uint8_t) * (state->cmds_buffer_len + increment));
if (ptmp == NULL) {
SCFree(state->cmds);
state->cmds = NULL;
SCLogDebug("SCRealloc failure");
return -1;
}
state->cmds = ptmp;
state->cmds_buffer_len += increment;
}
if (state->cmds_cnt >= 1 &&
((state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_STARTTLS) ||
(state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_DATA))) {
/* decoder event */
SMTPSetEvent(state, SMTP_DECODER_EVENT_INVALID_PIPELINED_SEQUENCE);
/* we have to have EHLO, DATA, VRFY, EXPN, TURN, QUIT, NOOP,
* STARTTLS as the last command in pipelined mode */
}
/** \todo decoder event */
if ((int)(state->cmds_cnt + 1) > (int)USHRT_MAX) {
SCLogDebug("command buffer overflow");
return -1;
}
state->cmds[state->cmds_cnt] = command;
state->cmds_cnt++;
return 0;
}
static int SMTPProcessCommandBDAT(SMTPState *state, Flow *f,
AppLayerParserState *pstate)
{
SCEnter();
state->bdat_chunk_idx += (state->current_line_len +
state->current_line_delimiter_len);
if (state->bdat_chunk_idx > state->bdat_chunk_len) {
state->parser_state &= ~SMTP_PARSER_STATE_COMMAND_DATA_MODE;
/* decoder event */
SMTPSetEvent(state, SMTP_DECODER_EVENT_BDAT_CHUNK_LEN_EXCEEDED);
SCReturnInt(-1);
} else if (state->bdat_chunk_idx == state->bdat_chunk_len) {
state->parser_state &= ~SMTP_PARSER_STATE_COMMAND_DATA_MODE;
}
SCReturnInt(0);
}
static void SetMimeEvents(SMTPState *state)
{
if (state->curr_tx->mime_state->msg == NULL) {
return;
}
/* Generate decoder events */
MimeDecEntity *msg = state->curr_tx->mime_state->msg;
if (msg->anomaly_flags & ANOM_INVALID_BASE64) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_INVALID_BASE64);
}
if (msg->anomaly_flags & ANOM_INVALID_QP) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_INVALID_QP);
}
if (msg->anomaly_flags & ANOM_LONG_LINE) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_LONG_LINE);
}
if (msg->anomaly_flags & ANOM_LONG_ENC_LINE) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_LONG_ENC_LINE);
}
if (msg->anomaly_flags & ANOM_LONG_HEADER_NAME) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_LONG_HEADER_NAME);
}
if (msg->anomaly_flags & ANOM_LONG_HEADER_VALUE) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_LONG_HEADER_VALUE);
}
if (msg->anomaly_flags & ANOM_MALFORMED_MSG) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_MALFORMED_MSG);
}
if (msg->anomaly_flags & ANOM_LONG_BOUNDARY) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_BOUNDARY_TOO_LONG);
}
}
/**
* \retval 0 ok
* \retval -1 error
*/
static int SMTPProcessCommandDATA(SMTPState *state, Flow *f,
AppLayerParserState *pstate)
{
SCEnter();
if (!(state->parser_state & SMTP_PARSER_STATE_COMMAND_DATA_MODE)) {
/* looks like are still waiting for a confirmination from the server */
return 0;
}
if (state->current_line_len == 1 && state->current_line[0] == '.') {
state->parser_state &= ~SMTP_PARSER_STATE_COMMAND_DATA_MODE;
/* kinda like a hack. The mail sent in DATA mode, would be
* acknowledged with a reply. We insert a dummy command to
* the command buffer to be used by the reply handler to match
* the reply received */
SMTPInsertCommandIntoCommandBuffer(SMTP_COMMAND_DATA_MODE, state, f);
if (smtp_config.decode_mime && state->curr_tx->mime_state != NULL) {
/* Complete parsing task */
int ret = MimeDecParseComplete(state->curr_tx->mime_state);
if (ret != MIME_DEC_OK) {
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_PARSE_FAILED);
SCLogDebug("MimeDecParseComplete() function failed");
}
/* Generate decoder events */
SetMimeEvents(state);
}
state->curr_tx->done = 1;
SCLogDebug("marked tx as done");
}
/* If DATA, then parse out a MIME message */
if (state->current_command == SMTP_COMMAND_DATA &&
(state->parser_state & SMTP_PARSER_STATE_COMMAND_DATA_MODE)) {
if (smtp_config.decode_mime && state->curr_tx->mime_state != NULL) {
int ret = MimeDecParseLine((const uint8_t *) state->current_line,
state->current_line_len, state->current_line_delimiter_len,
state->curr_tx->mime_state);
if (ret != MIME_DEC_OK) {
if (ret != MIME_DEC_ERR_STATE) {
/* Generate decoder events */
SetMimeEvents(state);
SCLogDebug("MimeDecParseLine() function returned an error code: %d", ret);
SMTPSetEvent(state, SMTP_DECODER_EVENT_MIME_PARSE_FAILED);
}
/* keep the parser in its error state so we can log that,
* the parser will reject new data */
}
}
}
return 0;
}
static int SMTPProcessCommandSTARTTLS(SMTPState *state, Flow *f,
AppLayerParserState *pstate)
{
return 0;
}
static int SMTPProcessReply(SMTPState *state, Flow *f,
AppLayerParserState *pstate,
SMTPThreadCtx *td)
{
SCEnter();
uint64_t reply_code = 0;
/* the reply code has to contain at least 3 bytes, to hold the 3 digit
* reply code */
if (state->current_line_len < 3) {
/* decoder event */
SMTPSetEvent(state, SMTP_DECODER_EVENT_INVALID_REPLY);
return -1;
}
if (state->current_line_len >= 4) {
if (state->parser_state & SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY) {
if (state->current_line[3] != '-') {
state->parser_state &= ~SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY;
}
} else {
if (state->current_line[3] == '-') {
state->parser_state |= SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY;
}
}
} else {
if (state->parser_state & SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY) {
state->parser_state &= ~SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY;
}
}
/* I don't like this pmq reset here. We'll devise a method later, that
* should make the use of the mpm very efficient */
PmqReset(td->pmq);
int mpm_cnt = mpm_table[SMTP_MPM].Search(smtp_mpm_ctx, td->smtp_mpm_thread_ctx,
td->pmq, state->current_line,
3);
if (mpm_cnt == 0) {
/* set decoder event - reply code invalid */
SMTPSetEvent(state, SMTP_DECODER_EVENT_INVALID_REPLY);
SCLogDebug("invalid reply code %02x %02x %02x",
state->current_line[0], state->current_line[1], state->current_line[2]);
SCReturnInt(-1);
}
reply_code = smtp_reply_map[td->pmq->rule_id_array[0]].enum_value;
if (state->cmds_idx == state->cmds_cnt) {
if (!(state->parser_state & SMTP_PARSER_STATE_FIRST_REPLY_SEEN)) {
/* the first server reply can be a multiline message. Let's
* flag the fact that we have seen the first reply only at the end
* of a multiline reply
*/
if (!(state->parser_state & SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY))
state->parser_state |= SMTP_PARSER_STATE_FIRST_REPLY_SEEN;
if (reply_code == SMTP_REPLY_220)
SCReturnInt(0);
else {
SMTPSetEvent(state, SMTP_DECODER_EVENT_INVALID_REPLY);
SCReturnInt(0);
}
} else {
/* decoder event - unable to match reply with request */
SCLogDebug("unable to match reply with request");
SCReturnInt(0);
}
}
if (state->cmds_cnt == 0) {
/* reply but not a command we have stored, fall through */
} else if (state->cmds[state->cmds_idx] == SMTP_COMMAND_STARTTLS) {
if (reply_code == SMTP_REPLY_220) {
/* we are entering STARRTTLS data mode */
state->parser_state |= SMTP_PARSER_STATE_COMMAND_DATA_MODE;
AppLayerRequestProtocolTLSUpgrade(f);
state->curr_tx->done = 1;
} else {
/* decoder event */
SMTPSetEvent(state, SMTP_DECODER_EVENT_TLS_REJECTED);
}
} else if (state->cmds[state->cmds_idx] == SMTP_COMMAND_DATA) {
if (reply_code == SMTP_REPLY_354) {
/* Next comes the mail for the DATA command in toserver direction */
state->parser_state |= SMTP_PARSER_STATE_COMMAND_DATA_MODE;
} else {
/* decoder event */
SMTPSetEvent(state, SMTP_DECODER_EVENT_DATA_COMMAND_REJECTED);
}
} else {
/* we don't care for any other command for now */
/* check if reply falls in the valid list of replies for SMTP. If not
* decoder event */
}
/* if it is a multi-line reply, we need to move the index only once for all