aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/suricata/src/app-layer-modbus.c
blob: fa965135d394c3218529a75e5d9aff8260155805 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
/*
 * 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 <diallo@et.esiea.fr>
 *
 * 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 "app-layer-protos.h"
#include "app-layer-parser.h"
#include "app-layer-modbus.h"

#include "app-layer-detect-proto.h"

#include "conf.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

static uint32_t request_flood = MODBUS_CONFIG_DEFAULT_REQUEST_FLOOD;

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;
}

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;

    /* 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;

    /* 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;
    uint8_t     byte, 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, quantity, word;
    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) {
        /* 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 {
        /* 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))

        /* 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;

    /* 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;

    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;

    /* Set default function code category */
    tx->category = MODBUS_CAT_NONE;

    /* Set default function primary table */
    tx->type = MODBUS_TYP_NONE;

    switch (tx->function) {
        case MODBUS_FUNC_NONE:
            ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_FUNCTION_CODE);
            break;

        case MODBUS_FUNC_READCOILS:
            /* Set function type */
            tx->type = (MODBUS_TYP_COILS | MODBUS_TYP_READ);
            break;

        case MODBUS_FUNC_READDISCINPUTS:
            /* Set function type */
            tx->type = (MODBUS_TYP_DISCRETES | MODBUS_TYP_READ);
            break;

        case MODBUS_FUNC_READHOLDREGS:
            /* Set function type */
            tx->type = (MODBUS_TYP_HOLDING | MODBUS_TYP_READ);
            break;

        case MODBUS_FUNC_READINPUTREGS:
            /* Set function type */
            tx->type = (MODBUS_TYP_INPUT | MODBUS_TYP_READ);
            break;

        case MODBUS_FUNC_WRITESINGLECOIL:
            /* Set function type */
            tx->type = (MODBUS_TYP_COILS | MODBUS_TYP_WRITE_SINGLE);
            break;

        case MODBUS_FUNC_WRITESINGLEREG:
            /* Set function type */
            tx->type = (MODBUS_TYP_HOLDING | MODBUS_TYP_WRITE_SINGLE);
            break;

        case MODBUS_FUNC_WRITEMULTCOILS:
            /* Set function type */
            tx->type = (MODBUS_TYP_COILS | MODBUS_TYP_WRITE_MULTIPLE);
            break;

        case MODBUS_FUNC_WRITEMULTREGS:
            /* Set function type */
            tx->type = (MODBUS_TYP_HOLDING | MODBUS_TYP_WRITE_MULTIPLE);
            break;

        case MODBUS_FUNC_MASKWRITEREG:
            /* Set function type */
            tx->type = (MODBUS_TYP_HOLDING | MODBUS_TYP_WRITE);
            break;

        case MODBUS_FUNC_READWRITEMULTREGS:
            /* Set function type */
            tx->type = (MODBUS_TYP_HOLDING | MODBUS_TYP_READ_WRITE_MULTIPLE);
            break;

        case MODBUS_FUNC_READFILERECORD:
        case MODBUS_FUNC_WRITEFILERECORD:
            /* Count/length (1 bytes) */
            if (ModbusExtractUint8(modbus, &count, input, input_len, &offset))
                goto end;

            /* Modbus Application Protocol Specification V1.1b3 6.14 and 6.15   */
            ModbusCheckHeaderLength(modbus, tx->length, 2 + count);
            break;

        case MODBUS_FUNC_DIAGNOSTIC:
            if(ModbusParseDiagnosticRequest(tx, modbus, input, input_len, &offset))
                goto end;
            break;

        case MODBUS_FUNC_READEXCSTATUS:
        case MODBUS_FUNC_GETCOMEVTCOUNTER:
        case MODBUS_FUNC_GETCOMEVTLOG:
        case MODBUS_FUNC_REPORTSERVERID:
            /* Modbus Application Protocol Specification V1.1b3 6.7, 6.9, 6.10 and 6.13 */
            ModbusCheckHeaderLength(modbus, tx->length, 2);
            break;

        case MODBUS_FUNC_READFIFOQUEUE:
            /* Modbus Application Protocol Specification V1.1b3 6.18 */
            ModbusCheckHeaderLength(modbus, tx->length, 4);
            break;

        case MODBUS_FUNC_ENCAPINTTRANS:
            /* MEI type (1 byte) */
           if (ModbusExtractUint8(modbus, &(tx->mei), input, input_len, &offset))
               goto end;

            if (tx->mei == MODBUS_MEI_ENCAPINTTRANS_READ) {
                /* Modbus Application Protocol Specification V1.1b3 6.21 */
                ModbusCheckHeaderLength(modbus, tx->length, 5);
            } else if (tx->mei != MODBUS_MEI_ENCAPINTTRANS_CAN) {
                /* Set function code category */
                tx->category = MODBUS_CAT_RESERVED;
                goto end;
            }
            break;

        default:
            /* Check if request is error. */
            if (tx->function & MODBUS_FUNC_ERRORMASK) {
                ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_INVALID_FUNCTION_CODE);
                goto end;
            }

            /* Get and store function code category */
            for (i = 0; modbusFunctionCodeRanges[i].category != MODBUS_CAT_NONE; i++) {
                if (tx->function <= modbusFunctionCodeRanges[i].function)
                    break;
                tx->category = modbusFunctionCodeRanges[i].category;
            }
            goto end;
    }

    /* Set function code category */
    tx->category = MODBUS_CAT_PUBLIC_ASSIGNED;

    if (tx->type & MODBUS_TYP_READ)
        ModbusParseReadRequest(tx, modbus, input, input_len, &offset);

    if (tx->type & MODBUS_TYP_WRITE)
        ModbusParseWriteRequest(tx, modbus, input, input_len, &offset);

