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 *input, uint32_t len)
268 {
269  DNP3LinkHeader *hdr = (DNP3LinkHeader *)input;
270 
271  /* Check that we have the minimum amount of bytes. */
272  if (len < sizeof(DNP3LinkHeader)) {
273  SCLogDebug("Length too small to be a DNP3 header.");
274  return ALPROTO_UNKNOWN;
275  }
276 
277  /* May be a banner. */
278  if (DNP3ContainsBanner(input, len)) {
279  SCLogDebug("Packet contains a DNP3 banner.");
280  goto end;
281  }
282 
283  /* Verify start value (from AN2013-004b). */
284  if (!DNP3CheckStartBytes(hdr)) {
285  SCLogDebug("Invalid start bytes.");
286  return ALPROTO_FAILED;
287  }
288 
289  /* Verify minimum length. */
290  if (hdr->len < DNP3_MIN_LEN) {
291  SCLogDebug("Packet too small to be a valid DNP3 fragment.");
292  return ALPROTO_FAILED;
293  }
294 
295 end:
296  SCLogDebug("Detected DNP3.");
297  return ALPROTO_DNP3;
298 }
299 
300 /**
301  * \brief Caculate the length of the transport layer with CRCs removed.
302  *
303  * \param input_len The length of the transport layer buffer.
304  *
305  * \retval The length of the buffer after CRCs are removed.
306  */
307 static int DNP3CalculateTransportLengthWithoutCRCs(uint32_t input_len)
308 {
309  /* Too small. */
310  if (input_len < DNP3_CRC_LEN) {
311  return -1;
312  }
313 
314  /* Get the number of complete blocks. */
315  int blocks = input_len / (DNP3_BLOCK_SIZE + DNP3_CRC_LEN);
316 
317  /* And the number of bytes in the last block. */
318  int rem = input_len - (blocks * (DNP3_BLOCK_SIZE + DNP3_CRC_LEN));
319 
320  if (rem) {
321  if (rem < DNP3_CRC_LEN) {
322  return -1;
323  }
324  return (blocks * DNP3_BLOCK_SIZE) + (rem - DNP3_CRC_LEN);
325  }
326  else {
327  return (blocks * DNP3_BLOCK_SIZE);
328  }
329 }
330 
331 /**
332  * \brief Reassemble the application layer by stripping the CRCs.
333  *
334  * Remove the CRCs from the user data blocks. The output is the user
335  * data with the CRCs removed as well as the transport header removed,
336  * but the input data still needs to include the transport header as
337  * its part of the first user data block.
338  *
339  * If the output length passed in is non-null, the new input data will
340  * be appended, and the output length pointer incremented as needed.
341  *
342  * \param input Input buffer starting at the transport header (which
343  * will be removed from the output).
344  * \param input_len Length of the input buffer.
345  * \param output Pointer to output buffer (may be realloc'd).
346  * \param output_len Pointer to output length.
347  *
348  * \retval 1 if reassembly was successful, otherwise 0.
349  */
350 static int DNP3ReassembleApplicationLayer(const uint8_t *input,
351  uint32_t input_len, uint8_t **output, uint32_t *output_len)
352 {
353  int len = DNP3CalculateTransportLengthWithoutCRCs(input_len);
354 
355  if (len <= 0) {
356  return 0;
357  }
358 
359  /* Remove one byte for the transport header and make sure we have
360  * at least one byte of user data. */
361  if (--len < 1) {
362  return 0;
363  }
364 
365  if (*output == NULL) {
366  *output = SCCalloc(1, len);
367  if (unlikely(*output == NULL)) {
368  return 0;
369  }
370  }
371  else {
372  uint8_t *ptr = SCRealloc(*output, (size_t)(*output_len + len));
373  if (unlikely(ptr == NULL)) {
374  return 0;
375  }
376  *output = ptr;
377  }
378 
379  int offset = 0, block_size;
380  while ((uint32_t)offset < input_len) {
381  if (input_len - offset > DNP3_BLOCK_SIZE + DNP3_CRC_LEN) {
382  block_size = DNP3_BLOCK_SIZE + DNP3_CRC_LEN;
383  }
384  else {
385  block_size = input_len - offset;
386  }
387 
388  /* If handling the first block (offset is 0), trim off the
389  * first byte which is the transport header, and not part of
390  * the application data. */
391  if (offset == 0) {
392  offset++;
393  block_size--;
394  }
395 
396  /* Need at least 3 bytes to continue. One for application
397  * data, and 2 for the CRC. If not, return failure for
398  * malformed frame. */
399  if (block_size < DNP3_CRC_LEN + 1) {
400  SCLogDebug("Not enough data to continue.");
401  return 0;
402  }
403 
404  /* Make sure there is enough space to write into. */
405  if (block_size - DNP3_CRC_LEN > len) {
406  SCLogDebug("Not enough data to continue.");
407  return 0;
408  }
409 
410  memcpy(*output + *output_len, input + offset,
411  block_size - DNP3_CRC_LEN);
412  *output_len += block_size - DNP3_CRC_LEN;
413  offset += block_size;
414  len -= block_size - DNP3_CRC_LEN;
415  }
416 
417  return 1;
418 }
419 
420 /**
421  * \brief Allocate a DNP3 state object.
422  *
423  * The DNP3 state object represents a single DNP3 TCP session.
424  */
425 static void *DNP3StateAlloc(void)
426 {
427  SCEnter();
428  DNP3State *dnp3;
429 
430  dnp3 = (DNP3State *)SCCalloc(1, sizeof(DNP3State));
431  if (unlikely(dnp3 == NULL)) {
432  return NULL;
433  }
434  TAILQ_INIT(&dnp3->tx_list);
435 
436  SCReturnPtr(dnp3, "void");
437 }
438 
439 /**
440  * \brief Set a DNP3 application layer event.
441  *
442  * Sets an event on the current transaction object.
443  */
444 static void DNP3SetEvent(DNP3State *dnp3, uint8_t event)
445 {
446  if (dnp3 && dnp3->curr) {
448  dnp3->events++;
449  }
450  else {
452  "Fail set set event, state or txn was NULL.");
453  }
454 }
455 
456 /**
457  * \brief Set a DNP3 application layer event on a transaction.
458  */
459 static void DNP3SetEventTx(DNP3Transaction *tx, uint8_t event)
460 {
462  tx->dnp3->events++;
463 }
464 
465 /**
466  * \brief Allocation a DNP3 transaction.
467  */
468 static DNP3Transaction *DNP3TxAlloc(DNP3State *dnp3)
469 {
470  DNP3Transaction *tx = SCCalloc(1, sizeof(DNP3Transaction));
471  if (unlikely(tx == NULL)) {
472  return NULL;
473  }
474  dnp3->transaction_max++;
475  dnp3->unreplied++;
476  dnp3->curr = tx;
477  tx->dnp3 = dnp3;
478  tx->tx_num = dnp3->transaction_max;
481  TAILQ_INSERT_TAIL(&dnp3->tx_list, tx, next);
482 
483  /* Check for flood state. */
485  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_FLOODED);
486  dnp3->flooded = 1;
487  }
488 
489  return tx;
490 }
491 
492 /**
493  * \brief Calculate the length of a link frame with CRCs.
494  *
495  * This is required as the length parameter in the DNP3 header does not
496  * include the added CRCs.
497  *
498  * \param length The length from the DNP3 link header.
499  *
500  * \retval The length of the frame with CRCs included or 0 if the length isn't
501  * long enough to be a valid DNP3 frame.
502  */
503 static uint32_t DNP3CalculateLinkLength(uint8_t length)
504 {
505  uint32_t frame_len = 0;
506  int rem;
507 
508  /* Fail early if the length is less than the minimum size. */
509  if (length < DNP3_LINK_HDR_LEN) {
510  return 0;
511  }
512 
513  /* Subtract the 5 bytes of the header that are included in the
514  * length. */
515  length -= DNP3_LINK_HDR_LEN;
516 
517  rem = length % DNP3_BLOCK_SIZE;
518  frame_len = (length / DNP3_BLOCK_SIZE) * (DNP3_BLOCK_SIZE + DNP3_CRC_LEN);
519  if (rem) {
520  frame_len += rem + DNP3_CRC_LEN;
521  }
522 
523  return frame_len + sizeof(DNP3LinkHeader);
524 }
525 
526 /**
527  * \brief Check if the link function code specifies user data.
528  *
529  * \param header Point to link header.
530  *
531  * \retval 1 if frame contains user data, otherwise 0.
532  */
533 static int DNP3IsUserData(const DNP3LinkHeader *header)
534 {
535  switch (DNP3_LINK_FC(header->control)) {
538  return 1;
539  default:
540  return 0;
541  }
542 }
543 
544 /**
545  * \brief Check if the frame has user data.
546  *
547  * Check if the DNP3 frame actually has user data by checking if data
548  * exists after the headers.
549  *
550  * \retval 1 if user data exists, otherwise 0.
551  */
552 static int DNP3HasUserData(const DNP3LinkHeader *header)
553 {
554  if (DNP3_LINK_DIR(header->control)) {
555  return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) +
556  sizeof(DNP3ApplicationHeader);
557  }
558  else {
559  return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) +
560  sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd);
561  }
562 }
563 
564 /**
565  * \brief Reset a DNP3Buffer.
566  */
567 static void DNP3BufferReset(DNP3Buffer *buffer)
568 {
569  buffer->offset = 0;
570  buffer->len = 0;
571 }
572 
573 /**
574  * \brief Add data to a DNP3 buffer, enlarging the buffer if required.
575  *
576  * \param buffer Buffer to add data data.
577  * \param data Data to be added to buffer.
578  * \param len Size of data to be added to buffer.
579  *
580  * \param 1 if data was added successful, otherwise 0.
581  */
582 static int DNP3BufferAdd(DNP3Buffer *buffer, const uint8_t *data, uint32_t len)
583 {
584  if (buffer->size == 0) {
585  buffer->buffer = SCCalloc(1, len);
586  if (unlikely(buffer->buffer == NULL)) {
587  return 0;
588  }
589  buffer->size = len;
590  }
591  else if (buffer->len + len > buffer->size) {
592  uint8_t *tmp = SCRealloc(buffer->buffer, buffer->len + len);
593  if (unlikely(tmp == NULL)) {
594  return 0;
595  }
596  buffer->buffer = tmp;
597  buffer->size = buffer->len + len;
598  }
599  memcpy(buffer->buffer + buffer->len, data, len);
600  buffer->len += len;
601 
602  return 1;
603 }
604 
605 /**
606  * \brief Trim a DNP3 buffer.
607  *
608  * Trimming a buffer moves the data in the buffer up to the front of
609  * the buffer freeing up room at the end for more incoming data.
610  *
611  * \param buffer The buffer to trim.
612  */
613 static void DNP3BufferTrim(DNP3Buffer *buffer)
614 {
615  if (buffer->offset == buffer->len) {
616  DNP3BufferReset(buffer);
617  }
618  else if (buffer->offset > 0) {
619  memmove(buffer->buffer, buffer->buffer + buffer->offset,
620  buffer->len - buffer->offset);
621  buffer->len = buffer->len - buffer->offset;
622  buffer->offset = 0;
623  }
624 }
625 
626 /**
627  * \brief Free a DNP3 object.
628  */
629 static void DNP3ObjectFree(DNP3Object *object)
630 {
631  if (object->points != NULL) {
632  DNP3FreeObjectPointList(object->group, object->variation,
633  object->points);
634  }
635  SCFree(object);
636 }
637 
638 /**
639  * \breif Allocate a DNP3 object.
640  */
641 static DNP3Object *DNP3ObjectAlloc(void)
642 {
643  DNP3Object *object = SCCalloc(1, sizeof(*object));
644  if (unlikely(object == NULL)) {
645  return NULL;
646  }
647  object->points = DNP3PointListAlloc();
648  if (object->points == NULL) {
649  DNP3ObjectFree(object);
650  return NULL;
651  }
652  return object;
653 }
654 
655 /**
656  * \brief Decode DNP3 application objects.
657  *
658  * This function decoded known DNP3 application objects. As the
659  * protocol isn't self describing, we can only decode the buffer while
660  * the application objects are known. As soon as an unknown
661  * group/variation is hit, we must stop processing.
662  *
663  * \param buf the input buffer
664  * \param len length of the input buffer
665  * \param objects pointer to list where decoded objects will be stored.
666  *
667  * \retval 1 if all objects decoded, 0 if all objects could not be decoded (
668  * unknown group/variations)
669  */
670 static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf,
671  uint32_t len, DNP3ObjectList *objects)
672 {
673  int retval = 0;
674 
675  if (buf == NULL || len == 0) {
676  return 1;
677  }
678 
679  while (len) {
680  uint32_t offset = 0;
681 
682  if (len < sizeof(DNP3ObjHeader)) {
683  goto done;
684  }
685  DNP3ObjHeader *header = (DNP3ObjHeader *)buf;
686  offset += sizeof(DNP3ObjHeader);
687 
688  DNP3Object *object = DNP3ObjectAlloc();
689  if (unlikely(object == NULL)) {
690  goto done;
691  }
692  TAILQ_INSERT_TAIL(objects, object, next);
693 
694  object->group = header->group;
695  object->variation = header->variation;
696  object->qualifier = header->qualifier;
697  object->prefix_code = DNP3_OBJ_PREFIX(header->qualifier);
698  object->range_code = DNP3_OBJ_RANGE(header->qualifier);
699 
700  /* IEEE 1815-2012, Table 4-5. */
701  switch (object->range_code) {
702  case 0x00:
703  case 0x03: {
704  /* 1 octet start and stop indexes OR 1 octet start and
705  * stop virtual addresses. */
706  if (offset + (sizeof(uint8_t) * 2) > len) {
707  /* Not enough data. */
708  SCLogDebug("Not enough data.");
709  goto not_enough_data;
710  }
711  object->start = buf[offset++];
712  object->stop = buf[offset++];
713  object->count = object->stop - object->start + 1;
714  break;
715  }
716  case 0x01:
717  case 0x04: {
718  /* 2 octet start and stop indexes OR 2 octect start
719  * and stop virtual addresses. */
720  if (offset + (sizeof(uint16_t) * 2) > len) {
721  /* Not enough data. */
722  SCLogDebug("Not enough data.");
723  goto not_enough_data;
724  }
725  object->start = DNP3_SWAP16(*(uint16_t *)(buf + offset));
726  offset += sizeof(uint16_t);
727  object->stop = DNP3_SWAP16(*(uint16_t *)(buf + offset));
728  offset += sizeof(uint16_t);
729  object->count = object->stop - object->start + 1;
730  break;
731  }
732  case 0x02:
733  case 0x05: {
734  /* 4 octet start and stop indexes OR 4 octect start
735  * and stop virtual addresses. */
736  if (offset + (sizeof(uint32_t) * 2) > len) {
737  /* Not enough data. */
738  SCLogDebug("Not enough data.");
739  goto not_enough_data;
740  }
741  object->start = DNP3_SWAP32(*(uint32_t *)(buf + offset));
742  offset += sizeof(uint32_t);
743  object->stop = DNP3_SWAP32(*(uint32_t *)(buf + offset));
744  offset += sizeof(uint32_t);
745  object->count = object->stop - object->start + 1;
746  break;
747  }
748  case 0x06:
749  /* No range field. */
750  object->count = 0;
751  break;
752  case 0x07:
753  /* 1 octet count of objects. */
754  if (offset + sizeof(uint8_t) > len) {
755  SCLogDebug("Not enough data.");
756  goto not_enough_data;
757  }
758  object->count = buf[offset];
759  offset += sizeof(uint8_t);
760  break;
761  case 0x08: {
762  /* 2 octet count of objects. */
763  if (offset + sizeof(uint16_t) > len) {
764  SCLogDebug("Not enough data.");
765  goto not_enough_data;
766  }
767  object->count = DNP3_SWAP16(*(uint16_t *)(buf + offset));
768  offset += sizeof(uint16_t);
769  break;
770  }
771  case 0x09: {
772  /* 4 octet count of objects. */
773  if (offset + sizeof(uint32_t) > len) {
774  SCLogDebug("Not enough data.");
775  goto not_enough_data;
776  }
777  object->count = DNP3_SWAP32(*(uint32_t *)(buf + offset));
778  offset += sizeof(uint32_t);
779  break;
780  }
781  case 0x0b: {
782  if (offset + sizeof(uint8_t) > len) {
783  /* Not enough data. */
784  SCLogDebug("Not enough data.");
785  goto not_enough_data;
786  }
787  object->count = *(uint8_t *)(buf + offset);
788  offset += sizeof(uint8_t);
789  break;
790  }
791  default:
792  SCLogDebug("Range code 0x%02x is reserved.",
793  object->range_code);
794  goto done;
795  }
796 
797  buf += offset;
798  len -= offset;
799 
800  if (object->variation == 0 || object->count == 0) {
801  goto next;
802  }
803 
804  int event = DNP3DecodeObject(header->group, header->variation, &buf,
805  &len, object->prefix_code, object->start, object->count,
806  object->points);
807  if (event) {
808  DNP3SetEventTx(tx, DNP3_DECODER_EVENT_UNKNOWN_OBJECT);
809  goto done;
810  }
811 
812  next:
813  continue;
814  }
815 
816  /* All objects were decoded. */
817  retval = 1;
818 
819 not_enough_data:
820 done:
821  return retval;
822 }
823 
824 /**
825  * \brief Handle DNP3 request user data.
826  *
827  * \param dnp3 the current DNP3State
828  * \param input pointer to the DNP3 frame (starting with link header)
829  * \param input_len length of the input frame
830  */
831 static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input,
832  uint32_t input_len)
833 {
834  DNP3LinkHeader *lh;
836  DNP3ApplicationHeader *ah;
837  DNP3Transaction *tx = NULL, *ttx;
838 
839  lh = (DNP3LinkHeader *)input;
840 
841  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
842  input_len - sizeof(DNP3LinkHeader))) {
843  return;
844  }
845 
846  th = input[sizeof(DNP3LinkHeader)];
847 
848  if (!DNP3_TH_FIR(th)) {
849  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
850  if (ttx->request_lh.src == lh->src &&
851  ttx->request_lh.dst == lh->dst &&
852  ttx->has_request &&
853  !ttx->request_done &&
854  NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->request_th)) == DNP3_TH_SEQ(th))
855  {
856  tx = ttx;
857  break;
858  }
859  }
860 
861  if (tx == NULL) {
862  return;
863  }
864 
865  /* Update the saved transport header so subsequent segments
866  * will be matched to this sequence number. */
867  tx->response_th = th;
868  }
869  else {
870  ah = (DNP3ApplicationHeader *)(input + sizeof(DNP3LinkHeader) +
871  sizeof(DNP3TransportHeader));
872 
873  /* Ignore confirms - for now. */
874  if (ah->function_code == DNP3_APP_FC_CONFIRM) {
875  return;
876  }
877 
878  /* Create a transaction. */
879  tx = DNP3TxAlloc(dnp3);
880  if (unlikely(tx == NULL)) {
881  return;
882  }
883  tx->request_lh = *lh;
884  tx->request_th = th;
885  tx->request_ah = *ah;
886  tx->has_request = 1;
887 
888  }
889 
890  if (!DNP3ReassembleApplicationLayer(input + sizeof(DNP3LinkHeader),
891  input_len - sizeof(DNP3LinkHeader),
892  &tx->request_buffer, &tx->request_buffer_len)) {
893 
894  /* Malformed, set event and mark as done. */
895  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_MALFORMED);
896  tx->request_done = 1;
897  return;
898  }
899 
900  /* If this is not the final segment, just return. */
901  if (!DNP3_TH_FIN(th)) {
902  return;
903  }
904 
905  tx->request_done = 1;
906 
907  /* Some function codes do not expect a reply. */
908  switch (tx->request_ah.function_code) {
909  case DNP3_APP_FC_CONFIRM:
915  tx->response_done = 1;
916  default:
917  break;
918  }
919 
920  if (DNP3DecodeApplicationObjects(
921  tx, tx->request_buffer + sizeof(DNP3ApplicationHeader),
922  tx->request_buffer_len - sizeof(DNP3ApplicationHeader),
923  &tx->request_objects)) {
924  tx->request_complete = 1;
925  }
926 }
927 
928 static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input,
929  uint32_t input_len)
930 {
931  DNP3LinkHeader *lh;
933  DNP3ApplicationHeader *ah;
934  DNP3InternalInd *iin;
935  DNP3Transaction *tx = NULL, *ttx;
936  uint32_t offset = 0;
937 
938  lh = (DNP3LinkHeader *)input;
939  offset += sizeof(DNP3LinkHeader);
940 
941  if (!DNP3CheckUserDataCRCs(input + offset, input_len - offset)) {
942  return;
943  }
944 
945  th = input[offset++];
946 
947  if (!DNP3_TH_FIR(th)) {
948  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
949  if (ttx->response_lh.src == lh->src &&
950  ttx->response_lh.dst == lh->dst &&
951  ttx->has_response && !ttx->response_done &&
952  NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->response_th)) == DNP3_TH_SEQ(th))
953  {
954  tx = ttx;
955  break;
956  }
957  }
958 
959  if (tx == NULL) {
960  return;
961  }
962 
963  /* Replace the transport header in the transaction with this
964  * one in case there are more frames. */
965  tx->response_th = th;
966  }
967  else {
968  ah = (DNP3ApplicationHeader *)(input + offset);
969  offset += sizeof(DNP3ApplicationHeader);
970  iin = (DNP3InternalInd *)(input + offset);
971 
972  if (ah->function_code == DNP3_APP_FC_UNSOLICITED_RESP) {
973  tx = DNP3TxAlloc(dnp3);
974  if (unlikely(tx == NULL)) {
975  return;
976  }
977 
978  /* There is no request associated with an unsolicited
979  * response, so mark the request done as far as
980  * transaction state handling is concerned. */
981  tx->request_done = 1;
982  }
983  else {
984  /* Find transaction. */
985  TAILQ_FOREACH(ttx, &dnp3->tx_list, next) {
986  if (ttx->has_request &&
987  ttx->request_done &&
988  ttx->request_lh.src == lh->dst &&
989  ttx->request_lh.dst == lh->src &&
990  !ttx->has_response &&
991  !ttx->response_done &&
992  DNP3_APP_SEQ(ttx->request_ah.control) == DNP3_APP_SEQ(ah->control)) {
993  tx = ttx;
994  break;
995  }
996  }
997  if (tx == NULL) {
998  return;
999  }
1000  }
1001 
1002  tx->has_response = 1;
1003  tx->response_lh = *lh;
1004  tx->response_th = th;
1005  tx->response_ah = *ah;
1006  tx->response_iin = *iin;
1007  }
1008 
1009  if (!DNP3ReassembleApplicationLayer(input + sizeof(DNP3LinkHeader),
1010  input_len - sizeof(DNP3LinkHeader),
1011  &tx->response_buffer, &tx->response_buffer_len)) {
1012  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_MALFORMED);
1013  return;
1014  }
1015 
1016  if (!DNP3_TH_FIN(th)) {
1017  return;
1018  }
1019 
1020  tx->response_done = 1;
1021 
1022  offset = sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd);
1023  if (DNP3DecodeApplicationObjects(tx, tx->response_buffer + offset,
1024  tx->response_buffer_len - offset,
1025  &tx->response_objects)) {
1026  tx->response_complete = 1;
1027  }
1028 }
1029 
1030 /**
1031  * \brief Decode the DNP3 request link layer.
1032  *
1033  * \retval number of bytes processed or -1 if the data stream does not look
1034  * like DNP3.
1035  */
1036 static int DNP3HandleRequestLinkLayer(DNP3State *dnp3, const uint8_t *input,
1037  uint32_t input_len)
1038 {
1039  SCEnter();
1040  uint32_t processed = 0;
1041 
1042  while (input_len) {
1043 
1044  /* Need at least enough bytes for a DNP3 header. */
1045  if (input_len < sizeof(DNP3LinkHeader)) {
1046  break;
1047  }
1048 
1049  DNP3LinkHeader *header = (DNP3LinkHeader *)input;
1050 
1051  if (!DNP3CheckStartBytes(header)) {
1052  goto error;
1053  }
1054 
1055  if (!DNP3CheckLinkHeaderCRC(header)) {
1056  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_LINK_CRC);
1057  goto error;
1058  }
1059 
1060  uint32_t frame_len = DNP3CalculateLinkLength(header->len);
1061  if (frame_len == 0) {
1062  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1063  goto error;
1064  }
1065  if (input_len < frame_len) {
1066  /* Insufficient data, just break - will wait for more data. */
1067  break;
1068  }
1069 
1070  /* Ignore non-user data for now. */
1071  if (!DNP3IsUserData(header)) {
1072  goto next;
1073  }
1074 
1075  /* Make sure the header length is large enough for transport and
1076  * application headers. */
1077  if (!DNP3HasUserData(header)) {
1078  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1079  goto next;
1080  }
1081 
1082  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
1083  frame_len - sizeof(DNP3LinkHeader))) {
1084  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC);
1085  goto next;
1086  }
1087 
1088  DNP3HandleUserDataRequest(dnp3, input, frame_len);
1089 
1090  next:
1091  /* Advance the input buffer. */
1092  input += frame_len;
1093  input_len -= frame_len;
1094  processed += frame_len;
1095  }
1096 
1097  SCReturnInt(processed);
1098 error:
1099  /* Error out. Should only happen if this doesn't look like a DNP3
1100  * frame. */
1101  SCReturnInt(-1);
1102 }
1103 
1104 /**
1105  * \brief Handle incoming request data.
1106  *
1107  * The actual request PDU parsing is done in
1108  * DNP3HandleRequestLinkLayer. This function takes care of buffering TCP
1109  * date if a segment does not contain a complete frame (or contains
1110  * multiple frames, but not the complete final frame).
1111  */
1112 static int DNP3ParseRequest(Flow *f, void *state, AppLayerParserState *pstate,
1113  uint8_t *input, uint32_t input_len, void *local_data,
1114  const uint8_t flags)
1115 {
1116  SCEnter();
1117  DNP3State *dnp3 = (DNP3State *)state;
1118  DNP3Buffer *buffer = &dnp3->request_buffer;
1119  int processed = 0;
1120 
1121  if (input_len == 0) {
1122  SCReturnInt(1);
1123  }
1124 
1125  if (buffer->len) {
1126  if (!DNP3BufferAdd(buffer, input, input_len)) {
1127  SCLogError(SC_ERR_MEM_ALLOC, "Failed to allocate memory to buffer "
1128  "DNP3 request data");
1129  goto error;
1130  }
1131  processed = DNP3HandleRequestLinkLayer(dnp3,
1132  buffer->buffer + buffer->offset,
1133  buffer->len - buffer->offset);
1134  if (processed < 0) {
1135  goto error;
1136  }
1137  buffer->offset += processed;
1138  DNP3BufferTrim(buffer);
1139  }
1140  else {
1141  processed = DNP3HandleRequestLinkLayer(dnp3, input, input_len);
1142  if (processed < 0) {
1143  SCLogDebug("Failed to process request link layer.");
1144  goto error;
1145  }
1146 
1147  input += processed;
1148  input_len -= processed;
1149 
1150  /* Not all data was processed, buffer it. */
1151  if (input_len) {
1152  if (!DNP3BufferAdd(buffer, input, input_len)) {
1154  "Failed to allocate memory to buffer DNP3 request data");
1155  goto error;
1156  }
1157  }
1158  }
1159 
1160  SCReturnInt(1);
1161 
1162 error:
1163  /* Reset the buffer. */
1164  DNP3BufferReset(buffer);
1165  SCReturnInt(-1);
1166 }
1167 
1168 /**
1169  * \brief Decode the DNP3 response link layer.
1170  *
1171  * \retval number of bytes processed or -1 if the data stream does not
1172  * like look DNP3.
1173  */
1174 static int DNP3HandleResponseLinkLayer(DNP3State *dnp3, const uint8_t *input,
1175  uint32_t input_len)
1176 {
1177  SCEnter();
1178  uint32_t processed = 0;
1179 
1180  while (input_len) {
1181 
1182  /* Need at least enough bytes for a DNP3 header. */
1183  if (input_len < sizeof(DNP3LinkHeader)) {
1184  break;
1185  }
1186 
1187  DNP3LinkHeader *header = (DNP3LinkHeader *)input;
1188 
1189  if (!DNP3CheckStartBytes(header)) {
1190  goto error;
1191  }
1192 
1193  if (!DNP3CheckLinkHeaderCRC(header)) {
1194  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_LINK_CRC);
1195  goto error;
1196  }
1197 
1198  /* Calculate the number of bytes needed to for this frame. */
1199  uint32_t frame_len = DNP3CalculateLinkLength(header->len);
1200  if (frame_len == 0) {
1201  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1202  goto error;
1203  }
1204  if (input_len < frame_len) {
1205  /* Insufficient data, just break - will wait for more data. */
1206  break;
1207  }
1208 
1209  /* Only handle user data frames for now. */
1210  if (!DNP3IsUserData(header)) {
1211  goto next;
1212  }
1213 
1214  /* Make sure the header length is large enough for transport and
1215  * application headers. */
1216  if (!DNP3HasUserData(header)) {
1217  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_LEN_TOO_SMALL);
1218  goto error;
1219  }
1220 
1221  if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader),
1222  frame_len - sizeof(DNP3LinkHeader))) {
1223  DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC);
1224  goto next;
1225  }
1226 
1227  DNP3HandleUserDataResponse(dnp3, input, frame_len);
1228 
1229  next:
1230  /* Advance the input buffer. */
1231  input += frame_len;
1232  input_len -= frame_len;
1233  processed += frame_len;
1234  }
1235 
1236  SCReturnInt(processed);
1237 error:
1238  /* Error out. Should only happen if the data stream no longer
1239  * looks like DNP3. */
1240  SCReturnInt(-1);
1241 }
1242 
1243 /**
1244  * \brief Parse incoming data.
1245  *
1246  * This is the entry function for DNP3 application layer data. Its
1247  * main responsibility is buffering incoming data that cannot be
1248  * processed.
1249  *
1250  * See DNP3ParseResponsePDUs for DNP3 frame handling.
1251  */
1252 static int DNP3ParseResponse(Flow *f, void *state, AppLayerParserState *pstate,
1253  uint8_t *input, uint32_t input_len, void *local_data,
1254  const uint8_t flags)
1255 {
1256  SCEnter();
1257  DNP3State *dnp3 = (DNP3State *)state;
1258  DNP3Buffer *buffer = &dnp3->response_buffer;
1259  int processed;
1260 
1261  if (buffer->len) {
1262  if (!DNP3BufferAdd(buffer, input, input_len)) {
1263  SCLogError(SC_ERR_MEM_ALLOC, "Failed to allocate memory to buffer "
1264  "DNP3 response data");
1265  goto error;
1266  }
1267  processed = DNP3HandleResponseLinkLayer(dnp3,
1268  buffer->buffer + buffer->offset,
1269  buffer->len - buffer->offset);
1270  if (processed < 0) {
1271  goto error;
1272  }
1273  buffer->offset += processed;
1274  DNP3BufferTrim(buffer);
1275  }
1276  else {
1277 
1278  /* Check if this is a banner, ignore if it is. */
1279  if (DNP3ContainsBanner(input, input_len)) {
1280  goto done;
1281  }
1282 
1283  processed = DNP3HandleResponseLinkLayer(dnp3, input, input_len);
1284  if (processed < 0) {
1285  goto error;
1286  }
1287  input += processed;
1288  input_len -= processed;
1289 
1290  /* Not all data was processed, buffer it. */
1291  if (input_len) {
1292  if (!DNP3BufferAdd(buffer, input, input_len)) {
1294  "Failed to allocate memory to buffer DNP3 response data");
1295  goto error;
1296  }
1297  }
1298  }
1299 
1300 done:
1301  SCReturnInt(1);
1302 
1303 error:
1304  /* An error occurred while processing DNP3 frames. Dump the
1305  * buffer as we can't be assured that they are valid anymore. */
1306  DNP3BufferReset(buffer);
1307  SCReturnInt(-1);
1308 }
1309 
1310 static AppLayerDecoderEvents *DNP3GetEvents(void *state, uint64_t tx_id)
1311 {
1312  DNP3State *dnp3 = state;
1313  DNP3Transaction *tx;
1314  uint64_t tx_num = tx_id + 1;
1315 
1316  if (dnp3->curr && dnp3->curr->tx_num == tx_num) {
1317  return dnp3->curr->decoder_events;
1318  }
1319 
1320  TAILQ_FOREACH(tx, &dnp3->tx_list, next) {
1321  if (tx->tx_num == tx_num) {
1322  return tx->decoder_events;
1323  }
1324  }
1325 
1326  return NULL;
1327 }
1328 
1329 static void *DNP3GetTx(void *alstate, uint64_t tx_id)
1330 {
1331  SCEnter();
1332  DNP3State *dnp3 = (DNP3State *)alstate;
1333  DNP3Transaction *tx = NULL;
1334  uint64_t tx_num = tx_id + 1;
1335 
1336  if (dnp3->curr && dnp3->curr->tx_num == (tx_num)) {
1337  SCReturnPtr(dnp3->curr, "void");
1338  }
1339 
1340  TAILQ_FOREACH(tx, &dnp3->tx_list, next) {
1341  if (tx_num != tx->tx_num) {
1342  continue;
1343  }
1344  SCReturnPtr(tx, "void");
1345  }
1346 
1347  SCReturnPtr(NULL, "void");
1348 }
1349 
1350 static uint64_t DNP3GetTxCnt(void *state)
1351 {
1352  SCEnter();
1353  uint64_t count = ((uint64_t)((DNP3State *)state)->transaction_max);
1354  SCReturnUInt(count);
1355 }
1356 
1357 /**
1358  * \brief Free all the objects in a DNP3ObjectList.
1359  */
1360 static void DNP3TxFreeObjectList(DNP3ObjectList *objects)
1361 {
1362  DNP3Object *object;
1363 
1364  while ((object = TAILQ_FIRST(objects)) != NULL) {
1365  TAILQ_REMOVE(objects, object, next);
1366  DNP3ObjectFree(object);
1367  }
1368 }
1369 
1370 /**
1371  * \brief Free a DNP3 transaction.
1372  */
1373 static void DNP3TxFree(DNP3Transaction *tx)
1374 {
1375  SCEnter();
1376 
1377  if (tx->request_buffer != NULL) {
1378  SCFree(tx->request_buffer);
1379  }
1380 
1381  if (tx->response_buffer != NULL) {
1382  SCFree(tx->response_buffer);
1383  }
1384 
1386 
1387  if (tx->de_state != NULL) {
1389  }
1390 
1391  DNP3TxFreeObjectList(&tx->request_objects);
1392  DNP3TxFreeObjectList(&tx->response_objects);
1393 
1394  SCFree(tx);
1395  SCReturn;
1396 }
1397 
1398 /**
1399  * \brief Free a transaction by ID on a specific DNP3 state.
1400  *
1401  * This function is called by the app-layer to free a transaction on a
1402  * specific DNP3 state object.
1403  */
1404 static void DNP3StateTxFree(void *state, uint64_t tx_id)
1405 {
1406  SCEnter();
1407  DNP3State *dnp3 = state;
1408  DNP3Transaction *tx = NULL, *ttx;
1409  uint64_t tx_num = tx_id + 1;
1410 
1411  TAILQ_FOREACH_SAFE(tx, &dnp3->tx_list, next, ttx) {
1412 
1413  if (tx->tx_num != tx_num) {
1414  continue;
1415  }
1416 
1417  if (tx == dnp3->curr) {
1418  dnp3->curr = NULL;
1419  }
1420 
1421  if (tx->decoder_events != NULL) {
1422  if (tx->decoder_events->cnt <= dnp3->events) {
1423  dnp3->events -= tx->decoder_events->cnt;
1424  }
1425  else {
1426  dnp3->events = 0;
1427  }
1428  }
1429  dnp3->unreplied--;
1430 
1431  /* Check flood state. */
1432  if (dnp3->flooded && dnp3->unreplied < DNP3_DEFAULT_REQ_FLOOD_COUNT) {
1433  dnp3->flooded = 0;
1434  }
1435 
1436  TAILQ_REMOVE(&dnp3->tx_list, tx, next);
1437  DNP3TxFree(tx);
1438  break;
1439  }
1440 
1441  SCReturn;
1442 }
1443 
1444 /**
1445  * \brief Free a DNP3 state.
1446  */
1447 static void DNP3StateFree(void *state)
1448 {
1449  SCEnter();
1450  DNP3State *dnp3 = state;
1451  DNP3Transaction *tx;
1452  if (state != NULL) {
1453  while ((tx = TAILQ_FIRST(&dnp3->tx_list)) != NULL) {
1454  TAILQ_REMOVE(&dnp3->tx_list, tx, next);
1455  DNP3TxFree(tx);
1456  }
1457  if (dnp3->request_buffer.buffer != NULL) {
1458  SCFree(dnp3->request_buffer.buffer);
1459  }
1460  if (dnp3->response_buffer.buffer != NULL) {
1461  SCFree(dnp3->response_buffer.buffer);
1462  }
1463  SCFree(dnp3);
1464  }
1465  SCReturn;
1466 }
1467 
1468 /**
1469  * \brief Called by the app-layer to get the state progress.
1470  */
1471 static int DNP3GetAlstateProgress(void *tx, uint8_t direction)
1472 {
1473  DNP3Transaction *dnp3tx = (DNP3Transaction *)tx;
1474  DNP3State *dnp3 = dnp3tx->dnp3;
1475  int retval = 0;
1476 
1477  /* If flooded, "ack" old transactions. */
1478  if (dnp3->flooded && (dnp3->transaction_max -
1479  dnp3tx->tx_num >= DNP3_DEFAULT_REQ_FLOOD_COUNT)) {
1480  SCLogDebug("flooded: returning tx as done.");
1481  SCReturnInt(1);
1482  }
1483 
1484  if (direction & STREAM_TOCLIENT && dnp3tx->response_done) {
1485  retval = 1;
1486  }
1487  else if (direction & STREAM_TOSERVER && dnp3tx->request_done) {
1488  retval = 1;
1489  }
1490 
1491  SCReturnInt(retval);
1492 }
1493 
1494 /**
1495  * \brief App-layer support.
1496  */
1497 static int DNP3GetAlstateProgressCompletionStatus(uint8_t direction)
1498 {
1499  return 1;
1500 }
1501 
1502 /**
1503  * \brief App-layer support.
1504  */
1505 static int DNP3StateGetEventInfo(const char *event_name, int *event_id,
1507 {
1508  *event_id = SCMapEnumNameToValue(event_name, dnp3_decoder_event_table);
1509  if (*event_id == -1) {
1510  SCLogError(SC_ERR_INVALID_ENUM_MAP, "Event \"%s\" not present in "
1511  "the DNP3 enum event map table.", event_name);
1512  return -1;
1513  }
1514 
1515  *event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
1516 
1517  return 0;
1518 }
1519 
1520 /**
1521  * \brief App-layer support.
1522  */
1523 static DetectEngineState *DNP3GetTxDetectState(void *vtx)
1524 {
1525  DNP3Transaction *tx = vtx;
1526  return tx->de_state;
1527 }
1528 
1529 /**
1530  * \brief App-layer support.
1531  */
1532 static int DNP3SetTxDetectState(void *vtx, DetectEngineState *s)
1533 {
1534  DNP3Transaction *tx = vtx;
1535  tx->de_state = s;
1536  return 0;
1537 }
1538 
1539 static void DNP3SetTxLogged(void *alstate, void *vtx, LoggerId logged)
1540 {
1541  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1542  tx->logged = logged;
1543 }
1544 
1545 static LoggerId DNP3GetTxLogged(void *alstate, void *vtx)
1546 {
1547  DNP3Transaction *tx = (DNP3Transaction *)vtx;
1548  return tx->logged;
1549 }
1550 
1551 /**
1552  * \brief Check if the prefix code is a size prefix.
1553  *
1554  * \retval 1 if the prefix_code specifies a size prefix, 0 if not.
1555  */
1556 int DNP3PrefixIsSize(uint8_t prefix_code)
1557 {
1558  switch (prefix_code) {
1559  case 0x04:
1560  case 0x05:
1561  case 0x06:
1562  return 1;
1563  break;
1564  default:
1565  return 0;
1566  }
1567 }
1568 
1569 /**
1570  * \brief Register the DNP3 application protocol parser.
1571  */
1573 {
1574  SCEnter();
1575 
1576  const char *proto_name = "dnp3";
1577 
1578  if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name))
1579  {
1581 
1582  if (RunmodeIsUnittests()) {
1584  ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader), STREAM_TOSERVER,
1585  DNP3ProbingParser, NULL);
1586  }
1587  else {
1588  if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP,
1589  proto_name, ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader),
1590  DNP3ProbingParser, NULL)) {
1591 #ifndef AFLFUZZ_APPLAYER
1592  return;
1593 #endif
1594  }
1595  }
1596 
1597  }
1598  else {
1599  SCLogConfig("Protocol detection and parser disabled for DNP3.");
1600  SCReturn;
1601  }
1602 
1603  if (AppLayerParserConfParserEnabled("tcp", proto_name))
1604  {
1605  SCLogConfig("Registering DNP3/tcp parsers.");
1606 
1608  DNP3ParseRequest);
1610  DNP3ParseResponse);
1611 
1613  DNP3StateAlloc, DNP3StateFree);
1614 
1616  DNP3GetEvents);
1618  DNP3GetTxDetectState, DNP3SetTxDetectState);
1619 
1620  AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTx);
1621  AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTxCnt);
1623  DNP3StateTxFree);
1624 
1626  DNP3GetAlstateProgress);
1628  DNP3GetAlstateProgressCompletionStatus);
1629 
1631  DNP3StateGetEventInfo);
1632 
1634  DNP3GetTxLogged, DNP3SetTxLogged);
1635  }
1636  else {
1637  SCLogConfig("Parser disabled for protocol %s. "
1638  "Protocol detection still on.", proto_name);
1639  }
1640 
1641 #ifdef UNITTESTS
1644 #endif
1645 
1646  SCReturn;
1647 }
1648 
1649 #ifdef UNITTESTS
1650 
1651 #include "flow-util.h"
1652 #include "stream-tcp.h"
1653 
1654 /**
1655  * \brief Utility function to fix CRCs when mangling a frame.
1656  */
1657 static void DNP3FixCrc(uint8_t *data, uint32_t len)
1658 {
1659  uint32_t block_size;
1660 
1661  while (len) {
1662  if (len >= DNP3_BLOCK_SIZE + DNP3_CRC_LEN) {
1663  block_size = DNP3_BLOCK_SIZE;
1664  } else {
1665  block_size = len - DNP3_CRC_LEN;
1666  }
1667  uint16_t crc = DNP3ComputeCRC(data, block_size);
1668  data[block_size + 1] = (crc >> 8) & 0xff;
1669  data[block_size] = crc & 0xff;
1670  data += block_size + DNP3_CRC_LEN;
1671  len -= block_size + DNP3_CRC_LEN;
1672  }
1673 }
1674 
1675 /**
1676  * \test Test CRC checking on partial and full blocks.
1677  */
1678 static int DNP3ParserTestCheckCRC(void)
1679 {
1680  uint8_t request[] = {
1681  /* DNP3 start. */
1682  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
1683  0xa5, 0xe9,
1684 
1685  /* Transport header. */
1686  0xff,
1687 
1688  /* Application layer - segment 1. */
1689  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
1690  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
1691  0xef,
1692 
1693  /* Application layer - segment 2. */
1694  0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
1695  };
1696 
1697  /* Check link header CRC. */
1698  FAIL_IF(!DNP3CheckCRC(request, sizeof(DNP3LinkHeader)));
1699 
1700  /* Check first application layer segment. */
1701  FAIL_IF(!DNP3CheckCRC(request + sizeof(DNP3LinkHeader),
1703 
1704  /* Change a byte in link header, should fail now. */
1705  request[2]++;
1706  FAIL_IF(DNP3CheckCRC(request, sizeof(DNP3LinkHeader)));
1707 
1708  /* Change a byte in the first application segment, should fail
1709  * now. */
1710  request[sizeof(DNP3LinkHeader) + 3]++;
1711  FAIL_IF(DNP3CheckCRC(request + sizeof(DNP3LinkHeader),
1713 
1714  PASS;
1715 }
1716 
1717 /**
1718  * \test Test validation of all CRCs in user data.
1719  */
1720 static int DNP3CheckUserDataCRCsTest(void)
1721 {
1722  /* Multi-block data with valid CRCs. */
1723  uint8_t data_valid[] = {
1724  0xff, 0xc9, 0x05, 0x0c,
1725  0x01, 0x28, 0x01, 0x00,
1726  0x00, 0x00, 0x01, 0x01,
1727  0x01, 0x00, 0x00, 0x00,
1728  0x72, 0xef, /* CRC. */
1729 
1730  0xff, 0xc9, 0x05, 0x0c,
1731  0x01, 0x28, 0x01, 0x00,
1732  0x00, 0x00, 0x01, 0x01,
1733  0x01, 0x00, 0x00, 0x00,
1734  0x72, 0xef, /* CRC. */
1735 
1736  0xff, 0xc9, 0x05, 0x0c,
1737  0x01, 0x28, 0x01, 0x00,
1738  0x00, 0x00, 0x01, 0x01,
1739  0x01, 0x00, 0x00, 0x00,
1740  0x72, 0xef, /* CRC. */
1741 
1742  0x00, 0x00, 0x00, 0x00,
1743  0x00,
1744  0xff, 0xff, /* CRC. */
1745  };
1746  FAIL_IF(!DNP3CheckUserDataCRCs(data_valid, sizeof(data_valid)));
1747 
1748  /* Multi-block data with one non-crc byte altered. */
1749  uint8_t data_invalid[] = {
1750  0xff, 0xc9, 0x05, 0x0c,
1751  0x01, 0x28, 0x01, 0x00,
1752  0x00, 0x00, 0x01, 0x01,
1753  0x01, 0x00, 0x00, 0x00,
1754  0x72, 0xef, /* CRC. */
1755 
1756  0xff, 0xc9, 0x05, 0x0c,
1757  0x01, 0x28, 0x01, 0x00,
1758  0x00, 0x00, 0x01, 0x01,
1759  0x01, 0x00, 0x00, 0x00,
1760  0x72, 0xef, /* CRC. */
1761 
1762  0xff, 0xc9, 0x05, 0x0c,
1763  0x01, 0x28, 0x01, 0x00,
1764  0x00, 0x00, 0x01, 0x01,
1765  0x01, 0x00, 0x00, 0x00,
1766  0x72, 0xef, /* CRC. */
1767 
1768  0x00, 0x00, 0x00, 0x00,
1769  0x01, /* Invalid byte. */
1770  0xff, 0xff, /* CRC. */
1771  };
1772  FAIL_IF(DNP3CheckUserDataCRCs(data_invalid, sizeof(data_invalid)));
1773 
1774  /* 1 byte - need at least 3. */
1775  uint8_t one_byte_nocrc[] = { 0x01 };
1776  FAIL_IF(DNP3CheckUserDataCRCs(one_byte_nocrc, sizeof(one_byte_nocrc)));
1777 
1778  /* 2 bytes - need at least 3. */
1779  uint8_t two_byte_nocrc[] = { 0x01, 0x02 };
1780  FAIL_IF(DNP3CheckUserDataCRCs(two_byte_nocrc, sizeof(two_byte_nocrc)));
1781 
1782  /* 3 bytes, valid CRC. */
1783  uint8_t three_bytes_good_crc[] = { 0x00, 0x00, 0x00 };
1784  *(uint16_t *)(three_bytes_good_crc + 1) = DNP3ComputeCRC(
1785  three_bytes_good_crc, 1);
1786  FAIL_IF(!DNP3CheckUserDataCRCs(three_bytes_good_crc,
1787  sizeof(three_bytes_good_crc)));
1788 
1789  PASS;
1790 }
1791 
1792 /**
1793  * \test Test the link layer length calculation.
1794  *
1795  * Test the calculation that converts the link provided in the DNP3
1796  * header to the actual length of the frame. That is the length with
1797  * CRCs as the length in the header does not include CRCs.
1798  */
1799 static int DNP3CalculateLinkLengthTest(void)
1800 {
1801  /* These are invalid. */
1802  FAIL_IF(DNP3CalculateLinkLength(0) != 0);
1803  FAIL_IF(DNP3CalculateLinkLength(1) != 0);
1804  FAIL_IF(DNP3CalculateLinkLength(2) != 0);
1805  FAIL_IF(DNP3CalculateLinkLength(3) != 0);
1806  FAIL_IF(DNP3CalculateLinkLength(4) != 0);
1807 
1808  /* This is the minimum size. */
1809  FAIL_IF(DNP3CalculateLinkLength(5) != 10);
1810 
1811  /* 1 full user data blocks of data. */
1812  FAIL_IF(DNP3CalculateLinkLength(21) != 28);
1813 
1814  /* 2 full user data blocks of data. */
1815  FAIL_IF(DNP3CalculateLinkLength(37) != 46);
1816 
1817  /* 2 full user data blocks, plus one more byte. */
1818  /* 2 full user data blocks of data. */
1819  FAIL_IF(DNP3CalculateLinkLength(38) != 49);
1820 
1821  /* The maximum size. */
1822  FAIL_IF(DNP3CalculateLinkLength(255) != 292);
1823 
1824  PASS;
1825 }
1826 
1827 /**
1828  * \test The conversion of length with CRCs to the length without
1829  * CRCs.
1830  */
1831 static int DNP3CalculateTransportLengthWithoutCRCsTest(void)
1832 {
1833  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(0) != -1);
1834  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(1) != -1);
1835  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(2) != 0);
1836  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(3) != 1);
1837  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(16) != 14);
1838  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(17) != 15);
1839  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(18) != 16);
1840 
1841  /* 19 bytes is not enough for a second block. */
1842  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(19) != -1);
1843 
1844  /* 20 bytes really isn't enough either, but is large enough to
1845  * satisfy the CRC on the second block. */
1846  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(20) != 16);
1847 
1848  FAIL_IF(DNP3CalculateTransportLengthWithoutCRCs(21) != 17);
1849 
1850  PASS;
1851 }
1852 
1853 /**
1854  * \test Test the validation of the link header CRC.
1855  */
1856 static int DNP3ParserCheckLinkHeaderCRC(void)
1857 {
1858  /* DNP3 frame with valid headers and CRCs. */
1859  uint8_t request[] = {
1860  /* DNP3 start. */
1861  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
1862  0xa5, 0xe9,
1863 
1864  /* Transport header. */
1865  0xff,
1866 
1867  /* Application layer. */
1868  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
1869  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
1870  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
1871  };
1872 
1873  DNP3LinkHeader *header = (DNP3LinkHeader *)request;
1874  FAIL_IF(!DNP3CheckLinkHeaderCRC(header));
1875 
1876  /* Alter a byte in the header. */
1877  request[4] = 0;
1878  FAIL_IF(DNP3CheckLinkHeaderCRC(header));
1879 
1880  PASS;
1881 }
1882 
1883 /**
1884  * \test Test removal of CRCs from user data.
1885  */
1886 static int DNP3ReassembleApplicationLayerTest01(void)
1887 {
1888  uint32_t reassembled_len = 0;
1889  uint8_t *output = NULL;
1890 
1891  uint8_t payload[] = {
1892 
1893  0xff, 0xc9, 0x05, 0x0c,
1894  0x01, 0x28, 0x01, 0x00,
1895  0x00, 0x00, 0x01, 0x01,
1896  0x01, 0x00, 0x00, 0x00,
1897  0x72, 0xef, /* CRC. */
1898 
1899  0xff, 0xc9, 0x05, 0x0c,
1900  0x01, 0x28, 0x01, 0x00,
1901  0x00, 0x00, 0x01, 0x01,
1902  0x01, 0x00, 0x00, 0x00,
1903  0x72, 0xef, /* CRC. */
1904 
1905  0xff, 0xc9, 0x05, 0x0c,
1906  0x01, 0x28, 0x01, 0x00,
1907  0x00, 0x00, 0x01, 0x01,
1908  0x01, 0x00, 0x00, 0x00,
1909  0x72, 0xef, /* CRC. */
1910 
1911  0x00, 0x00, 0x00, 0x00,
1912  0x00,
1913  0xff, 0xff, /* CRC. */
1914  };
1915 
1916  uint8_t expected[] = {
1917  0xc9, 0x05, 0x0c,
1918  0x01, 0x28, 0x01, 0x00,
1919  0x00, 0x00, 0x01, 0x01,
1920  0x01, 0x00, 0x00, 0x00,
1921  /* CRC removed. */
1922  0xff, 0xc9, 0x05, 0x0c,
1923  0x01, 0x28, 0x01, 0x00,
1924  0x00, 0x00, 0x01, 0x01,
1925  0x01, 0x00, 0x00, 0x00,
1926  /* CRC removed. */
1927  0xff, 0xc9, 0x05, 0x0c,
1928  0x01, 0x28, 0x01, 0x00,
1929  0x00, 0x00, 0x01, 0x01,
1930  0x01, 0x00, 0x00, 0x00,
1931  /* CRC removed. */
1932  0x00, 0x00, 0x00, 0x00,
1933  0x00
1934  /* CRC removed. */
1935  };
1936 
1937  /* Valid frame. */
1938  FAIL_IF(!DNP3ReassembleApplicationLayer(payload,
1939  sizeof(payload), &output, &reassembled_len));
1940  FAIL_IF(output == NULL);
1941  FAIL_IF(reassembled_len != sizeof(expected));
1942  FAIL_IF(memcmp(expected, output, reassembled_len));
1943  SCFree(output);
1944 
1945  /* 1 byte, invalid. */
1946  reassembled_len = 0;
1947  output = NULL;
1948  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 1, &output,
1949  &reassembled_len));
1950  FAIL_IF(output != NULL);
1951  FAIL_IF(reassembled_len != 0);
1952 
1953  /* 2 bytes, invalid. */
1954  reassembled_len = 0;
1955  output = NULL;
1956  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 2, &output,
1957  &reassembled_len));
1958  FAIL_IF(output != NULL);
1959  FAIL_IF(reassembled_len != 0);
1960 
1961  /* 3 bytes, minimum - but that would only be the transport header
1962  * which isn't included in the output. */
1963  reassembled_len = 0;
1964  output = NULL;
1965  FAIL_IF(DNP3ReassembleApplicationLayer(payload, 3, &output,
1966  &reassembled_len));
1967  FAIL_IF(output != NULL);
1968  FAIL_IF(reassembled_len != 0);
1969 
1970  /* 4 bytes is the minimum to get any reassembled data. */
1971  reassembled_len = 0;
1972  output = NULL;
1973  FAIL_IF(!DNP3ReassembleApplicationLayer(payload, 4, &output,
1974  &reassembled_len));
1975  FAIL_IF(output == NULL);
1976  FAIL_IF(reassembled_len != 1);
1977 
1978  /* Last block too short (by 1 byte) for data + CRC. */
1979  uint8_t short_payload1[] = {
1980 
1981  0xff, 0xc9, 0x05, 0x0c,
1982  0x01, 0x28, 0x01, 0x00,
1983  0x00, 0x00, 0x01, 0x01,
1984  0x01, 0x00, 0x00, 0x00,
1985  0x72, 0xef, /* CRC. */
1986 
1987  0xff, 0xc9, 0x05, 0x0c,
1988  0x01, 0x28, 0x01, 0x00,
1989  0x00, 0x00, 0x01, 0x01,
1990  0x01, 0x00, 0x00, 0x00,
1991  0x72, 0xef, /* CRC. */
1992 
1993  0xff, 0xc9, 0x05, 0x0c,
1994  0x01, 0x28, 0x01, 0x00,
1995  0x00, 0x00, 0x01, 0x01,
1996  0x01, 0x00, 0x00, 0x00,
1997  0x72, 0xef, /* CRC. */
1998 
1999  0x00, 0x00
2000  };
2001  reassembled_len = 0;
2002  FAIL_IF(DNP3ReassembleApplicationLayer(short_payload1,
2003  sizeof(short_payload1), &output, &reassembled_len));
2004 
2005  /* Last block too short (by 2 bytes) for data + CRC. */
2006  uint8_t short_payload2[] = {
2007 
2008  0xff, 0xc9, 0x05, 0x0c,
2009  0x01, 0x28, 0x01, 0x00,
2010  0x00, 0x00, 0x01, 0x01,
2011  0x01, 0x00, 0x00, 0x00,
2012  0x72, 0xef, /* CRC. */
2013 
2014  0xff, 0xc9, 0x05, 0x0c,
2015  0x01, 0x28, 0x01, 0x00,
2016  0x00, 0x00, 0x01, 0x01,
2017  0x01, 0x00, 0x00, 0x00,
2018  0x72, 0xef, /* CRC. */
2019 
2020  0xff, 0xc9, 0x05, 0x0c,
2021  0x01, 0x28, 0x01, 0x00,
2022  0x00, 0x00, 0x01, 0x01,
2023  0x01, 0x00, 0x00, 0x00,
2024  0x72, 0xef, /* CRC. */
2025 
2026  0x00,
2027  };
2028  reassembled_len = 0;
2029  FAIL_IF(DNP3ReassembleApplicationLayer(short_payload2,
2030  sizeof(short_payload2), &output, &reassembled_len));
2031 
2032  PASS;
2033 }
2034 
2035 /**
2036  * \test Test the probing parser.
2037  */
2038 static int DNP3ProbingParserTest(void)
2039 {
2040  uint8_t pkt[] = {
2041  0x05, 0x64, 0x05, 0xc9, 0x03, 0x00, 0x04, 0x00,
2042  0xbd, 0x71
2043  };
2044 
2045  /* Valid frame. */
2046  FAIL_IF(DNP3ProbingParser(NULL, pkt, sizeof(pkt)) != ALPROTO_DNP3);
2047 
2048  /* Send too little bytes. */
2049  FAIL_IF(DNP3ProbingParser(NULL, pkt, sizeof(DNP3LinkHeader) - 1) != ALPROTO_UNKNOWN);
2050 
2051  /* Bad start bytes. */
2052  pkt[0] = 0x06;
2053  FAIL_IF(DNP3ProbingParser(NULL, pkt, sizeof(pkt)) != ALPROTO_FAILED);
2054 
2055  /* Restore start byte. */
2056  pkt[0] = 0x05;
2057 
2058  /* Set the length to a value less than the minimum length of 5. */
2059  pkt[2] = 0x03;
2060  FAIL_IF(DNP3ProbingParser(NULL, pkt, sizeof(pkt)) != ALPROTO_FAILED);
2061 
2062  /* Send a banner. */
2063  char mybanner[] = "Welcome to DNP3 SCADA.";
2064  FAIL_IF(DNP3ProbingParser(NULL, (uint8_t *)mybanner, sizeof(mybanner)) != ALPROTO_DNP3);
2065 
2066  PASS;
2067 }
2068 
2069 /**
2070  * \test Test a basic request/response.
2071  */
2072 static int DNP3ParserTestRequestResponse(void)
2073 {
2074  DNP3State *state = NULL;
2075 
2076  uint8_t request[] = {
2077  /* DNP3 start. */
2078  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2079  0xa5, 0xe9,
2080 
2081  /* Transport header. */
2082  0xff,
2083 
2084  /* Application layer. */
2085  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2086  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2087  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2088  };
2089 
2090  uint8_t response[] = {
2091  /* DNP3 start. */
2092  0x05, 0x64, 0x1c, 0x44, 0x01, 0x00, 0x02, 0x00,
2093  0xe2, 0x59,
2094 
2095  /* Transport header. */
2096  0xc3,
2097 
2098  /* Application layer. */
2099  0xc9, 0x81, 0x00, 0x00, 0x0c, 0x01, 0x28, 0x01,
2100  0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x7a,
2101  0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2102  0xff, 0xff
2103  };
2104 
2106  Flow flow;
2107  TcpSession ssn;
2108 
2109  memset(&flow, 0, sizeof(flow));
2110  memset(&ssn, 0, sizeof(ssn));
2111 
2112  flow.protoctx = (void *)&ssn;
2113  flow.proto = IPPROTO_TCP;
2114  flow.alproto = ALPROTO_DNP3;
2115 
2117 
2118  SCMutexLock(&flow.m);
2119  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2120  STREAM_TOSERVER, request, sizeof(request)));
2121  SCMutexUnlock(&flow.m);
2122 
2123  state = flow.alstate;
2124  FAIL_IF(state == NULL);
2125 
2126  DNP3Transaction *tx = DNP3GetTx(state, 0);
2127  FAIL_IF(tx == NULL);
2128  FAIL_IF(tx->tx_num != 1);
2129  FAIL_IF(tx != state->curr);
2130  FAIL_IF(tx->request_buffer == NULL);
2131  FAIL_IF(tx->request_buffer_len != 20);
2132  FAIL_IF(tx->request_ah.function_code != DNP3_APP_FC_DIR_OPERATE);
2133 
2134  SCMutexLock(&flow.m);
2135  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2136  STREAM_TOCLIENT, response, sizeof(response)));
2137  SCMutexUnlock(&flow.m);
2138  FAIL_IF(DNP3GetTx(state, 0) != tx);
2139  FAIL_IF(!tx->response_done);
2140  FAIL_IF(tx->response_buffer == NULL);
2141 
2142  AppLayerParserThreadCtxFree(alp_tctx);
2144  FLOW_DESTROY(&flow);
2145  PASS;
2146 }
2147 
2148 /**
2149  * \test Test an unsolicited response from an outstation.
2150  *
2151  * This is kind of like a request initiated from the "server".
2152  */
2153 static int DNP3ParserTestUnsolicitedResponseConfirm(void)
2154 {
2155  DNP3State *state = NULL;
2156 
2157  /* Unsolicited response with confirm bit set. */
2158  uint8_t response[] = {
2159  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2160  0x89, 0xe5, 0xc4, 0xfa, 0x82, 0x00, 0x00, 0x02,
2161  0x02, 0x17, 0x01, 0x01, 0x81, 0xa7, 0x75, 0xd8,
2162  0x32, 0x4c, 0x81, 0x3e, 0x01, 0xa1, 0xc9
2163  };
2164 
2165  /* Confirm. */
2166  uint8_t confirm[] = {
2167  0x05, 0x64, 0x08, 0xc4, 0x02, 0x00,
2168  0x01, 0x00, 0xd3, 0xb7, 0xc0, 0xda, 0x00, 0x6a,
2169  0x3d
2170  };
2171 
2173  Flow flow;
2174  TcpSession ssn;
2175 
2176  memset(&flow, 0, sizeof(flow));
2177  memset(&ssn, 0, sizeof(ssn));
2178 
2179  flow.protoctx = (void *)&ssn;
2180  flow.proto = IPPROTO_TCP;
2181  flow.alproto = ALPROTO_DNP3;
2182 
2184 
2185  SCMutexLock(&flow.m);
2186  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2187  STREAM_TOCLIENT, response, sizeof(response)));
2188  SCMutexUnlock(&flow.m);
2189 
2190  state = flow.alstate;
2191  FAIL_IF(state == NULL);
2192 
2193  DNP3Transaction *tx = DNP3GetTx(state, 0);
2194  FAIL_IF(tx == NULL);
2195  FAIL_IF(tx->tx_num != 1);
2196  FAIL_IF(tx != state->curr);
2197  FAIL_IF(tx->request_buffer != NULL);
2198  FAIL_IF(tx->response_buffer == NULL);
2199  FAIL_IF(!tx->response_done);
2200  FAIL_IF(tx->response_ah.function_code != DNP3_APP_FC_UNSOLICITED_RESP);
2201 
2202  SCMutexLock(&flow.m);
2203  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2204  STREAM_TOSERVER, confirm, sizeof(confirm)));
2205  SCMutexUnlock(&flow.m);
2206  FAIL_IF(DNP3GetTx(state, 0) != tx);
2207  FAIL_IF(!tx->response_done);
2208  FAIL_IF(tx->response_buffer == NULL);
2209  /* FAIL_IF(tx->iin1 != 0 || tx->iin2 != 0); */
2210 
2211  AppLayerParserThreadCtxFree(alp_tctx);
2213  FLOW_DESTROY(&flow);
2214  PASS;
2215 }
2216 
2217 /**
2218  * \test Test flood state.
2219  */
2220 static int DNP3ParserTestFlooded(void)
2221 {
2222  DNP3State *state = NULL;
2223 
2224  uint8_t request[] = {
2225  /* DNP3 start. */
2226  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2227  0xa5, 0xe9,
2228 
2229  /* Transport header. */
2230  0xff,
2231 
2232  /* Application layer. */
2233  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2234  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2235  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2236  };
2237 
2239  Flow flow;
2240  TcpSession ssn;
2241 
2242  memset(&flow, 0, sizeof(flow));
2243  memset(&ssn, 0, sizeof(ssn));
2244 
2245  flow.protoctx = (void *)&ssn;
2246  flow.proto = IPPROTO_TCP;
2247  flow.alproto = ALPROTO_DNP3;
2248 
2250 
2251  SCMutexLock(&flow.m);
2252  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2253  STREAM_TOSERVER, request, sizeof(request)));
2254  SCMutexUnlock(&flow.m);
2255 
2256  state = flow.alstate;
2257  FAIL_IF(state == NULL);
2258 
2259  DNP3Transaction *tx = DNP3GetTx(state, 0);
2260  FAIL_IF(tx == NULL);
2261  FAIL_IF(tx->tx_num != 1);
2262  FAIL_IF(tx != state->curr);
2263  FAIL_IF(tx->request_buffer == NULL);
2264  FAIL_IF(tx->request_buffer_len != 20);
2265  /* FAIL_IF(tx->app_function_code != DNP3_APP_FC_DIR_OPERATE); */
2266  FAIL_IF(tx->response_done);
2267 
2268  for (int i = 0; i < DNP3_DEFAULT_REQ_FLOOD_COUNT - 1; i++) {
2269  SCMutexLock(&flow.m);
2270  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2271  STREAM_TOSERVER, request, sizeof(request)));
2272  SCMutexUnlock(&flow.m);
2273  }
2274  FAIL_IF(state->flooded);
2275  FAIL_IF(DNP3GetAlstateProgress(tx, 0));
2276 
2277  /* One more request should trip us into flooded state. */
2278  SCMutexLock(&flow.m);
2279  FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2280  STREAM_TOSERVER, request, sizeof(request)));
2281  SCMutexUnlock(&flow.m);
2282  FAIL_IF(!state->flooded);
2283 
2284  /* Progress for the oldest tx should return 1. */
2285  FAIL_IF(!DNP3GetAlstateProgress(tx, 0));
2286 
2287  /* But progress for the current state should still return 0. */
2288  FAIL_IF(DNP3GetAlstateProgress(state->curr, 0));
2289 
2290  AppLayerParserThreadCtxFree(alp_tctx);
2292  FLOW_DESTROY(&flow);
2293  PASS;
2294 }
2295 
2296 /**
2297  * \test Test parsing of partial frames.
2298  *
2299  * As DNP3 operates over TCP, it is possible that a partial DNP3 frame
2300  * is received. Test that the partial frame will be buffered until the
2301  * remainder is seen.
2302  */
2303 static int DNP3ParserTestPartialFrame(void)
2304 {
2305  DNP3State *state = NULL;
2306  DNP3Transaction *tx;
2307  int r;
2308 
2309  uint8_t request_partial1[] = {
2310  /* DNP3 start. */
2311  0x05, 0x64, 0x1a, 0xc4, 0x02, 0x00, 0x01, 0x00,
2312  0xa5, 0xe9,
2313 
2314  /* Transport header. */
2315  0xff,
2316 
2317  /* Application layer. */
2318  0xc9, 0x05, 0x0c, 0x01, 0x28, 0x01, 0x00, 0x00,
2319  };
2320 
2321  uint8_t request_partial2[] = {
2322  /* Remainder of application layer. */
2323  0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x72,
2324  0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff
2325  };
2326 
2327  uint8_t response_partial1[] = {
2328  /* DNP3 start. */
2329  0x05, 0x64, 0x1c, 0x44, 0x01, 0x00, 0x02, 0x00,
2330  0xe2, 0x59,
2331 
2332  /* Transport header. */
2333  0xc3,
2334 
2335  /* Application layer. */
2336  0xc9, 0x81, 0x00, 0x00, 0x0c, 0x01, 0x28, 0x01,
2337  };
2338 
2339  uint8_t response_partial2[] = {
2340  0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x7a,
2341  0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2342  0xff, 0xff
2343  };
2344 
2345  /* Boiler plate for app layer setup. */
2347  Flow flow;
2348  TcpSession ssn;
2349  memset(&flow, 0, sizeof(flow));
2350  memset(&ssn, 0, sizeof(ssn));
2351  flow.protoctx = (void *)&ssn;
2352  flow.proto = IPPROTO_TCP;
2353  flow.alproto = ALPROTO_DNP3;
2355 
2356  /* Pass in the first partial frame. */
2357 
2358  SCMutexLock(&flow.m);
2359  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2360  STREAM_TOSERVER, request_partial1, sizeof(request_partial1));
2361  SCMutexUnlock(&flow.m);
2362  FAIL_IF(r != 0);
2363 
2364  /* Frame should just be buffered, but not yet processed. */
2365  state = flow.alstate;
2366  FAIL_IF(state == NULL);
2367  FAIL_IF(state->request_buffer.len != sizeof(request_partial1));
2368  FAIL_IF(state->request_buffer.offset != 0);
2369  FAIL_IF(memcmp(state->request_buffer.buffer, request_partial1,
2370  sizeof(request_partial1)));
2371 
2372  /* There should not be a transaction yet. */
2373  FAIL_IF(state->transaction_max != 0);
2374  FAIL_IF(DNP3GetTx(state, 0) != NULL);
2375 
2376  /* Send the second partial. */
2377  SCMutexLock(&flow.m);
2378  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2379  STREAM_TOSERVER, request_partial2, sizeof(request_partial2));
2380  SCMutexUnlock(&flow.m);
2381  FAIL_IF(r != 0);
2382 
2383  /* The second partial completed the frame, the buffer should now
2384  * be clear. */
2385  FAIL_IF(state->request_buffer.len != 0);
2386  FAIL_IF(state->request_buffer.offset != 0);
2387 
2388  /* Should now have a complete transaction. */
2389  tx = DNP3GetTx(state, 0);
2390  FAIL_IF(tx == NULL);
2391  FAIL_IF(tx->tx_num != 1);
2392  FAIL_IF(tx != state->curr);
2393  FAIL_IF(tx->request_buffer == NULL);
2394  FAIL_IF(tx->request_buffer_len != 20);
2395  FAIL_IF(tx->request_ah.function_code != DNP3_APP_FC_DIR_OPERATE);
2396 
2397  /* Send partial response. */
2398  SCMutexLock(&flow.m);
2399  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2400  STREAM_TOCLIENT, response_partial1, sizeof(response_partial1));
2401  SCMutexUnlock(&flow.m);
2402  FAIL_IF(r != 0);
2403  FAIL_IF(state->response_buffer.len != sizeof(response_partial1));
2404  FAIL_IF(state->response_buffer.offset != 0);
2405  FAIL_IF(tx->response_done);
2406 
2407  /* Send rest of response. */
2408  SCMutexLock(&flow.m);
2409  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2410  STREAM_TOCLIENT, response_partial2, sizeof(response_partial2));
2411  SCMutexUnlock(&flow.m);
2412  FAIL_IF(r != 0);
2413 
2414  /* Buffer should now be empty. */
2415  FAIL_IF(state->response_buffer.len != 0);
2416  FAIL_IF(state->response_buffer.offset != 0);
2417 
2418  /* Transaction should be replied to now. */
2419  FAIL_IF(!tx->response_done);
2420  FAIL_IF(tx->response_buffer == NULL);
2421  FAIL_IF(tx->response_buffer_len == 0);
2422 
2423  AppLayerParserThreadCtxFree(alp_tctx);
2425  FLOW_DESTROY(&flow);
2426  PASS;
2427 }
2428 
2429 /**
2430  * \test Test multiple DNP3 frames in one TCP read.
2431  */
2432 static int DNP3ParserTestMultiFrame(void)
2433 {
2434  DNP3State *state = NULL;
2435 
2436  /* Unsolicited response 1. */
2437  uint8_t unsol_response1[] = {
2438  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2439  0x89, 0xe5, 0xc4, 0xfa, 0x82, 0x00, 0x00, 0x02,
2440  0x02, 0x17, 0x01, 0x01, 0x81, 0xa7, 0x75, 0xd8,
2441  0x32, 0x4c, 0x81, 0x3e, 0x01, 0xa1, 0xc9,
2442  };
2443 
2444  /* Unsolicited response 2. */
2445  uint8_t unsol_response2[] = {
2446  0x05, 0x64, 0x16, 0x44, 0x01, 0x00, 0x02, 0x00,
2447  0x89, 0xe5, 0xc5, 0xfb, 0x82, 0x00, 0x00, 0x02,
2448  0x02, 0x17, 0x01, 0x0c, 0x01, 0xd8, 0x75, 0xd8,
2449  0x32, 0x4c, 0xc9, 0x3c, 0x01, 0xa1, 0xc9,
2450  };
2451 
2452  uint8_t combined[sizeof(unsol_response1) + sizeof(unsol_response2)];
2453  memcpy(combined, unsol_response1, sizeof(unsol_response1));
2454  memcpy(combined + sizeof(unsol_response1), unsol_response2,
2455  sizeof(unsol_response2));
2456 
2457  /* Setup. */
2459  Flow flow;
2460  TcpSession ssn;
2461  int r;
2462  memset(&flow, 0, sizeof(flow));
2463  memset(&ssn, 0, sizeof(ssn));
2464  flow.protoctx = (void *)&ssn;
2465  flow.proto = IPPROTO_TCP;
2466  flow.alproto = ALPROTO_DNP3;
2468 
2469  SCMutexLock(&flow.m);
2470  r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3,
2471  STREAM_TOCLIENT, combined, sizeof(combined));
2472  SCMutexUnlock(&flow.m);
2473  FAIL_IF(r != 0);
2474 
2475  state = flow.alstate;
2476  FAIL_IF(state == NULL);
2477  FAIL_IF(state->transaction_max != 2);
2478 
2479  AppLayerParserThreadCtxFree(alp_tctx);
2481  FLOW_DESTROY(&flow);
2482  PASS;
2483 }
2484 
2485 /**
2486  * \test Test the parsing of a request PDU.
2487  *
2488  * The PDU under test contains a single read request object:
2489  * - Group: 1
2490  * - Variation: 0
2491  * - Count: 0
2492  */
2493 static int DNP3ParserTestParsePDU01(void)
2494 {
2495  /* Frame to be tested. This frame is a DNP3 request with one read
2496  * request data object, group 1, variation 0. */
2497  const uint8_t pkt[] = {
2498  0x05, 0x64,
2499  0x0b, 0xc4, 0x17, 0x00, 0xef, 0xff, 0xc4, 0x8f,
2500  0xe1, 0xc8, 0x01, 0x01, 0x00, 0x06, 0x77, 0x6e
2501  };
2502 
2503  DNP3State *dnp3state = DNP3StateAlloc();
2504  int pdus = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2505  FAIL_IF(pdus < 1);
2506  DNP3Transaction *dnp3tx = DNP3GetTx(dnp3state, 0);
2507  FAIL_IF_NULL(dnp3tx);
2508  FAIL_IF(!dnp3tx->has_request);
2509  FAIL_IF(TAILQ_EMPTY(&dnp3tx->request_objects));
2510  DNP3Object *object = TAILQ_FIRST(&dnp3tx->request_objects);
2511  FAIL_IF(object->group != 1 || object->variation != 0);
2512  FAIL_IF(object->count != 0);
2513 
2514  DNP3StateFree(dnp3state);
2515  PASS;
2516 }
2517 
2518 /**
2519  * \test Test the decode of a DNP3 fragment with a single 70:3 object.
2520  */
2521 static int DNP3ParserDecodeG70V3Test(void)
2522 {
2523  const uint8_t pkt[] = {
2524  0x05, 0x64,
2525  0x63, 0xc4, 0x04, 0x00, 0x03, 0x00, 0xc7, 0xee,
2526  0xc7, 0xc9, 0x1b, 0x46, 0x03, 0x5b, 0x01, 0x55,
2527  0x00, 0x1a, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00,
2528  0x9e, 0xc7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2529  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2530  0x00, 0x00, 0xff, 0xff, 0x00, 0x1e, 0x00, 0x43,
2531  0x3a, 0x2f, 0x74, 0x65, 0x6d, 0x70, 0x2f, 0x44,
2532  0x4e, 0x50, 0x44, 0x65, 0x67, 0x7d, 0x76, 0x69,
2533  0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
2534  0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x93, 0x0c,
2535  0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65,
2536  0x6e, 0x20, 0x74, 0x6f, 0x20, 0x52, 0x65, 0x6d,
2537  0x35, 0x20, 0x6f, 0x74, 0x65, 0x20, 0x44, 0x65,
2538  0x76, 0x69, 0x63, 0x65, 0x2e, 0x78, 0x6d, 0x6c,
2539  0xc4, 0x8b
2540  };
2541 
2542  DNP3State *dnp3state = DNP3StateAlloc();
2543  FAIL_IF_NULL(dnp3state);
2544  int bytes = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2545  FAIL_IF(bytes != sizeof(pkt));
2546  DNP3Transaction *tx = DNP3GetTx(dnp3state, 0);
2547  FAIL_IF_NULL(tx);
2548  FAIL_IF_NOT(tx->has_request);
2549  DNP3Object *obj = TAILQ_FIRST(&tx->request_objects);
2550  FAIL_IF_NULL(obj);
2551  FAIL_IF_NOT(obj->group == 70);
2552  FAIL_IF_NOT(obj->variation == 3);
2553  FAIL_IF_NOT(obj->prefix_code == 0x5);
2554  FAIL_IF_NOT(obj->range_code == 0xb);
2555  FAIL_IF_NOT(obj->count == 1);
2556  DNP3Point *point = TAILQ_FIRST(obj->points);
2557  FAIL_IF_NULL(point);
2558  FAIL_IF_NOT(point->prefix == 85);
2559  FAIL_IF_NOT(point->size == 85);
2560  FAIL_IF_NULL(point->data);
2561  DNP3ObjectG70V3 *data = point->data;
2562  FAIL_IF_NOT(strcmp(
2563  data->filename,
2564  "C:/temp/DNPDeviceConfiguration written to Remote Device.xml") == 0);
2565  DNP3StateFree(dnp3state);
2566  PASS;
2567 }
2568 
2569 /**
2570  * \brief Test that an alert is raised on an unknown object.
2571  */
2572 static int DNP3ParserUnknownEventAlertTest(void)
2573 {
2574  /* Valid DNP3 frame with 70:3 object. */
2575  uint8_t pkt[] = {
2576  0x05, 0x64, 0x63, 0xc4, 0x04, 0x00, 0x03, 0x00,
2577  0xc7, 0xee,
2578 
2579  0xc7, 0xc9, 0x1b,
2580 
2581  /* Object and variation. Originally 70:3, now 70:99, an
2582  * unknown object. */
2583  0x46, 0x63,
2584 
2585  0x5b, 0x01, 0x55,
2586  0x00, 0x1a, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00,
2587  0x9e, 0xc7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2588  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2589  0x00, 0x00, 0xff, 0xff, 0x00, 0x1e, 0x00, 0x43,
2590  0x3a, 0x2f, 0x74, 0x65, 0x6d, 0x70, 0x2f, 0x44,
2591  0x4e, 0x50, 0x44, 0x65, 0x67, 0x7d, 0x76, 0x69,
2592  0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
2593  0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x93, 0x0c,
2594  0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65,
2595  0x6e, 0x20, 0x74, 0x6f, 0x20, 0x52, 0x65, 0x6d,
2596  0x35, 0x20, 0x6f, 0x74, 0x65, 0x20, 0x44, 0x65,
2597  0x76, 0x69, 0x63, 0x65, 0x2e, 0x78, 0x6d, 0x6c,
2598  0xc4, 0x8b
2599  };
2600 
2601  DNP3FixCrc(pkt + 10, sizeof(pkt) - 10);
2602 
2603  DNP3State *dnp3state = DNP3StateAlloc();
2604  FAIL_IF_NULL(dnp3state);
2605  int bytes = DNP3HandleRequestLinkLayer(dnp3state, pkt, sizeof(pkt));
2606  FAIL_IF(bytes != sizeof(pkt));
2607 
2608  DNP3StateFree(dnp3state);
2609  PASS;
2610 }
2611 
2612 #endif
2613 
2615 {
2616 #ifdef UNITTESTS
2617  UtRegisterTest("DNP3ParserTestCheckCRC", DNP3ParserTestCheckCRC);
2618  UtRegisterTest("DNP3ParserCheckLinkHeaderCRC",
2619  DNP3ParserCheckLinkHeaderCRC);
2620  UtRegisterTest("DNP3CheckUserDataCRCsTest", DNP3CheckUserDataCRCsTest);
2621  UtRegisterTest("DNP3CalculateLinkLengthTest", DNP3CalculateLinkLengthTest);
2622  UtRegisterTest("DNP3CalculateTransportLengthWithoutCRCsTest",
2623  DNP3CalculateTransportLengthWithoutCRCsTest);
2624  UtRegisterTest("DNP3ReassembleApplicationLayerTest01",
2625  DNP3ReassembleApplicationLayerTest01);
2626  UtRegisterTest("DNP3ProbingParserTest", DNP3ProbingParserTest);
2627  UtRegisterTest("DNP3ParserTestRequestResponse",
2628  DNP3ParserTestRequestResponse);
2629  UtRegisterTest("DNP3ParserTestUnsolicitedResponseConfirm",
2630  DNP3ParserTestUnsolicitedResponseConfirm);
2631  UtRegisterTest("DNP3ParserTestPartialFrame", DNP3ParserTestPartialFrame);
2632  UtRegisterTest("DNP3ParserTestMultiFrame", DNP3ParserTestMultiFrame);
2633  UtRegisterTest("DNP3ParserTestFlooded", DNP3ParserTestFlooded);
2634  UtRegisterTest("DNP3ParserTestParsePDU01", DNP3ParserTestParsePDU01);
2635  UtRegisterTest("DNP3ParserDecodeG70V3Test", DNP3ParserDecodeG70V3Test);
2636  UtRegisterTest("DNP3ParserUnknownEventAlertTest",
2637  DNP3ParserUnknownEventAlertTest);
2638 #endif
2639 }
#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
#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:346
#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.
#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
#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
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:398
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:436
#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:205
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:115
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:392
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
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:190
#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:236
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)
void AppLayerParserRegisterGetEventsFunc(uint8_t ipproto, AppProto alproto, AppLayerDecoderEvents *(*StateGetEvents)(void *, uint64_t))
#define DNP3_APP_FC_UNSOLICITED_RESP
void AppLayerParserRegisterProtocolUnittests(uint8_t ipproto, AppProto alproto, void(*RegisterUnittests)(void))
#define SCMutexLock(mut)
#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.
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:407
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:327
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