forked from OISF/suricata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app-layer-modbus.c
3271 lines (2731 loc) · 114 KB
/
app-layer-modbus.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014 ANSSI
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* \author David DIALLO <[email protected]>
*
* App-layer parser for Modbus protocol
*
*/
#include "suricata-common.h"
#include "util-debug.h"
#include "util-byte.h"
#include "util-enum.h"
#include "util-mem.h"
#include "util-misc.h"
#include "stream.h"
#include "stream-tcp.h"
#include "app-layer-protos.h"
#include "app-layer-parser.h"
#include "app-layer-modbus.h"
#include "app-layer-detect-proto.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "decode.h"
SCEnumCharMap modbus_decoder_event_table[ ] = {
/* Modbus Application Data Unit messages - ADU Modbus */
{ "INVALID_PROTOCOL_ID", MODBUS_DECODER_EVENT_INVALID_PROTOCOL_ID },
{ "UNSOLICITED_RESPONSE", MODBUS_DECODER_EVENT_UNSOLICITED_RESPONSE },
{ "INVALID_LENGTH", MODBUS_DECODER_EVENT_INVALID_LENGTH },
{ "INVALID_UNIT_IDENTIFIER", MODBUS_DECODER_EVENT_INVALID_UNIT_IDENTIFIER},
/* Modbus Protocol Data Unit messages - PDU Modbus */
{ "INVALID_FUNCTION_CODE", MODBUS_DECODER_EVENT_INVALID_FUNCTION_CODE },
{ "INVALID_VALUE", MODBUS_DECODER_EVENT_INVALID_VALUE },
{ "INVALID_EXCEPTION_CODE", MODBUS_DECODER_EVENT_INVALID_EXCEPTION_CODE },
{ "VALUE_MISMATCH", MODBUS_DECODER_EVENT_VALUE_MISMATCH },
/* Modbus Decoder event */
{ "FLOODED", MODBUS_DECODER_EVENT_FLOODED},
{ NULL, -1 },
};
/* Modbus Application Data Unit (ADU) length range. */
#define MODBUS_MIN_ADU_LEN 2
#define MODBUS_MAX_ADU_LEN 254
/* Modbus Protocol version. */
#define MODBUS_PROTOCOL_VER 0
/* Modbus Unit Identifier range. */
#define MODBUS_MIN_INVALID_UNIT_ID 247
#define MODBUS_MAX_INVALID_UNIT_ID 255
/* Modbus Quantity range. */
#define MODBUS_MIN_QUANTITY 0
#define MODBUS_MAX_QUANTITY_IN_BIT_ACCESS 2000
#define MODBUS_MAX_QUANTITY_IN_WORD_ACCESS 125
/* Modbus Count range. */
#define MODBUS_MIN_COUNT 1
#define MODBUS_MAX_COUNT 250
/* Modbus Function Code. */
#define MODBUS_FUNC_NONE 0x00
#define MODBUS_FUNC_READCOILS 0x01
#define MODBUS_FUNC_READDISCINPUTS 0x02
#define MODBUS_FUNC_READHOLDREGS 0x03
#define MODBUS_FUNC_READINPUTREGS 0x04
#define MODBUS_FUNC_WRITESINGLECOIL 0x05
#define MODBUS_FUNC_WRITESINGLEREG 0x06
#define MODBUS_FUNC_READEXCSTATUS 0x07
#define MODBUS_FUNC_DIAGNOSTIC 0x08
#define MODBUS_FUNC_GETCOMEVTCOUNTER 0x0b
#define MODBUS_FUNC_GETCOMEVTLOG 0x0c
#define MODBUS_FUNC_WRITEMULTCOILS 0x0f
#define MODBUS_FUNC_WRITEMULTREGS 0x10
#define MODBUS_FUNC_REPORTSERVERID 0x11
#define MODBUS_FUNC_READFILERECORD 0x14
#define MODBUS_FUNC_WRITEFILERECORD 0x15
#define MODBUS_FUNC_MASKWRITEREG 0x16
#define MODBUS_FUNC_READWRITEMULTREGS 0x17
#define MODBUS_FUNC_READFIFOQUEUE 0x18
#define MODBUS_FUNC_ENCAPINTTRANS 0x2b
#define MODBUS_FUNC_MASK 0x7f
#define MODBUS_FUNC_ERRORMASK 0x80
/* Modbus Diagnostic functions: Subfunction Code. */
#define MODBUS_SUBFUNC_QUERY_DATA 0x00
#define MODBUS_SUBFUNC_RESTART_COM 0x01
#define MODBUS_SUBFUNC_DIAG_REGS 0x02
#define MODBUS_SUBFUNC_CHANGE_DELIMITER 0x03
#define MODBUS_SUBFUNC_LISTEN_MODE 0x04
#define MODBUS_SUBFUNC_CLEAR_REGS 0x0a
#define MODBUS_SUBFUNC_BUS_MSG_COUNT 0x0b
#define MODBUS_SUBFUNC_COM_ERR_COUNT 0x0c
#define MODBUS_SUBFUNC_EXCEPT_ERR_COUNT 0x0d
#define MODBUS_SUBFUNC_SERVER_MSG_COUNT 0x0e
#define MODBUS_SUBFUNC_SERVER_NO_RSP_COUNT 0x0f
#define MODBUS_SUBFUNC_SERVER_NAK_COUNT 0x10
#define MODBUS_SUBFUNC_SERVER_BUSY_COUNT 0x11
#define MODBUS_SUBFUNC_SERVER_CHAR_COUNT 0x12
#define MODBUS_SUBFUNC_CLEAR_COUNT 0x14
/* Modbus Encapsulated Interface Transport function: MEI type. */
#define MODBUS_MEI_ENCAPINTTRANS_CAN 0x0d
#define MODBUS_MEI_ENCAPINTTRANS_READ 0x0e
/* Modbus Exception Codes. */
#define MODBUS_ERROR_CODE_ILLEGAL_FUNCTION 0x01
#define MODBUS_ERROR_CODE_ILLEGAL_DATA_ADDRESS 0x02
#define MODBUS_ERROR_CODE_ILLEGAL_DATA_VALUE 0x03
#define MODBUS_ERROR_CODE_SERVER_DEVICE_FAILURE 0x04
#define MODBUS_ERROR_CODE_MEMORY_PARITY_ERROR 0x08
/* Modbus Application Protocol (MBAP) header. */
struct ModbusHeader_ {
uint16_t transactionId;
uint16_t protocolId;
uint16_t length;
uint8_t unitId;
} __attribute__((__packed__));
typedef struct ModbusHeader_ ModbusHeader;
/* Modbus Read/Write function and Access Types. */
#define MODBUS_TYP_WRITE_SINGLE (MODBUS_TYP_WRITE | MODBUS_TYP_SINGLE)
#define MODBUS_TYP_WRITE_MULTIPLE (MODBUS_TYP_WRITE | MODBUS_TYP_MULTIPLE)
#define MODBUS_TYP_READ_WRITE_MULTIPLE (MODBUS_TYP_READ | MODBUS_TYP_WRITE | MODBUS_TYP_MULTIPLE)
/* Macro to convert quantity value (in bit) into count value (in word): count = Ceil(quantity/8) */
#define CEIL(quantity) (((quantity) + 7)>>3)
/* Modbus Default unreplied Modbus requests are considered a flood */
#define MODBUS_CONFIG_DEFAULT_REQUEST_FLOOD 500
/* Modbus default stream reassembly depth */
#define MODBUS_CONFIG_DEFAULT_STREAM_DEPTH 0
static uint32_t request_flood = MODBUS_CONFIG_DEFAULT_REQUEST_FLOOD;
static uint32_t stream_depth = MODBUS_CONFIG_DEFAULT_STREAM_DEPTH;
int ModbusStateGetEventInfo(const char *event_name, int *event_id, AppLayerEventType *event_type) {
*event_id = SCMapEnumNameToValue(event_name, modbus_decoder_event_table);
if (*event_id == -1) {
SCLogError(SC_ERR_INVALID_ENUM_MAP, "event \"%s\" not present in "
"modbus's enum map table.", event_name);
/* yes this is fatal */
return -1;
}
*event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
return 0;
}
void ModbusSetEvent(ModbusState *modbus, uint8_t e) {
if (modbus && modbus->curr) {
SCLogDebug("modbus->curr->decoder_events %p", modbus->curr->decoder_events);
AppLayerDecoderEventsSetEventRaw(&modbus->curr->decoder_events, e);
SCLogDebug("modbus->curr->decoder_events %p", modbus->curr->decoder_events);
modbus->events++;
} else
SCLogDebug("couldn't set event %u", e);
}
AppLayerDecoderEvents *ModbusGetEvents(void *state, uint64_t id) {
ModbusState *modbus = (ModbusState *) state;
ModbusTransaction *tx;
if (modbus->curr && modbus->curr->tx_num == (id + 1))
return modbus->curr->decoder_events;
TAILQ_FOREACH(tx, &modbus->tx_list, next) {
if (tx->tx_num == (id+1))
return tx->decoder_events;
}
return NULL;
}
int ModbusHasEvents(void *state) {
return (((ModbusState *) state)->events > 0);
}
int ModbusGetAlstateProgress(void *modbus_tx, uint8_t direction) {
ModbusTransaction *tx = (ModbusTransaction *) modbus_tx;
ModbusState *modbus = tx->modbus;
if (tx->replied == 1)
return 1;
/* Check flood limit */
if ((modbus->givenup == 1) &&
((modbus->transaction_max - tx->tx_num) > request_flood))
return 1;
return 0;
}
/** \brief Get value for 'complete' status in Modbus
*/
int ModbusGetAlstateProgressCompletionStatus(uint8_t direction) {
return 1;
}
void *ModbusGetTx(void *alstate, uint64_t tx_id) {
ModbusState *modbus = (ModbusState *) alstate;
ModbusTransaction *tx = NULL;
if (modbus->curr && modbus->curr->tx_num == tx_id + 1)
return modbus->curr;
TAILQ_FOREACH(tx, &modbus->tx_list, next) {
SCLogDebug("tx->tx_num %"PRIu64", tx_id %"PRIu64, tx->tx_num, (tx_id+1));
if (tx->tx_num != (tx_id+1))
continue;
SCLogDebug("returning tx %p", tx);
return tx;
}
return NULL;
}
void ModbusSetTxLogged(void *alstate, void *vtx, uint32_t logger)
{
ModbusTransaction *tx = (ModbusTransaction *)vtx;
tx->logged |= logger;
}
int ModbusGetTxLogged(void *alstate, void *vtx, uint32_t logger)
{
ModbusTransaction *tx = (ModbusTransaction *)vtx;
if (tx->logged & logger)
return 1;
return 0;
}
uint64_t ModbusGetTxCnt(void *alstate) {
return ((uint64_t) ((ModbusState *) alstate)->transaction_max);
}
/** \internal
* \brief Find the Modbus Transaction in the state based on Transaction ID.
*
* \param modbus Pointer to Modbus state structure
* \param transactionId Transaction ID of the transaction
*
* \retval tx or NULL if not found
*/
static ModbusTransaction *ModbusTxFindByTransaction(const ModbusState *modbus,
const uint16_t transactionId) {
ModbusTransaction *tx = NULL;
if (modbus->curr == NULL)
return NULL;
/* fast path */
if ((modbus->curr->transactionId == transactionId) &&
!(modbus->curr->replied)) {
return modbus->curr;
/* slow path, iterate list */
} else {
TAILQ_FOREACH(tx, &modbus->tx_list, next) {
if ((tx->transactionId == transactionId) &&
!(modbus->curr->replied))
return tx;
}
}
/* not found */
return NULL;
}
/** \internal
* \brief Allocate a Modbus Transaction and
* add it into Transaction list of Modbus State
*
* \param modbus Pointer to Modbus state structure
*
* \retval Pointer to Transaction or NULL pointer
*/
static ModbusTransaction *ModbusTxAlloc(ModbusState *modbus) {
ModbusTransaction *tx;
tx = (ModbusTransaction *) SCCalloc(1, sizeof(ModbusTransaction));
if (unlikely(tx == NULL))
return NULL;
modbus->transaction_max++;
modbus->unreplied_cnt++;
/* Check flood limit */
if ((request_flood != 0) && (modbus->unreplied_cnt > request_flood)) {
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_FLOODED);
modbus->givenup = 1;
}
modbus->curr = tx;
SCLogDebug("modbus->transaction_max updated to %"PRIu64, modbus->transaction_max);
TAILQ_INSERT_TAIL(&modbus->tx_list, tx, next);
tx->modbus = modbus;
tx->tx_num = modbus->transaction_max;
return tx;
}
/** \internal
* \brief Free a Modbus Transaction
*
* \retval Pointer to Transaction or NULL pointer
*/
static void ModbusTxFree(ModbusTransaction *tx) {
SCEnter();
if (tx->data != NULL)
SCFree(tx->data);
AppLayerDecoderEventsFreeEvents(&tx->decoder_events);
if (tx->de_state != NULL)
DetectEngineStateFree(tx->de_state);
SCFree(tx);
SCReturn;
}
/**
* \brief Modbus transaction cleanup callback
*/
void ModbusStateTxFree(void *state, uint64_t tx_id) {
SCEnter();
ModbusState *modbus = (ModbusState *) state;
ModbusTransaction *tx = NULL, *ttx;
SCLogDebug("state %p, id %"PRIu64, modbus, tx_id);
TAILQ_FOREACH_SAFE(tx, &modbus->tx_list, next, ttx) {
SCLogDebug("tx %p tx->tx_num %"PRIu64", tx_id %"PRIu64, tx, tx->tx_num, (tx_id+1));
if (tx->tx_num != (tx_id+1))
continue;
if (tx == modbus->curr)
modbus->curr = NULL;
if (tx->decoder_events != NULL) {
if (tx->decoder_events->cnt <= modbus->events)
modbus->events -= tx->decoder_events->cnt;
else
modbus->events = 0;
}
modbus->unreplied_cnt--;
/* Check flood limit */
if ((modbus->givenup == 1) &&
(request_flood != 0) &&
(modbus->unreplied_cnt < request_flood) )
modbus->givenup = 0;
TAILQ_REMOVE(&modbus->tx_list, tx, next);
ModbusTxFree(tx);
break;
}
SCReturn;
}
/** \internal
* \brief Extract 8bits data from pointer the received input data
*
* \param res Pointer to the result
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static int ModbusExtractUint8(ModbusState *modbus,
uint8_t *res,
uint8_t *input,
uint32_t input_len,
uint16_t *offset) {
SCEnter();
if (input_len < (uint32_t) (*offset + sizeof(uint8_t))) {
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_LENGTH);
SCReturnInt(-1);
}
*res = *(input + *offset);
*offset += sizeof(uint8_t);
SCReturnInt(0);
}
/** \internal
* \brief Extract 16bits data from pointer the received input data
*
* \param res Pointer to the result
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static int ModbusExtractUint16(ModbusState *modbus,
uint16_t *res,
uint8_t *input,
uint32_t input_len,
uint16_t *offset) {
SCEnter();
if (input_len < (uint32_t) (*offset + sizeof(uint16_t))) {
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_LENGTH);
SCReturnInt(-1);
}
ByteExtractUint16(res, BYTE_BIG_ENDIAN, sizeof(uint16_t), (const uint8_t *) (input + *offset));
*offset += sizeof(uint16_t);
SCReturnInt(0);
}
/** \internal
* \brief Check length field in Modbus header according to code function
*
* \param modbus Pointer to Modbus state structure
* \param length Length field in Modbus Header
* \param len Length according to code functio
*/
static int ModbusCheckHeaderLength(ModbusState *modbus,
uint16_t length,
uint16_t len) {
SCEnter();
if (length != len) {
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_LENGTH);
SCReturnInt(-1);
}
SCReturnInt(0);
}
/** \internal
* \brief Check Modbus header
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param header Pointer to Modbus header state in which the value to be stored
*/
static void ModbusCheckHeader(ModbusState *modbus,
ModbusHeader *header)
{
SCEnter();
/* MODBUS protocol is identified by the value 0. */
if (header->protocolId != MODBUS_PROTOCOL_VER)
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_PROTOCOL_ID);
/* Check Length field that is a byte count of the following fields */
if ((header->length < MODBUS_MIN_ADU_LEN) ||
(header->length > MODBUS_MAX_ADU_LEN) )
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_LENGTH);
/* Check Unit Identifier field that is not in invalid range */
if ((header->unitId > MODBUS_MIN_INVALID_UNIT_ID) &&
(header->unitId < MODBUS_MAX_INVALID_UNIT_ID) )
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_UNIT_IDENTIFIER);
SCReturn;
}
/** \internal
* \brief Parse Exception Response and verify protocol compliance.
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static void ModbusExceptionResponse(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint8_t exception = 0;
/* Exception code (1 byte) */
if (ModbusExtractUint8(modbus, &exception, input, input_len, offset))
SCReturn;
switch (exception) {
case MODBUS_ERROR_CODE_ILLEGAL_FUNCTION:
case MODBUS_ERROR_CODE_SERVER_DEVICE_FAILURE:
break;
case MODBUS_ERROR_CODE_ILLEGAL_DATA_VALUE:
if (tx->function == MODBUS_FUNC_DIAGNOSTIC) {
break;
}
/* Fallthrough */
case MODBUS_ERROR_CODE_ILLEGAL_DATA_ADDRESS:
if ( (tx->type & MODBUS_TYP_ACCESS_FUNCTION_MASK) ||
(tx->function == MODBUS_FUNC_READFIFOQUEUE) ||
(tx->function == MODBUS_FUNC_ENCAPINTTRANS)) {
break;
}
/* Fallthrough */
case MODBUS_ERROR_CODE_MEMORY_PARITY_ERROR:
if ( (tx->function == MODBUS_FUNC_READFILERECORD) ||
(tx->function == MODBUS_FUNC_WRITEFILERECORD) ) {
break;
}
/* Fallthrough */
default:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_EXCEPTION_CODE);
break;
}
SCReturn;
}
/** \internal
* \brief Parse Read data Request, complete Transaction structure
* and verify protocol compliance.
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static void ModbusParseReadRequest(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint16_t quantity;
uint8_t type = tx->type;
/* Starting Address (2 bytes) */
if (ModbusExtractUint16(modbus, &(tx->read.address), input, input_len, offset))
goto end;
/* Quantity (2 bytes) */
if (ModbusExtractUint16(modbus, &(tx->read.quantity), input, input_len, offset))
goto end;
quantity = tx->read.quantity;
/* Check Quantity range */
if (type & MODBUS_TYP_BIT_ACCESS_MASK) {
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_BIT_ACCESS))
goto error;
} else {
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_WORD_ACCESS))
goto error;
}
if (~type & MODBUS_TYP_WRITE)
/* Except from Read/Write Multiple Registers function (code 23) */
/* The length of all Read Data function requests is 6 bytes */
/* Modbus Application Protocol Specification V1.1b3 from 6.1 to 6.4 */
ModbusCheckHeaderLength(modbus, tx->length, 6);
goto end;
error:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_VALUE);
end:
SCReturn;
}
/** \internal
* \brief Parse Read data Response and verify protocol compliance
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static void ModbusParseReadResponse(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint8_t count = 0;
/* Count (1 bytes) */
if (ModbusExtractUint8(modbus, &count, input, input_len, offset))
goto end;
/* Check Count range and value according to the request */
if ((tx->type) & MODBUS_TYP_BIT_ACCESS_MASK) {
if ( (count < MODBUS_MIN_COUNT) ||
(count > MODBUS_MAX_COUNT) ||
(count != CEIL(tx->read.quantity)))
goto error;
} else {
if ( (count == MODBUS_MIN_COUNT) ||
(count > MODBUS_MAX_COUNT) ||
(count != (2 * (tx->read.quantity))))
goto error;
}
/* Except from Read/Write Multiple Registers function (code 23) */
/* The length of all Read Data function responses is (3 bytes + count) */
/* Modbus Application Protocol Specification V1.1b3 from 6.1 to 6.4 */
ModbusCheckHeaderLength(modbus, tx->length, 3 + count);
goto end;
error:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_VALUE_MISMATCH);
end:
SCReturn;
}
/** \internal
* \brief Parse Write data Request, complete Transaction structure
* and verify protocol compliance.
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*
* \retval On success returns 0 or on failure returns -1.
*/
static int ModbusParseWriteRequest(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint16_t quantity = 1, word = 0;
uint8_t byte = 0, count = 1, type = tx->type;
int i = 0;
/* Starting/Output/Register Address (2 bytes) */
if (ModbusExtractUint16(modbus, &(tx->write.address), input, input_len, offset))
goto end;
if (type & MODBUS_TYP_SINGLE) {
/* The length of Write Single Coil (code 5) and */
/* Write Single Register (code 6) requests is 6 bytes */
/* Modbus Application Protocol Specification V1.1b3 6.5 and 6.6 */
if (ModbusCheckHeaderLength(modbus, tx->length, 6))
goto end;
} else if (type & MODBUS_TYP_MULTIPLE) {
/* Quantity (2 bytes) */
if (ModbusExtractUint16(modbus, &quantity, input, input_len, offset))
goto end;
tx->write.quantity = quantity;
/* Count (1 bytes) */
if (ModbusExtractUint8(modbus, &count, input, input_len, offset))
goto end;
tx->write.count = count;
if (type & MODBUS_TYP_BIT_ACCESS_MASK) {
/* Check Quantity range and conversion in byte (count) */
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_BIT_ACCESS) ||
(quantity != CEIL(count)))
goto error;
/* The length of Write Multiple Coils (code 15) request is (7 + count) */
/* Modbus Application Protocol Specification V1.1b3 6.11 */
if (ModbusCheckHeaderLength(modbus, tx->length, 7 + count))
goto end;
} else {
/* Check Quantity range and conversion in byte (count) */
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_WORD_ACCESS) ||
(count != (2 * quantity)))
goto error;
if (type & MODBUS_TYP_READ) {
/* The length of Read/Write Multiple Registers function (code 23) */
/* request is (11 bytes + count) */
/* Modbus Application Protocol Specification V1.1b3 6.17 */
if (ModbusCheckHeaderLength(modbus, tx->length, 11 + count))
goto end;
} else {
/* The length of Write Multiple Coils (code 15) and */
/* Write Multiple Registers (code 16) functions requests is (7 bytes + count) */
/* Modbus Application Protocol Specification V1.1b3 from 6.11 and 6.12 */
if (ModbusCheckHeaderLength(modbus, tx->length, 7 + count))
goto end;
}
}
} else {
/* Mask Write Register function (And_Mask and Or_Mask) */
quantity = 2;
/* The length of Mask Write Register (code 22) function request is 8 */
/* Modbus Application Protocol Specification V1.1b3 6.16 */
if (ModbusCheckHeaderLength(modbus, tx->length, 8))
goto end;
}
if (type & MODBUS_TYP_COILS) {
/* Output value (data block) unit is count */
tx->data = (uint16_t *) SCCalloc(1, count * sizeof(uint16_t));
if (unlikely(tx->data == NULL))
SCReturnInt(-1);
if (type & MODBUS_TYP_SINGLE) {
/* Outputs value (2 bytes) */
if (ModbusExtractUint16(modbus, &word, input, input_len, offset))
goto end;
tx->data[i] = word;
if ((word != 0x00) && (word != 0xFF00))
goto error;
} else {
for (i = 0; i < count; i++) {
/* Outputs value (1 byte) */
if (ModbusExtractUint8(modbus, &byte, input, input_len, offset))
goto end;
tx->data[i] = (uint16_t) byte;
}
}
} else {
/* Registers value (data block) unit is quantity */
tx->data = (uint16_t *) SCCalloc(1, quantity * sizeof(uint16_t));
if (unlikely(tx->data == NULL))
SCReturnInt(-1);
for (i = 0; i < quantity; i++) {
/* Outputs/Registers value (2 bytes) */
if (ModbusExtractUint16(modbus, &word, input, input_len, offset))
goto end;
tx->data[i] = word;
}
}
goto end;
error:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_VALUE);
end:
SCReturnInt(0);
}
/** \internal
* \brief Parse Write data Response and verify protocol compliance
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*/
static void ModbusParseWriteResponse(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint16_t address = 0, quantity = 0, word = 0;
uint8_t type = tx->type;
/* Starting Address (2 bytes) */
if (ModbusExtractUint16(modbus, &address, input, input_len, offset))
goto end;
if (address != tx->write.address)
goto error;
if (type & MODBUS_TYP_SINGLE) {
/* Check if Outputs/Registers value has been stored */
if (tx->data != NULL)
{
/* Outputs/Registers value (2 bytes) */
if (ModbusExtractUint16(modbus, &word, input, input_len, offset))
goto end;
/* Check with Outputs/Registers from request */
if (word != tx->data[0])
goto error;
}
} else if (type & MODBUS_TYP_MULTIPLE) {
/* Quantity (2 bytes) */
if (ModbusExtractUint16(modbus, &quantity, input, input_len, offset))
goto end;
/* Check Quantity range */
if (type & MODBUS_TYP_BIT_ACCESS_MASK) {
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_WORD_ACCESS))
goto error;
} else {
if ((quantity == MODBUS_MIN_QUANTITY) ||
(quantity > MODBUS_MAX_QUANTITY_IN_BIT_ACCESS))
goto error;
}
/* Check Quantity value according to the request */
if (quantity != tx->write.quantity)
goto error;
} else {
/* Check if And_Mask and Or_Mask values have been stored */
if (tx->data != NULL)
{
/* And_Mask value (2 bytes) */
if (ModbusExtractUint16(modbus, &word, input, input_len, offset))
goto end;
/* Check And_Mask value according to the request */
if (word != tx->data[0])
goto error;
/* And_Or_Mask value (2 bytes) */
if (ModbusExtractUint16(modbus, &word, input, input_len, offset))
goto end;
/* Check Or_Mask value according to the request */
if (word != tx->data[1])
goto error;
}
/* The length of Mask Write Register (code 22) function response is 8 */
/* Modbus Application Protocol Specification V1.1b3 6.16 */
ModbusCheckHeaderLength(modbus, tx->length, 8);
goto end;
}
/* Except from Mask Write Register (code 22) */
/* The length of all Write Data function responses is 6 */
/* Modbus Application Protocol Specification V1.1b3 6.5, 6.6, 6.11, 6.12 and 6.17 */
ModbusCheckHeaderLength(modbus, tx->length, 6);
goto end;
error:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_VALUE_MISMATCH);
end:
SCReturn;
}
/** \internal
* \brief Parse Diagnostic Request, complete Transaction
* structure (Category) and verify protocol compliance.
*
* \param tx Pointer to Modbus Transaction structure
* \param modbus Pointer to Modbus state structure
* \param input Pointer the received input data
* \param input_len Length of the received input data
* \param offset Offset of the received input data pointer
*
* \retval Reserved category function returns 1 otherwise returns 0.
*/
static int ModbusParseDiagnosticRequest(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len,
uint16_t *offset)
{
SCEnter();
uint16_t data = 0;
/* Sub-function (2 bytes) */
if (ModbusExtractUint16(modbus, &(tx->subFunction), input, input_len, offset))
goto end;
/* Data (2 bytes) */
if (ModbusExtractUint16(modbus, &data, input, input_len, offset))
goto end;
if (tx->subFunction != MODBUS_SUBFUNC_QUERY_DATA) {
switch (tx->subFunction) {
case MODBUS_SUBFUNC_RESTART_COM:
if ((data != 0x00) && (data != 0xFF00))
goto error;
break;
case MODBUS_SUBFUNC_CHANGE_DELIMITER:
if ((data & 0xFF) != 0x00)
goto error;
break;
case MODBUS_SUBFUNC_LISTEN_MODE:
/* No answer is expected then mark tx as completed. */
tx->replied = 1;
/* Fallthrough */
case MODBUS_SUBFUNC_DIAG_REGS:
case MODBUS_SUBFUNC_CLEAR_REGS:
case MODBUS_SUBFUNC_BUS_MSG_COUNT:
case MODBUS_SUBFUNC_COM_ERR_COUNT:
case MODBUS_SUBFUNC_EXCEPT_ERR_COUNT:
case MODBUS_SUBFUNC_SERVER_MSG_COUNT:
case MODBUS_SUBFUNC_SERVER_NO_RSP_COUNT:
case MODBUS_SUBFUNC_SERVER_NAK_COUNT:
case MODBUS_SUBFUNC_SERVER_BUSY_COUNT:
case MODBUS_SUBFUNC_SERVER_CHAR_COUNT:
case MODBUS_SUBFUNC_CLEAR_COUNT:
if (data != 0x00)
goto error;
break;
default:
/* Set function code category */
tx->category = MODBUS_CAT_RESERVED;
SCReturnInt(1);
}
/* The length of all Diagnostic Requests is 6 */
/* Modbus Application Protocol Specification V1.1b3 6.8 */
ModbusCheckHeaderLength(modbus, tx->length, 6);
}
goto end;
error:
ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_VALUE);
end:
SCReturnInt(0);
}
/* Modbus Function Code Categories structure. */
typedef struct ModbusFunctionCodeRange_ {
uint8_t function;
uint8_t category;
} ModbusFunctionCodeRange;
/* Modbus Function Code Categories table. */
static ModbusFunctionCodeRange modbusFunctionCodeRanges[] = {
{ 0, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 9, MODBUS_CAT_RESERVED },
{ 15, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 41, MODBUS_CAT_RESERVED },
{ 43, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 65, MODBUS_CAT_USER_DEFINED },
{ 73, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 90, MODBUS_CAT_RESERVED },
{ 92, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 100, MODBUS_CAT_USER_DEFINED },
{ 111, MODBUS_CAT_PUBLIC_UNASSIGNED},
{ 125, MODBUS_CAT_RESERVED },
{ 128, MODBUS_CAT_NONE }
};
/** \internal
* \brief Parse the Modbus Protocol Data Unit (PDU) Request
*
* \param tx Pointer to Modbus Transaction structure
* \param ModbusPdu Pointer the Modbus PDU state in which the value to be stored
* \param input Pointer the received input data
* \param input_len Length of the received input data
*/
static void ModbusParseRequestPDU(ModbusTransaction *tx,
ModbusState *modbus,
uint8_t *input,
uint32_t input_len)
{
SCEnter();
uint16_t offset = (uint16_t) sizeof(ModbusHeader);
uint8_t count = 0;
int i = 0;
/* Standard function codes used on MODBUS application layer protocol (1 byte) */
if (ModbusExtractUint8(modbus, &(tx->function), input, input_len, &offset))
goto end;