end:
    SCReturn;
}

/** \internal
 *  \brief Parse the Modbus Protocol Data Unit (PDU) Response
 *
 *  \param  tx          Pointer to Modbus Transaction structure
 *  \param  modbus      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
 *  \param  offset      Offset of the received input data pointer
 */
static void ModbusParseResponsePDU(ModbusTransaction    *tx,
                                   ModbusState          *modbus,
                                   uint8_t              *input,
                                   uint32_t             input_len)
{
    SCEnter();
    uint16_t    offset = (uint16_t) sizeof(ModbusHeader);
    uint8_t     count, error = FALSE, function, mei;

    /* Standard function codes used on MODBUS application layer protocol (1 byte) */
    if (ModbusExtractUint8(modbus, &function, input, input_len, &offset))
        goto end;

    /* Check if response is error */
    if(function & MODBUS_FUNC_ERRORMASK) {
        function &= MODBUS_FUNC_MASK;
        error = TRUE;
    }

    if (tx->category == MODBUS_CAT_PUBLIC_ASSIGNED) {
        /* Check if response is error. */
        if (error) {
            ModbusExceptionResponse(tx, modbus, input, input_len, &offset);
        } else {
            switch(function) {
                case MODBUS_FUNC_READEXCSTATUS:
                    /* Modbus Application Protocol Specification V1.1b3 6.7 */
                    ModbusCheckHeaderLength(modbus, tx->length, 3);
                    goto end;

                case MODBUS_FUNC_GETCOMEVTCOUNTER:
                    /* Modbus Application Protocol Specification V1.1b3 6.9 */
                    ModbusCheckHeaderLength(modbus, tx->length, 6);
                    goto end;

                case MODBUS_FUNC_READFILERECORD:
                case MODBUS_FUNC_WRITEFILERECORD:
                    /* Count/length (1 bytes) */
                    if (ModbusExtractUint8(modbus, &count, input, input_len, &offset))
                        goto end;

                    /* Modbus Application Protocol Specification V1.1b3 6.14 and 6.15 */
                    ModbusCheckHeaderLength(modbus, tx->length, 2 + count);
                    goto end;

                case MODBUS_FUNC_ENCAPINTTRANS:
                    /* MEI type (1 byte) */
                    if (ModbusExtractUint8(modbus, &mei, input, input_len, &offset))
                        goto end;

                    if (mei != tx->mei)
                        ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_VALUE_MISMATCH);
                    goto end;
            }

            if (tx->type & MODBUS_TYP_READ)
                ModbusParseReadResponse(tx, modbus, input, input_len, &offset);
            /* Read/Write response contents none write response part */
            else if (tx->type & MODBUS_TYP_WRITE)
                ModbusParseWriteResponse(tx, modbus, input, input_len, &offset);
        }
    }

end:
    SCReturn;
}

/** \internal
 *  \brief Parse the Modbus Application Protocol (MBAP) header
 *
 *  \param  header  Pointer the Modbus header state in which the value to be stored
 *  \param  input   Pointer the received input data
 */
static int ModbusParseHeader(ModbusState   *modbus,
                             ModbusHeader  *header,
                             uint8_t       *input,
                             uint32_t      input_len)
{
    SCEnter();
    uint16_t offset = 0;

    /* Transaction Identifier (2 bytes) */
    if (ModbusExtractUint16(modbus, &(header->transactionId), input, input_len, &offset)    ||
    /* Protocol Identifier (2 bytes) */
        ModbusExtractUint16(modbus, &(header->protocolId), input, input_len, &offset)       ||
    /* Length (2 bytes) */
        ModbusExtractUint16(modbus, &(header->length), input, input_len, &offset)           ||
    /* Unit Identifier (1 byte) */
        ModbusExtractUint8(modbus, &(header->unitId), input, input_len, &offset))
        SCReturnInt(-1);

    SCReturnInt(0);
}

/** \internal
 *
 * \brief This function is called to retrieve a Modbus Request
 *
 * \param state     Modbus state structure for the parser
 * \param input     Input line of the command
 * \param input_len Length of the request
 *
 * \retval 1 when the command is parsed, 0 otherwise
 */
