suricata
app-layer-dnp3.c
Go to the documentation of this file.
1 /* Copyright (C) 2015 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 #include "suricata-common.h"
19 #include "stream.h"
20 #include "util-byte.h"
21 #include "util-unittest.h"
22 #include "util-hashlist.h"
23 
24 #include "util-print.h"
25 
26 #include "app-layer-protos.h"
27 #include "app-layer-parser.h"
28 #include "app-layer-detect-proto.h"
29 
30 #include "app-layer-dnp3.h"
31 #include "app-layer-dnp3-objects.h"
32 
33 /* For hexdump(). */
35 
36 /* Default number of unreplied requests to be considered a flood. */
37 #define DNP3_DEFAULT_REQ_FLOOD_COUNT 500
38 
39 #define DNP3_DEFAULT_PORT "20000"
40 
41 /* Expected values for the start bytes. */
42 #define DNP3_START_BYTE0 0x05
43 #define DNP3_START_BYTE1 0x64
44 
45 /* Minimum length for a DNP3 frame. */
46 #define DNP3_MIN_LEN 5
47 
48 /* Length of each CRC. */
49 #define DNP3_CRC_LEN 2
50 
51 /* DNP3 block size. After the link header a CRC is inserted after
52  * after 16 bytes of data. */
53 #define DNP3_BLOCK_SIZE 16
54 
55 /* Maximum transport layer sequence number. */
56 #define DNP3_MAX_TRAN_SEQNO 64
57 
58 /* Maximum application layer sequence number. */
59 #define DNP3_MAX_APP_SEQNO 16
60 
61 /* The number of bytes in the header that are counted as part of the
62  * header length field. */
63 #define DNP3_LINK_HDR_LEN 5
64 
65 /* Link function codes. */
66 enum {
69 };
70 
71 /* Reserved addresses. */
72 #define DNP3_RESERVED_ADDR_MIN 0xfff0
73 #define DNP3_RESERVED_ADDR_MAX 0xfffb
74 
75 /* Source addresses must be < 0xfff0. */
76 #define DNP3_SRC_ADDR_MAX 0xfff0
77 
78 #define DNP3_OBJ_TIME_SIZE 6 /* AKA UINT48. */
79 #define DNP3_OBJ_G12_V1_SIZE 11
80 #define DNP3_OBJ_G12_V2_SIZE 11
81 #define DNP3_OBJ_G12_V3_SIZE 1
82 
83 /* Extract the prefix code from the object qualifier. */
84 #define DNP3_OBJ_PREFIX(x) ((x >> 4) & 0x7)
85 
86 /* Extract the range code from the object qualifier. */
87 #define DNP3_OBJ_RANGE(x) (x & 0xf)
88 
89 /* Decoder event map. */
91  {"FLOODED", DNP3_DECODER_EVENT_FLOODED},
92  {"LEN_TOO_SMALL", DNP3_DECODER_EVENT_LEN_TOO_SMALL},
93  {"BAD_LINK_CRC", DNP3_DECODER_EVENT_BAD_LINK_CRC},
94  {"BAD_TRANSPORT_CRC", DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC},
95  {"MALFORMED", DNP3_DECODER_EVENT_MALFORMED},
96  {"UNKNOWN_OBJECT", DNP3_DECODER_EVENT_UNKNOWN_OBJECT},
97  {NULL, -1},
98 };
99 
100 /* Some DNP3 servers start with a banner. */
101 static const char banner[] = "DNP3";
102 
103 /* Calculate the next transport sequence number. */
104 #define NEXT_TH_SEQNO(current) ((current + 1) % DNP3_MAX_TRAN_SEQNO)
105 
106 /* Calculate the next application sequence number. */
107 #define NEXT_APP_SEQNO(current) ((current + 1) % DNP3_MAX_APP_SEQNO)
108 
109 /* CRC table generated by pycrc - http://github.com/tpircher/pycrc.
110  * - Polynomial: 0x3d65. */
111 static const uint16_t crc_table[256] = {
112  0x0000, 0x365e, 0x6cbc, 0x5ae2, 0xd978, 0xef26, 0xb5c4, 0x839a,
113  0xff89, 0xc9d7, 0x9335, 0xa56b, 0x26f1, 0x10af, 0x4a4d, 0x7c13,
114  0xb26b, 0x8435, 0xded7, 0xe889, 0x6b13, 0x5d4d, 0x07af, 0x31f1,
115  0x4de2, 0x7bbc, 0x215e, 0x1700, 0x949a, 0xa2c4, 0xf826, 0xce78,
116  0x29af, 0x1ff1, 0x4513, 0x734d, 0xf0d7, 0xc689, 0x9c6b, 0xaa35,
117  0xd626, 0xe078, 0xba9a, 0x8cc4, 0x0f5e, 0x3900, 0x63e2, 0x55bc,
118  0x9bc4, 0xad9a, 0xf778, 0xc126, 0x42bc, 0x74e2, 0x2e00, 0x185e,
119  0x644d, 0x5213, 0x08f1, 0x3eaf, 0xbd35, 0x8b6b, 0xd189, 0xe7d7,
120  0x535e, 0x6500, 0x3fe2, 0x09bc, 0x8a26, 0xbc78, 0xe69a, 0xd0c4,
121  0xacd7, 0x9a89, 0xc06b, 0xf635, 0x75af, 0x43f1, 0x1913, 0x2f4d,
122  0xe135, 0xd76b, 0x8d89, 0xbbd7, 0x384d, 0x0e13, 0x54f1, 0x62af,
123  0x1ebc, 0x28e2, 0x7200, 0x445e, 0xc7c4, 0xf19a, 0xab78, 0x9d26,
124  0x7af1, 0x4caf, 0x164d, 0x2013, 0xa389, 0x95d7, 0xcf35, 0xf96b,
125  0x8578, 0xb326, 0xe9c4, 0xdf9a, 0x5c00, 0x6a5e, 0x30bc, 0x06e2,
126  0xc89a, 0xfec4, 0xa426, 0x9278, 0x11e2, 0x27bc, 0x7d5e, 0x4b00,
127  0x3713, 0x014d, 0x5baf, 0x6df1, 0xee6b, 0xd835, 0x82d7, 0xb489,
128  0xa6bc, 0x90e2, 0xca00, 0xfc5e, 0x7fc4, 0x499a, 0x1378, 0x2526,
129  0x5935, 0x6f6b, 0x3589, 0x03d7, 0x804d, 0xb613, 0xecf1, 0xdaaf,
130  0x14d7, 0x2289, 0x786b, 0x4e35, 0xcdaf, 0xfbf1, 0xa113, 0x974d,
131  0xeb5e, 0xdd00, 0x87e2, 0xb1bc, 0x3226, 0x0478, 0x5e9a, 0x68c4,
132  0x8f13, 0xb94d, 0xe3af, 0xd5f1, 0x566b, 0x6035, 0x3ad7, 0x0c89,
133  0x709a, 0x46c4, 0x1c26, 0x2a78, 0xa9e2, 0x9fbc, 0xc55e, 0xf300,
134  0x3d78, 0x0b26, 0x51c4, 0x679a, 0xe400, 0xd25e, 0x88bc, 0xbee2,
135  0xc2f1, 0xf4af, 0xae4d, 0x9813, 0x1b89, 0x2dd7, 0x7735, 0x416b,
136  0xf5e2, 0xc3bc, 0x995e, 0xaf00, 0x2c9a, 0x1ac4, 0x4026, 0x7678,
137  0x0a6b, 0x3c35, 0x66d7, 0x5089, 0xd313, 0xe54d, 0xbfaf, 0x89f1,
138  0x4789, 0x71d7, 0x2b35, 0x1d6b, 0x9ef1, 0xa8af, 0xf24d, 0xc413,
139  0xb800, 0x8e5e, 0xd4bc, 0xe2e2, 0x6178, 0x5726, 0x0dc4, 0x3b9a,
140  0xdc4d, 0xea13, 0xb0f1, 0x86af, 0x0535, 0x336b, 0x6989, 0x5fd7,
141  0x23c4, 0x159a, 0x4f78, 0x7926, 0xfabc, 0xcce2, 0x9600, 0xa05e,
142  0x6e26, 0x5878, 0x029a, 0x34c4, 0xb75e, 0x8100, 0xdbe2, 0xedbc,
143  0x91af, 0xa7f1, 0xfd13, 0xcb4d, 0x48d7, 0x7e89, 0x246b, 0x1235
144 };
145 
146 /**
147  * \brief Compute the CRC for a buffer.
148  *
149  * \param buf Buffer to create CRC from.
150  * \param len Length of buffer (number of bytes to use for CRC).
151 
152  */
153 static uint16_t DNP3ComputeCRC(const uint8_t *buf, uint32_t len)
154 {
155  const uint8_t *byte = buf;
156  uint16_t crc = 0;
157  int idx;
158 
159  while (len--) {
160  idx = (crc ^ *byte) & 0xff;
161  crc = (crc_table[idx] ^ (crc >> 8)) & 0xffff;
162  byte++;
163  }
164 
165  return ~crc & 0xffff;
166 }
167 
168 /**
169  * \brief Check the CRC of a block.
170  *
171  * \param block The block of data with CRC to be checked.
172  * \param len The size of the data block.
173  *
174  * \retval 1 if CRC is OK, otherwise 0.
175  */
176 static int DNP3CheckCRC(const uint8_t *block, uint32_t len)
177 {
178  uint32_t crc_offset;
179  uint16_t crc;
180 
181  /* Need at least one byte plus the CRC. */
182  if (len < DNP3_CRC_LEN + 1) {
183  return 0;
184  }
185 
186  crc_offset = len - DNP3_CRC_LEN;
187  crc = DNP3ComputeCRC(block, len - DNP3_CRC_LEN);
188  if (((crc & 0xff) == block[crc_offset]) &&
189  ((crc >> 8) == block[crc_offset + 1])) {
190  return 1;
191  }
192 
193  return 0;
194 }
195 
196 /**
197  * \brief Check the CRC of the link header.
198  *
199  * \param header Point to the link header.
200  *
201  * \retval 1 if header CRC is OK, otherwise 0.
202  */
203 static int DNP3CheckLinkHeaderCRC(const DNP3LinkHeader *header)
204 {
205  return DNP3CheckCRC((uint8_t *)header, sizeof(DNP3LinkHeader));
206 }
207 
208 /**
209  * \brief Check user data CRCs.
210  *
211  * \param data Pointer to user data.
212  * \param len Length of user data.
213  *
214  * \retval 1 if CRCs are OK, otherwise 0.
215  */
216 static int DNP3CheckUserDataCRCs(const uint8_t *data, uint32_t len)
217 {
218  uint32_t offset = 0;
219  uint32_t block_size;
220 
221  while (offset < len) {
222  if (len - offset >= DNP3_BLOCK_SIZE + DNP3_CRC_LEN) {
223  block_size = DNP3_BLOCK_SIZE + DNP3_CRC_LEN;
224  }
225  else {
226  block_size = len - offset;
227  }
228 
229  if (!DNP3CheckCRC(data + offset, block_size)) {
230  /* Once failed, may as well return immediately. */
231  return 0;
232  }
233 
234  offset += block_size;
235  }
236 
237  return 1;
238 }
239 
240 /**
241  * \brief Check the DNP3 frame start bytes.
242  *
243  * \retval 1 if valid, 0 if not.
244  */
245 static int DNP3CheckStartBytes(const DNP3LinkHeader *header)
246 {
247  return header->start_byte0 == DNP3_START_BYTE0 &&
248  header->start_byte1 == DNP3_START_BYTE1;
249 }
250 
251 /**
252  * \brief Check if a frame contains a banner.
253  *
254  * Some servers (outstations) appear to send back a banner that fails
255  * the normal frame checks. So first check for a banner.
256  *
257  * \retval 1 if a banner is found, 0 if not.
258  */
259 static int DNP3ContainsBanner(const uint8_t *input, uint32_t len)
260 {
261  return BasicSearch(input, len, (uint8_t *)banner, strlen(banner)) != NULL;
262 }
263 
264 /**
265  * \brief DNP3 probing parser.
266  */
267 static uint16_t DNP3ProbingParser(Flow *f, uint8_t direction,
268  uint8_t *input, uint32_t len,
269  uint8_t *rdir)
270 {
271  DNP3LinkHeader *hdr = (DNP3LinkHeader *)input;
272 
273  /* Check that we have the minimum amount of bytes. */
274  if (len < sizeof(DNP3LinkHeader)) {
275  SCLogDebug("Length too small to be a DNP3 header.");
276  return ALPROTO_UNKNOWN;
277  }
278 
279  /* May be a banner. */
280  if (DNP3ContainsBanner(input, len)) {
281  SCLogDebug("Packet contains a DNP3 banner.");
282  goto end;
283  }
284 
285  /* Verify start value (from AN2013-004b). */
286  if (!DNP3CheckStartBytes(hdr)) {
287  SCLogDebug("Invalid start bytes.");
288  return ALPROTO_FAILED;
289  }
290 
291  /* Verify minimum length. */
292  if (hdr->len < DNP3_MIN_LEN) {
293  SCLogDebug("Packet too small to be a valid DNP3 fragment.");
294  return ALPROTO_FAILED;
295  }
296 
297 end:
298  SCLogDebug("Detected DNP3.");
299  return ALPROTO_DNP3;
300 }
301 
302 /**
303  * \brief Caculate the length of the transport layer with CRCs removed.
304  *
305  * \param input_len The length of the transport layer buffer.
306  *
307  * \retval The length of the buffer after CRCs are removed.
308  */
309 static int DNP3CalculateTransportLengthWithoutCRCs(uint32_t input_len)
310 {
311  /* Too small. */
312  if (input_len < DNP3_CRC_LEN) {
313  return -1;
314  }
315 
316  /* Get the number of complete blocks. */
317  int blocks = input_len / (DNP3_BLOCK_SIZE + DNP3_CRC_LEN);
318 
319  /* And the number of bytes in the last block. */
320  int rem = input_len - (blocks * (DNP3_BLOCK_SIZE + DNP3_CRC_LEN));
321 
322  if (rem) {
323  if (rem < DNP3_CRC_LEN) {
324  return -1;
325  }
326  return (blocks * DNP3_BLOCK_SIZE) + (rem - DNP3_CRC_LEN);
327  }
328  else {
329  return (blocks * DNP3_BLOCK_SIZE);
330  }
331 }
332 
333 /**
334  * \brief Reassemble the application layer by stripping the CRCs.
335  *
336  * Remove the CRCs from the user data blocks. The output is the user
337  * data with the CRCs removed as well as the transport header removed,
338  * but the input data still needs to include the transport header as
339  * its part of the first user data block.
340  *
341  * If the output length passed in is non-null, the new input data will
342  * be appended, and the output length pointer incremented as needed.
343  *
344  * \param input Input buffer starting at the transport header (which
345  * will be removed from the output).
346  * \param input_len Length of the input buffer.
347  * \param output Pointer to output buffer (may be realloc'd).
348  * \param output_len Pointer to output length.
349  *
350  * \retval 1 if reassembly was successful, otherwise 0.
351  */
352 static int DNP3ReassembleApplicationLayer(const uint8_t *input,
353  uint32_t input_len, uint8_t **output, uint32_t *output_len)
354 {
355  int len = DNP3CalculateTransportLengthWithoutCRCs(input_len);
356 
357  if (len <= 0) {
358  return 0;
359  }
360 
361  /* Remove one byte for the transport header and make sure we have
362  * at least one byte of user data. */
363  if (--len < 1) {
364  return 0;
365  }
366 
367  if (*output == NULL) {
368  *output = SCCalloc(1, len);
369  if (unlikely(*output == NULL)) {
370  return 0;
371  }
372  }
373  else {
374  uint8_t *ptr = SCRealloc(*output, (size_t)(*output_len + len));
375  if (unlikely(ptr == NULL)) {
376  return 0;
377  }
378  *output = ptr;
379  }
380 
381  int offset = 0, block_size;
382  while ((uint32_t)offset < input_len) {
383  if (input_len - offset > DNP3_BLOCK_SIZE + DNP3_CRC_LEN) {
384  block_size = DNP3_BLOCK_SIZE + DNP3_CRC_LEN;
385  }
386  else {
387  block_size = input_len - offset;
388  }
389 
390  /* If handling the first block (offset is 0), trim off the
391  * first byte which is the transport header, and not part of
392  * the application data. */
393  if (offset == 0) {
394  offset++;
395  block_size--;
396  }
397 
398  /* Need at least 3 bytes to continue. One for application
399  * data, and 2 for the CRC. If not, return failure for
400  * malformed frame. */
401  if (block_size < DNP3_CRC_LEN + 1) {
402  SCLogDebug("Not enough data to continue.");
403  return 0;
404  }
405 
406  /* Make sure there is enough space to write into. */
407  if (block_size - DNP3_CRC_LEN > len) {
408  SCLogDebug("Not enough data to continue.");
409  return 0;
410  }
411 
412  memcpy(*output + *output_len, input + offset,
413  block_size - DNP3_CRC_LEN);
414  *output_len += block_size - DNP3_CRC_LEN;
415  offset += block_size;
416  len -= block_size - DNP3_CRC_LEN;
417  }
418 
419  return 1;
420 }
421 
422 /**
423  * \brief Allocate a DNP3 state object.
424  *
425  * The DNP3 state object represents a single DNP3 TCP session.
426  */
427 static void *DNP3StateAlloc(void)
428 {
429  SCEnter();
430  DNP3State *dnp3;
431 
432  dnp3 = (DNP3State *)SCCalloc(1, sizeof(DNP3State));
433  if (unlikely(dnp3 == NULL)) {
434  return NULL;
435  }
436  TAILQ_INIT(&dnp3->tx_list);
437 
438  SCReturnPtr(dnp3, "void");
439 }
440 
441 /**
442  * \brief Set a DNP3 application layer event.
443  *
444  * Sets an event on the current transaction object.
445  */
446 static void DNP3SetEvent(DNP3State *dnp3, uint8_t event)
447 {
448  if (dnp3 && dnp3->curr) {
450  dnp3->events++;
451  }
452  else {
454  "Fail set set event, state or txn was NULL.");
455  }
456 }
457 
458 /**
459  * \brief Set a DNP3 application layer event on a transaction.
460  */
461 static void DNP3SetEventTx(DNP3Transaction *tx, uint8_t event)
462 {
464  tx->dnp3->events++;
465 }
466 
467 /**
468  * \brief Allocation a DNP3 transaction.
469  */
470 static DNP3Transaction *DNP3TxAlloc(DNP3State *dnp3)
471 {
472  DNP3Transaction *tx = SCCalloc(1, sizeof(DNP3Transaction));
473  if (unlikely(tx == NULL)) {
474  return NULL;
475  }
476  dnp3->transaction_max++;
477  dnp3->unreplied++;
478  dnp3->curr = tx;
479  tx->dnp3 = dnp3;
480  tx->tx_num = dnp3->transaction_max;
483  TAILQ_INSERT_TAIL(&dnp3->tx_list, tx, next);
484 
485  /* Check for flood state. */
487  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_FLOODED);
488  dnp3->flooded = 1;
489  }
490 
491  return tx;
492 }
493 
494 /**
495  * \brief Calculate the length of a link frame with CRCs.
496  *
497  * This is required as the length parameter in the DNP3 header does not
498  * include the added CRCs.
499  *
500  * \param length The length from the DNP3 link header.
501  *
502  * \retval The length of the frame with CRCs included or 0 if the length isn't
503  * long enough to be a valid DNP3 frame.
504  */
505 static uint32_t DNP3CalculateLinkLength(uint8_t length)
506 {
507  uint32_t frame_len = 0;
508  int rem;
509 
510  /* Fail early if the length is less than the minimum size. */
511  if (length < DNP3_LINK_HDR_LEN) {
512  return 0;
513  }
514 
515  /* Subtract the 5 bytes of the header that are included in the
516  * length. */
517  length -= DNP3_LINK_HDR_LEN;
518 
519  rem = length % DNP3_BLOCK_SIZE;
520  frame_len = (length / DNP3_BLOCK_SIZE) * (DNP3_BLOCK_SIZE + DNP3_CRC_LEN);
521  if (rem) {
522  frame_len += rem + DNP3_CRC_LEN;
523  }
524 
525  return frame_len + sizeof(DNP3LinkHeader);
526 }
527 
528 /**
529  * \brief Check if the link function code specifies user data.
530  *
531  * \param header Point to link header.
532  *
533  * \retval 1 if frame contains user data, otherwise 0.
534  */
535 static int DNP3IsUserData(const DNP3LinkHeader *header)
536 {
537  switch (DNP3_LINK_FC(header->control)) {
540  return 1;
541  default:
542  return 0;
543  }
544 }
545 
546 /**
547  * \brief Check if the frame has user data.
548  *
549  * Check if the DNP3 frame actually has user data by checking if data
550  * exists after the headers.
551  *
552  * \retval 1 if user data exists, otherwise 0.
553  */
554 static int DNP3HasUserData(const DNP3LinkHeader *header)
555 {
556  if (DNP3_LINK_DIR(header->control)) {
557  return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) +
558  sizeof(DNP3ApplicationHeader);
559  }
560  else {
561  return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) +
562  sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd);
563  }
564 }
565 
566 /**
567  * \brief Reset a DNP3Buffer.
568  */
569 static void DNP3BufferReset(DNP3Buffer *buffer)
570 {
571  buffer->offset = 0;
572  buffer->len = 0;
573 }
574 
575 /**
576  * \brief Add data to a DNP3 buffer, enlarging the buffer if required.
577  *
578  * \param buffer Buffer to add data data.
579  * \param data Data to be added to buffer.
580  * \param len Size of data to be added to buffer.
581  *
582  * \param 1 if data was added successful, otherwise 0.
583  */
584 static int DNP3BufferAdd(DNP3Buffer *buffer, const uint8_t *data, uint32_t len)
585 {
586  if (buffer->size == 0) {
587  buffer->buffer = SCCalloc(1, len);
588  if (unlikely(buffer->buffer == NULL)) {
589  return 0;
590  }
591  buffer->size = len;
592  }
593  else if (buffer->len + len > buffer->size) {
594  uint8_t *tmp = SCRealloc(buffer->buffer, buffer->len + len);
595  if (unlikely(tmp == NULL)) {
596  return 0;
597  }
598  buffer->buffer = tmp;
599  buffer->size = buffer->len + len;
600  }
601  memcpy(buffer->buffer + buffer->len, data, len);
602  buffer->len += len;
603 
604  return 1;
605 }
606 
607 /**
608  * \brief Trim a DNP3 buffer.
609  *
610  * Trimming a buffer moves the data in the buffer up to the front of
611  * the buffer freeing up room at the end for more incoming data.
612  *
613  * \param buffer The buffer to trim.
614  */
615 static void DNP3BufferTrim(DNP3Buffer *buffer)
616 {
617  if (buffer->offset == buffer->len) {
618  DNP3BufferReset(buffer);
619  }
620  else if (buffer->offset > 0) {
621  memmove(buffer->buffer, buffer->buffer + buffer->offset,
622  buffer->len - buffer->offset);
623  buffer->len = buffer->len - buffer->offset;
624  buffer->offset = 0;
625  }
626 }
627 
628 /**
629  * \brief Free a DNP3 object.
630  */
631 static void DNP3ObjectFree(DNP3Object *object)
632 {
633  if (object->points != NULL) {
634  DNP3FreeObjectPointList(object->group, object->variation,
635  object->points);
636  }
637  SCFree(object);
638 }
639 
640 /**
641  * \breif Allocate a DNP3 object.
642  */
643 static DNP3Object *DNP3ObjectAlloc(void)
644 {
645  DNP3Object *object = SCCalloc(1, sizeof(*object));
646  if (unlikely(object == NULL)) {
647  return NULL;
648  }
649  object->points = DNP3PointListAlloc();
650  if (object->points == NULL) {
651  DNP3ObjectFree(object);
652  return NULL;
653  }
654  return object;
655 }
656 
657 /**
658  * \brief Decode DNP3 application objects.
659  *
660  * This function decoded known DNP3 application objects. As the
661  * protocol isn't self describing, we can only decode the buffer while
662  * the application objects are known. As soon as an unknown
663  * group/variation is hit, we must stop processing.
664  *
665  * \param buf the input buffer
666  * \param len length of the input buffer
667  * \param objects pointer to list where decoded objects will be stored.
668  *
669  * \retval 1 if all objects decoded, 0 if all objects could not be decoded (
670  * unknown group/variations)
671  */
672 static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf,
673  uint32_t len, DNP3ObjectList *objects)
674 {
675  int retval = 0;
676 
677  if (buf == NULL || len == 0) {
678  return 1;
679  }
680 
681  while (len) {
682  uint32_t offset = 0;
683 
684  if (len < sizeof(DNP3ObjHeader)) {
685  goto done;
686  }
687  DNP3ObjHeader *header = (DNP3ObjHeader *)buf;
688  offset += sizeof(DNP3ObjHeader);
689 
690  DNP3Object *object = DNP3ObjectAlloc();
691  if (unlikely(object == NULL)) {
692  goto done;
693  }
694  TAILQ_INSERT_TAIL(objects, object, next);
695 
696  object->group = header->group;
697  object->variation = header->variation;
698  object->qualifier = header->qualifier;
699  object->prefix_code = DNP3_OBJ_PREFIX(header->qualifier);
700  object->range_code = DNP3_OBJ_RANGE(header->qualifier);
701 
702  /* IEEE 1815-2012, Table 4-5. */
703  switch (object->range_code) {
704  case 0x00:
705  case 0x03: {
706  /* 1 octet start and stop indexes OR 1 octet start and
707  * stop virtual addresses. */
708  if (offset + (sizeof(uint8_t) * 2) > len) {
709  /* Not enough data. */
710  SCLogDebug("Not enough data.");
711  goto not_enough_data;
712  }
713  object->start = buf[offset++];
714  object->stop = buf[offset++];
715  object->count = object->stop - object->start + 1;
716  break;
717  }
718  case 0x01:
719  case 0x04: {
720  /* 2 octet start and stop indexes OR 2 octect start
721  * and stop virtual addresses. */
722  if (offset + (sizeof(uint16_t) * 2) > len) {
723  /* Not enough data. */
724  SCLogDebug("Not enough data.");
725  goto not_enough_data;
726  }
727  object->start = DNP3_SWAP16(*(uint16_t *)(buf + offset));
728  offset += sizeof(uint16_t);
729  object->stop = DNP3_SWAP16(*(uint16_t *)(buf + offset));
730  offset += sizeof(uint16_t);
731  object->count = object->stop - object->start + 1;
732  break;
733  }
734  case 0x02:
735  case 0x05: {
736  /* 4 octet start and stop indexes OR 4 octect start
737  * and stop virtual addresses. */
738  if (offset + (sizeof(uint32_t) * 2) > len) {
739  /* Not enough data. */
740  SCLogDebug("Not enough data.");
741  goto not_enough_data;
742  }
743  object->start = DNP3_SWAP32(*(uint32_t *)(buf + offset));
744  offset += sizeof(uint32_t);
745  object->stop = DNP3_SWAP32(*(uint32_t *)(buf + offset));
746  offset += sizeof(uint32_t);
747  object->count = object->stop - object->start + 1;
748  break;
749  }
750  case 0x06:
751  /* No range field. */
752  object->count = 0;
753  break;
754  case 0x07:
755  /* 1 octet count of objects. */
756  if (offset + sizeof(uint8_t) > len) {
757  SCLogDebug("Not enough data.");
758  goto not_enough_data;
759  }
760  object->count = buf[offset];
761  offset += sizeof(uint8_t);
762  break;
763  case 0x08: {
764  /* 2 octet count of objects. */
765  if (offset + sizeof(uint16_t) > len) {
766  SCLogDebug("Not enough data.");
767  goto not_enough_data;
768  }
769  object->count = DNP3_SWAP16(*(uint16_t *)(buf + offset));
770  offset += sizeof(uint16_t);
771  break;
772  }
773  case 0x09: {
774  /* 4 octet count of objects. */
775  if (offset + sizeof(uint32_t) > len) {
776  SCLogDebug("Not enough data.");
777  goto not_enough_data;
778  }
779  object->count = DNP3_SWAP32(*(uint32_t *)(buf + offset));
780  offset += sizeof(uint32_t);
781  break;
782  }
783  case 0x0b: {
784  if (offset + sizeof(uint8_t) > len) {
785  /* Not enough data. */
786  SCLogDebug("Not enough data.");
787  goto not_enough_data;
788  }
789  object->count = *(uint8_t *)(buf + offset);
790  offset += sizeof(uint8_t);
791  break;
792  }
793  default:
794  SCLogDebug("Range code 0x%02x is reserved.",
795  object->range_code);
796  goto done;
797  }
798 
799  buf += offset;
800  len -= offset;
801 
802  if (object->variation == 0 || object->count == 0) {
803  goto next;
804  }
805 
806  int event = DNP3DecodeObject(header->group, header->variation, &buf,
807  &len, object->prefix_code, object->start, object->count,
808  object->points);
809  if (event) {
810  DNP3SetEventTx(tx, DNP3_DECODER_EVENT_UNKNOWN_OBJECT);
811  goto done;
812  }
813 
814  next:
815  continue;
816  }
817 
818  /* All objects were decoded. */
819  retval = 1;
820 
821 not_enough_data:
822 done:
823  return retval;
824 }
825 
826 /**
827  * \brief Handle DNP3 request user data.
828  *
829  * \param dnp3 the current DNP3State
830  * \param input pointer to the DNP3 frame (starting with link header)
831  * \param input_len length of the input frame
832  */
833 static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input,
834  uint32_t input_len)
835 {
836  DNP3LinkHeader *lh;
838  DNP3ApplicationHeader *ah;
839  DNP3Transaction *tx = NULL, *ttx;
840 
841  lh = (DNP3LinkHeader *)input;
842 
843  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
844  input_len - sizeof(DNP3LinkHeader))) {
845  return;
846  }
847 
848  th = input[sizeof(DNP3LinkHeader)];
849 
850  if (!DNP3_TH_FIR(th)) {
851  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
852  if (ttx->request_lh.src == lh->src &&
853  ttx->request_lh.dst == lh->dst &&
854  ttx->has_request &&
855  !ttx->request_done &&
856  NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->request_th)) == DNP3_TH_SEQ(th))
857  {
858  tx = ttx;
859  break;
860  }
861  }
862 
863  if (tx == NULL) {
864  return;
865  }
866 
867  /* Update the saved transport header so subsequent segments
868  * will be matched to this sequence number. */
869  tx->response_th = th;
870  }
871  else {
872  ah = (DNP3ApplicationHeader *)(input + sizeof(DNP3LinkHeader) +
873  sizeof(DNP3TransportHeader));
874 
875  /* Ignore confirms - for now. */
876  if (ah->function_code == DNP3_APP_FC_CONFIRM) {
877  return;
878  }
879 
880  /* Create a transaction. */
881  tx = DNP3TxAlloc(dnp3);
882  if (unlikely(tx == NULL)) {
883  return;
884  }
885  tx->request_lh = *lh;
886  tx->request_th = th;
887  tx->request_ah = *ah;
888  tx->has_request = 1;
889 
890  }
891 
892  if (!DNP3ReassembleApplicationLayer(input + sizeof(DNP3LinkHeader),
893  input_len - sizeof(DNP3LinkHeader),
894  &tx->request_buffer, &tx->request_buffer_len)) {
895 
896  /* Malformed, set event and mark as done. */
897  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_MALFORMED);
898  tx->request_done = 1;
899  return;
900  }
901 
902  /* If this is not the final segment, just return. */
903  if (!DNP3_TH_FIN(th)) {
904  return;
905  }
906 
907  tx->request_done = 1;
908 
909  /* Some function codes do not expect a reply. */
910  switch (tx->request_ah.function_code) {
911  case DNP3_APP_FC_CONFIRM:
917  tx->response_done = 1;
918  default:
919  break;
920  }
921 
922  if (DNP3DecodeApplicationObjects(
923  tx, tx->request_buffer + sizeof(DNP3ApplicationHeader),
924  tx->request_buffer_len - sizeof(DNP3ApplicationHeader),
925  &tx->request_objects)) {
926  tx->request_complete = 1;
927  }
928 }
929 
930 static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input,
931  uint32_t input_len)
932 {
933  DNP3LinkHeader *lh;
935  DNP3ApplicationHeader *ah;
936  DNP3InternalInd *iin;
937  DNP3Transaction *tx = NULL, *ttx;
938  uint32_t offset = 0;
939 
940  lh = (DNP3LinkHeader *)input;
941  offset += sizeof(DNP3LinkHeader);
942 
943  if (!DNP3CheckUserDataCRCs(input + offset, input_len - offset)) {
944  return;
945  }
946 
947  th = input[offset++];
948 
949  if (!DNP3_TH_FIR(th)) {
950  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
951  if (ttx->response_lh.src == lh->src &&
952  ttx->response_lh.dst == lh->dst &&
953  ttx->has_response && !ttx->response_done &&
954  NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->response_th)) == DNP3_TH_SEQ(th))
955  {
956  tx = ttx;
957  break;
958  }
959  }
960 
961  if (tx == NULL) {
962  return;
963  }
964 
965  /* Replace the transport header in the transaction with this
966  * one in case there are more frames. */
967  tx->response_th = th;
968  }
969  else {
970  ah = (DNP3ApplicationHeader *)(input + offset);
971  offset += sizeof(DNP3ApplicationHeader);
972  iin = (DNP3InternalInd *)(input + offset);
973 
974  if (ah->function_code == DNP3_APP_FC_UNSOLICITED_RESP) {
975  tx = DNP3TxAlloc(dnp3);
976  if (unlikely(tx == NULL)) {
977  return;
978  }
979 
980  /* There is no request associated with an unsolicited
981  * response, so mark the request done as far as
982  * transaction state handling is concerned. */
983  tx->request_done = 1;
984  }
985  else {
986  /* Find transaction. */
987  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
988  if (ttx->has_request &&
989  ttx->request_done &&
990  ttx->request_lh.src == lh->dst &&
991  ttx->request_lh.dst == lh->src &&
992  !ttx->has_response &&
993  !ttx->response_done &&
994  DNP3_APP_SEQ(ttx->request_ah.control) == DNP3_APP_SEQ(ah->control)) {
995  tx = ttx;
996  break;
997  }
998  }
999  if (tx == NULL) {
1000  return;
1001  }
1002  }
1003 
1004  tx->has_response = 1;
1005  tx->response_lh = *lh;
1006  tx->response_th = th;
1007  tx->response_ah = *ah;
1008  tx->response_iin = *iin;
1009  }
1010 
1011  if (!DNP3ReassembleApplicationLayer(input + sizeof(DNP3LinkHeader),
1012  input_len - sizeof(DNP3LinkHeader),
1013  &tx->response_buffer, &tx->response_buffer_len)) {
1014  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_MALFORMED);
1015  return;
1016  }
1017 
1018  if (!DNP3_TH_FIN(th)) {
1019  return;
1020  }
1021 
1022  tx->response_done = 1;
1023 
1024  offset = sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd);
1025  if (DNP3DecodeApplicationObjects(tx, tx->response_buffer + offset,
1026  tx->response_buffer_len - offset,
1027  &tx->response_objects)) {
1028  tx->response_complete = 1;
1029  }
1030 }
1031 
1032 /**
1033  * \brief Decode the DNP3 request link layer.
1034  *
1035  * \retval number of bytes processed or -1 if the data stream does not look
1036  * like DNP3.
1037  */
1038 static int DNP3HandleRequestLinkLayer(DNP3State *dnp3, const uint8_t *input,
1039  uint32_t input_len)
1040 {
1041  SCEnter();
1042  uint32_t processed = 0;
1043 
1044  while (input_len) {
1045 
1046  /* Need at least enough bytes for a DNP3 header. */
1047  if (input_len < sizeof(DNP3LinkHeader)) {
1048  break;
1049  }
1050 
1051  DNP3LinkHeader *header = (DNP3LinkHeader *)input;
1052 
1053  if (!DNP3CheckStartBytes(header)) {
1054  goto error;
1055  }
1056 
1057  if (!DNP3CheckLinkHeaderCRC(header)) {
1058  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_LINK_CRC);
1059  goto error;
1060  }
1061 
1062  uint32_t frame_len = DNP3CalculateLinkLength(header->len);
1063  if (frame_len == 0) {
1064  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1065  goto error;
1066  }
1067  if (input_len < frame_len) {
1068  /* Insufficient data, just break - will wait for more data. */
1069  break;
1070  }
1071 
1072  /* Ignore non-user data for now. */
1073  if (!DNP3IsUserData(header)) {
1074  goto next;
1075  }
1076 
1077  /* Make sure the header length is large enough for transport and
1078  * application headers. */
1079  if (!DNP3HasUserData(header)) {
1080  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1081  goto next;
1082  }
1083 
1084  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
1085  frame_len - sizeof(DNP3LinkHeader))) {
1086  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC);
1087  goto next;
1088  }
1089 
1090  DNP3HandleUserDataRequest(dnp3, input, frame_len);
1091 
1092  next:
1093  /* Advance the input buffer. */
1094  input += frame_len;
1095  input_len -= frame_len;
1096  processed += frame_len;
1097  }
1098 
1099  SCReturnInt(processed);
1100 error:
1101  /* Error out. Should only happen if this doesn't look like a DNP3
1102  * frame. */
1103  SCReturnInt(-1);
1104 }
1105 
1106 /**
1107  * \brief Handle incoming request data.
1108  *
1109  * The actual request PDU parsing is done in
1110  * DNP3HandleRequestLinkLayer. This function takes care of buffering TCP
1111  * date if a segment does not contain a complete frame (or contains
1112  * multiple frames, but not the complete final frame).
1113  */
1114 static int DNP3ParseRequest(Flow *f, void *state, AppLayerParserState *pstate,
1115  uint8_t *input, uint32_t input_len, void *local_data,
1116  const uint8_t flags)
1117 {
1118  SCEnter();
1119  DNP3State *dnp3 = (DNP3State *)state;
1120  DNP3Buffer *buffer = &dnp3->request_buffer;
1121  int processed = 0;
1122 
1123  if (input_len == 0) {
1124  SCReturnInt(1);
1125  }
1126 
1127  if (buffer->len) {
1128  if (!DNP3BufferAdd(buffer, input, input_len)) {
1129  SCLogError(SC_ERR_MEM_ALLOC, "Failed to allocate memory to buffer "
1130  "DNP3 request data");
1131  goto error;
1132  }
1133  processed = DNP3HandleRequestLinkLayer(dnp3,
1134  buffer->buffer + buffer->offset,
1135  buffer->len - buffer->offset);
1136  if (processed < 0) {
1137  goto error;
1138  }
1139  buffer->offset += processed;
1140  DNP3BufferTrim(buffer);
1141  }
1142  else {
1143  processed = DNP3HandleRequestLinkLayer(dnp3, input, input_len);
1144  if (processed < 0) {
1145  SCLogDebug("Failed to process request link layer.");
1146  goto error;
1147  }
1148 
1149  input += processed;
1150  input_len -= processed;
1151 
1152  /* Not all data was processed, buffer it. */
1153  if (input_len) {
1154  if (!DNP3BufferAdd(buffer, input, input_len)) {
1156  "Failed to allocate memory to buffer DNP3 request data");
1157  goto error;
1158  }
1159  }
1160  }
1161 
1162  SCReturnInt(1);
1163 
1164 error:
1165  /* Reset the buffer. */
1166  DNP3BufferReset(buffer);
1167  SCReturnInt(-1);
1168 }
1169 
1170 /**
1171  * \brief Decode the DNP3 response link layer.
1172  *
1173  * \retval number of bytes processed or -1 if the data stream does not
1174  * like look DNP3.
1175  */
1176 static int DNP3HandleResponseLinkLayer(DNP3State *dnp3, const uint8_t *input,
1177  uint32_t input_len)
1178 {
1179  SCEnter();
1180  uint32_t processed = 0;
1181 
1182  while (input_len) {
1183 
1184  /* Need at least enough bytes for a DNP3 header. */
1185  if (input_len < sizeof(DNP3LinkHeader)) {
1186  break;
1187  }
1188 
1189  DNP3LinkHeader *header = (DNP3LinkHeader *)input;
1190 
1191  if (!DNP3CheckStartBytes(header)) {
1192  goto error;
1193  }
1194 
1195  if (!DNP3CheckLinkHeaderCRC(header)) {
1196  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_LINK_CRC);
1197  goto error;
1198  }
1199 
1200  /* Calculate the number of bytes needed to for this frame. */
1201  uint32_t frame_len = DNP3CalculateLinkLength(header->len);
1202  if (frame_len == 0) {
1203  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1204  goto error;
1205  }
1206  if (input_len < frame_len) {
1207  /* Insufficient data, just break - will wait for more data. */
1208  break;
1209  }
1210 
1211  /* Only handle user data frames for now. */
1212  if (!DNP3IsUserData(header)) {
1213  goto next;
1214  }
1215 
1216  /* Make sure the header length is large enough for transport and
1217  * application headers. */
1218  if (!DNP3HasUserData(header)) {
1219  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1220  goto error;
1221  }
1222 
1223  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
1224  frame_len - sizeof(DNP3LinkHeader))) {
1225  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC);
1226  goto next;
1227  }
1228 
1229  DNP3HandleUserDataResponse(dnp3, input, frame_len);
1230 
1231  next:
1232  /* Advance the input buffer. */
1233  input += frame_len;
1234  input_len -= frame_len;
1235  processed += frame_len;
1236  }
1237 
1238  SCReturnInt(processed);
1239 error:
1240  /* Error out. Should only happen if the data stream no longer
1241  * looks like DNP3. */
1242  SCReturnInt(-1);
1243 }
1244 
1245 /**
1246  * \brief Parse incoming data.
1247  *
1248  * This is the entry function for DNP3 application layer data. Its
1249  * main responsibility is buffering incoming data that cannot be
1250  * processed.
1251  *
1252  * See DNP3ParseResponsePDUs for DNP3 frame handling.
1253  */
1254 static int DNP3ParseResponse(Flow *f, void *state, AppLayerParserState *pstate,
1255  uint8_t *input, uint32_t input_len, void *local_data,
1256  const uint8_t flags)
1257 {
1258  SCEnter();
1259  DNP3State *dnp3 = (DNP3State *)state;
1260  DNP3Buffer *buffer = &dnp3->response_buffer;
1261  int processed;
1262 
1263  if (buffer->len) {
1264  if (!DNP3BufferAdd(buffer, input, input_len)) {
1265  SCLogError(SC_ERR_MEM_ALLOC, "Failed to allocate memory to buffer "
1266  "DNP3 response data");
1267  goto error;
1268  }
1269  processed = DNP3HandleResponseLinkLayer(dnp3,
1270  buffer->buffer + buffer->offset,
1271  buffer->len - buffer->offset);
1272  if (processed < 0) {
1273  goto error;
1274  }
1275  buffer->offset += processed;
1276  DNP3BufferTrim(buffer);
1277  }
1278  else {
1279 
1280  /* Check if this is a banner, ignore if it is. */
1281  if (DNP3ContainsBanner(input, input_len)) {
1282  goto done;
1283  }
1284 
1285  processed = DNP3HandleResponseLinkLayer(dnp3, input, input_len);
1286  if (processed < 0) {
1287  goto error;
1288  }
1289  input += processed;
1290  input_len -= processed;
1291 
1292  /* Not all data was processed, buffer it. */
1293  if (input_len) {
1294  if (!DNP3BufferAdd(buffer, input, input_len)) {
1296  "Failed to allocate memory to buffer DNP3 response data");
1297  goto error;
1298  }
1299  }
1300  }
1301 
1302 done:
1303  SCReturnInt(1);
1304 
1305 error:
1306  /* An error occurred while processing DNP3 frames. Dump the
1307  * buffer as we can't be assured that they are valid anymore. */
1308  DNP3BufferReset(buffer);
1309  SCReturnInt(-1);
1310 }
1311 
1312 static AppLayerDecoderEvents *DNP3GetEvents(void *tx)
1313 {
1314  return ((DNP3Transaction *) tx)->decoder_events;
1315 }
1316 
1317 static void *DNP3GetTx(void *alstate, uint64_t tx_id)
1318 {
1319  SCEnter();
1320  DNP3State *dnp3 = (DNP3State *)alstate;
1321  DNP3Transaction *tx = NULL;
1322  uint64_t tx_num = tx_id + 1;
1323 
1324  if (dnp3->curr && dnp3->curr->tx_num == (tx_num)) {
1325  SCReturnPtr(dnp3->curr, "void");
1326  }
1327 
1328  TAILQ_FOREACH(tx, &dnp3->tx_list, next) {
1329  if (tx_num != tx->tx_num) {
1330  continue;
1331  }
1332  SCReturnPtr(tx, "void");
1333  }
1334 
1335  SCReturnPtr(NULL, "void");
1336 }
1337 
1338 static uint64_t DNP3GetTxCnt(void *state)
1339 {
1340  SCEnter();
1341  uint64_t count = ((uint64_t)((DNP3State *)state)->transaction_max);
1342  SCReturnUInt(count);
1343 }
1344 
1345 /**
1346  * \brief Free all the objects in a DNP3ObjectList.
1347  */
1348 static void DNP3TxFreeObjectList(DNP3ObjectList *objects)
1349 {
1350  DNP3Object *object;
1351 
1352  while ((object = TAILQ_FIRST(objects)) != NULL) {
1353  TAILQ_REMOVE(objects, object, next);
1354  DNP3ObjectFree(object);
1355  }
1356 }
1357 
1358 /**
1359  * \brief Free a DNP3 transaction.
1360  */
1361 static void DNP3TxFree(DNP3Transaction *tx)
1362 {
1363  SCEnter();
1364 
1365  if (tx->request_buffer != NULL) {
1366  SCFree(tx->request_buffer);
1367  }
1368 
1369  if (tx->response_buffer != NULL) {
1370  SCFree(tx->response_buffer);
1371  }
1372 
1374 
1375  if (tx->de_state != NULL) {
1377  }
1378 
1379  DNP3TxFreeObjectList(&tx->request_objects);
1380  DNP3TxFreeObjectList(&tx->response_objects);
1381 
1382  SCFree(tx);
1383  SCReturn;
1384 }
1385 
1386 /**
1387  * \brief Free a transaction by ID on a specific DNP3 state.
1388  *
1389  * This function is called by the app-layer to free a transaction on a
1390  * specific DNP3 state object.
1391  */
1392 static void DNP3StateTxFree(void *state, uint64_t tx_id)
1393 {
1394  SCEnter();
1395  DNP3State *dnp3 = state;
1396  DNP3Transaction *tx = NULL, *ttx;
1397  uint64_t tx_num = tx_id + 1;
1398 
1399  TAILQ_FOREACH_SAFE(tx, &dnp3->tx_list, next, ttx) {
1400 
1401  if (tx->tx_num != tx_num) {
1402  continue;
1403  }
1404 
1405  if (tx == dnp3->curr) {
1406  dnp3->curr = NULL;
1407  }
1408 
1409  if (tx->decoder_events != NULL) {
1410  if (tx->decoder_events->cnt <= dnp3->events) {
1411  dnp3->events -= tx->decoder_events->cnt;
1412  }
1413  else {
1414  dnp3->events = 0;
1415  }
1416  }
1417  dnp3->unreplied--;
1418 
1419  /* Check flood state. */
1420  if (dnp3->flooded && dnp3->unreplied < DNP3_DEFAULT_REQ_FLOOD_COUNT) {
1421  dnp3->flooded = 0;
1422  }
1423 
1424  TAILQ_REMOVE(&dnp3->tx_list, tx, next);
1425  DNP3TxFree(tx);
1426  break;
1427  }
1428 
1429  SCReturn;
1430 }
1431 
1432 /**
1433  * \brief Free a DNP3 state.
1434  */
1435 static void DNP3StateFree(void *state)
1436 {
1437  SCEnter();
1438  DNP3State *dnp3 = state;
1439  DNP3Transaction *tx;
1440  if (state != NULL) {
1441  while ((tx = TAILQ_FIRST(&dnp3->tx_list)) != NULL) {
1442  TAILQ_REMOVE(&dnp3->tx_list, tx, next);
1443  DNP3TxFree(tx);
1444  }
1445  if (dnp3->request_buffer.buffer != NULL) {
1446  SCFree(dnp3->request_buffer.buffer);
1447  }
1448  if (dnp3->response_buffer.buffer != NULL) {
1449  SCFree(dnp3->response_buffer.buffer);
1450  }
1451  SCFree(dnp3);
1452  }
1453  SCReturn;
1454 }
1455 
1456 /**
1457  * \brief Called by the app-layer to get the state progress.
1458  */
1459 static int DNP3GetAlstateProgress(void *tx, uint8_t direction)
1460 {
1461  DNP3Transaction *dnp3tx = (DNP3Transaction *)tx;
1462  DNP3State *dnp3 = dnp3tx->dnp3;
1463  int retval = 0;
1464 
1465  /* If flooded, "ack" old transactions. */
1466  if (dnp3->flooded && (dnp3->transaction_max -
1467  dnp3tx->tx_num >= DNP3_DEFAULT_REQ_FLOOD_COUNT)) {
1468  SCLogDebug("flooded: returning tx as done.");
1469  SCReturnInt(1);
1470  }
1471 
1472  if (direction & STREAM_TOCLIENT && dnp3tx->response_done) {
1473  retval = 1;
1474  }
1475  else if (direction & STREAM_TOSERVER && dnp3tx->request_done) {
1476  retval = 1;
1477  }
1478 
1479  SCReturnInt(retval);
1480 }
1481 
1482 /**
1483  * \brief App-layer support.
1484  */
1485 static int DNP3GetAlstateProgressCompletionStatus(uint8_t direction)
1486 {
1487  return 1;
1488 }
1489 
1490 /**
1491  * \brief App-layer support.
1492  */
1493 static int DNP3StateGetEventInfo(const char *event_name, int *event_id,
1495 {
1496  *event_id = SCMapEnumNameToValue(event_name, dnp3_decoder_event_table);
1497  if (*event_id == -1) {
1498  SCLogError(SC_ERR_INVALID_ENUM_MAP, "Event \"%s\" not present in "
1499  "the DNP3 enum event map table.", event_name);
1500  return -1;
1501  }
1502 
1503  *event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
1504 
1505  return 0;
1506 }
1507 
1508 /**
1509  * \brief App-layer support.
1510  */
1511 static int DNP3StateGetEventInfoById(int event_id, const char **event_name,
1513 {
1514  *event_name = SCMapEnumValueToName(event_id, dnp3_decoder_event_table);
1515  if (*event_name == NULL) {
1516  SCLogError(SC_ERR_INVALID_ENUM_MAP, "Event \"%d\" not present in "
1517  "the DNP3 enum event map table.", event_id);
1518  return -1;
1519  }
1520 
1521  *event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
1522 
1523  return 0;
1524 }
1525 
1526 /**
1527  * \brief App-layer support.
1528  */
1529 static DetectEngineState *DNP3GetTxDetectState(void *vtx)
1530 {
1531  DNP3Transaction *tx = vtx;
1532  return tx->de_state;
1533 }
1534 
1535 /**
1536  * \brief App-layer support.
1537  */
1538 static int DNP3SetTxDetectState(void *vtx, DetectEngineState *s)
1539 {
1540  DNP3Transaction *tx = vtx;
1541  tx->de_state = s;
1542  return 0;
1543 }
1544 
1545 static void DNP3SetTxLogged(void *alstate, void *vtx, LoggerId logged)
1546 {
1547  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1548  tx->logged = logged;
1549 }
1550 
1551 static LoggerId DNP3GetTxLogged(void *alstate, void *vtx)
1552 {
1553  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1554  return tx->logged;
1555 }
1556 
1557 /**
1558  * \brief Check if the prefix code is a size prefix.
1559  *
1560  * \retval 1 if the prefix_code specifies a size prefix, 0 if not.
1561  */
1562 int DNP3PrefixIsSize(uint8_t prefix_code)
1563 {
1564  switch (prefix_code) {
1565  case 0x04:
1566  case 0x05:
1567  case 0x06:
1568  return 1;
1569  break;
1570  default:
1571  return 0;
1572  }
1573 }
1574 
1575 static uint64_t DNP3GetTxDetectFlags(void *vtx, uint8_t dir)
1576 {
1577  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1578  if (dir & STREAM_TOSERVER) {
1579  return tx->detect_flags_ts;
1580  } else {
1581  return tx->detect_flags_tc;
1582  }
1583 }
1584 
1585 static void DNP3SetTxDetectFlags(void *vtx, uint8_t dir, uint64_t detect_flags)
1586 {
1587  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1588  if (dir & STREAM_TOSERVER) {
1589  tx->detect_flags_ts = detect_flags;
1590  } else {
1591  tx->detect_flags_tc = detect_flags;
1592  }
1593  return;
1594 }
1595 
1596 /**
1597  * \brief Register the DNP3 application protocol parser.
1598  */
1600 {
1601  SCEnter();
1602 
1603  const char *proto_name = "dnp3";
1604 
1605  if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name))
1606  {
1608 
1609  if (RunmodeIsUnittests()) {
1611  ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader), STREAM_TOSERVER,
1612  DNP3ProbingParser, NULL);
1613  }
1614  else {
1615  if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP,
1616  proto_name, ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader),
1617  DNP3ProbingParser, NULL)) {
1618 #ifndef AFLFUZZ_APPLAYER
1619  return;
1620 #endif
1621  }
1622  }
1623 
1624  }
1625  else {
1626  SCLogConfig("Protocol detection and parser disabled for DNP3.");
1627  SCReturn;
1628  }
1629 
1630  if (AppLayerParserConfParserEnabled("tcp", proto_name))
1631  {
1632  SCLogConfig("Registering DNP3/tcp parsers.");
1633 
1635  DNP3ParseRequest);
1637  DNP3ParseResponse);
1638 
1640  DNP3StateAlloc, DNP3StateFree);
1641 
1643  DNP3GetEvents);
1645  DNP3GetTxDetectState, DNP3SetTxDetectState);
1647  DNP3GetTxDetectFlags, DNP3SetTxDetectFlags);
1648 
1649  AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTx);
1650  AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTxCnt);
1652  DNP3StateTxFree);
1653 
1655  DNP3GetAlstateProgress);
1657  DNP3GetAlstateProgressCompletionStatus);
1658 
1660  DNP3StateGetEventInfo);
1662  DNP3StateGetEventInfoById);
1663 
1665  DNP3GetTxLogged, DNP3SetTxLogged);
1666  }
1667  else {
1668  SCLogConfig("Parser disabled for protocol %s. "
1669  "Protocol detection still on.", proto_name);
1670  }
1671 
1672 #ifdef UNITTESTS
1675 #endif
1676 
1677  SCReturn;
1678 }
1679 
1680 #ifdef UNITTESTS
1681 
1682 #include "flow-util.h"
1683 #include "stream-tcp.h"
1684 
1685 /**
1686  * \brief Utility function to fix CRCs when mangling a frame.
1687  */
1688 static void DNP3FixCrc(uint8_t *data, uint32_t len)
1689 {
1690  uint32_t block_size;
1691 
1692  while (len) {
1693  if (len >= DNP3_BLOCK_SIZE + DNP3_CRC_LEN) {
1694  block_size = DNP3_BLOCK_SIZE;
1695  } else {
1696  block_size = len - DNP3_CRC_LEN;
1697  }
1698  uint16_t crc = DNP3ComputeCRC(data, block_size);
1699  data[block_size + 1] = (crc >> 8) & 0xff;
1700  data[block_size] = crc & 0xff;
1701  data += block_size + DNP3_CRC_LEN;
1702  len -= block_size + DNP3_CRC_LEN;
1703  }
1704 }
1705 
1706 /**
1707  * \test Test CRC checking on partial and full blocks.
1708  */
1709 static int DNP3ParserTestCheckCRC(void)
1710 {
1711  uint8_t request[] = {
1712  /* DNP3 start. */
1713  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
1714  0xa5, 0xe9,
1715 
1716  /* Transport header. */
1717  0xff,
1718 
1719  /* Application layer - segment 1. */
1720  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
1721  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
1722  0xef,
1723 
1724  /* Application layer - segment 2. */
1725  0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
1726  };
1727 
1728  /* Check link header CRC. */
1729  FAIL_IF(!DNP3CheckCRC(request, sizeof(DNP3LinkHeader)));
1730 
1731  /* Check first application layer segment. */
1732  FAIL_IF(!DNP3CheckCRC(request + sizeof(DNP3LinkHeader),
1734 
1735  /* Change a byte in link header, should fail now. */
1736  request[2]++;
1737  FAIL_IF(DNP3CheckCRC(request, sizeof(DNP3LinkHeader)));
1738 
1739  /* Change a byte in the first application segment, should fail
1740  * now. */
1741  request[sizeof(DNP3LinkHeader) + 3]++;
1742  FAIL_IF(DNP3CheckCRC(request + sizeof(DNP3LinkHeader),
1744 
1745  PASS;
1746 }
1747 
1748 /**
1749  * \test Test validation of all CRCs in user data.
1750  */
1751 static int DNP3CheckUserDataCRCsTest(void)
1752 {
1753  /* Multi-block data with valid CRCs. */
1754  uint8_t data_valid[] = {
1755  0xff, 0xc9, 0x05, 0x0c,
1756  0x01, 0x28, 0x01, 0x00,
1757  0x00, 0x00, 0x01, 0x01,
1758  0x01, 0x00, 0x00, 0x00,
1759  0x72, 0xef, /* CRC. */
1760 
1761  0xff, 0xc9, 0x05, 0x0c,
1762  0x01, 0x28, 0x01, 0x00,
1763  0x00, 0x00, 0x01, 0x01,
1764  0x01, 0x00, 0x00, 0x00,
1765  0x72, 0xef, /* CRC. */
1766 
1767  0xff, 0xc9, 0x05, 0x0c,
1768  0x01, 0x28, 0x01, 0x00,
1769  0x00, 0x00, 0x01, 0x01,
1770  0x01, 0x00, 0x00, 0x00,
1771  0x72, 0xef, /* CRC. */
1772 
1773  0x00, 0x00, 0x00, 0x00,
1774  0x00,
1775  0xff, 0xff, /* CRC. */
1776  };
1777  FAIL_IF(!DNP3CheckUserDataCRCs(data_valid, sizeof(data_valid)));
1778 
1779  /* Multi-block data with one non-crc byte altered. */
1780  uint8_t data_invalid[] = {
1781  0xff, 0xc9, 0x05, 0x0c,
1782  0x01, 0x28, 0x01, 0x00,
1783  0x00, 0x00, 0x01, 0x01,
1784  0x01, 0x00, 0x00, 0x00,
1785  0x72, 0xef, /* CRC. */
1786 
1787  0xff, 0xc9, 0x05, 0x0c,
1788  0x01, 0x28, 0x01, 0x00,
1789  0x00, 0x00, 0x01, 0x01,
1790  0x01, 0x00, 0x00, 0x00,
1791  0x72, 0xef, /* CRC. */
1792 
1793  0xff, 0xc9, 0x05, 0x0c,
1794  0x01, 0x28, 0x01, 0x00,
1795  0x00, 0x00, 0x01, 0x01,
1796  0x01, 0x00, 0x00, 0x00,
1797  0x72, 0xef, /* CRC. */
1798 
1799  0x00, 0x00, 0x00, 0x00,
1800  0x01, /* Invalid byte. */
1801  0xff, 0xff, /* CRC. */
1802  };
1803  FAIL_IF(DNP3CheckUserDataCRCs(data_invalid, sizeof(data_invalid)));
1804 
1805  /* 1 byte - need at least 3. */
1806  uint8_t one_byte_nocrc[] = { 0x01 };
1807  FAIL_IF(DNP3CheckUserDataCRCs(one_byte_nocrc, sizeof(one_byte_nocrc)));
1808 
1809  /* 2 bytes - need at least 3. */
1810  uint8_t two_byte_nocrc[] = { 0x01, 0x02 };
1811  FAIL_IF(DNP3CheckUserDataCRCs(two_byte_nocrc, sizeof(two_byte_nocrc)));
1812 
1813  /* 3 bytes, valid CRC. */
1814  uint8_t three_bytes_good_crc[] = { 0x00, 0x00, 0x00 };
1815  *(uint16_t *)(three_bytes_good_crc + 1) = DNP3ComputeCRC(
1816  three_bytes_good_crc, 1);
1817  FAIL_IF(!DNP3CheckUserDataCRCs(three_bytes_good_crc,
1818  sizeof(three_bytes_good_crc)));
1819 
1820  PASS;
1821 }
1822 
1823 /**
1824  * \test Test the link layer length calculation.
1825  *
1826  * Test the calculation that converts the link provided in the DNP3
1827  * header to the actual length of the frame. That is the length with
1828  * CRCs as the length in the header does not include CRCs.
1829  */
1830 static int DNP3CalculateLinkLengthTest(void)
1831 {
1832  /* These are invalid. */
1833  FAIL_IF(DNP3CalculateLinkLength(0) != 0);
1834  FAIL_IF(DNP3CalculateLinkLength(1) != 0);
1835  FAIL_IF(DNP3CalculateLinkLength(2) != 0);
1836  FAIL_IF(DNP3CalculateLinkLength(3) != 0);
1837  FAIL_IF(DNP3CalculateLinkLength(4) != 0);
1838 
1839  /* This is the minimum size. */
1840  FAIL_IF(DNP3CalculateLinkLength(5) != 10);
1841 
1842  /* 1 full user data blocks of data. */
1843  FAIL_IF(DNP3CalculateLinkLength(21) != 28);
1844 
1845  /* 2 full user data blocks of data. */
1846  FAIL_IF(DNP3CalculateLinkLength(37) != 46);
1847 
1848  /* 2 full user data blocks, plus one more byte. */
1849  /* 2 full user data blocks of data. */
1850  FAIL_IF(DNP3CalculateLinkLength(38) != 49);
1851 
1852  /* The maximum size. */
1853  FAIL_IF(DNP3CalculateLinkLength(255) != 292);
1854 
1855  PASS;
1856 }
1857 
1858 /**
1859  * \test The conversion of length with CRCs to the length without
1860  * CRCs.
1861  */
1862 static int DNP3CalculateTransportLengthWithoutCRCsTest(void)
1863 {
1864  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(0) != -1);
1865  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(1) != -1);
1866  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(2) != 0);
1867  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(3) != 1);
1868  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(16) != 14);
1869  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(17) != 15);
1870  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(18) != 16);
1871 
1872  /* 19 bytes is not enough for a second block. */
1873  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(19) != -1);
1874 
1875  /* 20 bytes really isn't enough either, but is large enough to
1876  * satisfy the CRC on the second block. */
1877  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(20) != 16);
1878 
1879  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(21) != 17);
1880 
1881  PASS;
1882 }
1883 
1884 /**
1885  * \test Test the validation of the link header CRC.
1886  */
1887 static int DNP3ParserCheckLinkHeaderCRC(void)
1888 {
1889  /* DNP3 frame with valid headers and CRCs. */
1890  uint8_t request[] = {
1891  /* DNP3 start. */
1892  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
1893  0xa5, 0xe9,
1894 
1895  /* Transport header. */
1896  0xff,
1897 
1898  /* Application layer. */
1899  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
1900  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
1901  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
1902  };
1903 
1904  DNP3LinkHeader *header = (DNP3LinkHeader *)request;
1905  FAIL_IF(!DNP3CheckLinkHeaderCRC(header));
1906 
1907  /* Alter a byte in the header. */
1908  request[4] = 0;
1909  FAIL_IF(DNP3CheckLinkHeaderCRC(header));
1910 
1911  PASS;
1912 }
1913 
1914 /**
1915  * \test Test removal of CRCs from user data.
1916  */
1917 static int DNP3ReassembleApplicationLayerTest01(void)
1918 {
1919  uint32_t reassembled_len = 0;
1920  uint8_t *output = NULL;
1921 
1922  uint8_t payload[] = {
1923 
1924  0xff, 0xc9, 0x05, 0x0c,
1925  0x01, 0x28, 0x01, 0x00,
1926  0x00, 0x00, 0x01, 0x01,
1927  0x01, 0x00, 0x00, 0x00,
1928  0x72, 0xef, /* CRC. */
1929 
1930  0xff, 0xc9, 0x05, 0x0c,
1931  0x01, 0x28, 0x01, 0x00,
1932  0x00, 0x00, 0x01, 0x01,
1933  0x01, 0x00, 0x00, 0x00,
1934  0x72, 0xef, /* CRC. */
1935 
1936  0xff, 0xc9, 0x05, 0x0c,
1937  0x01, 0x28, 0x01, 0x00,
1938  0x00, 0x00, 0x01, 0x01,
1939  0x01, 0x00, 0x00, 0x00,
1940  0x72, 0xef, /* CRC. */
1941 
1942  0x00, 0x00, 0x00, 0x00,
1943  0x00,
1944  0xff, 0xff, /* CRC. */
1945  };
1946 
1947  uint8_t expected[] = {
1948  0xc9, 0x05, 0x0c,
1949  0x01, 0x28, 0x01, 0x00,
1950  0x00, 0x00, 0x01, 0x01,
1951  0x01, 0x00, 0x00, 0x00,
1952  /* CRC removed. */
1953  0xff, 0xc9, 0x05, 0x0c,
1954  0x01, 0x28, 0x01, 0x00,
1955  0x00, 0x00, 0x01, 0x01,
1956  0x01, 0x00, 0x00, 0x00,
1957  /* CRC removed. */
1958  0xff, 0xc9, 0x05, 0x0c,
1959  0x01, 0x28, 0x01, 0x00,
1960  0x00, 0x00, 0x01, 0x01,
1961  0x01, 0x00, 0x00, 0x00,
1962  /* CRC removed. */
1963  0x00, 0x00, 0x00, 0x00,
1964  0x00
1965  /* CRC removed. */
1966  };
1967 
1968  /* Valid frame. */
1969  FAIL_IF(!DNP3ReassembleApplicationLayer(payload,
1970  sizeof(payload), &output, &reassembled_len));
1971  FAIL_IF(output == NULL);
1972  FAIL_IF(reassembled_len != sizeof(expected));
1973  FAIL_IF(memcmp(expected, output, reassembled_len));
1974  SCFree(output);
1975 
1976  /* 1 byte, invalid. */
1977  reassembled_len = 0;
1978  output = NULL;
1979  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 1, &output,
1980  &reassembled_len));
1981  FAIL_IF(output != NULL);
1982  FAIL_IF(reassembled_len != 0);
1983 
1984  /* 2 bytes, invalid. */
1985  reassembled_len = 0;
1986  output = NULL;
1987  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 2, &output,
1988  &reassembled_len));
1989  FAIL_IF(output != NULL);
1990  FAIL_IF(reassembled_len != 0);
1991 
1992  /* 3 bytes, minimum - but that would only be the transport header
1993  * which isn't included in the output. */
1994  reassembled_len = 0;
1995  output = NULL;
1996  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 3, &output,
1997  &reassembled_len));
1998  FAIL_IF(output != NULL);
1999  FAIL_IF(reassembled_len != 0);
2000 
2001  /* 4 bytes is the minimum to get any reassembled data. */
2002  reassembled_len = 0;
2003  output = NULL;
2004  FAIL_IF(!DNP3ReassembleApplicationLayer(payload, 4, &output,
2005  &reassembled_len));
2006  FAIL_IF(output == NULL);
2007  FAIL_IF(reassembled_len != 1);
2008 
2009  /* Last block too short (by 1 byte) for data + CRC. */
2010  uint8_t short_payload1[] = {
2011 
2012  0xff, 0xc9, 0x05, 0x0c,
2013  0x01, 0x28, 0x01, 0x00,
2014  0x00, 0x00, 0x01, 0x01,
2015  0x01, 0x00, 0x00, 0x00,
2016  0x72, 0xef, /* CRC. */
2017 
2018  0xff, 0xc9, 0x05, 0x0c,
2019  0x01, 0x28, 0x01, 0x00,
2020  0x00, 0x00, 0x01, 0x01,
2021  0x01, 0x00, 0x00, 0x00,
2022  0x72, 0xef, /* CRC. */
2023 
2024  0xff, 0xc9, 0x05, 0x0c,
2025  0x01, 0x28, 0x01, 0x00,
2026  0x00, 0x00, 0x01, 0x01,
2027  0x01, 0x00, 0x00, 0x00,
2028  0x72, 0xef, /* CRC. */
2029 
2030  0x00, 0x00
2031  };
2032  reassembled_len = 0;
2033  FAIL_IF(DNP3ReassembleApplicationLayer(short_payload1,
2034  sizeof(short_payload1), &output, &reassembled_len));
2035 
2036  /* Last block too short (by 2 bytes) for data + CRC. */
2037  uint8_t short_payload2[] = {
2038 
2039  0xff, 0xc9, 0x05, 0x0c,
2040  0x01, 0x28, 0x01, 0x00,
2041  0x00, 0x00, 0x01, 0x01,
2042  0x01, 0x00, 0x00, 0x00,
2043  0x72, 0xef, /* CRC. */
2044 
2045  0xff, 0xc9, 0x05, 0x0c,
2046  0x01, 0x28, 0x01, 0x00,
2047  0x00, 0x00, 0x01, 0x01,
2048  0x01, 0x00, 0x00, 0x00,
2049  0x72, 0xef, /* CRC. */
2050 
2051  0xff, 0xc9, 0x05, 0x0c,
2052  0x01, 0x28, 0x01, 0x00,
2053  0x00, 0x00, 0x01, 0x01,
2054  0x01, 0x00, 0x00, 0x00,
2055  0x72, 0xef, /* CRC. */
2056 
2057  0x00,
2058  };
2059  reassembled_len = 0;
2060  FAIL_IF(DNP3ReassembleApplicationLayer(short_payload2,
2061  sizeof(short_payload2), &output, &reassembled_len));
2062 
2063  PASS;
2064 }
2065 
2066 /**
2067  * \test Test the probing parser.
2068  */
2069 static int DNP3ProbingParserTest(void)
2070 {
2071  uint8_t pkt[] = {
2072  0x05, 0x64, 0x05, 0xc9, 0x03, 0x00, 0x04, 0x00,
2073  0xbd, 0x71
2074  };
2075  uint8_t rdir = 0;
2076 
2077  /* Valid frame. */
2078  FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(pkt), &rdir) != ALPROTO_DNP3);
2079 
2080  /* Send too little bytes. */
2081  FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(DNP3LinkHeader) - 1, &rdir) != ALPROTO_UNKNOWN);
2082 
2083  /* Bad start bytes. */
2084  pkt[0] = 0x06;
2085  FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(pkt), &rdir) != ALPROTO_FAILED);
2086 
2087  /* Restore start byte. */
2088  pkt[0] = 0x05;
2089 
2090  /* Set the length to a value less than the minimum length of 5. */
2091  pkt[2] = 0x03;
2092  FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(pkt), &rdir) != ALPROTO_FAILED);
2093 
2094  /* Send a banner. */
2095  char mybanner[] = "Welcome to DNP3 SCADA.";
2096  FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, (uint8_t *)mybanner, sizeof(mybanner), &rdir) != ALPROTO_DNP3);
2097 
2098  PASS;
2099 }
2100 
2101 /**
2102  * \test Test a basic request/response.
2103  */
2104 static int DNP3ParserTestRequestResponse(void)
2105 {
2106  DNP3State *state = NULL;
2107 
2108  uint8_t request[] = {
2109  /* DNP3 start. */
2110  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2111  0xa5, 0xe9,
2112 
2113  /* Transport header. */
2114  0xff,
2115 
2116  /* Application layer. */
2117  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2118  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2119  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2120  };
2121 
2122  uint8_t response[] = {
2123  /* DNP3 start. */
2124  0x05, 0x64, 0x1c, 0x44, 0x01, 0x00, 0x02, 0x00,
2125  0xe2, 0x59,
2126 
2127  /* Transport header. */
2128  0xc3,
2129 
2130  /* Application layer. */
2131  0xc9, 0x81, 0x00, 0x00, 0x0c, 0x01, 0x28, 0x01,
2132  0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x7a,
2133  0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2134  0xff, 0xff
2135  };
2136 
2138  Flow flow;
2139  TcpSession ssn;
2140 
2141  memset(&flow, 0, sizeof(flow));
2142  memset(&ssn, 0, sizeof(ssn));
2143 
2144  flow.protoctx = (void *)&ssn;
2145  flow.proto = IPPROTO_TCP;
2146  flow.alproto = ALPROTO_DNP3;
2147 
2149 
2150  SCMutexLock(&flow.m);
2151  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2152  STREAM_TOSERVER, request, sizeof(request)));
2153  SCMutexUnlock(&flow.m);
2154 
2155  state = flow.alstate;
2156  FAIL_IF(state == NULL);
2157 
2158  DNP3Transaction *tx = DNP3GetTx(state, 0);
2159  FAIL_IF(tx == NULL);
2160  FAIL_IF(tx->tx_num != 1);
2161  FAIL_IF(tx != state->curr);
2162  FAIL_IF(tx->request_buffer == NULL);
2163  FAIL_IF(tx->request_buffer_len != 20);
2164  FAIL_IF(tx->request_ah.function_code != DNP3_APP_FC_DIR_OPERATE);
2165 
2166  SCMutexLock(&flow.m);
2167  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2168  STREAM_TOCLIENT, response, sizeof(response)));
2169  SCMutexUnlock(&flow.m);
2170  FAIL_IF(DNP3GetTx(state, 0) != tx);
2171  FAIL_IF(!tx->response_done);
2172  FAIL_IF(tx->response_buffer == NULL);
2173 
2174  AppLayerParserThreadCtxFree(alp_tctx);
2176  FLOW_DESTROY(&flow);
2177  PASS;
2178 }
2179 
2180 /**
2181  * \test Test an unsolicited response from an outstation.
2182  *
2183  * This is kind of like a request initiated from the "server".
2184  */
2185 static int DNP3ParserTestUnsolicitedResponseConfirm(void)
2186 {
2187  DNP3State *state = NULL;
2188 
2189  /* Unsolicited response with confirm bit set. */
2190  uint8_t response[] = {
2191  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2192  0x89, 0xe5, 0xc4, 0xfa, 0x82, 0x00, 0x00, 0x02,
2193  0x02, 0x17, 0x01, 0x01, 0x81, 0xa7, 0x75, 0xd8,
2194  0x32, 0x4c, 0x81, 0x3e, 0x01, 0xa1, 0xc9
2195  };
2196 
2197  /* Confirm. */
2198  uint8_t confirm[] = {
2199  0x05, 0x64, 0x08, 0xc4, 0x02, 0x00,
2200  0x01, 0x00, 0xd3, 0xb7, 0xc0, 0xda, 0x00, 0x6a,
2201  0x3d
2202  };
2203 
2205  Flow flow;
2206  TcpSession ssn;
2207 
2208  memset(&flow, 0, sizeof(flow));
2209  memset(&ssn, 0, sizeof(ssn));
2210 
2211  flow.protoctx = (void *)&ssn;
2212  flow.proto = IPPROTO_TCP;
2213  flow.alproto = ALPROTO_DNP3;
2214 
2216 
2217  SCMutexLock(&flow.m);
2218  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2219  STREAM_TOCLIENT, response, sizeof(response)));
2220  SCMutexUnlock(&flow.m);
2221 
2222  state = flow.alstate;
2223  FAIL_IF(state == NULL);
2224 
2225  DNP3Transaction *tx = DNP3GetTx(state, 0);
2226  FAIL_IF(tx == NULL);
2227  FAIL_IF(tx->tx_num != 1);
2228  FAIL_IF(tx != state->curr);
2229  FAIL_IF(tx->request_buffer != NULL);
2230  FAIL_IF(tx->response_buffer == NULL);
2231  FAIL_IF(!tx->response_done);
2232  FAIL_IF(tx->response_ah.function_code != DNP3_APP_FC_UNSOLICITED_RESP);
2233 
2234  SCMutexLock(&flow.m);
2235  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2236  STREAM_TOSERVER, confirm, sizeof(confirm)));
2237  SCMutexUnlock(&flow.m);
2238  FAIL_IF(DNP3GetTx(state, 0) != tx);
2239  FAIL_IF(!tx->response_done);
2240  FAIL_IF(tx->response_buffer == NULL);
2241  /* FAIL_IF(tx->iin1 != 0 || tx->iin2 != 0); */
2242 
2243  AppLayerParserThreadCtxFree(alp_tctx);
2245  FLOW_DESTROY(&flow);
2246  PASS;
2247 }
2248 
2249 /**
2250  * \test Test flood state.
2251  */
2252 static int DNP3ParserTestFlooded(void)
2253 {
2254  DNP3State *state = NULL;
2255 
2256  uint8_t request[] = {
2257  /* DNP3 start. */
2258  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2259  0xa5, 0xe9,
2260 
2261  /* Transport header. */
2262  0xff,
2263 
2264  /* Application layer. */
2265  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2266  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2267  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2268  };
2269 
2271  Flow flow;
2272  TcpSession ssn;
2273 
2274  memset(&flow, 0, sizeof(flow));
2275  memset(&ssn, 0, sizeof(ssn));
2276 
2277  flow.protoctx = (void *)&ssn;
2278  flow.proto = IPPROTO_TCP;
2279  flow.alproto = ALPROTO_DNP3;
2280 
2282 
2283  SCMutexLock(&flow.m);
2284  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2285  STREAM_TOSERVER, request, sizeof(request)));
2286  SCMutexUnlock(&flow.m);
2287 
2288  state = flow.alstate;
2289  FAIL_IF(state == NULL);
2290 
2291  DNP3Transaction *tx = DNP3GetTx(state, 0);
2292  FAIL_IF(tx == NULL);
2293  FAIL_IF(tx->tx_num != 1);
2294  FAIL_IF(tx != state->curr);
2295  FAIL_IF(tx->request_buffer == NULL);
2296  FAIL_IF(tx->request_buffer_len != 20);
2297  /* FAIL_IF(tx->app_function_code != DNP3_APP_FC_DIR_OPERATE); */
2298  FAIL_IF(tx->response_done);
2299 
2300  for (int i = 0; i < DNP3_DEFAULT_REQ_FLOOD_COUNT - 1; i++) {
2301  SCMutexLock(&flow.m);
2302  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2303  STREAM_TOSERVER, request, sizeof(request)));
2304  SCMutexUnlock(&flow.m);
2305  }
2306  FAIL_IF(state->flooded);
2307  FAIL_IF(DNP3GetAlstateProgress(tx, 0));
2308 
2309  /* One more request should trip us into flooded state. */
2310  SCMutexLock(&flow.m);
2311  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2312  STREAM_TOSERVER, request, sizeof(request)));
2313  SCMutexUnlock(&flow.m);
2314  FAIL_IF(!state->flooded);
2315 
2316  /* Progress for the oldest tx should return 1. */
2317  FAIL_IF(!DNP3GetAlstateProgress(tx, 0));
2318 
2319  /* But progress for the current state should still return 0. */
2320  FAIL_IF(DNP3GetAlstateProgress(state->curr, 0));
2321 
2322  AppLayerParserThreadCtxFree(alp_tctx);
2324  FLOW_DESTROY(&flow);
2325  PASS;
2326 }
2327 
2328 /**
2329  * \test Test parsing of partial frames.
2330  *
2331  * As DNP3 operates over TCP, it is possible that a partial DNP3 frame
2332  * is received. Test that the partial frame will be buffered until the
2333  * remainder is seen.
2334  */
2335 static int DNP3ParserTestPartialFrame(void)
2336 {
2337  DNP3State *state = NULL;
2338  DNP3Transaction *tx;
2339  int r;
2340 
2341  uint8_t request_partial1[] = {
2342  /* DNP3 start. */
2343  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2344  0xa5, 0xe9,
2345 
2346  /* Transport header. */
2347  0xff,
2348 
2349  /* Application layer. */
2350  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2351  };
2352 
2353  uint8_t request_partial2[] = {
2354  /* Remainder of application layer. */
2355  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2356  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2357  };
2358 
2359  uint8_t response_partial1[] = {
2360  /* DNP3 start. */
2361  0x05, 0x64, 0x1c, 0x44, 0x01, 0x00, 0x02, 0x00,
2362  0xe2, 0x59,
2363 
2364  /* Transport header. */
2365  0xc3,
2366 
2367  /* Application layer. */
2368  0xc9, 0x81, 0x00, 0x00, 0x0c, 0x01, 0x28, 0x01,
2369  };
2370 
2371  uint8_t response_partial2[] = {
2372  0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x7a,
2373  0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2374  0xff, 0xff
2375  };
2376 
2377  /* Boiler plate for app layer setup. */
2379  Flow flow;
2380  TcpSession ssn;
2381  memset(&flow, 0, sizeof(flow));
2382  memset(&ssn, 0, sizeof(ssn));
2383  flow.protoctx = (void *)&ssn;
2384  flow.proto = IPPROTO_TCP;
2385  flow.alproto = ALPROTO_DNP3;
2387 
2388  /* Pass in the first partial frame. */
2389 
2390  SCMutexLock(&flow.m);
2391  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2392  STREAM_TOSERVER, request_partial1, sizeof(request_partial1));
2393  SCMutexUnlock(&flow.m);
2394  FAIL_IF(r != 0);
2395 
2396  /* Frame should just be buffered, but not yet processed. */
2397  state = flow.alstate;
2398  FAIL_IF(state == NULL);
2399  FAIL_IF(state->request_buffer.len != sizeof(request_partial1));
2400  FAIL_IF(state->request_buffer.offset != 0);
2401  FAIL_IF(memcmp(state->request_buffer.buffer, request_partial1,
2402  sizeof(request_partial1)));
2403 
2404  /* There should not be a transaction yet. */
2405  FAIL_IF(state->transaction_max != 0);
2406  FAIL_IF(DNP3GetTx(state, 0) != NULL);
2407 
2408  /* Send the second partial. */
2409  SCMutexLock(&flow.m);
2410  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2411  STREAM_TOSERVER, request_partial2, sizeof(request_partial2));
2412  SCMutexUnlock(&flow.m);
2413  FAIL_IF(r != 0);
2414 
2415  /* The second partial completed the frame, the buffer should now
2416  * be clear. */
2417  FAIL_IF(state->request_buffer.len != 0);
2418  FAIL_IF(state->request_buffer.offset != 0);
2419 
2420  /* Should now have a complete transaction. */
2421  tx = DNP3GetTx(state, 0);
2422  FAIL_IF(tx == NULL);
2423  FAIL_IF(tx->tx_num != 1);
2424  FAIL_IF(tx != state->curr);
2425  FAIL_IF(tx->request_buffer == NULL);
2426  FAIL_IF(tx->request_buffer_len != 20);
2427  FAIL_IF(tx->request_ah.function_code != DNP3_APP_FC_DIR_OPERATE);
2428 
2429  /* Send partial response. */
2430  SCMutexLock(&flow.m);
2431  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2432  STREAM_TOCLIENT, response_partial1, sizeof(response_partial1));
2433  SCMutexUnlock(&flow.m);
2434  FAIL_IF(r != 0);
2435  FAIL_IF(state->response_buffer.len != sizeof(response_partial1));
2436  FAIL_IF(state->response_buffer.offset != 0);
2437  FAIL_IF(tx->response_done);
2438 
2439  /* Send rest of response. */
2440  SCMutexLock(&flow.m);
2441  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2442  STREAM_TOCLIENT, response_partial2, sizeof(response_partial2));
2443  SCMutexUnlock(&flow.m);
2444  FAIL_IF(r != 0);
2445 
2446  /* Buffer should now be empty. */
2447  FAIL_IF(state->response_buffer.len != 0);
2448  FAIL_IF(state->response_buffer.offset != 0);
2449 
2450  /* Transaction should be replied to now. */
2451  FAIL_IF(!tx->response_done);
2452  FAIL_IF(tx->response_buffer == NULL);
2453  FAIL_IF(tx->response_buffer_len == 0);
2454 
2455  AppLayerParserThreadCtxFree(alp_tctx);
2457  FLOW_DESTROY(&flow);
2458  PASS;
2459 }
2460 
2461 /**
2462  * \test Test multiple DNP3 frames in one TCP read.
2463  */
2464 static int DNP3ParserTestMultiFrame(void)
2465 {
2466  DNP3State *state = NULL;
2467 
2468  /* Unsolicited response 1. */
2469  uint8_t unsol_response1[] = {
2470  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2471  0x89, 0xe5, 0xc4, 0xfa, 0x82, 0x00, 0x00, 0x02,
2472  0x02, 0x17, 0x01, 0x01, 0x81, 0xa7, 0x75, 0xd8,
2473  0x32, 0x4c, 0x81, 0x3e, 0x01, 0xa1, 0xc9,
2474  };
2475 
2476  /* Unsolicited response 2. */
2477  uint8_t unsol_response2[] = {
2478  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2479  0x89, 0xe5, 0xc5, 0xfb, 0x82, 0x00, 0x00, 0x02,
2480  0x02, 0x17, 0x01, 0x0c, 0x01, 0xd8, 0x75, 0xd8,
2481  0x32, 0x4c, 0xc9, 0x3c, 0x01, 0xa1, 0xc9,
2482  };
2483 
2484  uint8_t combined[sizeof(unsol_response1) + sizeof(unsol_response2)];
2485  memcpy(combined, unsol_response1, sizeof(unsol_response1));
2486  memcpy(combined + sizeof(unsol_response1), unsol_response2,
2487  sizeof(unsol_response2));
2488 
2489  /* Setup. */
2491  Flow flow;
2492  TcpSession ssn;
2493  int r;
2494  memset(&flow, 0, sizeof(flow));
2495  memset(&ssn, 0, sizeof(ssn));
2496  flow.protoctx = (void *)&ssn;
2497  flow.proto = IPPROTO_TCP;
2498  flow.alproto = ALPROTO_DNP3;
2500 
2501  SCMutexLock(&flow.m);
2502  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2503  STREAM_TOCLIENT, combined, sizeof(combined));
2504  SCMutexUnlock(&flow.m);
2505  FAIL_IF(r != 0);
2506 
2507  state = flow.alstate;
2508  FAIL_IF(state == NULL);
2509  FAIL_IF(state->transaction_max != 2);
2510 
2511  AppLayerParserThreadCtxFree(alp_tctx);
2513  FLOW_DESTROY(&flow);
2514  PASS;
2515 }
2516 
2517 /**
2518  * \test Test the parsing of a request PDU.
2519  *
2520  * The PDU under test contains a single read request object:
2521  * - Group: 1
2522  * - Variation: 0
2523  * - Count: 0
2524  */
2525 static int DNP3ParserTestParsePDU01(void)
2526 {
2527  /* Frame to be tested. This frame is a DNP3 request with one read
2528  * request data object, group 1, variation 0. */
2529  const uint8_t pkt[] = {
2530  0x05, 0x64,
2531  0x0b, 0xc4, 0x17, 0x00, 0xef, 0xff, 0xc4, 0x8f,
2532  0xe1, 0xc8, 0x01, 0x01, 0x00, 0x06, 0x77, 0x6e
2533  };
2534 
2535  DNP3State *dnp3state = DNP3StateAlloc();
2536  int pdus = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2537  FAIL_IF(pdus < 1);
2538  DNP3Transaction *dnp3tx = DNP3GetTx(dnp3state, 0);
2539  FAIL_IF_NULL(dnp3tx);
2540  FAIL_IF(!dnp3tx->has_request);
2541  FAIL_IF(TAILQ_EMPTY(&dnp3tx->request_objects));
2542  DNP3Object *object = TAILQ_FIRST(&dnp3tx->request_objects);
2543  FAIL_IF(object->group != 1 || object->variation != 0);
2544  FAIL_IF(object->count != 0);
2545 
2546  DNP3StateFree(dnp3state);
2547  PASS;
2548 }
2549 
2550 /**
2551  * \test Test the decode of a DNP3 fragment with a single 70:3 object.
2552  */
2553 static int DNP3ParserDecodeG70V3Test(void)
2554 {
2555  const uint8_t pkt[] = {
2556  0x05, 0x64,
2557  0x63, 0xc4, 0x04, 0x00, 0x03, 0x00, 0xc7, 0xee,
2558  0xc7, 0xc9, 0x1b, 0x46, 0x03, 0x5b, 0x01, 0x55,
2559  0x00, 0x1a, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00,
2560  0x9e, 0xc7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2561  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2562  0x00, 0x00, 0xff, 0xff, 0x00, 0x1e, 0x00, 0x43,
2563  0x3a, 0x2f, 0x74, 0x65, 0x6d, 0x70, 0x2f, 0x44,
2564  0x4e, 0x50, 0x44, 0x65, 0x67, 0x7d, 0x76, 0x69,
2565  0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
2566  0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x93, 0x0c,
2567  0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65,
2568  0x6e, 0x20, 0x74, 0x6f, 0x20, 0x52, 0x65, 0x6d,
2569  0x35, 0x20, 0x6f, 0x74, 0x65, 0x20, 0x44, 0x65,
2570  0x76, 0x69, 0x63, 0x65, 0x2e, 0x78, 0x6d, 0x6c,
2571  0xc4, 0x8b
2572  };
2573 
2574  DNP3State *dnp3state = DNP3StateAlloc();
2575  FAIL_IF_NULL(dnp3state);
2576  int bytes = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2577  FAIL_IF(bytes != sizeof(pkt));
2578  DNP3Transaction *tx = DNP3GetTx(dnp3state, 0);
2579  FAIL_IF_NULL(tx);
2580  FAIL_IF_NOT(tx->has_request);
2581  DNP3Object *obj = TAILQ_FIRST(&tx->request_objects);
2582  FAIL_IF_NULL(obj);
2583  FAIL_IF_NOT(obj->group == 70);
2584  FAIL_IF_NOT(obj->variation == 3);
2585  FAIL_IF_NOT(obj->prefix_code == 0x5);
2586  FAIL_IF_NOT(obj->range_code == 0xb);
2587  FAIL_IF_NOT(obj->count == 1);
2588  DNP3Point *point = TAILQ_FIRST(obj->points);
2589  FAIL_IF_NULL(point);
2590  FAIL_IF_NOT(point->prefix == 85);
2591  FAIL_IF_NOT(point->size == 85);
2592  FAIL_IF_NULL(point->data);
2593  DNP3ObjectG70V3 *data = point->data;
2594  FAIL_IF_NOT(strcmp(
2595  data->filename,
2596  "C:/temp/DNPDeviceConfiguration written to Remote Device.xml") == 0);
2597  DNP3StateFree(dnp3state);
2598  PASS;
2599 }
2600 
2601 /**
2602  * \brief Test that an alert is raised on an unknown object.
2603  */
2604 static int DNP3ParserUnknownEventAlertTest(void)
2605 {
2606  /* Valid DNP3 frame with 70:3 object. */
2607  uint8_t pkt[] = {
2608  0x05, 0x64, 0x63, 0xc4, 0x04, 0x00, 0x03, 0x00,
2609  0xc7, 0xee,
2610 
2611  0xc7, 0xc9, 0x1b,
2612 
2613  /* Object and variation. Originally 70:3, now 70:99, an
2614  * unknown object. */
2615  0x46, 0x63,
2616 
2617  0x5b, 0x01, 0x55,
2618  0x00, 0x1a, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00,
2619  0x9e, 0xc7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2620  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2621  0x00, 0x00, 0xff, 0xff, 0x00, 0x1e, 0x00, 0x43,
2622  0x3a, 0x2f, 0x74, 0x65, 0x6d, 0x70, 0x2f, 0x44,
2623  0x4e, 0x50, 0x44, 0x65, 0x67, 0x7d, 0x76, 0x69,
2624  0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
2625  0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x93, 0x0c,
2626  0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65,
2627  0x6e, 0x20, 0x74, 0x6f, 0x20, 0x52, 0x65, 0x6d,
2628  0x35, 0x20, 0x6f, 0x74, 0x65, 0x20, 0x44, 0x65,
2629  0x76, 0x69, 0x63, 0x65, 0x2e, 0x78, 0x6d, 0x6c,
2630  0xc4, 0x8b
2631  };
2632 
2633  DNP3FixCrc(pkt + 10, sizeof(pkt) - 10);
2634 
2635  DNP3State *dnp3state = DNP3StateAlloc();
2636  FAIL_IF_NULL(dnp3state);
2637  int bytes = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2638  FAIL_IF(bytes != sizeof(pkt));
2639 
2640  DNP3StateFree(dnp3state);
2641  PASS;
2642 }
2643 
2644 #endif
2645 
2647 {
2648 #ifdef UNITTESTS
2649  UtRegisterTest("DNP3ParserTestCheckCRC", DNP3ParserTestCheckCRC);
2650  UtRegisterTest("DNP3ParserCheckLinkHeaderCRC",
2651  DNP3ParserCheckLinkHeaderCRC);
2652  UtRegisterTest("DNP3CheckUserDataCRCsTest", DNP3CheckUserDataCRCsTest);
2653  UtRegisterTest("DNP3CalculateLinkLengthTest", DNP3CalculateLinkLengthTest);
2654  UtRegisterTest("DNP3CalculateTransportLengthWithoutCRCsTest",
2655  DNP3CalculateTransportLengthWithoutCRCsTest);
2656  UtRegisterTest("DNP3ReassembleApplicationLayerTest01",
2657  DNP3ReassembleApplicationLayerTest01);
2658  UtRegisterTest("DNP3ProbingParserTest", DNP3ProbingParserTest);
2659  UtRegisterTest("DNP3ParserTestRequestResponse",
2660  DNP3ParserTestRequestResponse);
2661  UtRegisterTest("DNP3ParserTestUnsolicitedResponseConfirm",
2662  DNP3ParserTestUnsolicitedResponseConfirm);
2663  UtRegisterTest("DNP3ParserTestPartialFrame", DNP3ParserTestPartialFrame);
2664  UtRegisterTest("DNP3ParserTestMultiFrame", DNP3ParserTestMultiFrame);
2665  UtRegisterTest("DNP3ParserTestFlooded", DNP3ParserTestFlooded);
2666  UtRegisterTest("DNP3ParserTestParsePDU01", DNP3ParserTestParsePDU01);
2667  UtRegisterTest("DNP3ParserDecodeG70V3Test", DNP3ParserDecodeG70V3Test);
2668  UtRegisterTest("DNP3ParserUnknownEventAlertTest",
2669  DNP3ParserUnknownEventAlertTest);
2670 #endif
2671 }
#define DNP3_START_BYTE1
#define DNP3_CRC_LEN
DNP3ApplicationHeader response_ah
uint8_t prefix_code
enum AppLayerEventType_ AppLayerEventType
uint32_t start
uint32_t unreplied
uint16_t flags
#define SCLogDebug(...)
Definition: util-debug.h:335
const char * SCMapEnumValueToName(int enum_value, SCEnumCharMap *table)
Maps an enum value to a string name, from the supplied table.
Definition: util-enum.c:69
#define TAILQ_FIRST(head)
Definition: queue.h:339
void AppLayerProtoDetectPPRegister(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
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:350
struct HtpBodyChunk_ * next
DNP3ObjectList request_objects
void AppLayerParserRegisterGetStateProgressFunc(uint8_t ipproto, AppProto alproto, int(*StateGetProgress)(void *alstate, uint8_t direction))
uint32_t event_type
uint8_t proto
Definition: flow.h:344
#define DNP3_LINK_DIR(control)
LoggerId
#define DNP3_TH_SEQ(x)
int logged
uint32_t prefix
#define PASS
Pass the test.
#define unlikely(expr)
Definition: util-optimize.h:35
uint8_t flooded
int AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto)
Given a protocol name, checks if proto detection is enabled in the conf file.
void AppLayerParserRegisterDetectFlagsFuncs(uint8_t ipproto, AppProto alproto, uint64_t(*GetTxDetectFlags)(void *tx, uint8_t dir), void(*SetTxDetectFlags)(void *tx, uint8_t dir, uint64_t))
#define DNP3_DEFAULT_REQ_FLOOD_COUNT
void AppLayerParserRegisterDetectStateFuncs(uint8_t ipproto, AppProto alproto, DetectEngineState *(*GetTxDetectState)(void *tx), int(*SetTxDetectState)(void *tx, DetectEngineState *))
SCEnumCharMap dnp3_decoder_event_table[]
Per flow DNP3 state.
DNP3Buffer response_buffer
#define DNP3_APP_FC_FREEZE_NR
#define TAILQ_FOREACH_SAFE(var, head, field, tvar)
Definition: queue.h:356
uint64_t offset
#define FAIL_IF(expr)
Fail a test if expression evaluates to false.
Definition: util-unittest.h:71
#define DNP3_OBJ_PREFIX(x)
void AppLayerParserThreadCtxFree(AppLayerParserThreadCtx *tctx)
Destroys the app layer parser thread context obtained using AppLayerParserThreadCtxAlloc().
#define SCReturnUInt(x)
Definition: util-debug.h:343
DNP3 transaction.
void AppLayerDecoderEventsSetEventRaw(AppLayerDecoderEvents **sevents, uint8_t event)
Set an app layer decoder event.
void StreamTcpFreeConfig(char quiet)
Definition: stream-tcp.c:669
DNP3TransportHeader response_th
void AppLayerParserRegisterGetEventsFunc(uint8_t ipproto, AppProto alproto, AppLayerDecoderEvents *(*StateGetEvents)(void *))
#define DNP3_APP_FC_DIR_OPERATE_NR
DNP3TransportHeader request_th
int SCMapEnumNameToValue(const char *enum_name, SCEnumCharMap *table)
Maps a string name to an enum value from the supplied table. Please specify the last element of any m...
Definition: util-enum.c:41
void AppLayerParserRegisterLoggerFuncs(uint8_t ipproto, AppProto alproto, LoggerId(*StateGetTxLogged)(void *, void *), void(*StateSetTxLogged)(void *, void *, LoggerId))
Struct to hold the list of decoded objects.
uint8_t request_complete
DNP3LinkHeader request_lh
uint16_t events
#define TRUE
#define SCMutexLock(mut)
DNP3Transaction * curr
uint8_t * BasicSearch(const uint8_t *haystack, uint32_t haystack_len, const uint8_t *needle, uint16_t needle_len)
Basic search improved. Limits are better handled, so it doesn&#39;t start searches that wont fit in the r...
Definition: util-spm-bs.c:48
void * protoctx
Definition: flow.h:400
uint8_t DNP3TransportHeader
DNP3 transport header.
void DNP3FreeObjectPointList(int group, int variation, DNP3PointList *list)
Free a DNP3PointList.
uint64_t transaction_max
DNP3ApplicationHeader request_ah
#define DNP3_APP_SEQ(x)
#define DNP3_TH_FIN(x)
#define DNP3_SWAP32(x)
void * alstate
Definition: flow.h:438
#define DNP3_APP_FC_AUTH_REQ_NR
int AppLayerParserConfParserEnabled(const char *ipproto, const char *alproto_name)
check if a parser is enabled in the config Returns enabled always if: were running unittests and when...
#define DNP3_OBJ_RANGE(x)
#define SCCalloc(nm, a)
Definition: util-mem.h:197
Data structure to store app layer decoder events.
#define DNP3_APP_FC_CONFIRM
int AppLayerParserRegisterParser(uint8_t ipproto, AppProto alproto, uint8_t direction, AppLayerParserFPtr Parser)
Register app layer parser for the protocol.
#define SCMutexUnlock(mut)
void AppLayerParserRegisterGetTx(uint8_t ipproto, AppProto alproto, void *(StateGetTx)(void *alstate, uint64_t tx_id))
uint32_t count
uint16_t crc
#define TAILQ_INIT(head)
Definition: queue.h:370
int AppLayerProtoDetectPPParseConfPorts(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)
void AppLayerParserRegisterGetEventInfo(uint8_t ipproto, AppProto alproto, int(*StateGetEventInfo)(const char *event_name, int *event_id, AppLayerEventType *event_type))
#define DNP3_BLOCK_SIZE
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:294
#define FLOW_DESTROY(f)
Definition: flow-util.h:119
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
#define TAILQ_REMOVE(head, elm, field)
Definition: queue.h:412
#define SCEnter(...)
Definition: util-debug.h:337
void StreamTcpInitConfig(char)
To initialize the stream global configuration data.
Definition: stream-tcp.c:365
DNP3 object point.
SCMutex m
Definition: flow.h:394
A struct used for buffering incoming data prior to reassembly.
#define STREAM_TOCLIENT
Definition: stream.h:32
void AppLayerParserRegisterGetStateProgressCompletionStatus(AppProto alproto, int(*StateGetProgressCompletionStatus)(uint8_t direction))
AppLayerParserThreadCtx * AppLayerParserThreadCtxAlloc(void)
Gets a new app layer protocol&#39;s parser thread context.
void DetectEngineStateFree(DetectEngineState *state)
Frees a DetectEngineState object.
int RunmodeIsUnittests(void)
Definition: suricata.c:261
#define SCReturnInt(x)
Definition: util-debug.h:341
void AppLayerParserRegisterGetEventInfoById(uint8_t ipproto, AppProto alproto, int(*StateGetEventInfoById)(int event_id, const char **event_name, AppLayerEventType *event_type))
uint8_t variation
DNP3Buffer request_buffer
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:281
DetectEngineState * de_state
#define SCRealloc(x, a)
Definition: util-mem.h:182
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:385
uint8_t response_complete
void AppLayerDecoderEventsFreeEvents(AppLayerDecoderEvents **events)
#define DNP3_LINK_HDR_LEN
void DNP3ParserRegisterTests(void)
#define DNP3_APP_FC_DIR_OPERATE
DNP3LinkHeader response_lh
#define DNP3_APP_FC_FREEZE_CLEAR_NR
uint8_t range_code
struct DNP3State_ * dnp3
#define DNP3_TH_FIR(x)
DNP3InternalInd response_iin
void AppLayerProtoDetectRegisterProtocol(AppProto alproto, const char *alproto_name)
Registers a protocol for protocol detection phase.
#define SCFree(a)
Definition: util-mem.h:228
uint16_t tx_id
int DNP3DecodeObject(int group, int variation, const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *points)
Decode a DNP3 object.
#define DNP3_LINK_FC(control)
#define DNP3_APP_FC_UNSOLICITED_RESP
void AppLayerParserRegisterProtocolUnittests(uint8_t ipproto, AppProto alproto, void(*RegisterUnittests)(void))
#define NEXT_TH_SEQNO(current)
#define STREAM_TOSERVER
Definition: stream.h:31
#define SCReturnPtr(x, type)
Definition: util-debug.h:353
uint32_t size
#define DNP3_START_BYTE0
int DNP3PrefixIsSize(uint8_t prefix_code)
Check if the prefix code is a size prefix.
uint64_t detect_flags_tc
DNP3PointList * DNP3PointListAlloc(void)
Allocate a list for DNP3 points.
#define FAIL_IF_NULL(expr)
Fail a test if expression evaluates to NULL.
Definition: util-unittest.h:89
uint16_t length
void RegisterDNP3Parsers(void)
Register the DNP3 application protocol parser.
DNP3PointList * points
uint8_t * request_buffer
#define TAILQ_EMPTY(head)
Definition: queue.h:347
uint32_t request_buffer_len
#define SCReturn
Definition: util-debug.h:339
void AppLayerParserRegisterGetTxCnt(uint8_t ipproto, AppProto alproto, uint64_t(*StateGetTxCnt)(void *alstate))
void AppLayerParserRegisterStateFuncs(uint8_t ipproto, AppProto alproto, void *(*StateAlloc)(void), void(*StateFree)(void *))
AppLayerDecoderEvents * decoder_events
uint8_t len
AppProto alproto
application level protocol
Definition: flow.h:409
struct SCLogConfig_ SCLogConfig
Holds the config state used by the logging api.
#define DNP3_SWAP16(x)
uint8_t * buffer
Flow data structure.
Definition: flow.h:325
uint64_t detect_flags_ts
uint8_t * response_buffer
#define DNP3_APP_FC_FREEZE_AT_TIME_NR
#define FAIL_IF_NOT(expr)
Fail a test if expression to true.
Definition: util-unittest.h:82
DNP3ObjectList response_objects
#define DNP3_DEFAULT_PORT
int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow *f, AppProto alproto, uint8_t flags, uint8_t *input, uint32_t input_len)
uint32_t response_buffer_len
void AppLayerParserRegisterTxFreeFunc(uint8_t ipproto, AppProto alproto, void(*StateTransactionFree)(void *, uint64_t))
#define DNP3_MIN_LEN