suricata
app-layer-ftp.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2025 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Pablo Rincon Crespo <pablo.rincon.crespo@gmail.com>
22  * \author Eric Leblond <eric@regit.org>
23  * \author Jeff Lucovsky <jlucovsky@oisf.net>
24  *
25  * App Layer Parser for FTP
26  */
27 
28 #include "suricata-common.h"
29 
30 #include "app-layer-ftp.h"
31 #include "app-layer.h"
32 #include "app-layer-parser.h"
33 #include "app-layer-expectation.h"
34 #include "app-layer-detect-proto.h"
35 #include "app-layer-events.h"
36 
37 #include "rust.h"
38 
39 #include "util-misc.h"
40 #include "util-mpm.h"
41 #include "util-validate.h"
42 
43 typedef struct FTPThreadCtx_ {
47 
48 #define FTP_MPM mpm_default_matcher
49 
50 static MpmCtx *ftp_mpm_ctx = NULL;
51 
52 uint64_t ftp_config_memcap = 0;
53 uint32_t ftp_config_maxtx = 1024;
54 uint32_t ftp_max_line_len = 4096;
55 
56 SC_ATOMIC_DECLARE(uint64_t, ftp_memuse);
57 SC_ATOMIC_DECLARE(uint64_t, ftp_memcap);
58 
59 static FTPTransaction *FTPGetOldestTx(const FtpState *, FTPTransaction *);
60 
61 static void FTPParseMemcap(void)
62 {
63  SCFTPGetConfigValues(&ftp_config_memcap, &ftp_config_maxtx, &ftp_max_line_len);
64 
65  SC_ATOMIC_INIT(ftp_memuse);
66  SC_ATOMIC_INIT(ftp_memcap);
67 }
68 
69 static void FTPIncrMemuse(uint64_t size)
70 {
71  (void)SC_ATOMIC_ADD(ftp_memuse, size);
72 }
73 
74 static void FTPDecrMemuse(uint64_t size)
75 {
76  (void)SC_ATOMIC_SUB(ftp_memuse, size);
77 }
78 
79 uint64_t FTPMemuseGlobalCounter(void)
80 {
81  uint64_t tmpval = SC_ATOMIC_GET(ftp_memuse);
82  return tmpval;
83 }
84 
85 uint64_t FTPMemcapGlobalCounter(void)
86 {
87  uint64_t tmpval = SC_ATOMIC_GET(ftp_memcap);
88  return tmpval;
89 }
90 
91 int FTPSetMemcap(uint64_t size)
92 {
93  if ((uint64_t)SC_ATOMIC_GET(ftp_memcap) < size) {
94  SC_ATOMIC_SET(ftp_memcap, size);
95  return 1;
96  }
97 
98  return 0;
99 }
100 
101 /**
102  * \brief Check if alloc'ing "size" would mean we're over memcap
103  *
104  * \retval 1 if in bounds
105  * \retval 0 if not in bounds
106  */
107 static int FTPCheckMemcap(uint64_t size)
108 {
109  if (ftp_config_memcap == 0 || size + SC_ATOMIC_GET(ftp_memuse) <= ftp_config_memcap)
110  return 1;
111  (void) SC_ATOMIC_ADD(ftp_memcap, 1);
112  return 0;
113 }
114 
115 static void *FTPCalloc(size_t n, size_t size)
116 {
117  if (FTPCheckMemcap((uint32_t)(n * size)) == 0) {
119  return NULL;
120  }
121 
122  void *ptr = SCCalloc(n, size);
123 
124  if (unlikely(ptr == NULL)) {
126  return NULL;
127  }
128 
129  FTPIncrMemuse((uint64_t)(n * size));
130  return ptr;
131 }
132 
133 static void *FTPRealloc(void *ptr, size_t orig_size, size_t size)
134 {
135  if (FTPCheckMemcap((uint32_t)(size - orig_size)) == 0) {
137  return NULL;
138  }
139 
140  void *rptr = SCRealloc(ptr, size);
141  if (rptr == NULL) {
143  return NULL;
144  }
145 
146  if (size > orig_size) {
147  FTPIncrMemuse(size - orig_size);
148  } else {
149  FTPDecrMemuse(orig_size - size);
150  }
151 
152  return rptr;
153 }
154 
155 static void FTPFree(void *ptr, size_t size)
156 {
157  SCFree(ptr);
158 
159  FTPDecrMemuse((uint64_t)size);
160 }
161 
162 static FTPResponseWrapper *FTPResponseWrapperAlloc(FTPResponseLine *response)
163 {
164  FTPResponseWrapper *wrapper = FTPCalloc(1, sizeof(FTPResponseWrapper));
165  if (likely(wrapper)) {
166  FTPIncrMemuse(response->total_size);
167  wrapper->response = response;
168  }
169  return wrapper;
170 }
171 
172 static void FTPResponseWrapperFree(FTPResponseWrapper *wrapper)
173 {
174  if (wrapper->response) {
175  FTPDecrMemuse(wrapper->response->total_size);
176  SCFTPFreeResponseLine(wrapper->response);
177  }
178 
179  FTPFree(wrapper, sizeof(FTPResponseWrapper));
180 }
181 
182 static void *FTPLocalStorageAlloc(void)
183 {
184  /* needed by the mpm */
185  FTPThreadCtx *td = SCCalloc(1, sizeof(*td));
186  if (td == NULL) {
187  exit(EXIT_FAILURE);
188  }
189 
190  td->pmq = SCCalloc(1, sizeof(*td->pmq));
191  if (td->pmq == NULL) {
192  exit(EXIT_FAILURE);
193  }
194  PmqSetup(td->pmq);
195 
196  td->ftp_mpm_thread_ctx = SCCalloc(1, sizeof(MpmThreadCtx));
197  if (unlikely(td->ftp_mpm_thread_ctx == NULL)) {
198  exit(EXIT_FAILURE);
199  }
200  MpmInitThreadCtx(td->ftp_mpm_thread_ctx, ftp_mpm_ctx, FTP_MPM);
201  return td;
202 }
203 
204 static void FTPLocalStorageFree(void *ptr)
205 {
206  FTPThreadCtx *td = ptr;
207  if (td != NULL) {
208  if (td->pmq != NULL) {
209  PmqFree(td->pmq);
210  SCFree(td->pmq);
211  }
212 
213  if (td->ftp_mpm_thread_ctx != NULL) {
216  }
217 
218  SCFree(td);
219  }
220 }
221 static FTPTransaction *FTPTransactionCreate(FtpState *state)
222 {
223  SCEnter();
224  FTPTransaction *firsttx = TAILQ_FIRST(&state->tx_list);
225  if (firsttx && state->tx_cnt - firsttx->tx_id > ftp_config_maxtx) {
226  FTPTransaction *tx_old;
227  TAILQ_FOREACH (tx_old, &state->tx_list, next) {
228  if (!tx_old->done) {
229  tx_old->done = true;
230  tx_old->tx_data.updated_ts = true;
231  tx_old->tx_data.updated_tc = true;
233  &tx_old->tx_data.events, FtpEventTooManyTransactions);
234  break;
235  }
236  }
237  return NULL;
238  }
239  FTPTransaction *tx = FTPCalloc(1, sizeof(*tx));
240  if (tx == NULL) {
241  return NULL;
242  }
243 
244  TAILQ_INSERT_TAIL(&state->tx_list, tx, next);
245  tx->tx_id = state->tx_cnt++;
246 
247  TAILQ_INIT(&tx->response_list);
248 
249  SCLogDebug("new transaction %p (state tx cnt %"PRIu64")", tx, state->tx_cnt);
250  return tx;
251 }
252 
253 static void FTPTransactionFree(FTPTransaction *tx)
254 {
255  SCEnter();
256 
258 
259  if (tx->request) {
260  FTPFree(tx->request, tx->request_length);
261  }
262 
263  FTPResponseWrapper *wrapper;
264  while ((wrapper = TAILQ_FIRST(&tx->response_list))) {
265  TAILQ_REMOVE(&tx->response_list, wrapper, next);
266  FTPResponseWrapperFree(wrapper);
267  }
268 
269  FTPFree(tx, sizeof(*tx));
270 }
271 
272 typedef struct FtpInput_ {
273  const uint8_t *buf;
274  int32_t consumed;
275  int32_t len;
276  int32_t orig_len;
278 
279 static AppLayerResult FTPGetLineForDirection(
280  FtpLineState *line, FtpInput *input, bool *current_line_truncated)
281 {
282  SCEnter();
283 
284  /* we have run out of input */
285  if (input->len <= 0)
286  return APP_LAYER_ERROR;
287 
288  const uint8_t *lf_idx = memchr(input->buf + input->consumed, 0x0a, input->len);
289 
290  if (lf_idx == NULL) {
291  if (!(*current_line_truncated) && (uint32_t)input->len >= ftp_max_line_len) {
292  *current_line_truncated = true;
293  line->buf = input->buf;
294  line->len = ftp_max_line_len;
295  line->delim_len = 0;
296  input->len = 0;
298  }
299  SCReturnStruct(APP_LAYER_INCOMPLETE(input->consumed, input->len + 1));
300  } else if (*current_line_truncated) {
301  // Whatever came in with first LF should also get discarded
302  *current_line_truncated = false;
303  line->len = 0;
304  line->delim_len = 0;
305  input->len = 0;
307  } else {
308  // There could be one chunk of command data that has LF but post the line limit
309  // e.g. input_len = 5077
310  // lf_idx = 5010
311  // max_line_len = 4096
312  uint32_t o_consumed = input->consumed;
313  input->consumed = (uint32_t)(lf_idx - input->buf + 1);
314  line->len = input->consumed - o_consumed;
315  input->len -= line->len;
316  line->lf_found = true;
317  DEBUG_VALIDATE_BUG_ON((input->consumed + input->len) != input->orig_len);
318  line->buf = input->buf + o_consumed;
319  if (line->len >= ftp_max_line_len) {
320  *current_line_truncated = true;
321  line->len = ftp_max_line_len;
323  }
324  if (input->consumed >= 2 && input->buf[input->consumed - 2] == 0x0D) {
325  line->delim_len = 2;
326  line->len -= 2;
327  } else {
328  line->delim_len = 1;
329  line->len -= 1;
330  }
332  }
333 }
334 
335 /**
336  * \brief This function is called to determine and set which command is being
337  * transferred to the ftp server
338  * \param thread context
339  * \param input input line of the command
340  * \param len of the command
341  * \param cmd_descriptor when the command has been parsed
342  *
343  * \retval 1 when the command is parsed, 0 otherwise
344  */
345 static int FTPParseRequestCommand(
346  FTPThreadCtx *td, FtpLineState *line, FtpCommandInfo *cmd_descriptor)
347 {
348  SCEnter();
349 
350  /* I don't like this pmq reset here. We'll devise a method later, that
351  * should make the use of the mpm very efficient */
352  PmqReset(td->pmq);
353  int mpm_cnt = mpm_table[FTP_MPM].Search(
354  ftp_mpm_ctx, td->ftp_mpm_thread_ctx, td->pmq, line->buf, line->len);
355  if (mpm_cnt) {
356  uint8_t command_code;
357  if (SCGetFtpCommandInfo(td->pmq->rule_id_array[0], NULL, &command_code, NULL)) {
358  cmd_descriptor->command_code = command_code;
359  /* FTP command indices are expressed in Rust as a u8 */
360  cmd_descriptor->command_index = (uint8_t)td->pmq->rule_id_array[0];
361  SCReturnInt(1);
362  } else {
363  /* Where is out command? */
365  }
366 #ifdef DEBUG
367  if (SCLogDebugEnabled()) {
368  const char *command_name = NULL;
369  (void)SCGetFtpCommandInfo(td->pmq->rule_id_array[0], &command_name, NULL, NULL);
370  SCLogDebug("matching FTP command is %s [code: %d, index %d]", command_name,
371  command_code, td->pmq->rule_id_array[0]);
372  }
373 #endif
374  }
375 
376  cmd_descriptor->command_code = FTP_COMMAND_UNKNOWN;
377  SCReturnInt(0);
378 }
379 
380 static void FtpTransferCmdFree(void *data)
381 {
382  FtpTransferCmd *cmd = (FtpTransferCmd *)data;
383  if (cmd == NULL)
384  return;
385  if (cmd->file_name) {
386  FTPFree((void *)cmd->file_name, cmd->file_len + 1);
387  }
388  SCFTPTransferCmdFree(cmd);
389  FTPDecrMemuse((uint64_t)sizeof(FtpTransferCmd));
390 }
391 
392 static uint32_t CopyCommandLine(uint8_t **dest, FtpLineState *line)
393 {
394  if (likely(line->len)) {
395  uint8_t *where = FTPCalloc(line->len + 1, sizeof(char));
396  if (unlikely(where == NULL)) {
397  return 0;
398  }
399  memcpy(where, line->buf, line->len);
400 
401  /* Remove trailing newlines/carriage returns */
402  while (line->len && isspace((unsigned char)where[line->len - 1])) {
403  line->len--;
404  }
405 
406  where[line->len] = '\0';
407  *dest = where;
408  }
409  /* either 0 or actual */
410  return line->len ? line->len + 1 : 0;
411 }
412 
413 #include "util-print.h"
414 
415 /**
416  * \brief This function is called to retrieve a ftp request
417  * \param ftp_state the ftp state structure for the parser
418  *
419  * \retval APP_LAYER_OK when input was process successfully
420  * \retval APP_LAYER_ERROR when a unrecoverable error was encountered
421  */
422 static AppLayerResult FTPParseRequest(Flow *f, void *ftp_state, AppLayerParserState *pstate,
423  StreamSlice stream_slice, void *local_data)
424 {
425  FTPThreadCtx *thread_data = local_data;
426 
427  SCEnter();
428  /* PrintRawDataFp(stdout, input,input_len); */
429 
430  FtpState *state = (FtpState *)ftp_state;
431  void *ptmp;
432 
433  const uint8_t *input = StreamSliceGetData(&stream_slice);
434  uint32_t input_len = StreamSliceGetDataLen(&stream_slice);
435 
436  if (input == NULL && SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS)) {
438  } else if (input == NULL || input_len == 0) {
440  }
441 
442  FtpInput ftpi = { .buf = input, .len = input_len, .orig_len = input_len, .consumed = 0 };
443  FtpLineState line = { .buf = NULL, .len = 0, .delim_len = 0, .lf_found = false };
444 
445  uint8_t direction = STREAM_TOSERVER;
446  AppLayerResult res;
447  while (1) {
448  res = FTPGetLineForDirection(&line, &ftpi, &state->current_line_truncated_ts);
449  if (res.status == 1) {
450  return res;
451  } else if (res.status == -1) {
452  break;
453  }
454 
455  FtpCommandInfo cmd_descriptor;
456  if (!FTPParseRequestCommand(thread_data, &line, &cmd_descriptor)) {
457  state->command = FTP_COMMAND_UNKNOWN;
458  continue;
459  }
460 
461  state->command = cmd_descriptor.command_code;
462  FTPTransaction *tx = FTPTransactionCreate(state);
463  if (unlikely(tx == NULL))
465  tx->tx_data.updated_ts = true;
466  state->curr_tx = tx;
467 
468  tx->command_descriptor = cmd_descriptor;
469  tx->request_length = CopyCommandLine(&tx->request, &line);
471 
472  if (line.lf_found) {
473  state->current_line_truncated_ts = false;
474  }
475  if (tx->request_truncated) {
476  SCAppLayerDecoderEventsSetEventRaw(&tx->tx_data.events, FtpEventRequestCommandTooLong);
477  }
478 
479  /* change direction (default to server) so expectation will handle
480  * the correct message when expectation will match.
481  * For ftp active mode, data connection direction is opposite to
482  * control direction.
483  */
484  if ((state->active &&
485  (state->command == FTP_COMMAND_STOR || state->command == FTP_COMMAND_APPE ||
486  state->command == FTP_COMMAND_STOU)) ||
487  (!state->active &&
488  (state->command == FTP_COMMAND_RETR || state->command == FTP_COMMAND_NLST ||
489  state->command == FTP_COMMAND_LIST ||
490  state->command == FTP_COMMAND_MLSD))) {
491  direction = STREAM_TOCLIENT;
492  }
493 
494  bool has_file = false;
495 
496  switch (state->command) {
497  case FTP_COMMAND_EPRT:
498  // fallthrough
499  case FTP_COMMAND_PORT:
500  if (line.len + 1 > state->port_line_size) {
501  /* Allocate an extra byte for a NULL terminator */
502  ptmp = FTPRealloc(state->port_line, state->port_line_size, line.len + 1);
503  if (ptmp == NULL) {
504  if (state->port_line) {
505  FTPFree(state->port_line, state->port_line_size);
506  state->port_line = NULL;
507  state->port_line_size = 0;
508  state->port_line_len = 0;
509  }
511  }
512  state->port_line = ptmp;
513  state->port_line_size = line.len + 1;
514  }
515  memcpy(state->port_line, line.buf, line.len);
516  state->port_line_len = line.len;
517  break;
518  case FTP_COMMAND_RETR:
519  // fallthrough
520  case FTP_COMMAND_STOR:
521  // fallthrough
522  case FTP_COMMAND_APPE:
523  /* Ensure that there is a file name
524  * -- need more than 5 chars: cmd [4], space, <filename>
525  */
526  if (line.len < 6) {
528  &tx->tx_data.events, FtpEventFileWithoutName);
529  break;
530  }
531  has_file = true;
532  /* fallthrough */
533  case FTP_COMMAND_STOU:
534  if (line.len >= 6) {
535  has_file = true;
536  }
537  /* fallthrough */
538  case FTP_COMMAND_NLST:
539  case FTP_COMMAND_LIST:
540  case FTP_COMMAND_MLSD: {
541  /* Ensure a port has been negotiated. */
542  if (state->dyn_port == 0) {
543  SCAppLayerDecoderEventsSetEventRaw(&tx->tx_data.events, FtpEventFileBeforePort);
544  break;
545  }
546 
547  FtpTransferCmd *data = SCFTPTransferCmdNew();
548  if (data == NULL)
550  FTPIncrMemuse((uint64_t)(sizeof *data));
551  data->cmd = state->command;
552  data->flow_id = FlowGetId(f);
553  data->direction = direction;
554  data->data_free = FtpTransferCmdFree;
555 
556  /*
557  * Min size has been checked in FTPParseRequestCommand
558  * SC_FILENAME_MAX includes the null
559  */
560  if (has_file) {
561  uint32_t file_name_len = MIN(SC_FILENAME_MAX - 1, line.len - 5);
562 #if SC_FILENAME_MAX > UINT16_MAX
563 #error SC_FILENAME_MAX is greater than UINT16_MAX
564 #endif
565  data->file_name = FTPCalloc(file_name_len + 1, sizeof(char));
566  if (data->file_name == NULL) {
567  FtpTransferCmdFree(data);
569  }
570  data->file_name[file_name_len] = 0;
571  data->file_len = (uint16_t)file_name_len;
572  memcpy(data->file_name, line.buf + 5, file_name_len);
573  } else if (state->command == FTP_COMMAND_STOU) {
574  const char default_file_name[] = "<stou>";
575  uint32_t file_name_len = sizeof(default_file_name);
576  data->file_name = FTPCalloc(file_name_len, sizeof(char));
577  if (data->file_name == NULL) {
578  FtpTransferCmdFree(data);
580  }
581  data->file_name[file_name_len - 1] = 0;
582  data->file_len = (uint16_t)file_name_len - 1;
583  memcpy(data->file_name, default_file_name, file_name_len);
584  }
585  int ret = AppLayerExpectationCreate(
586  f, direction, 0, state->dyn_port, ALPROTO_FTPDATA, data);
587  if (ret == -1) {
588  FtpTransferCmdFree(data);
589  SCLogDebug("No expectation created.");
591  } else {
592  SCLogDebug("Expectation created [direction: %s, dynamic port %" PRIu16 "].",
593  state->active ? "to server" : "to client", state->dyn_port);
594  }
595 
596  /* reset the dyn port to avoid duplicate */
597  state->dyn_port = 0;
598  /* reset active/passive indicator */
599  state->active = false;
600 
601  break;
602  }
603  default:
604  break;
605  }
606  if (line.len >= ftp_max_line_len) {
607  ftpi.consumed = ftpi.len + 1;
608  break;
609  }
610  SCAppLayerParserTriggerRawStreamInspection(f, STREAM_TOSERVER);
611  }
612 
614 }
615 
616 static int FTPParsePassiveResponse(FtpState *state, const uint8_t *input, uint32_t input_len)
617 {
618  uint16_t dyn_port = SCFTPParsePortPasv(input, input_len);
619  if (dyn_port == 0) {
620  return -1;
621  }
622  SCLogDebug("FTP passive mode (v4): dynamic port %"PRIu16"", dyn_port);
623  state->active = false;
624  state->dyn_port = dyn_port;
625  state->curr_tx->dyn_port = dyn_port;
626  state->curr_tx->active = false;
627 
628  return 0;
629 }
630 
631 static int FTPParsePassiveResponseV6(FtpState *state, const uint8_t *input, uint32_t input_len)
632 {
633  uint16_t dyn_port = SCFTPParsePortEpsv(input, input_len);
634  if (dyn_port == 0) {
635  return -1;
636  }
637  SCLogDebug("FTP passive mode (v6): dynamic port %"PRIu16"", dyn_port);
638  state->active = false;
639  state->dyn_port = dyn_port;
640  state->curr_tx->dyn_port = dyn_port;
641  state->curr_tx->active = false;
642  return 0;
643 }
644 
645 /**
646  * \brief Handle preliminary replies -- keep tx open
647  * \retval bool True for a positive preliminary reply; false otherwise
648  *
649  * 1yz Positive Preliminary reply
650  *
651  * The requested action is being initiated; expect another
652  * reply before proceeding with a new command
653  */
654 static inline bool FTPIsPPR(const uint8_t *input, uint32_t input_len)
655 {
656  return input_len >= 4 && isdigit(input[0]) && input[0] == '1' &&
657  isdigit(input[1]) && isdigit(input[2]) && isspace(input[3]);
658 }
659 
660 /**
661  * \brief This function is called to retrieve a ftp response
662  * \param ftp_state the ftp state structure for the parser
663  * \param input input line of the command
664  * \param input_len length of the request
665  * \param output the resulting output
666  *
667  * \retval 1 when the command is parsed, 0 otherwise
668  */
669 static AppLayerResult FTPParseResponse(Flow *f, void *ftp_state, AppLayerParserState *pstate,
670  StreamSlice stream_slice, void *local_data)
671 {
672  FtpState *state = (FtpState *)ftp_state;
673 
674  const uint8_t *input = StreamSliceGetData(&stream_slice);
675  uint32_t input_len = StreamSliceGetDataLen(&stream_slice);
676 
677  if (unlikely(input_len == 0)) {
679  }
680  FtpInput ftpi = { .buf = input, .len = input_len, .orig_len = input_len, .consumed = 0 };
681  FtpLineState line = { .buf = NULL, .len = 0, .delim_len = 0, .lf_found = false };
682 
683  FTPTransaction *lasttx = TAILQ_FIRST(&state->tx_list);
684  AppLayerResult res;
685  while (1) {
686  res = FTPGetLineForDirection(&line, &ftpi, &state->current_line_truncated_tc);
687  if (res.status == 1) {
688  return res;
689  } else if (res.status == -1) {
690  break;
691  }
692  FTPTransaction *tx = FTPGetOldestTx(state, lasttx);
693  if (tx == NULL) {
694  tx = FTPTransactionCreate(state);
695  if (tx != NULL) {
696  /* This is a TC only transaction, skip TS inspection. */
697  tx->tx_data.flags |= APP_LAYER_TX_SKIP_INSPECT_TS;
698  }
699  }
700  if (unlikely(tx == NULL)) {
702  }
703  lasttx = tx;
704  tx->tx_data.updated_tc = true;
705  if (state->command == FTP_COMMAND_UNKNOWN) {
706  /* unknown */
707  tx->command_descriptor.command_code = FTP_COMMAND_UNKNOWN;
708  }
709 
710  state->curr_tx = tx;
711  uint16_t dyn_port;
712  switch (state->command) {
713  case FTP_COMMAND_AUTH_TLS:
714  if (line.len >= 4 && SCMemcmp("234 ", line.buf, 4) == 0) {
716  }
717  break;
718 
719  case FTP_COMMAND_EPRT:
720  dyn_port = SCFTPParsePortEprt(state->port_line, state->port_line_len);
721  if (dyn_port == 0) {
722  goto tx_complete;
723  }
724  state->dyn_port = dyn_port;
725  state->active = true;
726  tx->dyn_port = dyn_port;
727  tx->active = true;
728  SCLogDebug("FTP active mode (v6): dynamic port %" PRIu16 "", dyn_port);
729  break;
730 
731  case FTP_COMMAND_PORT:
732  dyn_port = SCFTPParsePort(state->port_line, state->port_line_len);
733  if (dyn_port == 0) {
734  goto tx_complete;
735  }
736  state->dyn_port = dyn_port;
737  state->active = true;
738  tx->dyn_port = state->dyn_port;
739  tx->active = true;
740  SCLogDebug("FTP active mode (v4): dynamic port %" PRIu16 "", dyn_port);
741  break;
742 
743  case FTP_COMMAND_PASV:
744  if (line.len >= 4 && SCMemcmp("227 ", line.buf, 4) == 0) {
745  FTPParsePassiveResponse(ftp_state, line.buf, line.len);
746  }
747  break;
748 
749  case FTP_COMMAND_EPSV:
750  if (line.len >= 4 && SCMemcmp("229 ", line.buf, 4) == 0) {
751  FTPParsePassiveResponseV6(ftp_state, line.buf, line.len);
752  }
753  break;
754  default:
755  break;
756  }
757 
758  if (likely(line.len)) {
759  FTPResponseLine *response = SCFTPParseResponseLine((const char *)line.buf, line.len);
760  if (likely(response)) {
761  FTPResponseWrapper *wrapper = FTPResponseWrapperAlloc(response);
762  if (likely(wrapper)) {
763  response->truncated = state->current_line_truncated_tc;
764  if (response->truncated) {
766  &tx->tx_data.events, FtpEventResponseCommandTooLong);
767  }
768  if (line.lf_found) {
769  state->current_line_truncated_tc = false;
770  }
771  TAILQ_INSERT_TAIL(&tx->response_list, wrapper, next);
772  } else {
773  SCFTPFreeResponseLine(response);
774  }
775  } else {
776  SCLogDebug("unable to parse FTP response line \"%s\"", line.buf);
777  }
778  }
779 
780  /* Handle preliminary replies -- keep tx open */
781  if (FTPIsPPR(line.buf, line.len)) {
782  continue;
783  }
784  tx_complete:
785  tx->done = true;
786  SCAppLayerParserTriggerRawStreamInspection(f, STREAM_TOCLIENT);
787 
788  if (line.len >= ftp_max_line_len) {
789  ftpi.consumed = ftpi.len + 1;
790  break;
791  }
792  }
793 
795 }
796 
797 
798 #ifdef DEBUG
799 static SCMutex ftp_state_mem_lock = SCMUTEX_INITIALIZER;
800 static uint64_t ftp_state_memuse = 0;
801 static uint64_t ftp_state_memcnt = 0;
802 #endif
803 
804 static void *FTPStateAlloc(void *orig_state, AppProto proto_orig)
805 {
806  void *s = FTPCalloc(1, sizeof(FtpState));
807  if (unlikely(s == NULL))
808  return NULL;
809 
810  FtpState *ftp_state = (FtpState *) s;
811  TAILQ_INIT(&ftp_state->tx_list);
812 
813 #ifdef DEBUG
814  SCMutexLock(&ftp_state_mem_lock);
815  ftp_state_memcnt++;
816  ftp_state_memuse+=sizeof(FtpState);
817  SCMutexUnlock(&ftp_state_mem_lock);
818 #endif
819  return s;
820 }
821 
822 static void FTPStateFree(void *s)
823 {
824  FtpState *fstate = (FtpState *) s;
825  if (fstate->port_line != NULL)
826  FTPFree(fstate->port_line, fstate->port_line_size);
827 
828  FTPTransaction *tx = NULL;
829  while ((tx = TAILQ_FIRST(&fstate->tx_list))) {
830  TAILQ_REMOVE(&fstate->tx_list, tx, next);
831 #ifdef DEBUG
832  if (SCLogDebugEnabled()) {
833  const char *command_name = NULL;
834  (void)SCGetFtpCommandInfo(
835  tx->command_descriptor.command_index, &command_name, NULL, NULL);
836  SCLogDebug("[%s] state %p id %" PRIu64 ", Freeing %d bytes at %p",
837  command_name != NULL ? command_name : "n/a", s, tx->tx_id, tx->request_length,
838  tx->request);
839  }
840 #endif
841 
842  FTPTransactionFree(tx);
843  }
844 
845  FTPFree(s, sizeof(FtpState));
846 #ifdef DEBUG
847  SCMutexLock(&ftp_state_mem_lock);
848  ftp_state_memcnt--;
849  ftp_state_memuse-=sizeof(FtpState);
850  SCMutexUnlock(&ftp_state_mem_lock);
851 #endif
852 }
853 
854 /**
855  * \brief This function returns the oldest open transaction; if none
856  * are open, then the oldest transaction is returned
857  * \param ftp_state the ftp state structure for the parser
858  * \param starttx the ftp transaction where to start looking
859  *
860  * \retval transaction pointer when a transaction was found; NULL otherwise.
861  */
862 static FTPTransaction *FTPGetOldestTx(const FtpState *ftp_state, FTPTransaction *starttx)
863 {
864  if (unlikely(!ftp_state)) {
865  SCLogDebug("NULL state object; no transactions available");
866  return NULL;
867  }
868  FTPTransaction *tx = starttx;
869  FTPTransaction *lasttx = NULL;
870  while(tx != NULL) {
871  /* Return oldest open tx */
872  if (!tx->done) {
873  SCLogDebug("Returning tx %p id %"PRIu64, tx, tx->tx_id);
874  return tx;
875  }
876  /* save for the end */
877  lasttx = tx;
878  tx = TAILQ_NEXT(tx, next);
879  }
880  /* All tx are closed; return last element */
881  if (lasttx)
882  SCLogDebug("Returning OLDEST tx %p id %"PRIu64, lasttx, lasttx->tx_id);
883  return lasttx;
884 }
885 
886 static void *FTPGetTx(void *state, uint64_t tx_id)
887 {
888  FtpState *ftp_state = (FtpState *)state;
889  if (ftp_state) {
890  FTPTransaction *tx = NULL;
891 
892  if (ftp_state->curr_tx == NULL)
893  return NULL;
894  if (ftp_state->curr_tx->tx_id == tx_id)
895  return ftp_state->curr_tx;
896 
897  TAILQ_FOREACH(tx, &ftp_state->tx_list, next) {
898  if (tx->tx_id == tx_id)
899  return tx;
900  }
901  }
902  return NULL;
903 }
904 
905 static AppLayerTxData *FTPGetTxData(void *vtx)
906 {
907  FTPTransaction *tx = (FTPTransaction *)vtx;
908  return &tx->tx_data;
909 }
910 
911 static AppLayerStateData *FTPGetStateData(void *vstate)
912 {
913  FtpState *s = (FtpState *)vstate;
914  return &s->state_data;
915 }
916 
917 static void FTPStateTransactionFree(void *state, uint64_t tx_id)
918 {
919  FtpState *ftp_state = state;
920  FTPTransaction *tx = NULL;
921  TAILQ_FOREACH(tx, &ftp_state->tx_list, next) {
922  if (tx_id < tx->tx_id)
923  break;
924  else if (tx_id > tx->tx_id)
925  continue;
926 
927  if (tx == ftp_state->curr_tx)
928  ftp_state->curr_tx = NULL;
929  TAILQ_REMOVE(&ftp_state->tx_list, tx, next);
930  FTPTransactionFree(tx);
931  break;
932  }
933 }
934 
935 static uint64_t FTPGetTxCnt(void *state)
936 {
937  uint64_t cnt = 0;
938  FtpState *ftp_state = state;
939  if (ftp_state) {
940  cnt = ftp_state->tx_cnt;
941  }
942  SCLogDebug("returning state %p %"PRIu64, state, cnt);
943  return cnt;
944 }
945 
946 static int FTPGetAlstateProgress(void *vtx, uint8_t direction)
947 {
948  SCLogDebug("tx %p", vtx);
949  FTPTransaction *tx = vtx;
950 
951  /* having a tx implies request side is done */
952  if (direction == STREAM_TOSERVER) {
953  return FTP_STATE_FINISHED;
954  }
955  if (!tx->done) {
956  return FTP_STATE_IN_PROGRESS;
957  }
958 
959  return FTP_STATE_FINISHED;
960 }
961 
962 static AppProto FTPUserProbingParser(
963  const Flow *f, uint8_t direction, const uint8_t *input, uint32_t len, uint8_t *rdir)
964 {
965  if (f->alproto_tc == ALPROTO_POP3) {
966  // POP traffic begins by same "USER" pattern as FTP
967  return ALPROTO_FAILED;
968  }
969  return ALPROTO_FTP;
970 }
971 
972 static AppProto FTPQuitProbingParser(
973  const Flow *f, uint8_t direction, const uint8_t *input, uint32_t len, uint8_t *rdir)
974 {
975  // another check for minimum length
976  if (len < 5) {
977  return ALPROTO_UNKNOWN;
978  }
979  // begins by QUIT
980  if (SCMemcmp(input, "QUIT", 4) != 0) {
981  return ALPROTO_FAILED;
982  }
983  return ALPROTO_FTP;
984 }
985 
986 static AppProto FTPServerProbingParser(
987  const Flow *f, uint8_t direction, const uint8_t *input, uint32_t len, uint8_t *rdir)
988 {
989  // another check for minimum length
990  if (len < 5) {
991  return ALPROTO_UNKNOWN;
992  }
993  // begins by 220
994  if (input[0] != '2' || input[1] != '2' || input[2] != '0') {
995  return ALPROTO_FAILED;
996  }
997  // followed by space or hypen
998  if (input[3] != ' ' && input[3] != '-') {
999  return ALPROTO_FAILED;
1000  }
1001  if (f->alproto_ts == ALPROTO_FTP || (f->todstbytecnt > 4 && f->alproto_ts == ALPROTO_UNKNOWN)) {
1002  // only validates FTP if client side was FTP
1003  // or if client side is unknown despite having received bytes
1004  if (memchr(input + 4, '\n', len - 4) != NULL) {
1005  return ALPROTO_FTP;
1006  }
1007  }
1008  return ALPROTO_UNKNOWN;
1009 }
1010 
1011 static int FTPRegisterPatternsForProtocolDetection(void)
1012 {
1014  IPPROTO_TCP, ALPROTO_FTP, "220 (", 5, 0, STREAM_TOCLIENT) < 0) {
1015  return -1;
1016  }
1018  IPPROTO_TCP, ALPROTO_FTP, "FEAT", 4, 0, STREAM_TOSERVER) < 0) {
1019  return -1;
1020  }
1021  if (SCAppLayerProtoDetectPMRegisterPatternCSwPP(IPPROTO_TCP, ALPROTO_FTP, "USER ", 5, 0,
1022  STREAM_TOSERVER, FTPUserProbingParser, 5, 5) < 0) {
1023  return -1;
1024  }
1025 
1027  IPPROTO_TCP, ALPROTO_FTP, "PORT ", 5, 0, STREAM_TOSERVER) < 0) {
1028  return -1;
1029  }
1030  // Only check FTP on known ports as the banner has nothing special beyond
1031  // the response code shared with SMTP.
1033  "tcp", IPPROTO_TCP, "ftp", ALPROTO_FTP, 0, 5, NULL, FTPServerProbingParser)) {
1034  // STREAM_TOSERVER here means use 21 as flow destination port
1035  // and FTPServerProbingParser is probing parser to client
1036  SCAppLayerProtoDetectPPRegister(IPPROTO_TCP, "21", ALPROTO_FTP, 0, 5, STREAM_TOSERVER,
1037  FTPQuitProbingParser, FTPServerProbingParser);
1038  }
1039  return 0;
1040 }
1041 
1042 
1044 
1045 /**
1046  * \brief This function is called to retrieve a ftp request
1047  * \param ftp_state the ftp state structure for the parser
1048  * \param output the resulting output
1049  *
1050  * \retval 1 when the command is parsed, 0 otherwise
1051  */
1052 static AppLayerResult FTPDataParse(Flow *f, FtpDataState *ftpdata_state,
1053  AppLayerParserState *pstate, StreamSlice stream_slice, void *local_data, uint8_t direction)
1054 {
1055  const uint8_t *input = StreamSliceGetData(&stream_slice);
1056  uint32_t input_len = StreamSliceGetDataLen(&stream_slice);
1057  const bool eof = (direction & STREAM_TOSERVER)
1058  ? SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) != 0
1059  : SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC) != 0;
1060 
1061  SCTxDataUpdateFileFlags(&ftpdata_state->tx_data, ftpdata_state->state_data.file_flags);
1062  if (ftpdata_state->tx_data.file_tx == 0)
1063  ftpdata_state->tx_data.file_tx = direction & (STREAM_TOSERVER | STREAM_TOCLIENT);
1064  if (direction & STREAM_TOSERVER) {
1065  ftpdata_state->tx_data.updated_ts = true;
1066  } else {
1067  ftpdata_state->tx_data.updated_tc = true;
1068  }
1069  /* we depend on detection engine for file pruning */
1070  const uint16_t flags = SCFileFlowFlagsToFlags(ftpdata_state->tx_data.file_flags, direction);
1071  int ret = 0;
1072 
1073  SCLogDebug("FTP-DATA input_len %u flags %04x dir %d/%s EOF %s", input_len, flags, direction,
1074  (direction & STREAM_TOSERVER) ? "toserver" : "toclient", eof ? "true" : "false");
1075 
1076  SCLogDebug("FTP-DATA flags %04x dir %d", flags, direction);
1077  if (!ftpdata_state->initialized && input_len) {
1078  FtpTransferCmd *data =
1079  (FtpTransferCmd *)SCFlowGetStorageById(f, AppLayerExpectationGetFlowId());
1080  if (data == NULL) {
1082  }
1083 
1084  /* we shouldn't get data in the wrong dir. Don't set things up for this dir */
1085  if ((direction & data->direction) == 0) {
1086  // TODO set event for data in wrong direction
1087  SCLogDebug("input %u not for our direction (%s): %s/%s", input_len,
1088  (direction & STREAM_TOSERVER) ? "toserver" : "toclient",
1089  data->cmd == FTP_COMMAND_STOR ? "STOR" : "RETR",
1090  (data->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1092  }
1093 
1094  if (data->file_name) {
1095  ftpdata_state->files = FileContainerAlloc();
1096  if (ftpdata_state->files == NULL) {
1099  }
1100 
1101  ftpdata_state->file_name = data->file_name;
1102  ftpdata_state->file_len = data->file_len;
1103  data->file_name = NULL;
1104  data->file_len = 0;
1105  }
1106  f->parent_id = data->flow_id;
1107  ftpdata_state->command = data->cmd;
1108  switch (data->cmd) {
1109  case FTP_COMMAND_STOR:
1110  ftpdata_state->direction = data->direction;
1111  SCLogDebug("STOR data to %s",
1112  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1113  break;
1114  case FTP_COMMAND_APPE:
1115  ftpdata_state->direction = data->direction;
1116  SCLogDebug("APPE data to %s",
1117  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1118  break;
1119  case FTP_COMMAND_STOU:
1120  ftpdata_state->direction = data->direction;
1121  SCLogDebug("STOU data to %s",
1122  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1123  break;
1124  case FTP_COMMAND_RETR:
1125  ftpdata_state->direction = data->direction;
1126  SCLogDebug("RETR data to %s",
1127  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1128  break;
1129  case FTP_COMMAND_NLST:
1130  ftpdata_state->direction = data->direction;
1131  SCLogDebug("NLST data to %s",
1132  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1133  break;
1134  case FTP_COMMAND_LIST:
1135  ftpdata_state->direction = data->direction;
1136  SCLogDebug("LIST data to %s",
1137  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1138  break;
1139  case FTP_COMMAND_MLSD:
1140  ftpdata_state->direction = data->direction;
1141  SCLogDebug("MLSD data to %s",
1142  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1143  break;
1144  default:
1145  break;
1146  }
1147 
1148  if (ftpdata_state->file_name) {
1149  /* open with fixed track_id 0 as we can have just one
1150  * file per ftp-data flow. */
1151  if (FileOpenFileWithId(ftpdata_state->files, &sbcfg, 0ULL,
1152  (uint8_t *)ftpdata_state->file_name, ftpdata_state->file_len, input,
1153  input_len, flags) != 0) {
1154  SCLogDebug("Can't open file");
1155  ret = -1;
1156  }
1157  ftpdata_state->tx_data.files_opened = 1;
1158  }
1160 
1161  ftpdata_state->initialized = true;
1162  } else {
1163  if ((direction & ftpdata_state->direction) == 0) {
1164  if (input_len) {
1165  // TODO set event for data in wrong direction
1166  }
1167  SCLogDebug("input %u not for us (%s): %s/%s", input_len,
1168  (direction & STREAM_TOSERVER) ? "toserver" : "toclient",
1169  ftpdata_state->command == FTP_COMMAND_STOR ? "STOR" : "RETR",
1170  (ftpdata_state->direction & STREAM_TOSERVER) ? "toserver" : "toclient");
1172  }
1173  if (ftpdata_state->state == FTPDATA_STATE_FINISHED) {
1174  SCLogDebug("state is already finished");
1175  DEBUG_VALIDATE_BUG_ON(input_len); // data after state finished is a bug.
1177  }
1178  if (ftpdata_state->file_name && input_len != 0) {
1179  ret = FileAppendData(ftpdata_state->files, &sbcfg, input, input_len);
1180  if (ret == -2) {
1181  ret = 0;
1182  SCLogDebug("FileAppendData() - file no longer being extracted");
1183  goto out;
1184  } else if (ret < 0) {
1185  SCLogDebug("FileAppendData() failed: %d", ret);
1186  ret = -2;
1187  goto out;
1188  }
1189  }
1190  }
1191 
1192  DEBUG_VALIDATE_BUG_ON((direction & ftpdata_state->direction) == 0); // should be unreachable
1193  if (eof) {
1194  if (ftpdata_state->file_name) {
1195  ret = FileCloseFile(ftpdata_state->files, &sbcfg, NULL, 0, flags);
1196  }
1197  ftpdata_state->state = FTPDATA_STATE_FINISHED;
1198  SCLogDebug("closed because of eof: state now FTPDATA_STATE_FINISHED");
1199  }
1200 out:
1201  if (ret < 0) {
1203  }
1205 }
1206 
1207 static AppLayerResult FTPDataParseRequest(Flow *f, void *ftp_state, AppLayerParserState *pstate,
1208  StreamSlice stream_slice, void *local_data)
1209 {
1210  return FTPDataParse(f, ftp_state, pstate, stream_slice, local_data, STREAM_TOSERVER);
1211 }
1212 
1213 static AppLayerResult FTPDataParseResponse(Flow *f, void *ftp_state, AppLayerParserState *pstate,
1214  StreamSlice stream_slice, void *local_data)
1215 {
1216  return FTPDataParse(f, ftp_state, pstate, stream_slice, local_data, STREAM_TOCLIENT);
1217 }
1218 
1219 #ifdef DEBUG
1220 static SCMutex ftpdata_state_mem_lock = SCMUTEX_INITIALIZER;
1221 static uint64_t ftpdata_state_memuse = 0;
1222 static uint64_t ftpdata_state_memcnt = 0;
1223 #endif
1224 
1225 static void *FTPDataStateAlloc(void *orig_state, AppProto proto_orig)
1226 {
1227  void *s = FTPCalloc(1, sizeof(FtpDataState));
1228  if (unlikely(s == NULL))
1229  return NULL;
1230 
1231  FtpDataState *state = (FtpDataState *) s;
1232  state->state = FTPDATA_STATE_IN_PROGRESS;
1233 
1234 #ifdef DEBUG
1235  SCMutexLock(&ftpdata_state_mem_lock);
1236  ftpdata_state_memcnt++;
1237  ftpdata_state_memuse+=sizeof(FtpDataState);
1238  SCMutexUnlock(&ftpdata_state_mem_lock);
1239 #endif
1240  return s;
1241 }
1242 
1243 static void FTPDataStateFree(void *s)
1244 {
1245  FtpDataState *fstate = (FtpDataState *) s;
1246 
1247  SCAppLayerTxDataCleanup(&fstate->tx_data);
1248 
1249  if (fstate->file_name != NULL) {
1250  FTPFree(fstate->file_name, fstate->file_len + 1);
1251  }
1252 
1253  FileContainerFree(fstate->files, &sbcfg);
1254 
1255  FTPFree(s, sizeof(FtpDataState));
1256 #ifdef DEBUG
1257  SCMutexLock(&ftpdata_state_mem_lock);
1258  ftpdata_state_memcnt--;
1259  ftpdata_state_memuse-=sizeof(FtpDataState);
1260  SCMutexUnlock(&ftpdata_state_mem_lock);
1261 #endif
1262 }
1263 
1264 static AppLayerTxData *FTPDataGetTxData(void *vtx)
1265 {
1266  FtpDataState *ftp_state = (FtpDataState *)vtx;
1267  return &ftp_state->tx_data;
1268 }
1269 
1270 static AppLayerStateData *FTPDataGetStateData(void *vstate)
1271 {
1272  FtpDataState *ftp_state = (FtpDataState *)vstate;
1273  return &ftp_state->state_data;
1274 }
1275 
1276 static void FTPDataStateTransactionFree(void *state, uint64_t tx_id)
1277 {
1278  /* do nothing */
1279 }
1280 
1281 static void *FTPDataGetTx(void *state, uint64_t tx_id)
1282 {
1283  FtpDataState *ftp_state = (FtpDataState *)state;
1284  return ftp_state;
1285 }
1286 
1287 static uint64_t FTPDataGetTxCnt(void *state)
1288 {
1289  /* ftp-data is single tx */
1290  return 1;
1291 }
1292 
1293 static int FTPDataGetAlstateProgress(void *tx, uint8_t direction)
1294 {
1295  FtpDataState *ftpdata_state = (FtpDataState *)tx;
1296  if (direction == ftpdata_state->direction)
1297  return ftpdata_state->state;
1298  else
1299  return FTPDATA_STATE_FINISHED;
1300 }
1301 
1302 static AppLayerGetFileState FTPDataStateGetTxFiles(void *tx, uint8_t direction)
1303 {
1304  FtpDataState *ftpdata_state = (FtpDataState *)tx;
1305  AppLayerGetFileState files = { .fc = NULL, .cfg = &sbcfg };
1306 
1307  if (direction == ftpdata_state->direction)
1308  files.fc = ftpdata_state->files;
1309 
1310  return files;
1311 }
1312 
1313 static void FTPSetMpmState(void)
1314 {
1315  ftp_mpm_ctx = SCCalloc(1, sizeof(MpmCtx));
1316  if (unlikely(ftp_mpm_ctx == NULL)) {
1317  exit(EXIT_FAILURE);
1318  }
1319  MpmInitCtx(ftp_mpm_ctx, FTP_MPM);
1320 
1321  SCFTPSetMpmState(ftp_mpm_ctx);
1322  mpm_table[FTP_MPM].Prepare(NULL, ftp_mpm_ctx);
1323 }
1324 
1325 static void FTPFreeMpmState(void)
1326 {
1327  if (ftp_mpm_ctx != NULL) {
1328  mpm_table[FTP_MPM].DestroyCtx(ftp_mpm_ctx);
1329  SCFree(ftp_mpm_ctx);
1330  ftp_mpm_ctx = NULL;
1331  }
1332 }
1333 
1334 /** \brief FTP tx iterator, specialized for its linked list
1335  *
1336  * \retval txptr or NULL if no more txs in list
1337  */
1338 static AppLayerGetTxIterTuple FTPGetTxIterator(const uint8_t ipproto, const AppProto alproto,
1339  void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, AppLayerGetTxIterState *state)
1340 {
1341  FtpState *ftp_state = (FtpState *)alstate;
1342  AppLayerGetTxIterTuple no_tuple = { NULL, 0, false };
1343  if (ftp_state) {
1344  FTPTransaction *tx_ptr;
1345  if (state->un.ptr == NULL) {
1346  tx_ptr = TAILQ_FIRST(&ftp_state->tx_list);
1347  } else {
1348  tx_ptr = (FTPTransaction *)state->un.ptr;
1349  }
1350  if (tx_ptr) {
1351  while (tx_ptr->tx_id < min_tx_id) {
1352  tx_ptr = TAILQ_NEXT(tx_ptr, next);
1353  if (!tx_ptr) {
1354  return no_tuple;
1355  }
1356  }
1357  if (tx_ptr->tx_id >= max_tx_id) {
1358  return no_tuple;
1359  }
1360  state->un.ptr = TAILQ_NEXT(tx_ptr, next);
1361  AppLayerGetTxIterTuple tuple = {
1362  .tx_ptr = tx_ptr,
1363  .tx_id = tx_ptr->tx_id,
1364  .has_next = (state->un.ptr != NULL),
1365  };
1366  return tuple;
1367  }
1368  }
1369  return no_tuple;
1370 }
1371 
1373 {
1374  const char *proto_name = "ftp";
1375  const char *proto_data_name = "ftp-data";
1376 
1377  /** FTP */
1378  if (SCAppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) {
1380  if (FTPRegisterPatternsForProtocolDetection() < 0 )
1381  return;
1383  }
1384 
1385  if (SCAppLayerParserConfParserEnabled("tcp", proto_name)) {
1386  AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER,
1387  FTPParseRequest);
1388  AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOCLIENT,
1389  FTPParseResponse);
1390  AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_FTP, FTPStateAlloc, FTPStateFree);
1392  IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER | STREAM_TOCLIENT);
1393 
1394  AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_FTP, FTPStateTransactionFree);
1395 
1396  AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_FTP, FTPGetTx);
1397  AppLayerParserRegisterTxDataFunc(IPPROTO_TCP, ALPROTO_FTP, FTPGetTxData);
1398  AppLayerParserRegisterGetTxIterator(IPPROTO_TCP, ALPROTO_FTP, FTPGetTxIterator);
1399  AppLayerParserRegisterStateDataFunc(IPPROTO_TCP, ALPROTO_FTP, FTPGetStateData);
1400 
1401  AppLayerParserRegisterLocalStorageFunc(IPPROTO_TCP, ALPROTO_FTP, FTPLocalStorageAlloc,
1402  FTPLocalStorageFree);
1403  AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_FTP, FTPGetTxCnt);
1404 
1405  AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_FTP, FTPGetAlstateProgress);
1406 
1408  ALPROTO_FTP, FTP_STATE_FINISHED, FTP_STATE_FINISHED);
1409 
1411  AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER,
1412  FTPDataParseRequest);
1413  AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOCLIENT,
1414  FTPDataParseResponse);
1415  AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateAlloc, FTPDataStateFree);
1417  IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER | STREAM_TOCLIENT);
1418  AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateTransactionFree);
1419 
1420  AppLayerParserRegisterGetTxFilesFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateGetTxFiles);
1421 
1422  AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetTx);
1423  AppLayerParserRegisterTxDataFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetTxData);
1424  AppLayerParserRegisterStateDataFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetStateData);
1425 
1426  AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetTxCnt);
1427 
1428  AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetAlstateProgress);
1429 
1431  ALPROTO_FTPDATA, FTPDATA_STATE_FINISHED, FTPDATA_STATE_FINISHED);
1432 
1433  AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_FTP, ftp_get_event_info);
1434  AppLayerParserRegisterGetEventInfoById(IPPROTO_TCP, ALPROTO_FTP, ftp_get_event_info_by_id);
1435 
1438 
1439  sbcfg.buf_size = 4096;
1440  sbcfg.Calloc = FTPCalloc;
1441  sbcfg.Realloc = FTPRealloc;
1442  sbcfg.Free = FTPFree;
1443 
1444  FTPParseMemcap();
1445  } else {
1446  SCLogInfo("Parser disabled for %s protocol. Protocol detection still on.", proto_name);
1447  }
1448 
1449  FTPSetMpmState();
1450 
1451 #ifdef UNITTESTS
1453 #endif
1454 }
1455 
1456 /*
1457  * \brief Returns the ending offset of the next line from a multi-line buffer.
1458  *
1459  * "Buffer" refers to a FTP response in a single buffer containing multiple lines.
1460  * Here, "next line" is defined as terminating on
1461  * - Newline character
1462  * - Null character
1463  *
1464  * \param buffer Contains zero or more characters.
1465  * \param len Size, in bytes, of buffer.
1466  *
1467  * \retval Offset from the start of buffer indicating the where the
1468  * next "line ends". The characters between the input buffer and this
1469  * value comprise the line.
1470  *
1471  * NULL is found first or a newline isn't found, then UINT16_MAX is returned.
1472  */
1473 uint16_t JsonGetNextLineFromBuffer(const char *buffer, const uint16_t len)
1474 {
1475  if (!buffer || *buffer == '\0') {
1476  return UINT16_MAX;
1477  }
1478 
1479  const char *c = strchr(buffer, '\n');
1480  return c == NULL ? len : (uint16_t)(c - buffer + 1);
1481 }
1482 
1483 bool EveFTPDataAddMetadata(void *vtx, SCJsonBuilder *jb)
1484 {
1485  const FtpDataState *ftp_state = (FtpDataState *)vtx;
1486  SCJbOpenObject(jb, "ftp_data");
1487 
1488  if (ftp_state->file_name) {
1489  SCJbSetStringFromBytes(jb, "filename", ftp_state->file_name, ftp_state->file_len);
1490  }
1491  switch (ftp_state->command) {
1492  case FTP_COMMAND_STOR:
1493  JB_SET_STRING(jb, "command", "STOR");
1494  break;
1495  case FTP_COMMAND_APPE:
1496  JB_SET_STRING(jb, "command", "APPE");
1497  break;
1498  case FTP_COMMAND_STOU:
1499  JB_SET_STRING(jb, "command", "STOU");
1500  break;
1501  case FTP_COMMAND_RETR:
1502  JB_SET_STRING(jb, "command", "RETR");
1503  break;
1504  case FTP_COMMAND_NLST:
1505  JB_SET_STRING(jb, "command", "NLST");
1506  break;
1507  case FTP_COMMAND_LIST:
1508  JB_SET_STRING(jb, "command", "LIST");
1509  break;
1510  case FTP_COMMAND_MLSD:
1511  JB_SET_STRING(jb, "command", "MLSD");
1512  break;
1513  default:
1514  break;
1515  }
1516  SCJbClose(jb);
1517  return true;
1518 }
1519 
1520 /**
1521  * \brief Free memory allocated for global FTP parser state.
1522  */
1524 {
1525  FTPFreeMpmState();
1526 }
1527 
1528 /* UNITTESTS */
1529 #ifdef UNITTESTS
1530 #include "flow-util.h"
1531 #include "stream-tcp.h"
1532 
1533 /** \test Send a get request in one chunk. */
1534 static int FTPParserTest01(void)
1535 {
1536  Flow f;
1537  uint8_t ftpbuf[] = "PORT 192,168,1,1,0,80\r\n";
1538  uint32_t ftplen = sizeof(ftpbuf) - 1; /* minus the \0 */
1539  TcpSession ssn;
1541 
1542  memset(&f, 0, sizeof(f));
1543  memset(&ssn, 0, sizeof(ssn));
1544 
1545  f.protoctx = (void *)&ssn;
1546  f.proto = IPPROTO_TCP;
1547  f.alproto = ALPROTO_FTP;
1548 
1549  StreamTcpInitConfig(true);
1550 
1551  int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1552  STREAM_TOSERVER | STREAM_EOF, ftpbuf, ftplen);
1553  FAIL_IF(r != 0);
1554 
1555  FtpState *ftp_state = f.alstate;
1556  FAIL_IF_NULL(ftp_state);
1557  FAIL_IF(ftp_state->command != FTP_COMMAND_PORT);
1558 
1559  FLOW_DESTROY(&f);
1561  StreamTcpFreeConfig(true);
1562  PASS;
1563 }
1564 
1565 /** \test Supply RETR without a filename */
1566 static int FTPParserTest11(void)
1567 {
1568  Flow f;
1569  uint8_t ftpbuf1[] = "PORT 192,168,1,1,0,80\r\n";
1570  uint8_t ftpbuf2[] = "RETR\r\n";
1571  uint8_t ftpbuf3[] = "227 OK\r\n";
1572  TcpSession ssn;
1573 
1575 
1576  memset(&f, 0, sizeof(f));
1577  memset(&ssn, 0, sizeof(ssn));
1578 
1579  f.protoctx = (void *)&ssn;
1580  f.proto = IPPROTO_TCP;
1581  f.alproto = ALPROTO_FTP;
1582 
1583  StreamTcpInitConfig(true);
1584 
1585  int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1586  STREAM_TOSERVER | STREAM_START, ftpbuf1,
1587  sizeof(ftpbuf1) - 1);
1588  FAIL_IF(r != 0);
1589 
1590  /* Response */
1591  r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1592  STREAM_TOCLIENT,
1593  ftpbuf3,
1594  sizeof(ftpbuf3) - 1);
1595  FAIL_IF(r != 0);
1596 
1597  r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1598  STREAM_TOSERVER, ftpbuf2,
1599  sizeof(ftpbuf2) - 1);
1600  FAIL_IF(r != 0);
1601 
1602  FtpState *ftp_state = f.alstate;
1603  FAIL_IF_NULL(ftp_state);
1604 
1605  FAIL_IF(ftp_state->command != FTP_COMMAND_RETR);
1606 
1607  FLOW_DESTROY(&f);
1609  StreamTcpFreeConfig(true);
1610  PASS;
1611 }
1612 
1613 /** \test Supply STOR without a filename */
1614 static int FTPParserTest12(void)
1615 {
1616  Flow f;
1617  uint8_t ftpbuf1[] = "PORT 192,168,1,1,0,80\r\n";
1618  uint8_t ftpbuf2[] = "STOR\r\n";
1619  uint8_t ftpbuf3[] = "227 OK\r\n";
1620  TcpSession ssn;
1621 
1623 
1624  memset(&f, 0, sizeof(f));
1625  memset(&ssn, 0, sizeof(ssn));
1626 
1627  f.protoctx = (void *)&ssn;
1628  f.proto = IPPROTO_TCP;
1629  f.alproto = ALPROTO_FTP;
1630 
1631  StreamTcpInitConfig(true);
1632 
1633  int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1634  STREAM_TOSERVER | STREAM_START, ftpbuf1,
1635  sizeof(ftpbuf1) - 1);
1636  FAIL_IF(r != 0);
1637 
1638  /* Response */
1639  r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1640  STREAM_TOCLIENT,
1641  ftpbuf3,
1642  sizeof(ftpbuf3) - 1);
1643  FAIL_IF(r != 0);
1644 
1645  r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP,
1646  STREAM_TOSERVER, ftpbuf2,
1647  sizeof(ftpbuf2) - 1);
1648  FAIL_IF(r != 0);
1649 
1650  FtpState *ftp_state = f.alstate;
1651  FAIL_IF_NULL(ftp_state);
1652 
1653  FAIL_IF(ftp_state->command != FTP_COMMAND_STOR);
1654 
1655  FLOW_DESTROY(&f);
1657  StreamTcpFreeConfig(true);
1658  PASS;
1659 }
1660 #endif /* UNITTESTS */
1661 
1663 {
1664 #ifdef UNITTESTS
1665  UtRegisterTest("FTPParserTest01", FTPParserTest01);
1666  UtRegisterTest("FTPParserTest11", FTPParserTest11);
1667  UtRegisterTest("FTPParserTest12", FTPParserTest12);
1668 #endif /* UNITTESTS */
1669 }
FTPTransaction_::request_truncated
bool request_truncated
Definition: app-layer-ftp.h:70
PmqReset
void PmqReset(PrefilterRuleStore *pmq)
Reset a Pmq for reusage. Meant to be called after a single search.
Definition: util-prefilter.c:102
StreamSlice
Definition: app-layer-parser.h:120
AppLayerParserRegisterGetStateProgressFunc
void AppLayerParserRegisterGetStateProgressFunc(uint8_t ipproto, AppProto alproto, int(*StateGetProgress)(void *alstate, uint8_t direction))
Definition: app-layer-parser.c:536
len
uint8_t len
Definition: app-layer-dnp3.h:2
AppLayerTxData::flags
uint8_t flags
Definition: app-layer-parser.h:176
SCAppLayerParserStateIssetFlag
uint16_t SCAppLayerParserStateIssetFlag(AppLayerParserState *pstate, uint16_t flag)
Definition: app-layer-parser.c:2105
FAIL_IF_NULL
#define FAIL_IF_NULL(expr)
Fail a test if expression evaluates to NULL.
Definition: util-unittest.h:89
FTPTransaction_::request
uint8_t * request
Definition: app-layer-ftp.h:69
AppLayerGetTxIterState::ptr
void * ptr
Definition: app-layer-parser.h:144
FTPThreadCtx_
Definition: app-layer-ftp.c:43
StreamingBufferConfig_::buf_size
uint32_t buf_size
Definition: util-streaming-buffer.h:66
AppLayerParserRegisterLocalStorageFunc
void AppLayerParserRegisterLocalStorageFunc(uint8_t ipproto, AppProto alproto, void *(*LocalStorageAlloc)(void), void(*LocalStorageFree)(void *))
Definition: app-layer-parser.c:496
SCFileFlowFlagsToFlags
uint16_t SCFileFlowFlagsToFlags(const uint16_t flow_file_flags, uint8_t direction)
Definition: util-file.c:215
TAILQ_INIT
#define TAILQ_INIT(head)
Definition: queue.h:262
FtpState_::active
bool active
Definition: app-layer-ftp.h:89
flow-util.h
SC_ATOMIC_INIT
#define SC_ATOMIC_INIT(name)
wrapper for initializing an atomic variable.
Definition: util-atomic.h:314
FileContainerAlloc
FileContainer * FileContainerAlloc(void)
allocate a FileContainer
Definition: util-file.c:479
FtpDataState_::state
uint8_t state
Definition: app-layer-ftp.h:117
StreamingBufferConfig_::Calloc
void *(* Calloc)(size_t n, size_t size)
Definition: util-streaming-buffer.h:69
MpmThreadCtx_
Definition: util-mpm.h:48
stream-tcp.h
FtpState
struct FtpState_ FtpState
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SC_ATOMIC_SET
#define SC_ATOMIC_SET(name, val)
Set the value for the atomic variable.
Definition: util-atomic.h:386
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
EveFTPDataAddMetadata
bool EveFTPDataAddMetadata(void *vtx, SCJsonBuilder *jb)
Definition: app-layer-ftp.c:1483
SCFlowGetStorageById
void * SCFlowGetStorageById(const Flow *f, SCFlowStorageId id)
Definition: flow-storage.c:40
PrefilterRuleStore_
structure for storing potential rule matches
Definition: util-prefilter.h:34
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:282
SCAppLayerTxDataCleanup
void SCAppLayerTxDataCleanup(AppLayerTxData *txd)
Definition: app-layer-parser.c:823
FtpCommandInfo_
Definition: app-layer-ftp.h:56
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
Flow_::proto
uint8_t proto
Definition: flow.h:376
AppProto
uint16_t AppProto
Definition: app-layer-protos.h:87
FtpState_::command
FtpRequestCommand command
Definition: app-layer-ftp.h:98
ALPROTO_POP3
@ ALPROTO_POP3
Definition: app-layer-protos.h:71
SCAppLayerProtoDetectPMRegisterPatternCI
int SCAppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction)
Registers a case-insensitive pattern for protocol detection.
Definition: app-layer-detect-proto.c:1673
STREAMING_BUFFER_CONFIG_INITIALIZER
#define STREAMING_BUFFER_CONFIG_INITIALIZER
Definition: util-streaming-buffer.h:74
AppLayerStateData
Definition: app-layer-parser.h:149
FileContainerFree
void FileContainerFree(FileContainer *ffc, const StreamingBufferConfig *cfg)
Free a FileContainer.
Definition: util-file.c:515
Flow_
Flow data structure.
Definition: flow.h:354
FTPTransaction_::done
bool done
Definition: app-layer-ftp.h:76
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
AppLayerParserRegisterStateProgressCompletionStatus
void AppLayerParserRegisterStateProgressCompletionStatus(AppProto alproto, const int ts, const int tc)
Definition: app-layer-parser.c:584
FtpState_::current_line_truncated_tc
bool current_line_truncated_tc
Definition: app-layer-ftp.h:96
AppLayerParserRegisterTxFreeFunc
void AppLayerParserRegisterTxFreeFunc(uint8_t ipproto, AppProto alproto, void(*StateTransactionFree)(void *, uint64_t))
Definition: app-layer-parser.c:546
FTPTransaction_::tx_data
AppLayerTxData tx_data
Definition: app-layer-ftp.h:65
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:252
FtpDataState_::command
FtpRequestCommand command
Definition: app-layer-ftp.h:116
FTPMemuseGlobalCounter
uint64_t FTPMemuseGlobalCounter(void)
Definition: app-layer-ftp.c:79
AppLayerParserThreadCtxFree
void AppLayerParserThreadCtxFree(AppLayerParserThreadCtx *tctx)
Destroys the app layer parser thread context obtained using AppLayerParserThreadCtxAlloc().
Definition: app-layer-parser.c:356
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
rust.h
MIN
#define MIN(x, y)
Definition: suricata-common.h:416
FtpLineState_::buf
const uint8_t * buf
Definition: app-layer-ftp.h:39
ALPROTO_FTP
@ ALPROTO_FTP
Definition: app-layer-protos.h:37
SCMUTEX_INITIALIZER
#define SCMUTEX_INITIALIZER
Definition: threads-debug.h:122
FtpDataState_::file_len
int16_t file_len
Definition: app-layer-ftp.h:115
TAILQ_INSERT_TAIL
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:294
FTPResponseWrapper_
Definition: app-layer-ftp.h:45
app-layer-ftp.h
Flow_::protoctx
void * protoctx
Definition: flow.h:433
AppLayerGetTxIterTuple::tx_ptr
void * tx_ptr
Definition: app-layer-parser.h:154
FtpDataState_::direction
uint8_t direction
Definition: app-layer-ftp.h:118
FtpInput_::len
int32_t len
Definition: app-layer-ftp.c:275
SC_ELIMIT
@ SC_ELIMIT
Definition: util-error.h:31
SC_ATOMIC_DECLARE
SC_ATOMIC_DECLARE(uint64_t, ftp_memuse)
SCAppLayerProtoDetectPMRegisterPatternCSwPP
int SCAppLayerProtoDetectPMRegisterPatternCSwPP(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, ProbingParserFPtr PPFunc, uint16_t pp_min_depth, uint16_t pp_max_depth)
Definition: app-layer-detect-proto.c:1651
SC_ENOMEM
@ SC_ENOMEM
Definition: util-error.h:29
FTPParserCleanup
void FTPParserCleanup(void)
Free memory allocated for global FTP parser state.
Definition: app-layer-ftp.c:1523
SCAppLayerDecoderEventsSetEventRaw
void SCAppLayerDecoderEventsSetEventRaw(AppLayerDecoderEvents **sevents, uint8_t event)
Set an app layer decoder event.
Definition: app-layer-events.c:96
SCAppLayerProtoDetectConfProtoDetectionEnabled
int SCAppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto)
Given a protocol name, checks if proto detection is enabled in the conf file.
Definition: app-layer-detect-proto.c:1995
MpmInitCtx
void MpmInitCtx(MpmCtx *mpm_ctx, uint8_t matcher)
Definition: util-mpm.c:209
ftp_max_line_len
uint32_t ftp_max_line_len
Definition: app-layer-ftp.c:54
AppLayerResult
Definition: app-layer-parser.h:114
SCAppLayerParserTriggerRawStreamInspection
void SCAppLayerParserTriggerRawStreamInspection(Flow *f, int direction)
Definition: app-layer-parser.c:1813
FtpState_
Definition: app-layer-ftp.h:88
app-layer-expectation.h
app-layer-detect-proto.h
StreamTcpInitConfig
void StreamTcpInitConfig(bool)
To initialize the stream global configuration data.
Definition: stream-tcp.c:498
APP_LAYER_INCOMPLETE
#define APP_LAYER_INCOMPLETE(c, n)
Definition: app-layer-parser.h:70
TAILQ_REMOVE
#define TAILQ_REMOVE(head, elm, field)
Definition: queue.h:312
MpmDestroyThreadCtx
void MpmDestroyThreadCtx(MpmThreadCtx *mpm_thread_ctx, const uint16_t matcher)
Definition: util-mpm.c:202
JB_SET_STRING
#define JB_SET_STRING(jb, key, val)
Definition: rust.h:36
TAILQ_FIRST
#define TAILQ_FIRST(head)
Definition: queue.h:250
FtpState_::port_line
uint8_t * port_line
Definition: app-layer-ftp.h:102
AppLayerParserState_
Definition: app-layer-parser.c:148
PASS
#define PASS
Pass the test.
Definition: util-unittest.h:105
AppLayerTxData
Definition: app-layer-parser.h:166
FTPThreadCtx_::pmq
PrefilterRuleStore * pmq
Definition: app-layer-ftp.c:45
SCAppLayerParserConfParserEnabled
int SCAppLayerParserConfParserEnabled(const char *ipproto, const char *alproto_name)
check if a parser is enabled in the config Returns enabled always if: were running unittests
Definition: app-layer-parser.c:377
SC_FILENAME_MAX
#define SC_FILENAME_MAX
Definition: util-file.h:129
SCAppLayerParserRegisterLogger
void SCAppLayerParserRegisterLogger(uint8_t ipproto, AppProto alproto)
Definition: app-layer-parser.c:527
FtpDataState_::initialized
bool initialized
Definition: app-layer-ftp.h:121
FtpState_::curr_tx
FTPTransaction * curr_tx
Definition: app-layer-ftp.h:91
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:120
FtpDataState_::state_data
AppLayerStateData state_data
Definition: app-layer-ftp.h:120
alp_tctx
AppLayerParserThreadCtx * alp_tctx
Definition: fuzz_applayerparserparse.c:24
util-print.h
SCEnter
#define SCEnter(...)
Definition: util-debug.h:284
AppLayerParserRegisterStateFuncs
void AppLayerParserRegisterStateFuncs(uint8_t ipproto, AppProto alproto, void *(*StateAlloc)(void *, AppProto), void(*StateFree)(void *))
Definition: app-layer-parser.c:485
FtpLineState_::lf_found
bool lf_found
Definition: app-layer-ftp.h:42
app-layer-parser.h
Flow_::todstbytecnt
uint64_t todstbytecnt
Definition: flow.h:497
SCFlowFreeStorageById
void SCFlowFreeStorageById(Flow *f, SCFlowStorageId id)
Definition: flow-storage.c:50
AppLayerParserRegisterGetEventInfo
void AppLayerParserRegisterGetEventInfo(uint8_t ipproto, AppProto alproto, int(*StateGetEventInfo)(const char *event_name, uint8_t *event_id, AppLayerEventType *event_type))
Definition: app-layer-parser.c:663
FtpState_::state_data
AppLayerStateData state_data
Definition: app-layer-ftp.h:106
SC_ATOMIC_SUB
#define SC_ATOMIC_SUB(name, val)
sub a value from our atomic variable
Definition: util-atomic.h:341
FTPParserRegisterTests
void FTPParserRegisterTests(void)
Definition: app-layer-ftp.c:1662
RegisterFTPParsers
void RegisterFTPParsers(void)
Definition: app-layer-ftp.c:1372
FTPTransaction_::command_descriptor
FtpCommandInfo command_descriptor
Definition: app-layer-ftp.h:73
AppLayerParserRegisterProtocolUnittests
void AppLayerParserRegisterProtocolUnittests(uint8_t ipproto, AppProto alproto, void(*RegisterUnittests)(void))
Definition: app-layer-parser.c:2116
AppLayerExpectationCreate
int AppLayerExpectationCreate(Flow *f, int direction, Port src, Port dst, AppProto alproto, void *data)
Definition: app-layer-expectation.c:217
AppLayerGetTxIterState
Definition: app-layer-parser.h:142
FtpCommandInfo_::command_code
FtpRequestCommand command_code
Definition: app-layer-ftp.h:58
ftp_config_memcap
uint64_t ftp_config_memcap
Definition: app-layer-ftp.c:52
AppLayerRegisterExpectationProto
void AppLayerRegisterExpectationProto(uint8_t proto, AppProto alproto)
Definition: app-layer-detect-proto.c:2171
FTPResponseWrapper_::response
FTPResponseLine * response
Definition: app-layer-ftp.h:46
FileOpenFileWithId
int FileOpenFileWithId(FileContainer *ffc, const StreamingBufferConfig *sbcfg, uint32_t track_id, const uint8_t *name, uint16_t name_len, const uint8_t *data, uint32_t data_len, uint16_t flags)
Open a new File.
Definition: util-file.c:966
AppLayerParserRegisterGetTxFilesFunc
void AppLayerParserRegisterGetTxFilesFunc(uint8_t ipproto, AppProto alproto, AppLayerGetFileState(*GetTxFiles)(void *, uint8_t))
Definition: app-layer-parser.c:508
AppLayerProtoDetectRegisterProtocol
void AppLayerProtoDetectRegisterProtocol(AppProto alproto, const char *alproto_name)
Registers a protocol for protocol detection phase.
Definition: app-layer-detect-proto.c:1782
AppLayerGetTxIterTuple
Definition: app-layer-parser.h:153
FtpDataState
struct FtpDataState_ FtpDataState
FileAppendData
int FileAppendData(FileContainer *ffc, const StreamingBufferConfig *sbcfg, const uint8_t *data, uint32_t data_len)
Store/handle a chunk of file data in the File structure The last file in the FileContainer will be us...
Definition: util-file.c:765
FTPMemcapGlobalCounter
uint64_t FTPMemcapGlobalCounter(void)
Definition: app-layer-ftp.c:85
MpmTableElmt_::Search
uint32_t(* Search)(const struct MpmCtx_ *, struct MpmThreadCtx_ *, PrefilterRuleStore *, const uint8_t *, uint32_t)
Definition: util-mpm.h:186
FtpInput
struct FtpInput_ FtpInput
FtpDataState_::tx_data
AppLayerTxData tx_data
Definition: app-layer-ftp.h:119
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:232
AppLayerParserRegisterParser
int AppLayerParserRegisterParser(uint8_t ipproto, AppProto alproto, uint8_t direction, AppLayerParserFPtr Parser)
Register app layer parser for the protocol.
Definition: app-layer-parser.c:452
FtpInput_::orig_len
int32_t orig_len
Definition: app-layer-ftp.c:276
SCRealloc
#define SCRealloc(ptr, sz)
Definition: util-mem.h:50
SCAppLayerProtoDetectPPRegister
void SCAppLayerProtoDetectPPRegister(uint8_t ipproto, const char *portstr, AppProto alproto, uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2)
register parser at a port
Definition: app-layer-detect-proto.c:1541
AppLayerParserThreadCtxAlloc
AppLayerParserThreadCtx * AppLayerParserThreadCtxAlloc(void)
Gets a new app layer protocol's parser thread context.
Definition: app-layer-parser.c:329
AppLayerParserRegisterGetTx
void AppLayerParserRegisterGetTx(uint8_t ipproto, AppProto alproto, void *(StateGetTx)(void *alstate, uint64_t tx_id))
Definition: app-layer-parser.c:566
APP_LAYER_OK
#define APP_LAYER_OK
Definition: app-layer-parser.h:58
cnt
uint32_t cnt
Definition: tmqh-packetpool.h:7
SCReturnStruct
#define SCReturnStruct(x)
Definition: util-debug.h:304
FTPTransaction_::request_length
uint32_t request_length
Definition: app-layer-ftp.h:68
FAIL_IF
#define FAIL_IF(expr)
Fail a test if expression evaluates to true.
Definition: util-unittest.h:71
util-mpm.h
StreamTcpFreeConfig
void StreamTcpFreeConfig(bool quiet)
Definition: stream-tcp.c:866
flags
uint8_t flags
Definition: decode-gre.h:0
AppLayerParserParse
int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow *f, AppProto alproto, uint8_t flags, const uint8_t *input, uint32_t input_len)
Definition: app-layer-parser.c:1554
AppLayerGetFileState
Definition: util-file.h:44
FtpLineState_
Definition: app-layer-ftp.h:36
suricata-common.h
AppLayerGetFileState::fc
FileContainer * fc
Definition: util-file.h:45
ftp_config_maxtx
uint32_t ftp_config_maxtx
Definition: app-layer-ftp.c:53
AppLayerTxData::updated_tc
bool updated_tc
Definition: app-layer-parser.h:173
SCAppLayerParserRegisterParserAcceptableDataDirection
void SCAppLayerParserRegisterParserAcceptableDataDirection(uint8_t ipproto, AppProto alproto, uint8_t direction)
Definition: app-layer-parser.c:464
FtpState_::port_line_len
uint32_t port_line_len
Definition: app-layer-ftp.h:100
FtpState_::dyn_port
uint16_t dyn_port
Definition: app-layer-ftp.h:104
AppLayerTxData::files_opened
uint32_t files_opened
track file open/logs so we can know how long to keep the tx
Definition: app-layer-parser.h:182
TAILQ_NEXT
#define TAILQ_NEXT(elm, field)
Definition: queue.h:307
ALPROTO_FTPDATA
@ ALPROTO_FTPDATA
Definition: app-layer-protos.h:53
AppLayerParserRegisterStateDataFunc
void AppLayerParserRegisterStateDataFunc(uint8_t ipproto, AppProto alproto, AppLayerStateData *(*GetStateData)(void *state))
Definition: app-layer-parser.c:684
AppLayerParserRegisterTxDataFunc
void AppLayerParserRegisterTxDataFunc(uint8_t ipproto, AppProto alproto, AppLayerTxData *(*GetTxData)(void *tx))
Definition: app-layer-parser.c:674
Flow_::parent_id
int64_t parent_id
Definition: flow.h:430
SCAppLayerRequestProtocolTLSUpgrade
bool SCAppLayerRequestProtocolTLSUpgrade(Flow *f)
request applayer to wrap up this protocol and rerun protocol detection with expectation of TLS....
Definition: app-layer-detect-proto.c:1873
FtpDataState_
Definition: app-layer-ftp.h:110
app-layer-events.h
util-validate.h
StreamingBufferConfig_
Definition: util-streaming-buffer.h:65
FTPSetMemcap
int FTPSetMemcap(uint64_t size)
Definition: app-layer-ftp.c:91
FtpLineState_::delim_len
uint8_t delim_len
Definition: app-layer-ftp.h:41
AppLayerParserRegisterGetTxIterator
void AppLayerParserRegisterGetTxIterator(uint8_t ipproto, AppProto alproto, AppLayerGetTxIteratorFunc Func)
Definition: app-layer-parser.c:576
MpmTableElmt_::Prepare
int(* Prepare)(MpmConfig *, struct MpmCtx_ *)
Definition: util-mpm.h:179
MpmTableElmt_::DestroyCtx
void(* DestroyCtx)(struct MpmCtx_ *)
Definition: util-mpm.h:158
AppLayerResult::status
int32_t status
Definition: app-layer-parser.h:115
FileCloseFile
int FileCloseFile(FileContainer *ffc, const StreamingBufferConfig *sbcfg, const uint8_t *data, uint32_t data_len, uint16_t flags)
Close a File.
Definition: util-file.c:1050
SCFree
#define SCFree(p)
Definition: util-mem.h:61
Flow_::alproto_ts
AppProto alproto_ts
Definition: flow.h:451
Flow_::alstate
void * alstate
Definition: flow.h:479
SCAppLayerProtoDetectPPParseConfPorts
int SCAppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, uint8_t ipproto, const char *alproto_name, AppProto alproto, uint16_t min_depth, uint16_t max_depth, ProbingParserFPtr ProbingParserTs, ProbingParserFPtr ProbingParserTc)
Definition: app-layer-detect-proto.c:1577
StreamingBufferConfig_::Free
void(* Free)(void *ptr, size_t size)
Definition: util-streaming-buffer.h:71
FtpCommandInfo_::command_index
uint8_t command_index
Definition: app-layer-ftp.h:57
FtpState_::tx_cnt
uint64_t tx_cnt
Definition: app-layer-ftp.h:93
FtpState_::current_line_truncated_ts
bool current_line_truncated_ts
Definition: app-layer-ftp.h:95
sc_errno
thread_local SCError sc_errno
Definition: util-error.c:31
MpmInitThreadCtx
void MpmInitThreadCtx(MpmThreadCtx *mpm_thread_ctx, MpmCtx *mpm_ctx, uint16_t matcher)
Definition: util-mpm.c:195
ALPROTO_UNKNOWN
@ ALPROTO_UNKNOWN
Definition: app-layer-protos.h:29
ALPROTO_FAILED
@ ALPROTO_FAILED
Definition: app-layer-protos.h:33
mpm_table
MpmTableElmt mpm_table[MPM_TABLE_SIZE]
Definition: util-mpm.c:47
AppLayerExpectationGetFlowId
SCFlowStorageId AppLayerExpectationGetFlowId(void)
Definition: app-layer-expectation.c:286
FtpLineState_::len
uint32_t len
Definition: app-layer-ftp.h:40
AppLayerParserRegisterGetTxCnt
void AppLayerParserRegisterGetTxCnt(uint8_t ipproto, AppProto alproto, uint64_t(*StateGetTxCnt)(void *alstate))
Definition: app-layer-parser.c:556
APP_LAYER_ERROR
#define APP_LAYER_ERROR
Definition: app-layer-parser.h:62
FtpState_::port_line_size
uint32_t port_line_size
Definition: app-layer-ftp.h:101
PmqFree
void PmqFree(PrefilterRuleStore *pmq)
Cleanup and free a Pmq.
Definition: util-prefilter.c:126
FTP_MPM
#define FTP_MPM
Definition: app-layer-ftp.c:48
FTPTransaction_::tx_id
uint64_t tx_id
Definition: app-layer-ftp.h:63
FTPTransaction_::dyn_port
uint16_t dyn_port
Definition: app-layer-ftp.h:75
FTPTransaction_::active
bool active
Definition: app-layer-ftp.h:77
AppLayerTxData::events
AppLayerDecoderEvents * events
Definition: app-layer-parser.h:218
AppLayerParserRegisterGetEventInfoById
void AppLayerParserRegisterGetEventInfoById(uint8_t ipproto, AppProto alproto, int(*StateGetEventInfoById)(uint8_t event_id, const char **event_name, AppLayerEventType *event_type))
Definition: app-layer-parser.c:599
FtpDataState_::files
FileContainer * files
Definition: app-layer-ftp.h:113
likely
#define likely(expr)
Definition: util-optimize.h:32
AppLayerParserThreadCtx_
Definition: app-layer-parser.c:60
SC_ATOMIC_GET
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:375
MpmCtx_
Definition: util-mpm.h:97
TcpSession_
Definition: stream-tcp-private.h:283
JsonGetNextLineFromBuffer
uint16_t JsonGetNextLineFromBuffer(const char *buffer, const uint16_t len)
Definition: app-layer-ftp.c:1473
util-misc.h
AppLayerTxData::file_flags
uint16_t file_flags
Definition: app-layer-parser.h:186
FTPTransaction_
Definition: app-layer-ftp.h:61
FTPThreadCtx
struct FTPThreadCtx_ FTPThreadCtx
Flow_::alproto_tc
AppProto alproto_tc
Definition: flow.h:452
FtpInput_::buf
const uint8_t * buf
Definition: app-layer-ftp.c:273
Flow_::alproto
AppProto alproto
application level protocol
Definition: flow.h:450
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:288
SCMemcmp
#define SCMemcmp(a, b, c)
Definition: util-memcmp.h:290
SCMutex
#define SCMutex
Definition: threads-debug.h:114
FTPThreadCtx_::ftp_mpm_thread_ctx
MpmThreadCtx * ftp_mpm_thread_ctx
Definition: app-layer-ftp.c:44
SCLogDebugEnabled
int SCLogDebugEnabled(void)
Returns whether debug messages are enabled to be logged or not.
Definition: util-debug.c:768
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:109
FtpInput_::consumed
int32_t consumed
Definition: app-layer-ftp.c:274
FLOW_DESTROY
#define FLOW_DESTROY(f)
Definition: flow-util.h:119
PmqSetup
int PmqSetup(PrefilterRuleStore *pmq)
Setup a pmq.
Definition: util-prefilter.c:37
AppLayerStateData::file_flags
uint16_t file_flags
Definition: app-layer-parser.h:150
StreamingBufferConfig_::Realloc
void *(* Realloc)(void *ptr, size_t orig_size, size_t size)
Definition: util-streaming-buffer.h:70
FtpDataState_::file_name
uint8_t * file_name
Definition: app-layer-ftp.h:112
FtpInput_
Definition: app-layer-ftp.c:272
AppLayerGetTxIterState::un
union AppLayerGetTxIterState::@7 un
AppLayerTxData::file_tx
uint8_t file_tx
Definition: app-layer-parser.h:193
AppLayerTxData::updated_ts
bool updated_ts
Definition: app-layer-parser.h:174
app-layer.h
PrefilterRuleStore_::rule_id_array
SigIntId * rule_id_array
Definition: util-prefilter.h:38