static int ModbusParseRequest(Flow                  *f,
                              void                  *state,
                              AppLayerParserState   *pstate,
                              uint8_t               *input,
                              uint32_t              input_len,
                              void                  *local_data)
{
    SCEnter();
    ModbusState         *modbus = (ModbusState *) state;
    ModbusTransaction   *tx;
    ModbusHeader        header;

    if (input == NULL && AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF)) {
        SCReturnInt(1);
    } else if (input == NULL || input_len == 0) {
        SCReturnInt(-1);
    }

    while (input_len > 0) {
        uint32_t    adu_len = input_len;
        uint8_t     *adu = input;

        /* Extract MODBUS Header */
        if (ModbusParseHeader(modbus, &header, adu, adu_len))
            SCReturnInt(0);

        /* Update ADU length with length in Modbus header. */
        adu_len = (uint32_t) sizeof(ModbusHeader) + (uint32_t) header.length - 1;
        if (adu_len > input_len)
            SCReturnInt(0);

        /* Allocate a Transaction Context and add it to Transaction list */
        tx = ModbusTxAlloc(modbus);
        if (tx == NULL)
            SCReturnInt(0);

        /* Check MODBUS Header */
        ModbusCheckHeader(modbus, &header);

        /* Store Transaction ID & PDU length */
        tx->transactionId   = header.transactionId;
        tx->length          = header.length;

        /* Extract MODBUS PDU and fill Transaction Context */
        ModbusParseRequestPDU(tx, modbus, adu, adu_len);

        /* Update input line and remaining input length of the command */
        input       += adu_len;
        input_len   -= adu_len;
    }

    SCReturnInt(1);
}

/** \internal
 * \brief This function is called to retrieve a Modbus response
 *
 * \param state     Pointer to Modbus state structure for the parser
 * \param input     Input line of the command
 * \param input_len Length of the request
 *
 * \retval 1 when the command is parsed, 0 otherwise
 */
static int ModbusParseResponse(Flow                 *f,
                               void                 *state,
                               AppLayerParserState  *pstate,
                               uint8_t              *input,
                               uint32_t             input_len,
                               void                 *local_data)
{
    SCEnter();
    ModbusHeader        header;
    ModbusState         *modbus = (ModbusState *) state;
    ModbusTransaction   *tx;

    if (input == NULL && AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF)) {
        SCReturnInt(1);
    } else if (input == NULL || input_len == 0) {
        SCReturnInt(-1);
    }

    while (input_len > 0) {
        uint32_t    adu_len = input_len;
        uint8_t     *adu = input;

        /* Extract MODBUS Header */
        if (ModbusParseHeader(modbus, &header, adu, adu_len))
            SCReturnInt(0);

        /* Update ADU length with length in Modbus header. */
        adu_len = (uint32_t) sizeof(ModbusHeader) + (uint32_t) header.length - 1;
        if (adu_len > input_len)
            SCReturnInt(0);

        /* Find the transaction context thanks to transaction ID (and function code) */
        tx = ModbusTxFindByTransaction(modbus, header.transactionId);
        if (tx == NULL) {
            /* Allocate a Transaction Context if not previous request */
            /* and add it to Transaction list */
            tx = ModbusTxAlloc(modbus);
            if (tx == NULL)
                SCReturnInt(0);

            SCLogDebug("MODBUS_DECODER_EVENT_UNSOLICITED_RESPONSE");
            ModbusSetEvent(modbus, MODBUS_DECODER_EVENT_UNSOLICITED_RESPONSE);
        } else {
            /* Store PDU length */
            tx->length = header.length;

            /* Extract MODBUS PDU and fill Transaction Context */
            ModbusParseResponsePDU(tx, modbus, adu, adu_len);
        }

        /* Check and store MODBUS Header */
        ModbusCheckHeader(modbus, &header);

        /* Mark as completed */
        tx->replied = 1;

        /* Update input line and remaining input length of the command */
        input       += adu_len;
        input_len   -= adu_len;
    }

    SCReturnInt(1);
}

/** \internal
 *     \brief Function to allocate the Modbus state memory
 */
static void *ModbusStateAlloc(void)
{
    ModbusState *modbus;

    modbus = (ModbusState *) SCCalloc(1, sizeof(ModbusState));
    if (unlikely(modbus == NULL))
        return NULL;

    TAILQ_INIT(&modbus->tx_list);

    return (void *) modbus;
}

/** \internal
 *  \brief Function to free the Modbus state memory
 */
static void ModbusStateFree(void *state)
{
    SCEnter();
    ModbusState         *modbus = (ModbusState *) state;
    ModbusTransaction   *tx = NULL, *ttx;

    if (state) {
        TAILQ_FOREACH_SAFE(tx, &modbus->tx_list, next, ttx) {
            ModbusTxFree(tx);
        }

        SCFree(state);
    }
    SCReturn;
}

static uint16_t ModbusProbingParser(uint8_t     *input,
                                    uint32_t    input_len,
                                    uint32_t    *offset)
{
    ModbusHeader *header = (ModbusHeader *) input;

    /* Modbus header is 7 bytes long */
    if (input_len < sizeof(ModbusHeader))
        return ALPROTO_UNKNOWN;

    /* MODBUS protocol is identified by the value 0. */
    if (header->protocolId != 0)
        return ALPROTO_FAILED;

    return ALPROTO_MODBUS;
}

