1 /* packet-mbtcp.c
2  * Routines for Modbus/TCP and Modbus/UDP dissection
3  * By Riaan Swart <rswart@cs.sun.ac.za>
4  * Copyright 2001, Institute for Applied Computer Science
5  *                   University of Stellenbosch
6  *
7  * See http://www.modbus.org/ for information on Modbus/TCP.
8  *
9  * Updated to v1.1b of the Modbus Application Protocol specification
10  *   Michael Mann * Copyright 2011
11  *
12  *****************************************************************************************************
13  * A brief explanation of the distinction between Modbus/TCP and Modbus RTU over TCP:
14  *
15  * Consider a Modbus poll message: Unit 01, Scan Holding Register Address 0 for 30 Registers
16  *
17  * The Modbus/TCP message structure will follow the pattern below:
18  * 00 00 00 00 00 06 01 03 00 00 00 1E
19  * AA AA BB BB CC CC DD EE FF FF GG GG
20  *
21  * A = 16-bit Transaction Identifier (typically increments, or is locked at zero)
22  * B = 16-bit Protocol Identifier (typically zero)
23  * C = 16-bit Length of data payload following (and inclusive of) the length byte
24  * D = 8-bit Unit / Slave ID
25  * E = 8-bit Modbus Function Code
26  * F = 16-bit Reference Number / Register Base Address
27  * G = 16-bit Word Count / Number of Registers to scan
28  *
29  * A identical Modbus RTU (or Modbus RTU over TCP) message will overlay partially with the msg above
30  * and contain 16-bit CRC at the end:
31  * 00 00 00 00 00 06 01 03 00 00 00 1E -- -- (Modbus/TCP message, repeated from above)
32  * -- -- -- -- -- -- 01 03 00 00 00 1E C5 C2 (Modbus RTU over TCP message, includes 16-bit CRC footer)
33  * AA AA BB BB CC CC DD EE FF FF GG GG HH HH
34  *
35  * A = Not present in Modbus RTU message
36  * B = Not present in Modbus RTU message
37  * C = Not present in Modbus RTU message
38  * D = 8-bit Unit / Slave ID
39  * E = 8-bit Modbus Function Code
40  * F = 16-bit Reference Number / Register Base Address
41  * G = 16-bit Word Count / Number of Registers to scan
42  * H = 16-bit CRC
43  *
44  *****************************************************************************************************
45  * Wireshark - Network traffic analyzer
46  * By Gerald Combs <gerald@wireshark.org>
47  * Copyright 1998 Gerald Combs
48  *
49  * SPDX-License-Identifier: GPL-2.0-or-later
50  */
51 
52 #include "config.h"
53 
54 #include <epan/packet.h>
55 #include "packet-tcp.h"
56 #include "packet-mbtcp.h"
57 #include <epan/prefs.h>
58 #include <epan/expert.h>
59 #include <epan/crc16-tvb.h> /* For CRC verification */
60 #include <epan/proto_data.h>
61 #include "packet-tls.h"
62 
63 void proto_register_modbus(void);
64 void proto_reg_handoff_mbtcp(void);
65 void proto_reg_handoff_mbrtu(void);
66 
67 /* Initialize the protocol and registered fields */
68 static int proto_mbtcp = -1;
69 static int proto_mbudp = -1;
70 static int proto_mbrtu = -1;
71 static int proto_modbus = -1;
72 static int hf_mbtcp_transid = -1;
73 static int hf_mbtcp_protid = -1;
74 static int hf_mbtcp_len = -1;
75 static int hf_mbtcp_unitid = -1;
76 static int hf_modbus_request_frame = -1;
77 static int hf_modbus_response_time = -1;
78 static int hf_modbus_functioncode = -1;
79 static int hf_modbus_reference = -1;
80 static int hf_modbus_padding = -1;
81 static int hf_modbus_lreference = -1;
82 static int hf_modbus_reftype = -1;
83 static int hf_modbus_readref = -1;
84 static int hf_modbus_writeref = -1;
85 static int hf_modbus_wordcnt = -1;
86 static int hf_modbus_readwordcnt = -1;
87 static int hf_modbus_writewordcnt = -1;
88 static int hf_modbus_bytecnt = -1;
89 static int hf_modbus_lbytecnt = -1;
90 static int hf_modbus_bitcnt = -1;
91 static int hf_modbus_exceptioncode = -1;
92 static int hf_modbus_diag_sf = -1;
93 static int hf_modbus_diag_return_query_data_request = -1;
94 static int hf_modbus_diag_return_query_data_echo = -1;
95 static int hf_modbus_diag_restart_communication_option = -1;
96 static int hf_modbus_diag_return_diag_register = -1;
97 static int hf_modbus_diag_ascii_input_delimiter = -1;
98 static int hf_modbus_diag_clear_ctr_diag_reg = -1;
99 static int hf_modbus_diag_return_bus_message_count = -1;
100 static int hf_modbus_diag_return_bus_comm_error_count = -1;
101 static int hf_modbus_diag_return_bus_exception_error_count = -1;
102 static int hf_modbus_diag_return_slave_message_count = -1;
103 static int hf_modbus_diag_return_no_slave_response_count = -1;
104 static int hf_modbus_diag_return_slave_nak_count = -1;
105 static int hf_modbus_diag_return_slave_busy_count = -1;
106 static int hf_modbus_diag_return_bus_char_overrun_count = -1;
107 static int hf_modbus_status = -1;
108 static int hf_modbus_event = -1;
109 static int hf_modbus_event_count = -1;
110 static int hf_modbus_message_count = -1;
111 static int hf_modbus_event_recv_comm_err = -1;
112 static int hf_modbus_event_recv_char_over = -1;
113 static int hf_modbus_event_recv_lo_mode = -1;
114 static int hf_modbus_event_recv_broadcast = -1;
115 static int hf_modbus_event_send_read_ex = -1;
116 static int hf_modbus_event_send_slave_abort_ex = -1;
117 static int hf_modbus_event_send_slave_busy_ex = -1;
118 static int hf_modbus_event_send_slave_nak_ex = -1;
119 static int hf_modbus_event_send_write_timeout = -1;
120 static int hf_modbus_event_send_lo_mode = -1;
121 static int hf_modbus_andmask = -1;
122 static int hf_modbus_ormask = -1;
123 static int hf_modbus_data = -1;
124 static int hf_modbus_mei = -1;
125 static int hf_modbus_read_device_id = -1;
126 static int hf_modbus_object_id = -1;
127 static int hf_modbus_num_objects = -1;
128 static int hf_modbus_list_object_len = -1;
129 static int hf_modbus_conformity_level = -1;
130 static int hf_modbus_more_follows = -1;
131 static int hf_modbus_next_object_id = -1;
132 static int hf_modbus_object_str_value = -1;
133 static int hf_modbus_object_value = -1;
134 static int hf_modbus_bitnum = -1;
135 static int hf_modbus_bitval = -1;
136 static int hf_modbus_regnum16 = -1;
137 static int hf_modbus_regnum32 = -1;
138 static int hf_modbus_regval_uint16 = -1;
139 static int hf_modbus_regval_int16 = -1;
140 static int hf_modbus_regval_uint32 = -1;
141 static int hf_modbus_regval_int32 = -1;
142 static int hf_modbus_regval_ieee_float = -1;
143 static int hf_modbus_regval_modicon_float = -1;
144 static int hf_mbrtu_unitid = -1;
145 static int hf_mbrtu_crc16 = -1;
146 static int hf_mbrtu_crc16_status = -1;
147 
148 /* Initialize the subtree pointers */
149 static gint ett_mbtcp = -1;
150 static gint ett_mbrtu = -1;
151 static gint ett_modbus_hdr = -1;
152 static gint ett_group_hdr = -1;
153 static gint ett_events = -1;
154 static gint ett_events_recv = -1;
155 static gint ett_events_send = -1;
156 static gint ett_device_id_objects = -1;
157 static gint ett_device_id_object_items = -1;
158 static gint ett_bit = -1;
159 static gint ett_register = -1;
160 
161 static expert_field ei_mbrtu_crc16_incorrect = EI_INIT;
162 static expert_field ei_modbus_data_decode = EI_INIT;
163 static expert_field ei_mbtcp_cannot_classify = EI_INIT;
164 
165 static dissector_handle_t modbus_handle;
166 static dissector_handle_t mbtcp_handle;
167 static dissector_handle_t mbtls_handle;
168 static dissector_handle_t mbudp_handle;
169 static dissector_handle_t mbrtu_handle;
170 
171 static dissector_table_t   modbus_data_dissector_table;
172 static dissector_table_t   modbus_dissector_table;
173 
174 
175 /* Globals for Modbus/TCP Preferences */
176 static gboolean mbtcp_desegment = TRUE;
177 static guint global_mbus_tcp_port = PORT_MBTCP; /* Port 502, by default */
178 static guint global_mbus_udp_port = PORT_MBTCP; /* Port 502, by default */
179 static guint global_mbus_tls_port = PORT_MBTLS; /* Port 802, by default */
180 
181 /* Globals for Modbus RTU over TCP Preferences */
182 static gboolean mbrtu_desegment = TRUE;
183 static guint global_mbus_tcp_rtu_port = PORT_MBRTU; /* 0, by default        */
184 static guint global_mbus_udp_rtu_port = PORT_MBRTU; /* 0, by default        */
185 static gboolean mbrtu_crc = FALSE;
186 
187 /* Globals for Modbus Preferences */
188 static gint global_mbus_register_format = MODBUS_PREF_REGISTER_FORMAT_UINT16;
189 
190 typedef struct {
191     guint8  function_code;
192     gint    register_format;
193     guint16 reg_base;
194     guint16 num_reg;
195     guint32 req_frame_num;
196     nstime_t req_time;
197     gboolean request_found;
198 } modbus_pkt_info_t;
199 
200 static int
classify_mbtcp_packet(packet_info * pinfo,guint port)201 classify_mbtcp_packet(packet_info *pinfo, guint port)
202 {
203     /* see if nature of packets can be derived from src/dst ports */
204     /* if so, return as found */
205     /*                        */
206     /* XXX Update Oct 2012 - It can be difficult to determine if a packet is a query or response; some way to track  */
207     /* the Modbus/TCP transaction ID for each pair of messages would allow for detection based on a new seq. number. */
208     /* Otherwise, we can stick with this method; a configurable port option has been added to allow for usage of     */
209     /* user ports either than the default of 502.                                                                    */
210     if (( pinfo->srcport == port ) && ( pinfo->destport != port ))
211         return RESPONSE_PACKET;
212     if (( pinfo->srcport != port ) && ( pinfo->destport == port ))
213         return QUERY_PACKET;
214 
215     /* else, cannot classify */
216     return CANNOT_CLASSIFY;
217 }
218 
219 static int
classify_mbrtu_packet(packet_info * pinfo,tvbuff_t * tvb,guint port)220 classify_mbrtu_packet(packet_info *pinfo, tvbuff_t *tvb, guint port)
221 {
222     guint8 func, len;
223 
224     func = tvb_get_guint8(tvb, 1);
225     len = tvb_reported_length(tvb);
226 
227     /* see if nature of packets can be derived from src/dst ports */
228     /* if so, return as found */
229     if (( pinfo->srcport == port ) && ( pinfo->destport != port ))
230         return RESPONSE_PACKET;
231     if (( pinfo->srcport != port ) && ( pinfo->destport == port ))
232         return QUERY_PACKET;
233 
234 
235     /* We may not have an Ethernet header or unique ports. */
236     /* Dig into these a little deeper to try to guess the message type */
237 
238     /* The 'exception' bit is set, so this is a response */
239     if (func & 0x80) {
240         return RESPONSE_PACKET;
241     }
242     switch (func) {
243         case READ_COILS:
244         case READ_DISCRETE_INPUTS:
245             /* Only possible to get a response message of 8 bytes with Discrete or Coils */
246             if (len == 8) {
247                 /* If this is, in fact, a response then the data byte count will be 3 */
248                 /* This will correctly identify all messages except for those that are discrete or coil polls */
249                 /* where the base address range happens to have 0x03 in the upper 16-bit address register     */
250                 if (tvb_get_guint8(tvb, 2) == 3) {
251                     return RESPONSE_PACKET;
252                 }
253                 else {
254                     return QUERY_PACKET;
255                 }
256             }
257             else {
258                 return RESPONSE_PACKET;
259             }
260             break;
261 
262         case READ_HOLDING_REGS:
263         case READ_INPUT_REGS:
264             if (len == 8) {
265                 return QUERY_PACKET;
266             }
267             else {
268                 return RESPONSE_PACKET;
269             }
270             break;
271 
272         case WRITE_SINGLE_COIL:
273         case WRITE_SINGLE_REG:
274             /* Normal response is echo of the request */
275             return CANNOT_CLASSIFY;
276 
277         case WRITE_MULT_REGS:
278         case WRITE_MULT_COILS:
279             if (len == 8) {
280                 return RESPONSE_PACKET;
281             }
282             else {
283                 return QUERY_PACKET;
284             }
285             break;
286     }
287 
288 
289     /* else, cannot classify */
290     return CANNOT_CLASSIFY;
291 }
292 
293 /* Translate function to string, as given on p6 of
294  * "Open Modbus/TCP Specification", release 1 by Andy Swales.
295  */
296 static const value_string function_code_vals[] = {
297     { READ_COILS,             "Read Coils" },
298     { READ_DISCRETE_INPUTS,   "Read Discrete Inputs" },
299     { READ_HOLDING_REGS,      "Read Holding Registers" },
300     { READ_INPUT_REGS,        "Read Input Registers" },
301     { WRITE_SINGLE_COIL,      "Write Single Coil" },
302     { WRITE_SINGLE_REG,       "Write Single Register" },
303     { READ_EXCEPT_STAT,       "Read Exception Status" },
304     { DIAGNOSTICS,            "Diagnostics" },
305     { GET_COMM_EVENT_CTRS,    "Get Comm. Event Counters" },
306     { GET_COMM_EVENT_LOG,     "Get Comm. Event Log" },
307     { WRITE_MULT_COILS,       "Write Multiple Coils" },
308     { WRITE_MULT_REGS,        "Write Multiple Registers" },
309     { REPORT_SLAVE_ID,        "Report Slave ID" },
310     { READ_FILE_RECORD,       "Read File Record" },
311     { WRITE_FILE_RECORD,      "Write File Record" },
312     { MASK_WRITE_REG,         "Mask Write Register" },
313     { READ_WRITE_REG,         "Read Write Register" },
314     { READ_FIFO_QUEUE,        "Read FIFO Queue" },
315     { ENCAP_INTERFACE_TRANSP, "Encapsulated Interface Transport" },
316     { UNITY_SCHNEIDER,        "Unity (Schneider)" },
317     { 0,                      NULL }
318 };
319 
320 /* Translate exception code to string */
321 static const value_string exception_code_vals[] = {
322     { ILLEGAL_FUNCTION,    "Illegal function" },
323     { ILLEGAL_ADDRESS,     "Illegal data address" },
324     { ILLEGAL_VALUE,       "Illegal data value" },
325     { SLAVE_FAILURE,       "Slave device failure" },
326     { ACKNOWLEDGE,         "Acknowledge" },
327     { SLAVE_BUSY,          "Slave device busy" },
328     { MEMORY_ERR,          "Memory parity error" },
329     { GATEWAY_UNAVAILABLE, "Gateway path unavailable" },
330     { GATEWAY_TRGT_FAIL,   "Gateway target device failed to respond" },
331     { 0,                    NULL }
332 };
333 
334 /* Translate Modbus Encapsulation Interface (MEI) code to string */
335 static const value_string encap_interface_code_vals[] = {
336     { CANOPEN_REQ_RESP, "CANopen Request/Response " },
337     { READ_DEVICE_ID,   "Read Device Identification" },
338     { 0,                NULL }
339 };
340 
341 /* Translate Modbus Diagnostic subfunction code to string */
342 static const value_string diagnostic_code_vals[] = {
343     { RETURN_QUERY_DATA,                "Return Query Data" },
344     { RESTART_COMMUNICATION_OPTION,     "Restart Communications Option" },
345     { RETURN_DIAGNOSTIC_REGISTER,       "Return Diagnostic Register" },
346     { CHANGE_ASCII_INPUT_DELIMITER,     "Change ASCII Input Delimiter" },
347     { FORCE_LISTEN_ONLY_MODE,           "Force Listen Only Mode" },
348     { CLEAR_COUNTERS_AND_DIAG_REG,      "Clear Counters and Diagnostic Register" },
349     { RETURN_BUS_MESSAGE_COUNT,         "Return Bus Message Count" },
350     { RETURN_BUS_COMM_ERROR_COUNT,      "Return Bus Communication Error Count" },
351     { RETURN_BUS_EXCEPTION_ERROR_COUNT, "Return Bus Exception Error Count" },
352     { RETURN_SLAVE_MESSAGE_COUNT,       "Return Slave Message Count" },
353     { RETURN_SLAVE_NO_RESPONSE_COUNT,   "Return Slave No Response Count" },
354     { RETURN_SLAVE_NAK_COUNT,           "Return Slave NAK Count" },
355     { RETURN_SLAVE_BUSY_COUNT,          "Return Slave Busy Count" },
356     { RETURN_BUS_CHAR_OVERRUN_COUNT,    "Return Bus Character Overrun Count" },
357     { CLEAR_OVERRUN_COUNTER_AND_FLAG,   "Clear Overrun Counter and Flag" },
358     { 0,                                NULL }
359 };
360 
361 static const value_string diagnostic_restart_communication_option_vals[] = {
362     { 0,        "Leave Log" },
363     { 0xFF,     "Clear Log" },
364     { 0,        NULL }
365 };
366 
367 /* Translate read device code to string */
368 static const value_string read_device_id_vals[] = {
369     { 1,        "Basic Device Identification" },
370     { 2,        "Regular Device Identification"  },
371     { 3,        "Extended Device Identification"  },
372     { 4,        "Specific Identification Object"  },
373 
374     { 0,        NULL             }
375 };
376 
377 /* Translate read device code to string */
378 static const value_string object_id_vals[] = {
379     { 0,        "VendorName" },
380     { 1,        "ProductCode" },
381     { 2,        "MajorMinorRevision"  },
382     { 3,        "VendorURL"  },
383     { 4,        "ProductName"  },
384     { 5,        "ModelName"  },
385     { 6,        "UserApplicationName"  },
386 
387     { 0,        NULL             }
388 };
389 
390 static const value_string conformity_level_vals[] = {
391     { 0x01,     "Basic Device Identification (stream)" },
392     { 0x02,     "Regular Device Identification (stream)"  },
393     { 0x03,     "Extended Device Identification (stream)"  },
394     { 0x81,     "Basic Device Identification (stream and individual)" },
395     { 0x82,     "Regular Device Identification (stream and individual)"  },
396     { 0x83,     "Extended Device Identification (stream and individual)"  },
397 
398     { 0,        NULL             }
399 };
400 
401 static const enum_val_t mbus_register_format[] = {
402   { "UINT16     ", "UINT16     ",  MODBUS_PREF_REGISTER_FORMAT_UINT16  },
403   { "INT16      ", "INT16      ",  MODBUS_PREF_REGISTER_FORMAT_INT16   },
404   { "UINT32     ", "UINT32     ",  MODBUS_PREF_REGISTER_FORMAT_UINT32  },
405   { "INT32      ", "INT32      ",  MODBUS_PREF_REGISTER_FORMAT_INT32  },
406   { "IEEE FLT   ", "IEEE FLT   ",  MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT  },
407   { "MODICON FLT", "MODICON FLT",  MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT  },
408   { NULL, NULL, 0 }
409 };
410 
411 /* Code to dissect Modbus/TCP packets */
412 static int
dissect_mbtcp_pdu_common(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,int proto,guint port)413 dissect_mbtcp_pdu_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int proto, guint port)
414 {
415 /* Set up structures needed to add the protocol subtree and manage it */
416     proto_item    *mi;
417     proto_tree    *mbtcp_tree;
418     int           offset;
419     tvbuff_t      *next_tvb;
420     const char    *func_string = "";
421     const char    *pkt_type_str = "";
422     const char    *err_str = "";
423     guint16       transaction_id, protocol_id, len;
424     guint8        unit_id, function_code, exception_code, subfunction_code;
425     modbus_data_t modbus_data;
426 
427     transaction_id = tvb_get_ntohs(tvb, 0);
428     protocol_id = tvb_get_ntohs(tvb, 2);
429     len = tvb_get_ntohs(tvb, 4);
430 
431     unit_id = tvb_get_guint8(tvb, 6);
432     function_code = tvb_get_guint8(tvb, 7) & 0x7F;
433 
434     offset = 0;
435 
436     /* "Request" or "Response" */
437     modbus_data.packet_type = classify_mbtcp_packet(pinfo, port);
438     /* Save the transaction and unit id to find the request to a response */
439     modbus_data.mbtcp_transid = transaction_id;
440     modbus_data.unit_id = unit_id;
441 
442     switch ( modbus_data.packet_type ) {
443         case QUERY_PACKET :
444             pkt_type_str="Query";
445             break;
446         case RESPONSE_PACKET :
447             pkt_type_str="Response";
448             break;
449         case CANNOT_CLASSIFY :
450             err_str="Unable to classify as query or response.";
451             pkt_type_str="unknown";
452             break;
453         default :
454             break;
455     }
456 
457     /* Find exception - last bit set in function code */
458     if (tvb_get_guint8(tvb, 7) & 0x80) {
459         exception_code = tvb_get_guint8(tvb, offset + 8);
460     }
461     else {
462         exception_code = 0;
463     }
464 
465     if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0))  {
466         func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 8), encap_interface_code_vals, "Encapsulated Interface Transport");
467         subfunction_code = 1;
468     }
469     else if ((function_code == DIAGNOSTICS) && (exception_code == 0))  {
470         func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 8), diagnostic_code_vals, "Diagnostics");
471         subfunction_code = 1;
472     }
473     else {
474         func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
475         subfunction_code = 0;
476     }
477 
478     if ( exception_code != 0 )
479         err_str="Exception returned ";
480 
481     /* Make entries in Info column on summary display */
482     if (subfunction_code == 0) {
483         if (strlen(err_str) > 0) {
484             col_add_fstr(pinfo->cinfo, COL_INFO,
485                     "%8s: Trans: %5u; Unit: %3u, Func: %3u: %s. %s",
486                     pkt_type_str, transaction_id, unit_id,
487                     function_code, func_string, err_str);
488         }
489         else {
490             col_add_fstr(pinfo->cinfo, COL_INFO,
491                     "%8s: Trans: %5u; Unit: %3u, Func: %3u: %s",
492                     pkt_type_str, transaction_id, unit_id,
493                     function_code, func_string);
494         }
495     }
496     else {
497         if (strlen(err_str) > 0) {
498             col_add_fstr(pinfo->cinfo, COL_INFO,
499                     "%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s. %s",
500                     pkt_type_str, transaction_id, unit_id,
501                     function_code, subfunction_code, func_string, err_str);
502         }
503         else {
504             col_add_fstr(pinfo->cinfo, COL_INFO,
505                     "%8s: Trans: %5u; Unit: %3u, Func: %3u/%3u: %s",
506                     pkt_type_str, transaction_id, unit_id,
507                     function_code, subfunction_code, func_string);
508         }
509     }
510 
511     /* Create protocol tree */
512     mi = proto_tree_add_item(tree, proto, tvb, offset, len+6, ENC_NA);
513     mbtcp_tree = proto_item_add_subtree(mi, ett_mbtcp);
514 
515     if (modbus_data.packet_type == CANNOT_CLASSIFY)
516         expert_add_info(pinfo, mi, &ei_mbtcp_cannot_classify);
517 
518     /* Add items to protocol tree specific to Modbus/TCP */
519     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_transid, tvb, offset, 2, transaction_id);
520     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_protid, tvb, offset + 2, 2, protocol_id);
521     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_len, tvb, offset + 4, 2, len);
522     proto_tree_add_uint(mbtcp_tree, hf_mbtcp_unitid, tvb, offset + 6, 1, unit_id);
523 
524     /* dissect the Modbus PDU */
525     next_tvb = tvb_new_subset_length( tvb, offset+7, len-1);
526 
527     /* Continue with dissection of Modbus data payload following Modbus/TCP frame */
528     if( tvb_reported_length_remaining(tvb, offset) > 0 )
529         call_dissector_with_data(modbus_handle, next_tvb, pinfo, tree, &modbus_data);
530 
531     return tvb_captured_length(tvb);
532 }
533 
534 static int
dissect_mbtcp_pdu(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data _U_)535 dissect_mbtcp_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
536 {
537     /* Make entries in Protocol column on summary display */
538     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP");
539     col_clear(pinfo->cinfo, COL_INFO);
540 
541     return dissect_mbtcp_pdu_common(tvb, pinfo, tree, proto_mbtcp, global_mbus_tcp_port);
542 }
543 
544 static int
dissect_mbtls_pdu(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data _U_)545 dissect_mbtls_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
546 {
547     /* Make entries in Protocol column on summary display */
548     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/TCP Security");
549     col_clear(pinfo->cinfo, COL_INFO);
550 
551     return dissect_mbtcp_pdu_common(tvb, pinfo, tree, proto_mbtcp, global_mbus_tls_port);
552 }
553 
554 /* Code to dissect Modbus RTU */
555 static int
dissect_mbrtu_pdu_common(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,guint port)556 dissect_mbrtu_pdu_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint port)
557 {
558 /* Set up structures needed to add the protocol subtree and manage it */
559     proto_item    *mi;
560     proto_tree    *mbrtu_tree;
561     int           offset;
562     tvbuff_t      *next_tvb;
563     const char    *func_string = "";
564     const char    *pkt_type_str = "";
565     const char    *err_str = "";
566     guint16       len, calc_crc16;
567     guint8        unit_id, function_code, exception_code, subfunction_code;
568     modbus_data_t modbus_data;
569 
570     /* Make entries in Protocol column on summary display */
571     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus RTU");
572     col_clear(pinfo->cinfo, COL_INFO);
573 
574     len = tvb_reported_length(tvb);
575 
576     unit_id = tvb_get_guint8(tvb, 0);
577     function_code = tvb_get_guint8(tvb, 1) & 0x7F;
578 
579     offset = 0;
580 
581     /* "Request" or "Response" */
582     modbus_data.packet_type = classify_mbrtu_packet(pinfo, tvb, port);
583     /* Transaction ID is available only in Modbus TCP */
584     modbus_data.mbtcp_transid = 0;
585     modbus_data.unit_id = unit_id;
586 
587     switch ( modbus_data.packet_type ) {
588         case QUERY_PACKET :
589             pkt_type_str="Query";
590             break;
591         case RESPONSE_PACKET :
592             pkt_type_str="Response";
593             break;
594         case CANNOT_CLASSIFY :
595             err_str="Unable to classify as query or response.";
596             pkt_type_str="unknown";
597             break;
598         default :
599             break;
600     }
601 
602     /* Find exception - last bit set in function code */
603     if (tvb_get_guint8(tvb, 1) & 0x80) {
604         exception_code = tvb_get_guint8(tvb, offset + 2);
605     }
606     else {
607         exception_code = 0;
608     }
609 
610     if ((function_code == ENCAP_INTERFACE_TRANSP) && (exception_code == 0))  {
611         func_string = val_to_str_const(tvb_get_guint8(tvb, offset + 2), encap_interface_code_vals, "Encapsulated Interface Transport");
612         subfunction_code = 1;
613     }
614     else if ((function_code == DIAGNOSTICS) && (exception_code == 0))  {
615         func_string = val_to_str_const(tvb_get_ntohs(tvb, offset + 2), diagnostic_code_vals, "Diagnostics");
616         subfunction_code = 1;
617     }
618     else {
619         func_string = val_to_str(function_code, function_code_vals, "Unknown function (%d)");
620         subfunction_code = 0;
621     }
622 
623     if ( exception_code != 0 )
624         err_str="Exception returned ";
625 
626     /* Make entries in Info column on summary display */
627     if (subfunction_code == 0) {
628         if (strlen(err_str) > 0) {
629             col_add_fstr(pinfo->cinfo, COL_INFO,
630                     "%8s: Unit: %3u, Func: %3u: %s. %s",
631                     pkt_type_str, unit_id,
632                     function_code, func_string, err_str);
633         }
634         else {
635             col_add_fstr(pinfo->cinfo, COL_INFO,
636                     "%8s: Unit: %3u, Func: %3u: %s",
637                     pkt_type_str, unit_id,
638                     function_code, func_string);
639         }
640     }
641     else {
642         if (strlen(err_str) > 0) {
643             col_add_fstr(pinfo->cinfo, COL_INFO,
644                     "%8s: Unit: %3u, Func: %3u/%3u: %s. %s",
645                     pkt_type_str, unit_id,
646                     function_code, subfunction_code, func_string, err_str);
647         }
648         else {
649             col_add_fstr(pinfo->cinfo, COL_INFO,
650                     "%8s: Unit: %3u, Func: %3u/%3u: %s",
651                     pkt_type_str, unit_id,
652                     function_code, subfunction_code, func_string);
653         }
654     }
655 
656     /* Create protocol tree */
657     mi = proto_tree_add_protocol_format(tree, proto_mbrtu, tvb, offset,
658             len, "Modbus RTU");
659     mbrtu_tree = proto_item_add_subtree(mi, ett_mbrtu);
660 
661     /* Add items to protocol tree specific to Modbus RTU */
662     proto_tree_add_uint(mbrtu_tree, hf_mbrtu_unitid, tvb, offset, 1, unit_id);
663 
664     /* CRC validation */
665     if (mbrtu_crc)
666     {
667         calc_crc16 = crc16_plain_tvb_offset_seed(tvb, offset, len-2, 0xFFFF);
668         proto_tree_add_checksum(mbrtu_tree, tvb, len-2, hf_mbrtu_crc16, hf_mbrtu_crc16_status, &ei_mbrtu_crc16_incorrect, pinfo, g_htons(calc_crc16), ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY);
669     }
670     else
671     {
672         proto_tree_add_checksum(mbrtu_tree, tvb, len-2, hf_mbrtu_crc16, hf_mbrtu_crc16_status, &ei_mbrtu_crc16_incorrect, pinfo, 0, ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);
673     }
674 
675     /* when determining payload length, make sure to ignore the unit ID header & CRC-16 footer bytes */
676     len = len - 3;
677 
678     /* dissect the Modbus PDU                      */
679     next_tvb = tvb_new_subset_length( tvb, offset+1, len);
680 
681     /* Continue with dissection of Modbus data payload following Modbus RTU frame */
682     if( tvb_reported_length_remaining(tvb, offset) > 0 )
683         call_dissector_with_data(modbus_handle, next_tvb, pinfo, tree, &modbus_data);
684 
685     return tvb_captured_length(tvb);
686 }
687 
688 /* Code to dissect Modbus RTU over TCP packets */
689 static int
dissect_mbrtu_pdu(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data _U_)690 dissect_mbrtu_pdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
691 {
692     return dissect_mbrtu_pdu_common(tvb, pinfo, tree, global_mbus_tcp_rtu_port);
693 }
694 
695 /* Return length of Modbus/TCP message */
696 static guint
get_mbtcp_pdu_len(packet_info * pinfo _U_,tvbuff_t * tvb,int offset,void * data _U_)697 get_mbtcp_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset, void *data _U_)
698 {
699     guint16 plen;
700 
701     /*
702      * Get the length of the data from the encapsulation header.
703      */
704     plen = tvb_get_ntohs(tvb, offset + 4);
705 
706     /*
707      * That length doesn't include the encapsulation header itself;
708      * add that in.
709      */
710     return plen + 6;
711 }
712 
713 /* Return length of Modbus RTU over TCP message */
714 static guint
get_mbrtu_pdu_len(packet_info * pinfo _U_,tvbuff_t * tvb,int offset _U_,void * data _U_)715 get_mbrtu_pdu_len(packet_info *pinfo _U_, tvbuff_t *tvb,
716                   int offset _U_, void *data _U_)
717 {
718     int packet_type;
719     guint8 function_code;
720 
721     function_code = tvb_get_guint8(tvb, 1);
722 
723     /* Modbus RTU requests do not contain a length field but they are typically a consistent size.
724        Responses do contain a usable 'length' byte at offset 2
725        XXX - Note that only some function codes are supported by this lookup function;
726              the rest can be added as pcap examples are made available */
727 
728     /* Determine "Query" or "Response" */
729     packet_type = classify_mbrtu_packet(pinfo, tvb, global_mbus_tcp_rtu_port);
730 
731     switch ( packet_type ) {
732         case QUERY_PACKET :
733             switch (function_code) {
734                 case READ_COILS:   /* Query messages of these types are always 8 bytes */
735                 case READ_DISCRETE_INPUTS:
736                 case READ_HOLDING_REGS:
737                 case READ_INPUT_REGS:
738                 case WRITE_SINGLE_COIL:
739                 case WRITE_SINGLE_REG:
740                     return 8;
741                     break;
742                 case WRITE_MULT_REGS:
743                 case WRITE_MULT_COILS:
744                     return tvb_get_guint8(tvb, 6) + 9; /* Reported size does not include 2 header, 4 FC15/16-specific, 1 size byte or 2 CRC16 bytes */
745                     break;
746                 default :
747                     return tvb_captured_length(tvb);  /* Fall back on tvb length */
748                     break;
749             }
750         case RESPONSE_PACKET :
751             /* The 'exception' bit is set, so this is a 5-byte response */
752             if (function_code & 0x80) {
753                 return 5;
754             }
755 
756             switch (function_code) {
757                 case READ_COILS:
758                 case READ_DISCRETE_INPUTS:
759                 case READ_HOLDING_REGS:
760                 case READ_INPUT_REGS:
761                     return tvb_get_guint8(tvb, 2) + 5;  /* Reported size does not include 2 header, 1 size byte, 2 CRC16 bytes */
762                     break;
763                 case WRITE_SINGLE_COIL: /* Response messages of FC5/6/15/16 are always 8 bytes */
764                 case WRITE_SINGLE_REG:
765                 case WRITE_MULT_REGS:
766                 case WRITE_MULT_COILS:
767                     return 8;
768                     break;
769                 default :
770                     return tvb_captured_length(tvb);  /* Fall back on tvb length */
771                     break;
772             }
773         case CANNOT_CLASSIFY :
774         default :
775             return tvb_captured_length(tvb);  /* Fall back on tvb length */
776             break;
777     }
778 
779 }
780 
781 
782 /* Code to dissect Modbus/TCP messages */
783 static int
dissect_mbtcp_common(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data,dissector_t dissect_pdu)784 dissect_mbtcp_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data, dissector_t dissect_pdu)
785 {
786 
787     /* Make sure there's at least enough data to determine it's a Modbus TCP packet */
788     if (!tvb_bytes_exist(tvb, 0, 8))
789         return 0;
790 
791     /* check that it actually looks like Modbus/TCP */
792     /* protocol id == 0 */
793     if(tvb_get_ntohs(tvb, 2) != 0 ){
794         return 0;
795     }
796     /* length is at least 2 (unit_id + function_code) */
797     if(tvb_get_ntohs(tvb, 4) < 2 ){
798         return 0;
799     }
800 
801     /* build up protocol tree and iterate over multiple packets */
802     tcp_dissect_pdus(tvb, pinfo, tree, mbtcp_desegment, 6,
803                      get_mbtcp_pdu_len, dissect_pdu, data);
804 
805     return tvb_captured_length(tvb);
806 }
807 
808 static int
dissect_mbtcp(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data)809 dissect_mbtcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
810 {
811     return dissect_mbtcp_common(tvb, pinfo, tree, data, dissect_mbtcp_pdu);
812 }
813 
814 static int
dissect_mbtls(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data)815 dissect_mbtls(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
816 {
817     return dissect_mbtcp_common(tvb, pinfo, tree, data, dissect_mbtls_pdu);
818 }
819 
820 static int
dissect_mbudp(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data _U_)821 dissect_mbudp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
822 {
823 
824     /* Make sure there's at least enough data to determine it's a Modbus UDP packet */
825     if (!tvb_bytes_exist(tvb, 0, 8))
826         return 0;
827 
828     /* check that it actually looks like Modbus/TCP */
829     /* protocol id == 0 */
830     if(tvb_get_ntohs(tvb, 2) != 0 ){
831         return 0;
832     }
833     /* length is at least 2 (unit_id + function_code) */
834     if(tvb_get_ntohs(tvb, 4) < 2 ){
835         return 0;
836     }
837 
838     /* Make entries in Protocol column on summary display */
839     col_set_str(pinfo->cinfo, COL_PROTOCOL, "Modbus/UDP");
840     col_clear(pinfo->cinfo, COL_INFO);
841 
842     return dissect_mbtcp_pdu_common(tvb, pinfo, tree, proto_mbudp, global_mbus_udp_port);
843 }
844 
845 /* Code to dissect Modbus RTU over TCP messages */
846 static int
dissect_mbrtu(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data)847 dissect_mbrtu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
848 {
849 
850     /* Make sure there's at least enough data to determine it's a Modbus packet */
851     /* 5 bytes is the smallest possible valid message (exception response) */
852     if (!tvb_bytes_exist(tvb, 0, 5))
853         return 0;
854 
855     /* For Modbus RTU mode, confirm that the first byte is a valid address (non-zero), */
856     /* so we can eliminate false-posititves on Modbus TCP messages loaded as RTU       */
857     if(tvb_get_guint8(tvb, 0) == 0 )
858         return 0;
859 
860     /* build up protocol tree and iterate over multiple packets */
861     tcp_dissect_pdus(tvb, pinfo, tree, mbrtu_desegment, 5,
862                      get_mbrtu_pdu_len, dissect_mbrtu_pdu, data);
863 
864     return tvb_captured_length(tvb);
865 }
866 
867 static int
dissect_mbrtu_udp(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data _U_)868 dissect_mbrtu_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
869 {
870 
871     /* Make sure there's at least enough data to determine it's a Modbus packet */
872     /* 5 bytes is the smallest possible valid message (exception response) */
873     if (tvb_reported_length(tvb) < 5)
874         return 0;
875 
876     return dissect_mbrtu_pdu_common(tvb, pinfo, tree, global_mbus_udp_rtu_port);
877 }
878 
879 
880 /* Code to allow further dissection of Modbus data payload */
881 /* Common to both Modbus/TCP and Modbus RTU dissectors     */
882 static void
dissect_modbus_data(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,guint8 function_code,gint payload_start,gint payload_len,gint register_format,guint16 reg_base,guint16 num_reg)883 dissect_modbus_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 function_code,
884                     gint payload_start, gint payload_len, gint register_format, guint16 reg_base, guint16 num_reg)
885 {
886     gint reported_len, data_offset;
887     guint8   data8, ii;
888     gboolean data_bool;
889     gint16  data16s;
890     gint32  data32s;
891     guint16 data16, modflt_lo, modflt_hi, reg_num=reg_base;
892     guint32 data32, modflt_comb;
893     gfloat data_float, modfloat;
894     proto_tree    *bit_tree = NULL;
895     proto_item    *bitnum_ti = NULL;
896     proto_item    *register_item = NULL;
897     proto_tree    *register_tree = NULL;
898     tvbuff_t *next_tvb;
899 
900     reported_len = tvb_reported_length_remaining(tvb, payload_start);
901     data_offset = 0;
902 
903     if ( payload_start < 0 || ( payload_len + payload_start ) == 0 )
904         return;
905 
906     /* If calculated length from remaining tvb data != bytes in packet, do not attempt to decode      */
907     if ( payload_len != reported_len ) {
908         proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, reported_len, ENC_NA);
909         return;
910     }
911 
912     /* If data type of payload is Holding or Input registers */
913     /* AND */
914     /* if payload length is not a multiple of 4, don't attempt to decode anything in 32-bit format */
915     if ((function_code == READ_HOLDING_REGS) || (function_code == READ_INPUT_REGS) || (function_code == WRITE_MULT_REGS)) {
916         if ((payload_len % 4 != 0) && ( (register_format == MODBUS_PREF_REGISTER_FORMAT_UINT32) ||
917             (register_format == MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT) ||
918             (register_format == MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT) ) ) {
919             register_item = proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
920             expert_add_info(pinfo, register_item, &ei_modbus_data_decode);
921             return;
922         }
923     }
924 
925     /* Build a new tvb containing just the data payload   */
926     next_tvb = tvb_new_subset_length_caplen(tvb, payload_start, payload_len, reported_len);
927 
928     switch ( function_code ) {
929         case READ_COILS:
930         case READ_DISCRETE_INPUTS:
931             /* The bit data is packed, 8 bits per byte of data, loop over each bit */
932             while (data_offset < payload_len) {
933                 data8 = tvb_get_guint8(next_tvb, data_offset);
934                 for (ii = 0; ii < 8; ii++) {
935                     data_bool = (data8 & (1 << ii)) > 0;
936                     bit_tree = proto_tree_add_subtree_format(tree, next_tvb, data_offset, 1,
937                         ett_bit, NULL, "Bit %u : %u", reg_num, data_bool);
938                     bitnum_ti = proto_tree_add_uint(bit_tree, hf_modbus_bitnum, next_tvb, data_offset, 1, reg_num);
939                     proto_item_set_generated(bitnum_ti);
940                     proto_tree_add_boolean(bit_tree, hf_modbus_bitval, next_tvb, data_offset, 1, data_bool);
941                     reg_num++;
942 
943                     /* If all the requested bits have been read, stop now */
944                     if ((reg_num - reg_base) >= num_reg) {
945                         break;
946                     }
947                 }
948                 data_offset++;
949             }
950             break;
951 
952         case READ_HOLDING_REGS:
953         case READ_INPUT_REGS:
954         case WRITE_MULT_REGS:
955             while (data_offset < payload_len) {
956                 /* Use "Preferences" options to determine decoding format of register data, as no format is implied by the protocol itself. */
957                 /* Based on a standard register size of 16-bits, use decoding format preference to step through each register and display  */
958                 /* it in an appropriate fashion. */
959                 switch (register_format) {
960                     case MODBUS_PREF_REGISTER_FORMAT_UINT16: /* Standard-size unsigned integer 16-bit register */
961                         data16 = tvb_get_ntohs(next_tvb, data_offset);
962                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 2,
963                             ett_register, NULL, "Register %u (UINT16): %u", reg_num, data16);
964 
965                         proto_tree_add_uint(register_tree, hf_modbus_regnum16, next_tvb, data_offset, 2, reg_num);
966                         proto_tree_add_uint(register_tree, hf_modbus_regval_uint16, next_tvb, data_offset, 2, data16);
967 
968                         data_offset += 2;
969                         reg_num += 1;
970                         break;
971                     case MODBUS_PREF_REGISTER_FORMAT_INT16: /* Standard-size signed integer 16-bit register */
972                         data16s = tvb_get_ntohs(next_tvb, data_offset);
973                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 2,
974                             ett_register, NULL, "Register %u (INT16): %d", reg_num, data16s);
975 
976                         proto_tree_add_uint(register_tree, hf_modbus_regnum16, next_tvb, data_offset, 2, reg_num);
977                         proto_tree_add_int(register_tree, hf_modbus_regval_int16, next_tvb, data_offset, 2, data16s);
978 
979                         data_offset += 2;
980                         reg_num += 1;
981                         break;
982                     case MODBUS_PREF_REGISTER_FORMAT_UINT32: /* Double-size 32-bit unsigned integer (2 sequential 16-bit registers) */
983                         data32 = tvb_get_ntohl(next_tvb, data_offset);
984                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 4,
985                             ett_register, NULL, "Register %u (UINT32): %u", reg_num, data32);
986 
987                         proto_tree_add_uint(register_tree, hf_modbus_regnum32, next_tvb, data_offset, 4, reg_num);
988                         proto_tree_add_uint(register_tree, hf_modbus_regval_uint32, next_tvb, data_offset, 4, data32);
989 
990                         data_offset += 4;
991                         reg_num += 2;
992                         break;
993                     case MODBUS_PREF_REGISTER_FORMAT_INT32: /* Double-size 32-bit signed integer (2 sequential 16-bit registers) */
994                         data32s = tvb_get_ntohl(next_tvb, data_offset);
995                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 4,
996                             ett_register, NULL, "Register %u (INT32): %d", reg_num, data32s);
997 
998                         proto_tree_add_uint(register_tree, hf_modbus_regnum32, next_tvb, data_offset, 4, reg_num);
999                         proto_tree_add_int(register_tree, hf_modbus_regval_int32, next_tvb, data_offset, 4, data32s);
1000 
1001                         data_offset += 4;
1002                         reg_num += 2;
1003                         break;
1004                     case MODBUS_PREF_REGISTER_FORMAT_IEEE_FLOAT: /* 32-bit IEEE Floating Point, (2 sequential 16-bit registers) */
1005                         data_float = tvb_get_ntohieee_float(next_tvb, data_offset);
1006 
1007                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 4,
1008                             ett_register, NULL, "Register %u (IEEE Float): %f", reg_num, data_float);
1009 
1010                         proto_tree_add_uint(register_tree, hf_modbus_regnum32, next_tvb, data_offset, 4, reg_num);
1011                         proto_tree_add_float(register_tree, hf_modbus_regval_ieee_float, next_tvb, data_offset, 4, data_float);
1012 
1013                         data_offset += 4;
1014                         reg_num += 2;
1015                         break;
1016                     case MODBUS_PREF_REGISTER_FORMAT_MODICON_FLOAT: /* Modicon Floating Point (word-swapped, 2 sequential 16-bit registers) */
1017                         /* Modicon-style Floating Point values are stored in reverse-word order.                     */
1018                         /* ie: a standard IEEE float value 59.991459 is equal to 0x426ff741                          */
1019                         /*     while the Modicon equivalent to this value is 0xf741426f                              */
1020                         /* To re-assemble a proper IEEE float, we must retrieve the 2 x 16-bit words, bit-shift the  */
1021                         /* "hi" component by 16-bits and then OR them together into a combined 32-bit int.           */
1022                         /* Following that operation, use some memcpy magic to copy the 4 raw data bytes from the     */
1023                         /* 32-bit integer into a standard float.  Not sure if there is a cleaner way possible using  */
1024                         /* the Wireshark libraries, but this seems to work OK.                                        */
1025 
1026                         modflt_lo = tvb_get_ntohs(next_tvb, data_offset);
1027                         modflt_hi = tvb_get_ntohs(next_tvb, data_offset+2);
1028                         modflt_comb = (guint32)(modflt_hi<<16) | modflt_lo;
1029                         memcpy(&modfloat, &modflt_comb, 4);
1030 
1031                         register_tree = proto_tree_add_subtree_format( tree, next_tvb, data_offset, 4,
1032                             ett_register, NULL, "Register %u (Modicon Float): %f", reg_num, modfloat);
1033 
1034                         proto_tree_add_uint(register_tree, hf_modbus_regnum32, next_tvb, data_offset, 4, reg_num);
1035                         proto_tree_add_float(register_tree, hf_modbus_regval_modicon_float, next_tvb, data_offset, 4, modfloat);
1036 
1037                         data_offset += 4;
1038                         reg_num += 2;
1039                         break;
1040                     default:
1041                         /* Avoid any chance of an infinite loop */
1042                         data_offset = payload_len;
1043                         break;
1044                     } /* register format switch */
1045 
1046                 } /* while loop */
1047 
1048                 break;
1049 
1050         default:
1051             if ( ! dissector_try_string(modbus_data_dissector_table, "data", next_tvb, pinfo, tree, NULL) )
1052                 proto_tree_add_item(tree, hf_modbus_data, tvb, payload_start, payload_len, ENC_NA);
1053             break;
1054         }
1055 }
1056 
1057 /* Code to dissect Modbus request message */
1058 static int
dissect_modbus_request(tvbuff_t * tvb,packet_info * pinfo,proto_tree * modbus_tree,guint8 function_code,gint payload_start,gint payload_len,modbus_pkt_info_t * pkt_info)1059 dissect_modbus_request(tvbuff_t *tvb, packet_info *pinfo, proto_tree *modbus_tree, guint8 function_code, gint payload_start, gint payload_len, modbus_pkt_info_t *pkt_info)
1060 {
1061     proto_tree    *group_tree;
1062     gint          byte_cnt, group_offset, ii;
1063     guint8        mei_code;
1064     guint16       reg_base=0, diagnostic_code;
1065     guint32       group_byte_cnt, group_word_cnt;
1066 
1067     if (!pkt_info) {
1068         return 0;
1069     }
1070 
1071     switch (function_code) {
1072 
1073         case READ_COILS:
1074         case READ_DISCRETE_INPUTS:
1075             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1076             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1077             break;
1078 
1079         case READ_HOLDING_REGS:
1080         case READ_INPUT_REGS:
1081             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1082             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1083             break;
1084 
1085         case WRITE_SINGLE_COIL:
1086             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1087             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, pkt_info->register_format, reg_base, 0);
1088             proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
1089             break;
1090 
1091         case WRITE_SINGLE_REG:
1092             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1093             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, pkt_info->register_format, reg_base, 0);
1094             break;
1095 
1096         case READ_EXCEPT_STAT:
1097             /* Do Nothing  */
1098             break;
1099 
1100         case DIAGNOSTICS:
1101             diagnostic_code = tvb_get_ntohs(tvb, payload_start);
1102             proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
1103             switch(diagnostic_code)
1104             {
1105                 case RETURN_QUERY_DATA:
1106                     if (payload_len > 2)
1107                         proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_request, tvb, payload_start+2, payload_len-2, ENC_NA);
1108                     break;
1109                 case RESTART_COMMUNICATION_OPTION:
1110                     proto_tree_add_item(modbus_tree, hf_modbus_diag_restart_communication_option, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1111                     break;
1112                 case CHANGE_ASCII_INPUT_DELIMITER:
1113                     proto_tree_add_item(modbus_tree, hf_modbus_diag_ascii_input_delimiter, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1114                     break;
1115                 case RETURN_DIAGNOSTIC_REGISTER:           /* 00 00 Data Field */
1116                 case FORCE_LISTEN_ONLY_MODE:               /* 00 00 Data Field */
1117                 case CLEAR_COUNTERS_AND_DIAG_REG:          /* 00 00 Data Field */
1118                 case RETURN_BUS_MESSAGE_COUNT:             /* 00 00 Data Field */
1119                 case RETURN_BUS_COMM_ERROR_COUNT:          /* 00 00 Data Field */
1120                 case RETURN_BUS_EXCEPTION_ERROR_COUNT:     /* 00 00 Data Field */
1121                 case RETURN_SLAVE_MESSAGE_COUNT:           /* 00 00 Data Field */
1122                 case RETURN_SLAVE_NO_RESPONSE_COUNT:       /* 00 00 Data Field */
1123                 case RETURN_SLAVE_NAK_COUNT:               /* 00 00 Data Field */
1124                 case RETURN_SLAVE_BUSY_COUNT:              /* 00 00 Data Field */
1125                 case RETURN_BUS_CHAR_OVERRUN_COUNT:        /* 00 00 Data Field */
1126                 case CLEAR_OVERRUN_COUNTER_AND_FLAG:
1127                 default:
1128                     if (payload_len > 2)
1129                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, pkt_info->register_format, reg_base, 0);
1130                     break;
1131             }
1132             break;
1133         case WRITE_MULT_COILS:
1134             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1135             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1136             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
1137             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1, byte_cnt);
1138             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, pkt_info->register_format, reg_base, 0);
1139             break;
1140 
1141         case WRITE_MULT_REGS:
1142             reg_base = tvb_get_ntohs(tvb, payload_start);
1143             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1144             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1145             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 4);
1146             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 4, 1, byte_cnt);
1147             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 5, byte_cnt, pkt_info->register_format, reg_base, 0);
1148             break;
1149 
1150         case READ_FILE_RECORD:
1151             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1152             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
1153                     byte_cnt);
1154 
1155             /* add subtrees to describe each group of packet */
1156             group_offset = payload_start + 1;
1157             for (ii = 0; ii < byte_cnt / 7; ii++) {
1158                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, 7,
1159                         ett_group_hdr, NULL, "Group %u", ii);
1160                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1161                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1162                 proto_tree_add_item(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, ENC_BIG_ENDIAN);
1163                 group_offset += 7;
1164             }
1165             break;
1166 
1167         case WRITE_FILE_RECORD:
1168             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1169             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1170 
1171             /* add subtrees to describe each group of packet */
1172             group_offset = payload_start + 1;
1173             ii = 0;
1174             while (byte_cnt > 0) {
1175                 group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
1176                 group_byte_cnt = (2 * group_word_cnt) + 7;
1177                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset,
1178                         group_byte_cnt, ett_group_hdr, NULL, "Group %u", ii);
1179                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1180                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1181                 proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, group_word_cnt);
1182                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7, pkt_info->register_format, reg_base, 0);
1183                 group_offset += group_byte_cnt;
1184                 byte_cnt -= group_byte_cnt;
1185                 ii++;
1186             }
1187             break;
1188 
1189         case MASK_WRITE_REG:
1190             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1191             proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1192             proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1193             break;
1194 
1195         case READ_WRITE_REG:
1196             proto_tree_add_item(modbus_tree, hf_modbus_readref, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1197             proto_tree_add_item(modbus_tree, hf_modbus_readwordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1198             proto_tree_add_item(modbus_tree, hf_modbus_writeref, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1199             proto_tree_add_item(modbus_tree, hf_modbus_writewordcnt, tvb, payload_start + 6, 2, ENC_BIG_ENDIAN);
1200             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start + 8);
1201             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start + 8, 1, byte_cnt);
1202             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 9, byte_cnt, pkt_info->register_format, reg_base, 0);
1203             break;
1204 
1205         case READ_FIFO_QUEUE:
1206             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1207             break;
1208 
1209         case ENCAP_INTERFACE_TRANSP:
1210             proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
1211             mei_code = tvb_get_guint8(tvb, payload_start);
1212             switch (mei_code)
1213             {
1214                 case READ_DEVICE_ID:
1215                     proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
1216                     proto_tree_add_item(modbus_tree, hf_modbus_object_id, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1217                     break;
1218 
1219                 case CANOPEN_REQ_RESP:
1220                     /* CANopen protocol not part of the Modbus/TCP specification */
1221                 default:
1222                     if (payload_len > 1)
1223                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, pkt_info->register_format, reg_base, 0);
1224                     break;
1225             }
1226 
1227             break;
1228 
1229         case REPORT_SLAVE_ID:
1230         default:
1231             if (payload_len > 0)
1232                 dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, pkt_info->register_format, reg_base, 0);
1233             break;
1234 
1235     } /* Function Code */
1236 
1237     return tvb_captured_length(tvb);
1238 }
1239 
1240 /* Code to dissect Modbus Response message */
1241 static int
dissect_modbus_response(tvbuff_t * tvb,packet_info * pinfo,proto_tree * modbus_tree,guint8 function_code,gint payload_start,gint payload_len,modbus_pkt_info_t * pkt_info)1242 dissect_modbus_response(tvbuff_t *tvb, packet_info *pinfo, proto_tree *modbus_tree, guint8 function_code, gint payload_start, gint payload_len, modbus_pkt_info_t *pkt_info)
1243 {
1244 
1245     proto_tree    *group_tree, *event_tree, *event_item_tree, *device_objects_tree, *device_objects_item_tree;
1246     proto_item    *mei;
1247     gint          byte_cnt, group_offset, event_index, object_index, object_len, num_objects, ii;
1248     guint8        object_type, mei_code, event_code;
1249     guint16       diagnostic_code, num_reg;
1250     guint32       group_byte_cnt, group_word_cnt;
1251 
1252     nstime_t      response_time;
1253     proto_item    *request_frame_item, *response_time_item;
1254 
1255     if (!pkt_info) {
1256         return 0;
1257     }
1258 
1259     num_reg = pkt_info->num_reg;
1260 
1261     if (pkt_info->request_found == TRUE) {
1262         request_frame_item = proto_tree_add_uint(modbus_tree, hf_modbus_request_frame, tvb, 0, 0, pkt_info->req_frame_num);
1263         proto_item_set_generated(request_frame_item);
1264 
1265         nstime_delta(&response_time, &pinfo->abs_ts, &pkt_info->req_time);
1266         response_time_item = proto_tree_add_time(modbus_tree, hf_modbus_response_time, tvb, 0, 0, &response_time);
1267         proto_item_set_generated(response_time_item);
1268     }
1269 
1270     switch (function_code) {
1271 
1272         case READ_COILS:
1273         case READ_DISCRETE_INPUTS:
1274             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1275             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1276             //if the request wasn't found set number of coils based on byte count
1277             if (!pkt_info->request_found)
1278                 num_reg = byte_cnt*8;
1279             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, pkt_info->register_format, pkt_info->reg_base, num_reg);
1280             break;
1281 
1282         case READ_HOLDING_REGS:
1283         case READ_INPUT_REGS:
1284             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1285             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1286             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, pkt_info->register_format, pkt_info->reg_base, 0);
1287             break;
1288 
1289         case WRITE_SINGLE_COIL:
1290             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1291             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 1, pkt_info->register_format, pkt_info->reg_base, 0);
1292             proto_tree_add_item(modbus_tree, hf_modbus_padding, tvb, payload_start + 3, 1, ENC_NA);
1293             break;
1294 
1295         case WRITE_SINGLE_REG:
1296             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1297             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 2, 2, pkt_info->register_format, pkt_info->reg_base, 0);
1298             break;
1299 
1300         case READ_EXCEPT_STAT:
1301             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, 1, pkt_info->register_format, pkt_info->reg_base, 0);
1302             break;
1303 
1304         case DIAGNOSTICS:
1305             diagnostic_code = tvb_get_ntohs(tvb, payload_start);
1306             proto_tree_add_uint(modbus_tree, hf_modbus_diag_sf, tvb, payload_start, 2, diagnostic_code);
1307             switch(diagnostic_code)
1308             {
1309                 case RETURN_QUERY_DATA: /* Echo of Request */
1310                     if (payload_len > 2)
1311                         proto_tree_add_item(modbus_tree, hf_modbus_diag_return_query_data_echo, tvb, payload_start+2, payload_len-2, ENC_NA);
1312                     break;
1313                 case RESTART_COMMUNICATION_OPTION:  /* Echo of Request */
1314                     proto_tree_add_item(modbus_tree, hf_modbus_diag_restart_communication_option, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1315                     break;
1316                 case RETURN_DIAGNOSTIC_REGISTER:
1317                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_diag_register, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1318                     break;
1319                 case CHANGE_ASCII_INPUT_DELIMITER:   /* XXX - Do we expect this to ever be a response? */
1320                     proto_tree_add_item(modbus_tree, hf_modbus_diag_ascii_input_delimiter, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1321                     break;
1322                 case CLEAR_COUNTERS_AND_DIAG_REG:   /* Echo of Request */
1323                     proto_tree_add_item(modbus_tree, hf_modbus_diag_clear_ctr_diag_reg, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1324                     break;
1325                 case RETURN_BUS_MESSAGE_COUNT:
1326                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1327                     break;
1328                 case RETURN_BUS_COMM_ERROR_COUNT:
1329                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_comm_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1330                     break;
1331                 case RETURN_BUS_EXCEPTION_ERROR_COUNT:
1332                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_exception_error_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1333                     break;
1334                 case RETURN_SLAVE_MESSAGE_COUNT:
1335                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_message_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1336                     break;
1337                 case RETURN_SLAVE_NO_RESPONSE_COUNT:
1338                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_no_slave_response_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1339                     break;
1340                 case RETURN_SLAVE_NAK_COUNT:
1341                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_nak_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1342                     break;
1343                 case RETURN_SLAVE_BUSY_COUNT:
1344                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_slave_busy_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1345                     break;
1346                 case RETURN_BUS_CHAR_OVERRUN_COUNT:
1347                     proto_tree_add_item(modbus_tree, hf_modbus_diag_return_bus_char_overrun_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1348                     break;
1349                 case CLEAR_OVERRUN_COUNTER_AND_FLAG:        /* Echo of Request */
1350                 case FORCE_LISTEN_ONLY_MODE:                /* No response anticipated */
1351                 default:
1352                     if (payload_len > 2)
1353                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start+2, payload_len-2, pkt_info->register_format, pkt_info->reg_base, 0);
1354                     break;
1355             } /* diagnostic_code */
1356             break;
1357 
1358         case GET_COMM_EVENT_CTRS:
1359             proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1360             proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+2, 2, ENC_BIG_ENDIAN);
1361             break;
1362 
1363         case GET_COMM_EVENT_LOG:
1364             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1365             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1366             proto_tree_add_item(modbus_tree, hf_modbus_status, tvb, payload_start+1, 2, ENC_BIG_ENDIAN);
1367             proto_tree_add_item(modbus_tree, hf_modbus_event_count, tvb, payload_start+3, 2, ENC_BIG_ENDIAN);
1368             proto_tree_add_item(modbus_tree, hf_modbus_message_count, tvb, payload_start+5, 2, ENC_BIG_ENDIAN);
1369             if (byte_cnt-6 > 0) {
1370                 byte_cnt -= 6;
1371                 event_index = 0;
1372                 event_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+7, byte_cnt, ett_events, NULL, "Events");
1373                 while (byte_cnt > 0) {
1374                     event_code = tvb_get_guint8(tvb, payload_start+7+event_index);
1375                     if (event_code == 0) {
1376                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Initiated Communication Restart");
1377                     }
1378                     else if (event_code == 4) {
1379                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Entered Listen Only Mode");
1380                     }
1381                     else if (event_code & REMOTE_DEVICE_RECV_EVENT_MASK) {
1382                         mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
1383                                     event_code, "Receive Event: 0x%02X", event_code);
1384                         event_item_tree = proto_item_add_subtree(mei, ett_events_recv);
1385 
1386                         /* add subtrees to describe each event bit */
1387                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_comm_err,
1388                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1389                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_char_over,
1390                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1391                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_lo_mode,
1392                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1393                         proto_tree_add_item(event_item_tree, hf_modbus_event_recv_broadcast,
1394                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1395                     }
1396                     else if ((event_code & REMOTE_DEVICE_SEND_EVENT_MASK) == REMOTE_DEVICE_SEND_EVENT_VALUE) {
1397                         mei = proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1,
1398                                     event_code, "Send Event: 0x%02X", event_code);
1399                         event_item_tree = proto_item_add_subtree(mei, ett_events_send);
1400 
1401                         /* add subtrees to describe each event bit */
1402                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_read_ex,
1403                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1404                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_abort_ex,
1405                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1406                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_busy_ex,
1407                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1408                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_slave_nak_ex,
1409                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1410                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_write_timeout,
1411                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1412                         proto_tree_add_item(event_item_tree, hf_modbus_event_send_lo_mode,
1413                           tvb, payload_start+7+event_index, 1, ENC_LITTLE_ENDIAN );
1414                     }
1415                     else {
1416                         proto_tree_add_uint_format(event_tree, hf_modbus_event, tvb, payload_start+7+event_index, 1, event_code, "Unknown Event");
1417                     }
1418 
1419                     byte_cnt--;
1420                     event_index++;
1421                 }
1422             }
1423             break;
1424 
1425         case WRITE_MULT_COILS:
1426             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1427             proto_tree_add_item(modbus_tree, hf_modbus_bitcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1428             break;
1429 
1430         case WRITE_MULT_REGS:
1431             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1432             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1433             break;
1434 
1435         case READ_FILE_RECORD:
1436             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1437             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1,
1438                     byte_cnt);
1439 
1440             /* add subtrees to describe each group of packet */
1441             group_offset = payload_start + 1;
1442             ii = 0;
1443             while (byte_cnt > 0) {
1444                 group_byte_cnt = (guint32)tvb_get_guint8(tvb, group_offset);
1445                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset, group_byte_cnt + 1,
1446                         ett_group_hdr, NULL, "Group %u", ii);
1447                 proto_tree_add_uint(group_tree, hf_modbus_bytecnt, tvb, group_offset, 1,
1448                         group_byte_cnt);
1449                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset + 1, 1, ENC_BIG_ENDIAN);
1450                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 2, group_byte_cnt - 1, pkt_info->register_format, pkt_info->reg_base, 0);
1451                 group_offset += (group_byte_cnt + 1);
1452                 byte_cnt -= (group_byte_cnt + 1);
1453                 ii++;
1454             }
1455             break;
1456 
1457         case WRITE_FILE_RECORD:   /* Normal response is echo of request */
1458             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1459             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1460 
1461             /* add subtrees to describe each group of packet */
1462             group_offset = payload_start + 1;
1463             ii = 0;
1464             while (byte_cnt > 0) {
1465                 group_word_cnt = tvb_get_ntohs(tvb, group_offset + 5);
1466                 group_byte_cnt = (2 * group_word_cnt) + 7;
1467                 group_tree = proto_tree_add_subtree_format( modbus_tree, tvb, group_offset,
1468                         group_byte_cnt, ett_group_hdr, NULL, "Group %u", ii);
1469                 proto_tree_add_item(group_tree, hf_modbus_reftype, tvb, group_offset, 1, ENC_BIG_ENDIAN);
1470                 proto_tree_add_item(group_tree, hf_modbus_lreference, tvb, group_offset + 1, 4, ENC_BIG_ENDIAN);
1471                 proto_tree_add_uint(group_tree, hf_modbus_wordcnt, tvb, group_offset + 5, 2, group_word_cnt);
1472                 dissect_modbus_data(tvb, pinfo, group_tree, function_code, group_offset + 7, group_byte_cnt - 7, pkt_info->register_format, pkt_info->reg_base, 0);
1473                 group_offset += group_byte_cnt;
1474                 byte_cnt -= group_byte_cnt;
1475                 ii++;
1476             }
1477             break;
1478 
1479         case MASK_WRITE_REG:      /* Normal response is echo of request */
1480             proto_tree_add_item(modbus_tree, hf_modbus_reference, tvb, payload_start, 2, ENC_BIG_ENDIAN);
1481             proto_tree_add_item(modbus_tree, hf_modbus_andmask, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1482             proto_tree_add_item(modbus_tree, hf_modbus_ormask, tvb, payload_start + 4, 2, ENC_BIG_ENDIAN);
1483             break;
1484 
1485         case READ_WRITE_REG:
1486             byte_cnt = (guint32)tvb_get_guint8(tvb, payload_start);
1487             proto_tree_add_uint(modbus_tree, hf_modbus_bytecnt, tvb, payload_start, 1, byte_cnt);
1488             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 1, byte_cnt, pkt_info->register_format, pkt_info->reg_base, 0);
1489             break;
1490 
1491         case READ_FIFO_QUEUE:
1492             byte_cnt = (guint32)tvb_get_ntohs(tvb, payload_start);
1493             proto_tree_add_uint(modbus_tree, hf_modbus_lbytecnt, tvb, payload_start, 2, byte_cnt);
1494             proto_tree_add_item(modbus_tree, hf_modbus_wordcnt, tvb, payload_start + 2, 2, ENC_BIG_ENDIAN);
1495             dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start + 4, byte_cnt - 2, pkt_info->register_format, pkt_info->reg_base, 0);
1496             break;
1497 
1498         case ENCAP_INTERFACE_TRANSP:
1499             proto_tree_add_item(modbus_tree, hf_modbus_mei, tvb, payload_start, 1, ENC_BIG_ENDIAN);
1500             mei_code = tvb_get_guint8(tvb, payload_start);
1501             switch (mei_code)
1502             {
1503                 case READ_DEVICE_ID:
1504                     proto_tree_add_item(modbus_tree, hf_modbus_read_device_id, tvb, payload_start+1, 1, ENC_BIG_ENDIAN);
1505                     proto_tree_add_item(modbus_tree, hf_modbus_conformity_level, tvb, payload_start+2, 1, ENC_BIG_ENDIAN);
1506                     proto_tree_add_item(modbus_tree, hf_modbus_more_follows, tvb, payload_start+3, 1, ENC_BIG_ENDIAN);
1507                     proto_tree_add_item(modbus_tree, hf_modbus_next_object_id, tvb, payload_start+4, 1, ENC_BIG_ENDIAN);
1508                     num_objects = tvb_get_guint8(tvb, payload_start+5);
1509                     proto_tree_add_uint(modbus_tree, hf_modbus_num_objects, tvb, payload_start+5, 1, num_objects);
1510                     device_objects_tree = proto_tree_add_subtree(modbus_tree, tvb, payload_start+6, payload_len-6,
1511                                                                     ett_device_id_objects, NULL, "Objects");
1512 
1513                     object_index = 0;
1514                     for (ii = 0; ii < num_objects; ii++)
1515                     {
1516                         /* add each "object item" as its own subtree */
1517 
1518                         /* compute length of object */
1519                         object_type = tvb_get_guint8(tvb, payload_start+6+object_index);
1520                         object_len = tvb_get_guint8(tvb, payload_start+6+object_index+1);
1521 
1522                         device_objects_item_tree = proto_tree_add_subtree_format(device_objects_tree, tvb, payload_start+6+object_index, 2+object_len,
1523                                                     ett_device_id_object_items, NULL, "Object #%d", ii+1);
1524 
1525                         proto_tree_add_item(device_objects_item_tree, hf_modbus_object_id, tvb, payload_start+6+object_index, 1, ENC_BIG_ENDIAN);
1526                         object_index++;
1527 
1528                         proto_tree_add_uint(device_objects_item_tree, hf_modbus_list_object_len, tvb, payload_start+6+object_index, 1, object_len);
1529                         object_index++;
1530 
1531                         if (object_type < 7)
1532                         {
1533                             proto_tree_add_item(device_objects_item_tree, hf_modbus_object_str_value, tvb, payload_start+6+object_index, object_len, ENC_ASCII|ENC_NA);
1534                         }
1535                         else
1536                         {
1537                             if (object_len > 0)
1538                                 proto_tree_add_item(device_objects_item_tree, hf_modbus_object_value, tvb, payload_start+6+object_index, object_len, ENC_NA);
1539                         }
1540                         object_index += object_len;
1541                     } /* for ii */
1542                     break;
1543 
1544                 case CANOPEN_REQ_RESP:
1545                     /* CANopen protocol not part of the Modbus/TCP specification */
1546                 default:
1547                     if (payload_len > 1)
1548                         dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len-1, pkt_info->register_format, pkt_info->reg_base, 0);
1549                     break;
1550             } /* mei_code */
1551             break;
1552 
1553         case REPORT_SLAVE_ID:
1554         default:
1555             if (payload_len > 0)
1556                 dissect_modbus_data(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, pkt_info->register_format, pkt_info->reg_base, 0);
1557             break;
1558 
1559     } /* function code */
1560 
1561     return tvb_captured_length(tvb);
1562 }
1563 
1564 
1565 /* Dissect the Modbus Payload.  Called from either Modbus/TCP or Modbus RTU Dissector */
1566 static int
dissect_modbus(tvbuff_t * tvb,packet_info * pinfo,proto_tree * tree,void * data)1567 dissect_modbus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1568 {
1569     proto_tree          *modbus_tree;
1570     proto_item          *mi;
1571     int                 offset = 0;
1572     modbus_data_t       *modbus_data = (modbus_data_t*)data;
1573     gint                payload_start, payload_len, len;
1574     guint8              function_code, exception_code;
1575     modbus_pkt_info_t   *pkt_info;
1576     guint32             conv_key;
1577 
1578     /* Reject the packet if data passed from the mbrtu or mbtcp dissector is NULL */
1579     if (modbus_data == NULL)
1580         return 0;
1581 
1582     len = tvb_captured_length(tvb);
1583 
1584     /* If the packet is zero-length, we should not attempt to dissect any further */
1585     if (len == 0)
1586         return 0;
1587 
1588     /* Add items to protocol tree specific to Modbus */
1589     mi = proto_tree_add_protocol_format(tree, proto_modbus, tvb, offset, len, "Modbus");
1590     modbus_tree = proto_item_add_subtree(mi, ett_modbus_hdr);
1591 
1592     function_code = tvb_get_guint8(tvb, offset) & 0x7F;
1593     proto_tree_add_item(modbus_tree, hf_modbus_functioncode, tvb, offset, 1, ENC_BIG_ENDIAN);
1594 
1595     /* Conversation support */
1596     /* Use a combination of unit and transaction-id as key for identifying a request to a response*/
1597     conv_key = (guint32)modbus_data->mbtcp_transid | ((guint32)modbus_data->unit_id << 16);
1598     if (!pinfo->fd->visited) {
1599         conversation_t       *conversation = NULL;
1600         modbus_conversation  *modbus_conv_data = NULL;
1601 
1602         /* Find a conversation, create a new if no one exists */
1603         conversation = find_or_create_conversation(pinfo);
1604         modbus_conv_data = (modbus_conversation *)conversation_get_proto_data(conversation, proto_modbus);
1605         pkt_info = wmem_new0(wmem_file_scope(), modbus_pkt_info_t);
1606 
1607         if (modbus_conv_data == NULL){
1608            modbus_conv_data = wmem_new(wmem_file_scope(), modbus_conversation);
1609            modbus_conv_data->modbus_request_frame_data = wmem_list_new(wmem_file_scope());
1610            modbus_conv_data->register_format = global_mbus_register_format;
1611            conversation_add_proto_data(conversation, proto_modbus, (void *)modbus_conv_data);
1612         }
1613 
1614         pkt_info->register_format = modbus_conv_data->register_format;
1615 
1616         if (modbus_data->packet_type == QUERY_PACKET) {
1617             /*create the modbus_request frame. It holds the request information.*/
1618             modbus_request_info_t    *frame_ptr = wmem_new0(wmem_file_scope(), modbus_request_info_t);
1619             gint captured_length = tvb_captured_length(tvb);
1620 
1621             /* load information into the modbus request frame */
1622             frame_ptr->fnum = pinfo->num;
1623             frame_ptr->function_code = function_code;
1624             frame_ptr->mbtcp_transid = modbus_data->mbtcp_transid;
1625             frame_ptr->unit_id = modbus_data->unit_id;
1626             if (captured_length >= 3) {
1627                 pkt_info->reg_base = frame_ptr->base_address = tvb_get_ntohs(tvb, 1);
1628                 if (captured_length >= 5)
1629                     pkt_info->num_reg = frame_ptr->num_reg = tvb_get_ntohs(tvb, 3);
1630             }
1631             frame_ptr->req_time = pinfo->abs_ts;
1632 
1633             wmem_list_prepend(modbus_conv_data->modbus_request_frame_data, frame_ptr);
1634         }
1635         else if (modbus_data->packet_type == RESPONSE_PACKET) {
1636             guint8                req_function_code;
1637             guint16               req_transaction_id;
1638             guint8                req_unit_id;
1639             guint32               req_frame_num;
1640             modbus_request_info_t *request_data;
1641 
1642             wmem_list_frame_t *frame = wmem_list_head(modbus_conv_data->modbus_request_frame_data);
1643             /* Step backward through all logged instances of request frames, looking for a request frame number that
1644             occurred immediately prior to current frame number that has a matching function code,
1645             unit-id and transaction identifier */
1646             while (frame && !pkt_info->request_found) {
1647                 request_data = (modbus_request_info_t *)wmem_list_frame_data(frame);
1648                 req_frame_num = request_data->fnum;
1649                 req_function_code = request_data->function_code;
1650                 req_transaction_id = request_data->mbtcp_transid;
1651                 req_unit_id = request_data->unit_id;
1652                 if ((pinfo->num > req_frame_num) && (req_function_code == function_code) &&
1653                     (req_transaction_id == modbus_data->mbtcp_transid) && (req_unit_id == modbus_data->unit_id)) {
1654                     pkt_info->reg_base = request_data->base_address;
1655                     pkt_info->num_reg = request_data->num_reg;
1656                     pkt_info->request_found = TRUE;
1657                     pkt_info->req_frame_num = req_frame_num;
1658                     pkt_info->req_time = request_data->req_time;
1659                 }
1660                 frame = wmem_list_frame_next(frame);
1661             }
1662 
1663 
1664         }
1665         p_add_proto_data(wmem_file_scope(), pinfo, proto_modbus, conv_key, pkt_info);
1666 
1667     }
1668     else { /* !visited */
1669         pkt_info = (modbus_pkt_info_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_modbus, conv_key);
1670     }
1671 
1672 
1673     /* Find exception - last bit set in function code */
1674     if (tvb_get_guint8(tvb, offset) & 0x80 ) {
1675         exception_code = tvb_get_guint8(tvb, offset+1);
1676     }
1677     else {
1678         exception_code = 0;
1679     }
1680 
1681     payload_start = offset + 1;
1682     payload_len = len - 1;
1683 
1684     if (exception_code != 0) {
1685         proto_item_set_text(mi, "Function %u:  %s.  Exception: %s",
1686                             function_code,
1687                             val_to_str_const(function_code, function_code_vals, "Unknown Function"),
1688                             val_to_str(exception_code,
1689                                        exception_code_vals,
1690                                        "Unknown Exception Code (%u)"));
1691         proto_tree_add_uint(modbus_tree, hf_modbus_exceptioncode, tvb, payload_start, 1,
1692                             exception_code);
1693     }
1694     else {
1695 
1696         /* Follow different dissection path depending on whether packet is query or response */
1697         if (modbus_data->packet_type == QUERY_PACKET) {
1698             dissect_modbus_request(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, pkt_info);
1699         }
1700         else if (modbus_data->packet_type == RESPONSE_PACKET) {
1701             dissect_modbus_response(tvb, pinfo, modbus_tree, function_code, payload_start, payload_len, pkt_info);
1702         }
1703 
1704     }
1705 
1706     return tvb_captured_length(tvb);
1707 }
1708 
1709 static void
apply_mbtcp_prefs(void)1710 apply_mbtcp_prefs(void)
1711 {
1712     /* Modbus/RTU uses the port preference to determine request/response */
1713     global_mbus_tcp_port = prefs_get_uint_value("mbtcp", "tcp.port");
1714     global_mbus_udp_port = prefs_get_uint_value("mbudp", "udp.port");
1715     global_mbus_tls_port = prefs_get_uint_value("mbtcp", "tls.port");
1716 }
1717 
1718 static void
apply_mbrtu_prefs(void)1719 apply_mbrtu_prefs(void)
1720 {
1721     /* Modbus/RTU uses the port preference to determine request/response */
1722     global_mbus_tcp_rtu_port = prefs_get_uint_value("mbrtu", "tcp.port");
1723     global_mbus_udp_rtu_port = prefs_get_uint_value("mbrtu", "udp.port");
1724 }
1725 
1726 /* Register the protocol with Wireshark */
1727 void
proto_register_modbus(void)1728 proto_register_modbus(void)
1729 {
1730     /* Modbus/TCP header fields */
1731     static hf_register_info mbtcp_hf[] = {
1732         { &hf_mbtcp_transid,
1733             { "Transaction Identifier", "mbtcp.trans_id",
1734             FT_UINT16, BASE_DEC, NULL, 0x0,
1735             NULL, HFILL }
1736         },
1737         { &hf_mbtcp_protid,
1738             { "Protocol Identifier", "mbtcp.prot_id",
1739             FT_UINT16, BASE_DEC, NULL, 0x0,
1740             NULL, HFILL }
1741         },
1742         { &hf_mbtcp_len,
1743             { "Length", "mbtcp.len",
1744             FT_UINT16, BASE_DEC, NULL, 0x0,
1745             NULL, HFILL }
1746         },
1747         { &hf_mbtcp_unitid,
1748             { "Unit Identifier", "mbtcp.unit_id",
1749             FT_UINT8, BASE_DEC, NULL, 0x0,
1750             NULL, HFILL }
1751         },
1752     };
1753 
1754     static ei_register_info mbtcp_ei[] = {
1755         { &ei_mbtcp_cannot_classify,
1756           { "mbtcp.cannot_classify", PI_PROTOCOL, PI_WARN,
1757             "Cannot classify packet type. Try setting Modbus/TCP Port preference to this destination or source port", EXPFILL }
1758         },
1759     };
1760 
1761     /* Modbus RTU header fields */
1762     static hf_register_info mbrtu_hf[] = {
1763         { &hf_mbrtu_unitid,
1764             { "Unit ID", "mbrtu.unit_id",
1765             FT_UINT8, BASE_DEC, NULL, 0x0,
1766             NULL, HFILL }
1767         },
1768         { &hf_mbrtu_crc16,
1769             { "CRC-16", "mbrtu.crc16",
1770             FT_UINT16, BASE_HEX, NULL, 0x0,
1771             NULL, HFILL }
1772         },
1773         { &hf_mbrtu_crc16_status,
1774             { "CRC-16 Status", "mbrtu.crc16.status",
1775             FT_UINT8, BASE_NONE, VALS(proto_checksum_vals), 0x0,
1776             NULL, HFILL }
1777         },
1778     };
1779 
1780     static ei_register_info mbrtu_ei[] = {
1781         { &ei_mbrtu_crc16_incorrect,
1782           { "mbrtu.crc16.incorrect", PI_CHECKSUM, PI_WARN,
1783             "Incorrect CRC", EXPFILL }
1784         },
1785     };
1786 
1787     /* Modbus header fields */
1788     static hf_register_info hf[] = {
1789         { &hf_modbus_request_frame,
1790             { "Request Frame", "modbus.request_frame",
1791             FT_FRAMENUM, BASE_NONE,
1792             NULL, 0x0,
1793             NULL, HFILL }
1794         },
1795         { &hf_modbus_response_time,
1796             { "Time from request", "modbus.response_time",
1797             FT_RELATIVE_TIME, BASE_NONE,
1798             NULL, 0x0,
1799             "Time between request and reply", HFILL }
1800         },
1801         { &hf_modbus_functioncode,
1802             { "Function Code", "modbus.func_code",
1803             FT_UINT8, BASE_DEC, VALS(function_code_vals), 0x7F,
1804             NULL, HFILL }
1805         },
1806         { &hf_modbus_reference,
1807             { "Reference Number", "modbus.reference_num",
1808             FT_UINT16, BASE_DEC, NULL, 0x0,
1809             NULL, HFILL }
1810         },
1811         { &hf_modbus_padding,
1812             { "Padding", "modbus.padding",
1813             FT_UINT8, BASE_HEX, NULL, 0x0,
1814             NULL, HFILL }
1815         },
1816         { &hf_modbus_lreference,
1817             { "Reference Number (32 bit)", "modbus.reference_num_32",
1818             FT_UINT32, BASE_DEC, NULL, 0x0,
1819             NULL, HFILL }
1820         },
1821         { &hf_modbus_reftype,
1822             { "Reference Type", "modbus.reference_type",
1823             FT_UINT8, BASE_DEC, NULL, 0x0,
1824             NULL, HFILL }
1825         },
1826         { &hf_modbus_readref,
1827             { "Read Reference Number", "modbus.read_reference_num",
1828             FT_UINT16, BASE_DEC, NULL, 0x0,
1829             NULL, HFILL }
1830         },
1831         { &hf_modbus_writeref,
1832             { "Write Reference Number", "modbus.write_reference_num",
1833             FT_UINT16, BASE_DEC, NULL, 0x0,
1834             NULL, HFILL }
1835         },
1836         { &hf_modbus_wordcnt,
1837             { "Word Count", "modbus.word_cnt",
1838             FT_UINT16, BASE_DEC, NULL, 0x0,
1839             NULL, HFILL }
1840         },
1841         { &hf_modbus_readwordcnt,
1842             { "Read Word Count", "modbus.read_word_cnt",
1843             FT_UINT16, BASE_DEC, NULL, 0x0,
1844             NULL, HFILL }
1845         },
1846         { &hf_modbus_writewordcnt,
1847             { "Write Word Count", "modbus.write_word_cnt",
1848             FT_UINT16, BASE_DEC, NULL, 0x0,
1849             NULL, HFILL }
1850         },
1851         { &hf_modbus_bitcnt,
1852             { "Bit Count", "modbus.bit_cnt",
1853             FT_UINT16, BASE_DEC, NULL, 0x0,
1854             NULL, HFILL }
1855         },
1856         { &hf_modbus_bytecnt,
1857             { "Byte Count", "modbus.byte_cnt",
1858             FT_UINT8, BASE_DEC, NULL, 0x0,
1859             NULL, HFILL }
1860         },
1861         { &hf_modbus_lbytecnt,
1862             { "Byte Count (16-bit)", "modbus.byte_cnt_16",
1863             FT_UINT8, BASE_DEC, NULL, 0x0,
1864             NULL, HFILL }
1865         },
1866         { &hf_modbus_exceptioncode,
1867             { "Exception Code", "modbus.exception_code",
1868             FT_UINT8, BASE_DEC, VALS(exception_code_vals), 0x0,
1869             NULL, HFILL }
1870         },
1871         { &hf_modbus_diag_sf,
1872             { "Diagnostic Code", "modbus.diagnostic_code",
1873             FT_UINT16, BASE_DEC, VALS(diagnostic_code_vals), 0x0,
1874             NULL, HFILL }
1875         },
1876         { &hf_modbus_diag_return_query_data_request,
1877             { "Request Data", "modbus.diagnostic.return_query_data.request",
1878             FT_BYTES, BASE_NONE, NULL, 0x0,
1879             NULL, HFILL }
1880         },
1881         { &hf_modbus_diag_return_query_data_echo,
1882             { "Echo Data", "modbus.diagnostic.return_query_data.echo",
1883             FT_BYTES, BASE_NONE, NULL, 0x0,
1884             NULL, HFILL }
1885         },
1886         { &hf_modbus_diag_restart_communication_option,
1887             { "Restart Communication Option", "modbus.diagnostic.restart_communication_option",
1888             FT_UINT16, BASE_HEX, VALS(diagnostic_restart_communication_option_vals), 0x0,
1889             NULL, HFILL }
1890         },
1891         { &hf_modbus_diag_return_diag_register,
1892             { "Diagnostic Register Contents", "modbus.diagnostic.return_diag_register",
1893             FT_UINT16, BASE_HEX, NULL, 0x0,
1894             NULL, HFILL }
1895         },
1896         { &hf_modbus_diag_ascii_input_delimiter,
1897             { "CHAR", "modbus.diagnostic.ascii_input_delimiter",
1898             FT_UINT8, BASE_HEX, NULL, 0x0,
1899             NULL, HFILL }
1900         },
1901         { &hf_modbus_diag_clear_ctr_diag_reg,
1902             { "Clear Counters & Diag Register Echo", "modbus.diagnostic.clear_ctr_diag_reg",
1903             FT_UINT16, BASE_DEC, NULL, 0x0,
1904             NULL, HFILL }
1905         },
1906         { &hf_modbus_diag_return_bus_message_count,
1907             { "Total Message Count", "modbus.diagnostic.bus_message_count",
1908             FT_UINT16, BASE_DEC, NULL, 0x0,
1909             NULL, HFILL }
1910         },
1911         { &hf_modbus_diag_return_bus_comm_error_count,
1912             { "CRC Error Count", "modbus.diagnostic.bus_comm_error_count",
1913             FT_UINT16, BASE_DEC, NULL, 0x0,
1914             NULL, HFILL }
1915         },
1916         { &hf_modbus_diag_return_bus_exception_error_count,
1917             { "Exception Error Count", "modbus.diagnostic.bus_exception_error_count",
1918             FT_UINT16, BASE_DEC, NULL, 0x0,
1919             NULL, HFILL }
1920         },
1921         { &hf_modbus_diag_return_slave_message_count,
1922             { "Slave Message Count", "modbus.diagnostic.slave_message_count",
1923             FT_UINT16, BASE_DEC, NULL, 0x0,
1924             NULL, HFILL }
1925         },
1926         { &hf_modbus_diag_return_no_slave_response_count,
1927             { "Slave No Response Count", "modbus.diagnostic.no_slave_response_count",
1928             FT_UINT16, BASE_DEC, NULL, 0x0,
1929             NULL, HFILL }
1930         },
1931         { &hf_modbus_diag_return_slave_nak_count,
1932             { "Slave NAK Count", "modbus.diagnostic.slave_nak_count",
1933             FT_UINT16, BASE_DEC, NULL, 0x0,
1934             NULL, HFILL }
1935         },
1936         { &hf_modbus_diag_return_slave_busy_count,
1937             { "Slave Device Busy Count", "modbus.diagnostic.slave_busy_count",
1938             FT_UINT16, BASE_DEC, NULL, 0x0,
1939             NULL, HFILL }
1940         },
1941         { &hf_modbus_diag_return_bus_char_overrun_count,
1942             { "Slave Character Overrun Count", "modbus.diagnostic.bus_char_overrun_count",
1943             FT_UINT16, BASE_DEC, NULL, 0x0,
1944             NULL, HFILL }
1945         },
1946         { &hf_modbus_status,
1947             { "Status", "modbus.ev_status",
1948             FT_UINT16, BASE_HEX, NULL, 0x0,
1949             NULL, HFILL }
1950         },
1951         { &hf_modbus_event,
1952             { "Event", "modbus.event",
1953             FT_UINT8, BASE_DEC, NULL, 0x0,
1954             NULL, HFILL }
1955         },
1956         { &hf_modbus_event_count,
1957             { "Event Count", "modbus.ev_count",
1958             FT_UINT16, BASE_DEC, NULL, 0x0,
1959             NULL, HFILL }
1960         },
1961         { &hf_modbus_message_count,
1962             { "Message Count", "modbus.ev_msg_count",
1963             FT_UINT16, BASE_DEC, NULL, 0x0,
1964             NULL, HFILL }
1965         },
1966         { &hf_modbus_event_recv_comm_err,
1967             { "Communication Error", "modbus.ev_recv_comm_err",
1968             FT_UINT8, BASE_DEC, NULL, 0x02,
1969             NULL, HFILL }
1970         },
1971         { &hf_modbus_event_recv_char_over,
1972             { "Character Overrun", "modbus.ev_recv_char_over",
1973             FT_UINT8, BASE_DEC, NULL, 0x10,
1974             NULL, HFILL }
1975         },
1976         { &hf_modbus_event_recv_lo_mode,
1977             { "Currently in Listen Only Mode", "modbus.ev_recv_lo_mode",
1978             FT_UINT8, BASE_DEC, NULL, 0x20,
1979             NULL, HFILL }
1980         },
1981         { &hf_modbus_event_recv_broadcast,
1982             { "Broadcast Received", "modbus.ev_recv_broadcast",
1983             FT_UINT8, BASE_DEC, NULL, 0x40,
1984             NULL, HFILL }
1985         },
1986         { &hf_modbus_event_send_read_ex,
1987             { "Read Exception Sent", "modbus.ev_send_read_ex",
1988             FT_UINT8, BASE_DEC, NULL, 0x01,
1989             NULL, HFILL }
1990         },
1991         { &hf_modbus_event_send_slave_abort_ex,
1992             { "Slave Abort Exception Sent", "modbus.ev_send_slave_abort_ex",
1993             FT_UINT8, BASE_DEC, NULL, 0x02,
1994             NULL, HFILL }
1995         },
1996         { &hf_modbus_event_send_slave_busy_ex,
1997             { "Slave Busy Exception Sent", "modbus.ev_send_slave_busy_ex",
1998             FT_UINT8, BASE_DEC, NULL, 0x04,
1999             NULL, HFILL }
2000         },
2001         { &hf_modbus_event_send_slave_nak_ex,
2002             { "Slave Program NAK Exception Sent", "modbus.ev_send_slave_nak_ex",
2003             FT_UINT8, BASE_DEC, NULL, 0x08,
2004             NULL, HFILL }
2005         },
2006         { &hf_modbus_event_send_write_timeout,
2007             { "Write Timeout Error Occurred", "modbus.ev_send_write_timeout",
2008             FT_UINT8, BASE_DEC, NULL, 0x10,
2009             NULL, HFILL }
2010         },
2011         { &hf_modbus_event_send_lo_mode,
2012             { "Currently in Listen Only Mode", "modbus.ev_send_lo_mode",
2013             FT_UINT8, BASE_DEC, NULL, 0x20,
2014             NULL, HFILL }
2015         },
2016         { &hf_modbus_andmask,
2017             { "AND mask", "modbus.and_mask",
2018             FT_UINT16, BASE_HEX, NULL, 0x0,
2019             NULL, HFILL }
2020         },
2021         { &hf_modbus_ormask,
2022             { "OR mask", "modbus.or_mask",
2023             FT_UINT16, BASE_HEX, NULL, 0x0,
2024             NULL, HFILL }
2025         },
2026         { &hf_modbus_data,
2027             { "Data",  "modbus.data",
2028             FT_BYTES,  BASE_NONE, NULL,    0x0, NULL, HFILL }
2029         },
2030         { &hf_modbus_mei,
2031             { "MEI type", "modbus.mei",
2032             FT_UINT8, BASE_DEC, VALS(encap_interface_code_vals), 0x0,
2033             NULL, HFILL }
2034         },
2035         { &hf_modbus_read_device_id,
2036             { "Read Device ID", "modbus.read_device_id",
2037             FT_UINT8, BASE_DEC, VALS(read_device_id_vals), 0x0,
2038             NULL, HFILL }
2039         },
2040         { &hf_modbus_object_id,
2041             { "Object ID", "modbus.object_id",
2042             FT_UINT8, BASE_DEC, VALS(object_id_vals), 0x0,
2043             NULL, HFILL }
2044         },
2045         { &hf_modbus_num_objects,
2046             { "Number of Objects", "modbus.num_objects",
2047             FT_UINT8, BASE_DEC, NULL, 0x0,
2048             NULL, HFILL }
2049         },
2050         { &hf_modbus_list_object_len,
2051             { "Object length", "modbus.objects_len",
2052             FT_UINT8, BASE_DEC, NULL, 0x0,
2053             NULL, HFILL }
2054         },
2055         { &hf_modbus_conformity_level,
2056             { "Conformity Level", "modbus.conformity_level",
2057             FT_UINT8, BASE_HEX, VALS(conformity_level_vals), 0x0,
2058             NULL, HFILL }
2059         },
2060         { &hf_modbus_more_follows,
2061             { "More Follows", "modbus.more_follows",
2062             FT_UINT8, BASE_HEX, NULL, 0x0,
2063             NULL, HFILL }
2064         },
2065         { &hf_modbus_next_object_id,
2066             { "Next Object ID", "modbus.next_object_id",
2067             FT_UINT8, BASE_DEC, NULL, 0x0,
2068             NULL, HFILL }
2069         },
2070         { &hf_modbus_object_str_value,
2071             { "Object String Value", "modbus.object_str_value",
2072             FT_STRING, BASE_NONE, NULL, 0x0,
2073             NULL, HFILL }
2074         },
2075         { &hf_modbus_object_value,
2076             { "Object Value", "modbus.object_value",
2077             FT_BYTES, BASE_NONE, NULL, 0x0,
2078             NULL, HFILL }
2079         },
2080         { &hf_modbus_bitnum,
2081             { "Bit Number", "modbus.bitnum",
2082             FT_UINT16, BASE_DEC, NULL, 0x0,
2083             NULL, HFILL }
2084         },
2085         { &hf_modbus_bitval,
2086             { "Bit Value", "modbus.bitval",
2087             FT_BOOLEAN, 8, NULL, 0x01,
2088             NULL, HFILL }
2089         },
2090         { &hf_modbus_regnum16,
2091             { "Register Number", "modbus.regnum16",
2092             FT_UINT16, BASE_DEC, NULL, 0x0,
2093             NULL, HFILL }
2094         },
2095         { &hf_modbus_regnum32,
2096             { "Register Number", "modbus.regnum32",
2097             FT_UINT32, BASE_DEC, NULL, 0x0,
2098             NULL, HFILL }
2099         },
2100         { &hf_modbus_regval_uint16,
2101             { "Register Value (UINT16)", "modbus.regval_uint16",
2102             FT_UINT16, BASE_DEC, NULL, 0x0,
2103             NULL, HFILL }
2104         },
2105         { &hf_modbus_regval_int16,
2106             { "Register Value (INT16)", "modbus.regval_int16",
2107             FT_INT16, BASE_DEC, NULL, 0x0,
2108             NULL, HFILL }
2109         },
2110         { &hf_modbus_regval_uint32,
2111             { "Register Value (UINT32)", "modbus.regval_uint32",
2112             FT_UINT32, BASE_DEC, NULL, 0x0,
2113             NULL, HFILL }
2114         },
2115         { &hf_modbus_regval_int32,
2116             { "Register Value (INT32)", "modbus.regval_int32",
2117             FT_INT32, BASE_DEC, NULL, 0x0,
2118             NULL, HFILL }
2119         },
2120         { &hf_modbus_regval_ieee_float,
2121             { "Register Value (IEEE Float)", "modbus.regval_float",
2122             FT_FLOAT, BASE_NONE, NULL, 0x0,
2123             NULL, HFILL }
2124         },
2125         { &hf_modbus_regval_modicon_float,
2126             { "Register Value (Modicon Float)", "modbus.regval_float",
2127             FT_FLOAT, BASE_NONE, NULL, 0x0,
2128             NULL, HFILL }
2129         },
2130         };
2131 
2132     /* Setup protocol subtree array */
2133     static gint *ett[] = {
2134         &ett_mbtcp,
2135         &ett_mbrtu,
2136         &ett_modbus_hdr,
2137         &ett_group_hdr,
2138         &ett_events,
2139         &ett_events_recv,
2140         &ett_events_send,
2141         &ett_device_id_objects,
2142         &ett_device_id_object_items,
2143         &ett_bit,
2144         &ett_register
2145     };
2146 
2147     static ei_register_info ei[] = {
2148         { &ei_modbus_data_decode,
2149           { "modbus.data.decode", PI_PROTOCOL, PI_WARN,
2150             "Invalid decoding options, register data not a multiple of 4!", EXPFILL }
2151         },
2152     };
2153     module_t *mbtcp_module;
2154     module_t *mbrtu_module;
2155     module_t *modbus_module;
2156     expert_module_t* expert_mbtcp;
2157     expert_module_t* expert_mbrtu;
2158     expert_module_t* expert_modbus;
2159 
2160     /* Register the protocol name and description */
2161     proto_mbtcp = proto_register_protocol("Modbus/TCP", "Modbus/TCP", "mbtcp");
2162     proto_mbudp = proto_register_protocol("Modbus/UDP", "Modbus/UDP", "mbudp");
2163     proto_mbrtu = proto_register_protocol("Modbus RTU", "Modbus RTU", "mbrtu");
2164     proto_modbus = proto_register_protocol("Modbus", "Modbus", "modbus");
2165 
2166     /* Registering protocol to be called by another dissector */
2167     modbus_handle = register_dissector("modbus", dissect_modbus, proto_modbus);
2168     mbtcp_handle = register_dissector("mbtcp", dissect_mbtcp, proto_mbtcp);
2169     mbtls_handle = register_dissector("mbtls", dissect_mbtls, proto_mbtcp);
2170     mbrtu_handle = register_dissector("mbrtu", dissect_mbrtu, proto_mbrtu);
2171     mbudp_handle = register_dissector("mbudp", dissect_mbudp, proto_mbudp);
2172 
2173     /* Registering subdissectors table */
2174     modbus_data_dissector_table = register_dissector_table("modbus.data", "Modbus Data", proto_modbus, FT_STRING, BASE_NONE);
2175     modbus_dissector_table = register_dissector_table("mbtcp.prot_id", "Modbus/TCP protocol identifier", proto_mbtcp, FT_UINT16, BASE_DEC);
2176 
2177     /* Required function calls to register the header fields and subtrees used */
2178     proto_register_field_array(proto_mbtcp, mbtcp_hf, array_length(mbtcp_hf));
2179     proto_register_field_array(proto_mbrtu, mbrtu_hf, array_length(mbrtu_hf));
2180     proto_register_field_array(proto_modbus, hf, array_length(hf));
2181     proto_register_subtree_array(ett, array_length(ett));
2182     expert_mbtcp = expert_register_protocol(proto_mbtcp);
2183     expert_register_field_array(expert_mbtcp, mbtcp_ei, array_length(mbtcp_ei));
2184     expert_mbrtu = expert_register_protocol(proto_mbrtu);
2185     expert_register_field_array(expert_mbrtu, mbrtu_ei, array_length(mbrtu_ei));
2186     expert_modbus = expert_register_protocol(proto_modbus);
2187     expert_register_field_array(expert_modbus, ei, array_length(ei));
2188 
2189 
2190     /* Register required preferences for Modbus Protocol variants */
2191     mbtcp_module = prefs_register_protocol(proto_mbtcp, apply_mbtcp_prefs);
2192     mbrtu_module = prefs_register_protocol(proto_mbrtu, apply_mbrtu_prefs);
2193     modbus_module = prefs_register_protocol(proto_modbus, NULL);
2194 
2195     /* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
2196     prefs_register_bool_preference(mbtcp_module, "desegment",
2197                                   "Desegment all Modbus RTU packets spanning multiple TCP segments",
2198                                   "Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
2199                                   &mbtcp_desegment);
2200 
2201     /* Modbus RTU Preference - Desegment, defaults to TRUE for TCP desegmentation */
2202     prefs_register_bool_preference(mbrtu_module, "desegment",
2203                                   "Desegment all Modbus RTU packets spanning multiple TCP segments",
2204                                   "Whether the Modbus RTU dissector should desegment all messages spanning multiple TCP segments",
2205                                   &mbrtu_desegment);
2206 
2207     /* Modbus RTU Preference - CRC verification, defaults to FALSE (no verification)*/
2208     prefs_register_bool_preference(mbrtu_module, "crc_verification",
2209                                   "Validate CRC",
2210                                   "Whether to validate the CRC",
2211                                   &mbrtu_crc);
2212 
2213     /* Modbus Preference - Holding/Input Register format, this allows for deeper dissection of response data */
2214     prefs_register_enum_preference(modbus_module, "mbus_register_format",
2215                                     "Holding/Input Register Format",
2216                                     "Register Format",
2217                                     &global_mbus_register_format,
2218                                     mbus_register_format,
2219                                     FALSE);
2220 
2221     /* Obsolete Preferences */
2222     prefs_register_obsolete_preference(mbtcp_module, "mbus_register_addr_type");
2223     prefs_register_obsolete_preference(mbtcp_module, "mbus_register_format");
2224     prefs_register_obsolete_preference(mbrtu_module, "mbus_register_addr_type");
2225     prefs_register_obsolete_preference(mbrtu_module, "mbus_register_format");
2226 
2227 }
2228 
2229 
2230 /* If this dissector uses sub-dissector registration add a registration routine.
2231    This format is required because a script is used to find these routines and
2232    create the code that calls these routines.
2233  */
2234 void
proto_reg_handoff_mbtcp(void)2235 proto_reg_handoff_mbtcp(void)
2236 {
2237     dissector_add_uint_with_preference("tcp.port", PORT_MBTCP, mbtcp_handle);
2238     dissector_add_uint_with_preference("udp.port", PORT_MBTCP, mbudp_handle);
2239     dissector_add_uint_with_preference("tls.port", PORT_MBTLS, mbtls_handle);
2240     apply_mbtcp_prefs();
2241 
2242     dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
2243 
2244     ssl_dissector_add(PORT_MBTLS, mbtls_handle);
2245 }
2246 
2247 void
proto_reg_handoff_mbrtu(void)2248 proto_reg_handoff_mbrtu(void)
2249 {
2250     dissector_handle_t mbrtu_udp_handle = create_dissector_handle(dissect_mbrtu_udp, proto_mbrtu);
2251 
2252     /* Make sure to use Modbus RTU Preferences field to determine default TCP port */
2253     dissector_add_for_decode_as_with_preference("udp.port", mbrtu_udp_handle);
2254     dissector_add_for_decode_as_with_preference("tcp.port", mbrtu_handle);
2255     apply_mbrtu_prefs();
2256 
2257     dissector_add_uint("mbtcp.prot_id", MODBUS_PROTOCOL_ID, modbus_handle);
2258     dissector_add_for_decode_as("rtacser.data", mbrtu_handle);
2259     dissector_add_for_decode_as("usb.device", mbrtu_handle);
2260     dissector_add_for_decode_as("usb.product", mbrtu_handle);
2261     dissector_add_for_decode_as("usb.protocol", mbrtu_handle);
2262 
2263 }
2264 
2265 /*
2266  * Editor modelines
2267  *
2268  * Local Variables:
2269  * c-basic-offset: 4
2270  * tab-width: 8
2271  * indent-tabs-mode: nil
2272  * End:
2273  *
2274  * ex: set shiftwidth=4 tabstop=8 expandtab:
2275  * :indentSize=4:tabSize=8:noTabs=true:
2276  */
2277