DetectEngineState *ModbusGetTxDetectState(void *vtx)
{
    ModbusTransaction *tx = (ModbusTransaction *)vtx;
    return tx->de_state;
}

int ModbusSetTxDetectState(void *state, void *vtx, DetectEngineState *s)
{
    ModbusTransaction *tx = (ModbusTransaction *)vtx;
    tx->de_state = s;
    return 0;
}

/**
 * \brief Function to register the Modbus protocol parsers and other functions
 */
void RegisterModbusParsers(void)
{
    SCEnter();
    char *proto_name = "modbus";

    /* Modbus application protocol V1.1b3 */
    if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) {
        AppLayerProtoDetectRegisterProtocol(ALPROTO_MODBUS, proto_name);

        if (RunmodeIsUnittests()) {
            AppLayerProtoDetectPPRegister(IPPROTO_TCP,
                                          "502",
                                          ALPROTO_MODBUS,
                                          0, sizeof(ModbusHeader),
                                          STREAM_TOSERVER,
                                          ModbusProbingParser);
        } else {
            /* if we have no config, we enable the default port 502 */
            if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP,
                                                proto_name, ALPROTO_MODBUS,
                                                0, sizeof(ModbusHeader),
                                                ModbusProbingParser)) {
                SCLogWarning(SC_ERR_MODBUS_CONFIG, "no Modbus TCP config found, "
                                                "enabling Modbus detection on "
                                                "port 502.");

                AppLayerProtoDetectPPRegister(IPPROTO_TCP,
                                              "502",
                                              ALPROTO_MODBUS,
                                              0, sizeof(ModbusHeader),
                                              STREAM_TOSERVER,
                                              ModbusProbingParser);
            }
        }

        ConfNode *p = ConfGetNode("app-layer.protocols.modbus.request-flood");
        if (p != NULL) {
            uint32_t value;
            if (ParseSizeStringU32(p->val, &value) < 0) {
                SCLogError(SC_ERR_MODBUS_CONFIG, "invalid value for request-flood %s", p->val);
            } else {
                request_flood = value;
            }
        }
        SCLogInfo("Modbus request flood protection level: %u", request_flood);
    } else {
        SCLogInfo("Protocol detection and parser disabled for %s protocol.", proto_name);
        return;
    }

    if (AppLayerParserConfParserEnabled("tcp", proto_name)) {
        AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_MODBUS, STREAM_TOSERVER, ModbusParseRequest);
        AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_MODBUS, STREAM_TOCLIENT, ModbusParseResponse);
        AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_MODBUS, ModbusStateAlloc, ModbusStateFree);

        AppLayerParserRegisterGetEventsFunc(IPPROTO_TCP, ALPROTO_MODBUS, ModbusGetEvents);
        AppLayerParserRegisterHasEventsFunc(IPPROTO_TCP, ALPROTO_MODBUS, ModbusHasEvents);
        AppLayerParserRegisterDetectStateFuncs(IPPROTO_TCP, ALPROTO_MODBUS, NULL,
                                               ModbusGetTxDetectState, ModbusSetTxDetectState);

        AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_MODBUS, ModbusGetTx);
        AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_MODBUS, ModbusGetTxCnt);
        AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_MODBUS, ModbusStateTxFree);

        AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_MODBUS, ModbusGetAlstateProgress);
        AppLayerParserRegisterGetStateProgressCompletionStatus(IPPROTO_TCP, ALPROTO_MODBUS,
                                                                ModbusGetAlstateProgressCompletionStatus);

        AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_MODBUS, ModbusStateGetEventInfo);

        AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, ALPROTO_MODBUS, STREAM_TOSERVER);
    } else {
        SCLogInfo("Parsed disabled for %s protocol. Protocol detection" "still on.", proto_name);
    }
#ifdef UNITTESTS
    AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_MODBUS, ModbusParserRegisterTests);
#endif

    SCReturn;
}

/* UNITTESTS */
#ifdef UNITTESTS
#include "detect.h"
#include "detect-engine.h"
#include "detect-parse.h"

#include "flow-util.h"

#include "util-unittest.h"
#include "util-unittest-helper.h"

#include "stream-tcp.h"
#include "stream-tcp-private.h"

/* Modbus Application Protocol Specification V1.1b3 6.1: Read Coils */
/* Example of a request to read discrete outputs 20-38 */
static uint8_t readCoilsReq[] = {/* Transaction ID */    0x00, 0x00,
                                 /* Protocol ID */       0x00, 0x00,
                                 /* Length */            0x00, 0x06,
                                 /* Unit ID */           0x00,
                                 /* Function code */     0x01,
                                 /* Starting Address */  0x78, 0x90,
                                 /* Quantity of coils */ 0x00, 0x13 };

static uint8_t readCoilsRsp[] = {/* Transaction ID */    0x00, 0x00,
                                 /* Protocol ID */       0x00, 0x00,
                                 /* Length */            0x00, 0x06,
                                 /* Unit ID */           0x00,
                                 /* Function code */     0x01,
                                 /* Byte count */        0x03,
                                 /* Coil Status */       0xCD, 0x6B, 0x05 };

static uint8_t readCoilsErrorRsp[] = {/* Transaction ID */    0x00, 0x00,
                                      /* Protocol ID */       0x00, 0x00,
                                      /* Length */            0x00, 0x03,
                                      /* Unit ID */           0x00,
                                      /* Function code */     0x81,
                                      /* Exception code */    0x05};

/* Modbus Application Protocol Specification V1.1b3 6.12: Write Multiple registers */
/* Example of a request to write two registers starting at 2 to 00 0A and 01 02 hex */
static uint8_t writeMultipleRegistersReq[] = {/* Transaction ID */          0x00, 0x0A,
                                              /* Protocol ID */             0x00, 0x00,
                                              /* Length */                  0x00, 0x0B,
                                              /* Unit ID */                 0x00,
                                              /* Function code */           0x10,
                                              /* Starting Address */        0x00, 0x01,
                                              /* Quantity of Registers */   0x00, 0x02,
                                              /* Byte count */              0x04,
                                              /* Registers Value */         0x00, 0x0A,
                                                                            0x01, 0x02};

static uint8_t writeMultipleRegistersRsp[] = {/* Transaction ID */          0x00, 0x0A,
                                              /* Protocol ID */             0x00, 0x00,
                                              /* Length */                  0x00, 0x06,
                                              /* Unit ID */                 0x00,
                                              /* Function code */           0x10,
                                              /* Starting Address */        0x00, 0x01,
                                              /* Quantity of Registers */   0x00, 0x02};

/* Modbus Application Protocol Specification V1.1b3 6.17: Read/Write Multiple registers */
/* Example of a request to read six registers starting at register 4, */
/* and to write three registers starting at register 15 */
static uint8_t readWriteMultipleRegistersReq[] = {/* Transaction ID */          0x12, 0x34,
                                                  /* Protocol ID */             0x00, 0x00,
                                                  /* Length */                  0x00, 0x11,
                                                  /* Unit ID */                 0x00,
                                                  /* Function code */           0x17,
                                                  /* Read Starting Address */   0x00, 0x03,
                                                  /* Quantity to Read */        0x00, 0x06,
                                                  /* Write Starting Address */  0x00, 0x0E,
                                                  /* Quantity to Write */       0x00, 0x03,
                                                  /* Write Byte count */        0x06,
                                                  /* Write Registers Value */   0x12, 0x34,
                                                                                0x56, 0x78,
                                                                                0x9A, 0xBC};

/* Mismatch value in Byte count 0x0B instead of 0x0C */
static uint8_t readWriteMultipleRegistersRsp[] = {/* Transaction ID */          0x12, 0x34,
                                                  /* Protocol ID */             0x00, 0x00,
                                                  /* Length */                  0x00, 0x0E,
                                                  /* Unit ID */                 0x00,
                                                  /* Function code */           0x17,
                                                  /* Byte count */              0x0B,
                                                  /* Read Registers Value */    0x00, 0xFE,
                                                                                0x0A, 0xCD,
                                                                                0x00, 0x01,
                                                                                0x00, 0x03,
                                                                                0x00, 0x0D,
                                                                                0x00};

/* Modbus Application Protocol Specification V1.1b3 6.8.1: 04 Force Listen Only Mode */
/* Example of a request to to remote device to its Listen Only MOde for Modbus Communications. */
static uint8_t forceListenOnlyMode[] = {/* Transaction ID */     0x0A, 0x00,
                                        /* Protocol ID */        0x00, 0x00,
                                        /* Length */             0x00, 0x06,
                                        /* Unit ID */            0x00,
                                        /* Function code */      0x08,
                                        /* Sub-function code */  0x00, 0x04,
                                        /* Data */               0x00, 0x00};

static uint8_t invalidProtocolIdReq[] = {/* Transaction ID */    0x00, 0x00,
                                         /* Protocol ID */       0x00, 0x01,
                                         /* Length */            0x00, 0x06,
                                         /* Unit ID */           0x00,
                                         /* Function code */     0x01,
                                         /* Starting Address */  0x78, 0x90,
                                         /* Quantity of coils */ 0x00, 0x13 };

static uint8_t invalidLengthWriteMultipleRegistersReq[] = {
                                              /* Transaction ID */          0x00, 0x0A,
                                              /* Protocol ID */             0x00, 0x00,
                                              /* Length */                  0x00, 0x09,
                                              /* Unit ID */                 0x00,
                                              /* Function code */           0x10,
                                              /* Starting Address */        0x00, 0x01,
                                              /* Quantity of Registers */   0x00, 0x02,
                                              /* Byte count */              0x04,
                                              /* Registers Value */         0x00, 0x0A,
                                                                            0x01, 0x02};

static uint8_t exceededLengthWriteMultipleRegistersReq[] = {
                                              /* Transaction ID */          0x00, 0x0A,
                                              /* Protocol ID */             0x00, 0x00,
                                              /* Length */                  0xff, 0xfa,
                                              /* Unit ID */                 0x00,
                                              /* Function code */           0x10,
                                              /* Starting Address */        0x00, 0x01,
                                              /* Quantity of Registers */   0x7f, 0xf9,
                                              /* Byte count */              0xff};

static uint8_t invalidLengthPDUWriteMultipleRegistersReq[] = {
                                              /* Transaction ID */          0x00, 0x0A,
                                              /* Protocol ID */             0x00, 0x00,
                                              /* Length */                  0x00, 0x02,
                                              /* Unit ID */                 0x00,
                                              /* Function code */           0x10};

/** \test Send Modbus Read Coils request/response. */
static int ModbusParserTest01(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    Flow f;
    TcpSession ssn;

    int result = 0;

    memset(&f, 0, sizeof(f));
    memset(&ssn, 0, sizeof(ssn));

    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;

    StreamTcpInitConfig(TRUE);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    readCoilsReq, sizeof(readCoilsReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 1) || (tx->read.address != 0x7890) || (tx->read.quantity != 19)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 1, tx->function);
        printf("expected address %" PRIu8 ", got %" PRIu8 ": ", 0x7890, tx->read.address);
        printf("expected quantity %" PRIu8 ", got %" PRIu8 ": ", 19, tx->read.quantity);
        goto end;
    }

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                    readCoilsRsp, sizeof(readCoilsRsp));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    if (modbus_state->transaction_max !=1) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 1, modbus_state->transaction_max);
        goto end;
    }

    result = 1;
end:
    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    return result;
}

/** \test Send Modbus Write Multiple registers request/response. */
static int ModbusParserTest02(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    Flow f;
    TcpSession ssn;

    int result = 0;

    memset(&f, 0, sizeof(f));
    memset(&ssn, 0, sizeof(ssn));

    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;

    StreamTcpInitConfig(TRUE);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    writeMultipleRegistersReq, sizeof(writeMultipleRegistersReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 16) || (tx->write.address != 0x01) || (tx->write.quantity != 2) ||
        (tx->write.count != 4) || (tx->data[0] != 0x000A) || (tx->data[1] != 0x0102)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 16, tx->function);
        printf("expected write address %" PRIu8 ", got %" PRIu8 ": ", 0x01, tx->write.address);
        printf("expected write quantity %" PRIu8 ", got %" PRIu8 ": ", 2, tx->write.quantity);
        printf("expected write count %" PRIu8 ", got %" PRIu8 ": ", 4, tx->write.count);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x000A, tx->data[0]);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x0102, tx->data[1]);
        goto end;
    }

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                            writeMultipleRegistersRsp, sizeof(writeMultipleRegistersRsp));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    if (modbus_state->transaction_max !=1) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 1, modbus_state->transaction_max);
        goto end;
    }

    result = 1;
end:
    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    return result;
}

/** \test Send Modbus Read/Write Multiple registers request/response with mismatch value. */
static int ModbusParserTest03(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus Data mismatch\"; "
                                      "app-layer-event: "
                                      "modbus.value_mismatch; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                readWriteMultipleRegistersReq, sizeof(readWriteMultipleRegistersReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 23) || (tx->read.address != 0x03) || (tx->read.quantity != 6) ||
        (tx->write.address != 0x0E) || (tx->write.quantity != 3) || (tx->write.count != 6) ||
        (tx->data[0] != 0x1234) || (tx->data[1] != 0x5678) || (tx->data[2] != 0x9ABC)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 23, tx->function);
        printf("expected read address %" PRIu8 ", got %" PRIu8 ": ", 0x03, tx->read.address);
        printf("expected read quantity %" PRIu8 ", got %" PRIu8 ": ", 6, tx->read.quantity);
        printf("expected write address %" PRIu8 ", got %" PRIu8 ": ", 0x0E, tx->write.address);
        printf("expected write quantity %" PRIu8 ", got %" PRIu8 ": ", 3, tx->write.quantity);
        printf("expected write count %" PRIu8 ", got %" PRIu8 ": ", 6, tx->write.count);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x1234, tx->data[0]);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x5678, tx->data[1]);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x9ABC, tx->data[2]);
        goto end;
    }

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                readWriteMultipleRegistersRsp, sizeof(readWriteMultipleRegistersRsp));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    if (modbus_state->transaction_max !=1) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 1, modbus_state->transaction_max);
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Send Modbus Force Listen Only Mode request. */
static int ModbusParserTest04(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    Flow f;
    TcpSession ssn;

    int result = 0;

    memset(&f, 0, sizeof(f));
    memset(&ssn, 0, sizeof(ssn));

    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;

    StreamTcpInitConfig(TRUE);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                        forceListenOnlyMode, sizeof(forceListenOnlyMode));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 8) || (tx->subFunction != 4)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 8, tx->function);
        printf("expected sub-function %" PRIu8 ", got %" PRIu8 ": ", 0x04, tx->subFunction);
        goto end;
    }

    result = 1;
end:
    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    return result;
}

/** \test Send Modbus invalid Protocol version in request. */
static int ModbusParserTest05(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus invalid Protocol version\"; "
                                      "app-layer-event: "
                                      "modbus.invalid_protocol_id; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                invalidProtocolIdReq, sizeof(invalidProtocolIdReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Send Modbus unsolicited response. */
static int ModbusParserTest06(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus unsolicited response\"; "
                                      "app-layer-event: "
                                      "modbus.unsolicited_response; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                    readCoilsRsp, sizeof(readCoilsRsp));
    if (r != 0) {
        printf("toclient chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Send Modbus invalid Length request. */
static int ModbusParserTest07(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus invalid Length\"; "
                                      "app-layer-event: "
                                      "modbus.invalid_length; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    invalidLengthWriteMultipleRegistersReq,
                                    sizeof(invalidLengthWriteMultipleRegistersReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Send Modbus Read Coils request and error response with Exception code invalid. */
static int ModbusParserTest08(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus Exception code invalid\"; "
                                      "app-layer-event: "
                                      "modbus.invalid_exception_code; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    readCoilsReq, sizeof(readCoilsReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 1) || (tx->read.address != 0x7890) || (tx->read.quantity != 19)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 1, tx->function);
        printf("expected address %" PRIu8 ", got %" PRIu8 ": ", 0x7890, tx->read.address);
        printf("expected quantity %" PRIu8 ", got %" PRIu8 ": ", 19, tx->read.quantity);
        goto end;
    }

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                readCoilsErrorRsp, sizeof(readCoilsErrorRsp));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    if (modbus_state->transaction_max !=1) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 1, modbus_state->transaction_max);
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Modbus fragmentation - 1 ADU over 2 TCP packets. */
static int ModbusParserTest09(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    Flow f;
    TcpSession ssn;

    uint32_t    input_len = sizeof(readCoilsReq), part2_len = 3;
    uint8_t     *input = readCoilsReq;

    int result = 0;

    memset(&f, 0, sizeof(f));
    memset(&ssn, 0, sizeof(ssn));

    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;

    StreamTcpInitConfig(TRUE);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    input, input_len - part2_len);
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }

    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                        input, input_len);
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 0);

    if ((tx->function != 1) || (tx->read.address != 0x7890) || (tx->read.quantity != 19)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 1, tx->function);
        printf("expected address %" PRIu8 ", got %" PRIu8 ": ", 0x7890, tx->read.address);
        printf("expected quantity %" PRIu8 ", got %" PRIu8 ": ", 19, tx->read.quantity);
        goto end;
    }

    input_len = sizeof(readCoilsRsp);
    part2_len = 10;
    input = readCoilsRsp;

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                input, input_len - part2_len);
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }

    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                input, input_len);
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    if (modbus_state->transaction_max !=1) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 1, modbus_state->transaction_max);
        goto end;
    }

    result = 1;
end:
    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    return result;
}

/** \test Modbus fragmentation - 2 ADU in 1 TCP packet. */
static int ModbusParserTest10(void) {
    uint32_t    input_len = sizeof(readCoilsReq) + sizeof(writeMultipleRegistersReq);
    uint8_t     *input, *ptr;

    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    Flow f;
    TcpSession ssn;

    int result = 0;

    input  = (uint8_t *) SCMalloc (input_len * sizeof(uint8_t));
    if (unlikely(input == NULL))
        goto end;

    memcpy(input, readCoilsReq, sizeof(readCoilsReq));
    memcpy(input + sizeof(readCoilsReq), writeMultipleRegistersReq, sizeof(writeMultipleRegistersReq));

    memset(&f, 0, sizeof(f));
    memset(&ssn, 0, sizeof(ssn));

    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;

    StreamTcpInitConfig(TRUE);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    input, input_len);
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    if (modbus_state->transaction_max !=2) {
        printf("expected transaction_max %" PRIu8 ", got %" PRIu64 ": ", 2, modbus_state->transaction_max);
        goto end;
    }

    ModbusTransaction *tx = ModbusGetTx(modbus_state, 1);

    if ((tx->function != 16) || (tx->write.address != 0x01) || (tx->write.quantity != 2) ||
        (tx->write.count != 4) || (tx->data[0] != 0x000A) || (tx->data[1] != 0x0102)) {
        printf("expected function %" PRIu8 ", got %" PRIu8 ": ", 16, tx->function);
        printf("expected write address %" PRIu8 ", got %" PRIu8 ": ", 0x01, tx->write.address);
        printf("expected write quantity %" PRIu8 ", got %" PRIu8 ": ", 2, tx->write.quantity);
        printf("expected write count %" PRIu8 ", got %" PRIu8 ": ", 4, tx->write.count);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x000A, tx->data[0]);
        printf("expected data %" PRIu8 ", got %" PRIu8 ": ", 0x0102, tx->data[1]);
        goto end;
    }

    input_len = sizeof(readCoilsRsp) + sizeof(writeMultipleRegistersRsp);

    ptr = (uint8_t *) SCRealloc (input, input_len * sizeof(uint8_t));
    if (unlikely(ptr == NULL))
        goto end;
    input = ptr;

    memcpy(input, readCoilsRsp, sizeof(readCoilsRsp));
    memcpy(input + sizeof(readCoilsRsp), writeMultipleRegistersRsp, sizeof(writeMultipleRegistersRsp));

    SCMutexLock(&f.m);
    r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT,
                                input, sizeof(input_len));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    result = 1;
end:
    if (input != NULL)
        SCFree(input);
    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    return result;
}

/** \test Send Modbus exceed Length request. */
static int ModbusParserTest11(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus invalid Length\"; "
                                      "app-layer-event: "
                                      "modbus.invalid_length; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    exceededLengthWriteMultipleRegistersReq,
                                    sizeof(exceededLengthWriteMultipleRegistersReq) + 65523 /* header.length - 7 */ * sizeof(uint8_t));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}

/** \test Send Modbus invalid PDU Length. */
static int ModbusParserTest12(void) {
    AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc();
    DetectEngineThreadCtx *det_ctx = NULL;
    Flow f;
    Packet *p = NULL;
    Signature *s = NULL;
    TcpSession ssn;
    ThreadVars tv;

    int result = 0;

    memset(&tv, 0, sizeof(ThreadVars));
    memset(&f, 0, sizeof(Flow));
    memset(&ssn, 0, sizeof(TcpSession));

    p = UTHBuildPacket(NULL, 0, IPPROTO_TCP);

    FLOW_INITIALIZE(&f);
    f.alproto   = ALPROTO_MODBUS;
    f.protoctx  = (void *)&ssn;
    f.proto     = IPPROTO_TCP;
    f.flags     |= FLOW_IPV4;

    p->flow         = &f;
    p->flags        |= PKT_HAS_FLOW | PKT_STREAM_EST;
    p->flowflags    |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED;

    StreamTcpInitConfig(TRUE);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    if (de_ctx == NULL)
        goto end;

    de_ctx->flags |= DE_QUIET;
    s = DetectEngineAppendSig(de_ctx, "alert modbus any any -> any any "
                                      "(msg:\"Modbus invalid Length\"; "
                                      "app-layer-event: "
                                      "modbus.invalid_length; "
                                      "sid:1;)");
    if (s == NULL)
        goto end;

    SigGroupBuild(de_ctx);
    DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx);

    SCMutexLock(&f.m);
    int r = AppLayerParserParse(alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER,
                                    invalidLengthPDUWriteMultipleRegistersReq,
                                    sizeof(invalidLengthPDUWriteMultipleRegistersReq));
    if (r != 0) {
        printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r);
        SCMutexUnlock(&f.m);
        goto end;
    }
    SCMutexUnlock(&f.m);

    ModbusState    *modbus_state = f.alstate;
    if (modbus_state == NULL) {
        printf("no modbus state: ");
        goto end;
    }

    /* do detect */
    SigMatchSignatures(&tv, de_ctx, det_ctx, p);

    if (!PacketAlertCheck(p, 1)) {
        printf("sid 1 didn't match.  Should have matched: ");
        goto end;
    }

    result = 1;
end:
    SigGroupCleanup(de_ctx);
    SigCleanSignatures(de_ctx);

    DetectEngineThreadCtxDeinit(&tv, (void *)det_ctx);
    DetectEngineCtxFree(de_ctx);

    if (alp_tctx != NULL)
        AppLayerParserThreadCtxFree(alp_tctx);
    StreamTcpFreeConfig(TRUE);
    FLOW_DESTROY(&f);
    UTHFreePackets(&p, 1);
    return result;
}
#endif /* UNITTESTS */

void ModbusParserRegisterTests(void) {
#ifdef UNITTESTS
    UtRegisterTest("ModbusParserTest01 - Modbus Read Coils request", ModbusParserTest01, 1);
    UtRegisterTest("ModbusParserTest02 - Modbus Write Multiple registers request", ModbusParserTest02, 1);
    UtRegisterTest("ModbusParserTest03 - Modbus Read/Write Multiple registers request", ModbusParserTest03, 1);
    UtRegisterTest("ModbusParserTest04 - Modbus Force Listen Only Mode request", ModbusParserTest04, 1);
    UtRegisterTest("ModbusParserTest05 - Modbus invalid Protocol version", ModbusParserTest05, 1);
    UtRegisterTest("ModbusParserTest06 - Modbus unsolicited response", ModbusParserTest06, 1);
    UtRegisterTest("ModbusParserTest07 - Modbus invalid Length request", ModbusParserTest07, 1);
    UtRegisterTest("ModbusParserTest08 - Modbus Exception code invalid", ModbusParserTest08, 1);
    UtRegisterTest("ModbusParserTest09 - Modbus fragmentation - 1 ADU in 2 TCP packets", ModbusParserTest09, 1);
    UtRegisterTest("ModbusParserTest10 - Modbus fragmentation - 2 ADU in 1 TCP packet", ModbusParserTest10, 1);
    UtRegisterTest("ModbusParserTest11 - Modbus exceeded Length request", ModbusParserTest11, 1);
    UtRegisterTest("ModbusParserTest12 - Modbus invalid PDU Length", ModbusParserTest12, 1);
#endif /* UNITTESTS */
}