aboutsummaryrefslogtreecommitdiffstats
path: root/plugins/epan/opcua/opcua.c
blob: 2f0dd80ecfac544c359f2ed0646eb8a258f1858e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
/******************************************************************************
** Copyright (C) 2006-2007 ascolab GmbH. All Rights Reserved.
** Web: http://www.ascolab.com
**
** SPDX-License-Identifier: GPL-2.0-or-later
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** Project: OpcUa Wireshark Plugin
**
** Description: OpcUa Protocol Decoder.
**
** Author: Gerhard Gappmeier <gerhard.gappmeier@ascolab.com>
******************************************************************************/

#include <epan/dissectors/packet-tcp.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/range.h>
#include <epan/reassemble.h>
#include <epan/tvbuff.h>
#include <gcrypt.h>
#include <wsutil/file_util.h>

#include "config.h"
#include "opcua_application_layer.h"
#include "opcua_complextypeparser.h"
#include "opcua_enumparser.h"
#include "opcua_hfindeces.h"
#include "opcua_keyset.h"
#include "opcua_security_layer.h"
#include "opcua_serviceparser.h"
#include "opcua_serviceids.h"
#include "opcua_simpletypes.h"
#include "opcua_transport_layer.h"

void proto_register_opcua(void);

extern const value_string g_requesttypes[];
extern const int g_NumServices;
static const gchar *g_opcua_debug_file_name = NULL;

/* forward reference */
void proto_reg_handoff_opcua(void);
/* declare parse function pointer */
typedef int (*FctParse)(proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, gint *pOffset, struct ua_metadata *data);

int proto_opcua = -1;
static dissector_handle_t opcua_handle;
static module_t *opcua_module;

/* #define OPCUA_DEBUG */
#ifdef OPCUA_DEBUG
# define debugprintf(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__);
#else
# define debugprintf(fmt, ...)
#endif

/** Official IANA registered port for OPC UA Binary Protocol. */
#define OPCUA_DEFAULT_PORT 4840
/* default port range for preferences */
#define OPCUA_PORT_RANGE "4840"
/** header length that is needed to compute the pdu length.
  * @see get_opcua_message_len
  */
#define FRAME_HEADER_LEN 8
/* AES block size: for both AES128 and AES256 the block size is 128 bits */
#define AES_BLOCK_SIZE 16

/** subtree types used in opcua_transport_layer.c */
gint ett_opcua_extensionobject = -1;
gint ett_opcua_nodeid = -1;

/** subtree types used locally */
static gint ett_opcua_transport = -1;
static gint ett_opcua_fragment = -1;
static gint ett_opcua_fragments = -1;

static int hf_opcua_fragments = -1;
static int hf_opcua_fragment = -1;
static int hf_opcua_fragment_overlap = -1;
static int hf_opcua_fragment_overlap_conflicts = -1;
static int hf_opcua_fragment_multiple_tails = -1;
static int hf_opcua_fragment_too_long_fragment = -1;
static int hf_opcua_fragment_error = -1;
static int hf_opcua_fragment_count = -1;
static int hf_opcua_reassembled_in = -1;
static int hf_opcua_reassembled_length = -1;

static const fragment_items opcua_frag_items = {
    /* Fragment subtrees */
    &ett_opcua_fragment,
    &ett_opcua_fragments,
    /* Fragment fields */
    &hf_opcua_fragments,
    &hf_opcua_fragment,
    &hf_opcua_fragment_overlap,
    &hf_opcua_fragment_overlap_conflicts,
    &hf_opcua_fragment_multiple_tails,
    &hf_opcua_fragment_too_long_fragment,
    &hf_opcua_fragment_error,
    &hf_opcua_fragment_count,
    /* Reassembled in field */
    &hf_opcua_reassembled_in,
    /* Reassembled length field */
    &hf_opcua_reassembled_length,
    /* Reassembled data field */
    NULL,
    /* Tag */
    "Message fragments"
};


static reassembly_table opcua_reassembly_table;

/** OpcUa Transport Message Types */
enum MessageType
{
    MSG_HELLO = 0,
    MSG_ACKNOWLEDGE,
    MSG_ERROR,
    MSG_REVERSEHELLO,
    MSG_MESSAGE,
    MSG_OPENSECURECHANNEL,
    MSG_CLOSESECURECHANNEL,
    MSG_INVALID
};

/** OpcUa Transport Message Type Names */
static const char* g_szMessageTypes[] =
{
    "Hello message",
    "Acknowledge message",
    "Error message",
    "Reverse Hello message",
    "UA Secure Conversation Message",
    "OpenSecureChannel message",
    "CloseSecureChannel message",
    "Invalid message"
};

/** returns the length of an OpcUa message.
  * This function reads the length information from
  * the transport header.
  */
static guint get_opcua_message_len(packet_info *pinfo _U_, tvbuff_t *tvb,
                                   int offset, void *data _U_)
{
    gint32 plen;

    /* the message length starts at offset 4 */
    plen = tvb_get_letohl(tvb, offset + 4);

    return plen;
}

/* Helper function to convert hex string to binary data */
guint hex_to_bin(const char *hex_string, unsigned char *binary_data, unsigned int binary_size)
{
    guint length = (guint)strlen(hex_string);
    guint i;

    for (i = 0; i < length / 2 && i < binary_size; ++i) {
        sscanf(hex_string + 2 * i, "%2hhx", &binary_data[i]);
    }

    return i;
}

/**
 * Loads the configured OPCUA Keylog file.
 */
void load_keysets(const char *filename)
{
    struct ua_keyset *keyset = NULL;
    char key[33]; /* 32 chars + null terminator */
    char value[65]; /* 64 hex chars + null terminator */
    const char *parts[4]; /* for string split */
    unsigned int num_parts;
    char *tmp;
    uint32_t token_id = 0;
    uint32_t channel_id = 0;
    uint64_t id = 0;
    uint64_t last_id = 0;
    int n;

    debugprintf("Loading key file '%s'...\n", filename);
    FILE *f = ws_fopen(filename, "r");
    if (f == NULL) {
        debugprintf("error: '%s' not found\n", filename);
        return;
    }

    while ((n = fscanf(f, "%32[^:]: %64s\n", key, value)) == 2) {
        debugprintf("%s = %s\n", key, value);
        /* split key into parts */
        num_parts = 0;
        tmp = strtok(key, "_");
        while (tmp) {
            parts[num_parts++] = tmp;
            tmp = strtok(NULL, "_");
        }
        if (num_parts != 4) continue; /* skip invalid enty */
        channel_id = (uint32_t)strtoul(parts[2], NULL, 10);
        token_id = (uint32_t)strtoul(parts[3], NULL, 10);

        debugprintf("channel_id = %u\n", channel_id);
        debugprintf("token_id = %u\n", token_id);

        /* create unique keyset id */
        id = ua_keyset_id(channel_id, token_id);

        if (keyset == NULL || id != last_id) {
            debugprintf("Adding new keyset for id %lu...\n", id);
            /* create new keyset for new id */
            keyset = ua_keysets_add();
            keyset->id = id;
            last_id = id;
        }
        if (keyset) {
            /* store key material */
            if (strcmp(parts[0], "client") == 0) {
                if (strcmp(parts[1], "iv") == 0) {
                    hex_to_bin(value, keyset->client_iv, sizeof(keyset->client_iv));
                } else if (strcmp(parts[1], "key") == 0) {
                    keyset->client_key_len = (unsigned int)hex_to_bin(value, keyset->client_key, sizeof(keyset->client_key));
                } else if (strcmp(parts[1], "siglen") == 0) {
                    keyset->client_sig_len = (unsigned int)strtoul(value, NULL, 10);
                }
            } else if (strcmp(parts[0], "server") == 0) {
                if (strcmp(parts[1], "iv") == 0) {
                    hex_to_bin(value, keyset->server_iv, sizeof(keyset->server_iv));
                } else if (strcmp(parts[1], "key") == 0) {
                    keyset->server_key_len = (unsigned int)hex_to_bin(value, keyset->server_key, sizeof(keyset->server_key));
                } else if (strcmp(parts[1], "siglen") == 0) {
                    keyset->server_sig_len = (unsigned int)strtoul(value, NULL, 10);
                }
            }
        }
    }
    /* sort data by id to make lookup working */
    ua_keysets_sort();

    fclose(f);
}


/**
 * Checks the padding of a symetric signed message.
 * A message always contains a padding_len byte, which tells us the length of
 * the padding. All following padding bytes contain the same value. This makes it
 * possible the padding from the end of the message.
 * Example Paddings:
 * - 00
 * - 01 01
 * - 02 02 02
 * @param padding Pointer to last padding byte.
 * @return padding length on success, -1 if the paddding is invalid.
 */
static int verify_padding(const guint8 *padding)
{
    uint8_t pad_len;
    uint8_t i;

    pad_len = *padding;

    for (i = 0; i < pad_len; ++i) {
        if (padding[-pad_len + i] != pad_len) return -1;
    }

    return pad_len;
}
/**
 * Gets security footer info.
 *
 * @param channel_id SecureChannelId for keyset lookup.
 * @param token_id TokenId for keyset lookup.
 * @param sig_len Returns the length of the signature.
 * @param from_server True of the message is sent from the server, false when sent from the client.
 *
 * @return Returns 0 on success, -1 if parsing failed.
 */
static int opcua_get_footer_info(uint32_t channel_id, uint32_t token_id, guint8 *sig_len, bool from_server)
{
    struct ua_keyset *keyset;
    uint64_t id;

    id = ua_keyset_id(channel_id, token_id);

    /* try to get correct signature length from key log file */
    keyset = ua_keysets_lookup(id);
    if (keyset) {
        /* The Client keys are used to secure Messages sent by the Client. The Server keys are used to
         * secure Messages sent by the Server.
         */
        if (from_server) {
            *sig_len = keyset->server_sig_len;
        } else {
            *sig_len = keyset->client_sig_len;
        }
    }

    debugprintf("no keyset found for channel_id=%u and token_id=%u\n", channel_id, token_id);
    /* we use sig_len set from OpenSecurehChannel Policy in this case.
     * this requires to have the OPN in the capture file, otherwise we are out of luck.
     */

    return 0;
}

/**
 * This function to perform AES decryption on service data in-place.
 * Add also determines the payload length by removing the padding and signature.
 *
 * @param channel_id SecureChannelId for keyset lookup.
 * @param token_id TokenId for keyset lookup.
 * @param cipher The cipher text.
 * @param cipher_len The cipher test length in bytes.
 * @param plaintext The plaintext to return.
 * @param plaintext_len The plaintext in bytes, should be the same as cipher_len.
 * @param padding_len Returns the length of the padding.
 * @param sig_len Returns the length of the signature.
 * @param from_server True of the message is sent from the server, false when sent from the client.
 *
 * @return Returns 0 on success, -1 if decryption failed.
 */
static int decrypt_opcua(
        uint32_t channel_id, uint32_t token_id,
        const guint8 *cipher, guint cipher_len,
        guint8 *plaintext, guint plaintext_len,
        guint8 *padding_len, guint8 *sig_len, bool from_server)
{
    struct ua_keyset *keyset;
    uint64_t id;
    unsigned int keylen, ivlen;
    unsigned char *keydata, *ivdata;
    int cipher_mode;
    gcry_error_t res;
    int ret = 0;

    id = ua_keyset_id(channel_id, token_id);

    keyset = ua_keysets_lookup(id);
    if (keyset == NULL) {
        debugprintf("no keyset found for channel_id=%u and token_id=%u\n", channel_id, token_id);
        /* col_append_fstr(pinfo->cinfo, COL_INFO, " (encrypted)"); */
        return -1;
    }
    debugprintf("found keyset for channel_id=%u and token_id=%u\n", channel_id, token_id);

    /* The Client keys are used to secure Messages sent by the Client. The Server keys are used to
     * secure Messages sent by the Server.
     */
    if (from_server) {
        ivlen = sizeof(keyset->server_iv);
        ivdata = keyset->server_iv;
        keylen = keyset->server_key_len;
        keydata = keyset->server_key;
        *sig_len = keyset->server_sig_len;
    } else {
        ivlen = sizeof(keyset->client_iv);
        ivdata = keyset->client_iv;
        keylen = keyset->client_key_len;
        keydata = keyset->client_key;
        *sig_len = keyset->client_sig_len;
    }
    /* derive AES mode from key length */
    switch (keylen) {
    case 16:
        debugprintf("using AES-128-CBC\n");
        cipher_mode = GCRY_CIPHER_AES128;
        break;
    case 32:
        debugprintf("using AES-256-CBC\n");
        cipher_mode = GCRY_CIPHER_AES256;
        break;
    default:
        debugprintf("invalid AES key length: %u bytes\n", keylen);
        /* col_append_fstr(pinfo->cinfo, COL_INFO, " (encrypted)"); */
        return -1;
    }

    debugprintf("cipher_len=%u\n", cipher_len);
    if (cipher_len % 16 != 0) {
        debugprintf("warning: cipher_len not a multiple of 16.\n");
    }

    gcry_cipher_hd_t handle;
    gcry_cipher_open(&handle, cipher_mode, GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_CBC_CTS);
    gcry_cipher_setkey(handle, keydata, keylen);
    gcry_cipher_setiv(handle, ivdata, ivlen);

    /* Decrypt the data in-place */
    res = gcry_cipher_decrypt(handle, plaintext, plaintext_len, cipher, cipher_len);
    if (res == 0) {
        /* col_append_fstr(pinfo->cinfo, COL_INFO, " (decrypted)"); */
    } else {
        /* col_append_fstr(pinfo->cinfo, COL_INFO, " (encrypted)"); */
        debugprintf("decryption failed.\n");
        ret = -1;
    }
    gcry_cipher_close(handle);

    ret = verify_padding(&plaintext[plaintext_len - *sig_len - 1]);
    if (ret < 0) {
        debugprintf("padding is invalid.\n");
    }

    /* return padding length */
    *padding_len = plaintext[plaintext_len - *sig_len - 1];
    debugprintf("sig_len=%u\n", *sig_len);
    debugprintf("pad_len=%u\n", *padding_len);

    return 0;
}

/** The OpcUa message dissector.
  * This method dissects full OpcUa messages.
  * It gets only called with reassembled data
  * from tcp_dissect_pdus.
  */
static int dissect_opcua_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
    FctParse pfctParse = NULL;
    enum MessageType msgtype = MSG_INVALID;
    guint16 src_port = pinfo->srcport;
    range_t *port_range;
    bool from_server = false;
    bool decrypted = false; /* succesfully decrypted secure message */
    enum ua_message_mode mode = UA_MessageMode_None;
    uint8_t sig_len = 0;
    struct ua_metadata metadata;
    tvbuff_t *decrypted_tvb = NULL;
    int ret;

    /* determine if telegram is from server or from client by checking the port number */
    if (src_port == OPCUA_DEFAULT_PORT) {
        from_server = true;
    } else {
        port_range = prefs_get_range_value("opcua", "tcp.port");
        if (port_range && value_is_in_range(port_range, src_port)) {
            from_server = true;
        }
    }

    metadata.encrypted = false;
    get_encryption_info(pinfo, &mode, &sig_len);

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "OpcUa");


    /* parse message type */
    if (tvb_memeql(tvb, 0, (const guint8 * )"HEL", 3) == 0)
    {
        msgtype = MSG_HELLO;
        pfctParse = parseHello;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"ACK", 3) == 0)
    {
        msgtype = MSG_ACKNOWLEDGE;
        pfctParse = parseAcknowledge;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"ERR", 3) == 0)
    {
        msgtype = MSG_ERROR;
        pfctParse = parseError;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"RHE", 3) == 0)
    {
        msgtype = MSG_REVERSEHELLO;
        pfctParse = parseReverseHello;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"MSG", 3) == 0)
    {
        msgtype = MSG_MESSAGE;
        pfctParse = parseMessage;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"OPN", 3) == 0)
    {
        msgtype = MSG_OPENSECURECHANNEL;
        pfctParse = parseOpenSecureChannel;
    }
    else if (tvb_memeql(tvb, 0, (const guint8*)"CLO", 3) == 0)
    {
        msgtype = MSG_CLOSESECURECHANNEL;
        pfctParse = parseCloseSecureChannel;
    }
    else
    {
        msgtype = MSG_INVALID;

        /* Clear out stuff in the info column */
        col_set_str(pinfo->cinfo, COL_INFO, g_szMessageTypes[msgtype]);

        /* add empty item to make filtering by 'opcua' work */
        proto_tree_add_item(tree, proto_opcua, tvb, 0, -1, ENC_NA);

        return tvb_reported_length(tvb);
    }

    /* Clear out stuff in the info column */
    col_set_str(pinfo->cinfo, COL_INFO, g_szMessageTypes[msgtype]);

    if (pfctParse)
    {
        gint offset = 0;
        int iServiceId = -1;
        gboolean bParseService = FALSE; /* Only MSG, OPN and CLO have a service payload */
        gboolean bIsFinalChunk = FALSE;
        guint payload_len = 0;
        guint8 pad_len = 0;

        /* we are being asked for details */
        proto_item *ti = NULL;
        proto_tree *transport_tree = NULL;

        ti = proto_tree_add_item(tree, proto_opcua, tvb, 0, -1, ENC_NA);
        transport_tree = proto_item_add_subtree(ti, ett_opcua_transport);

        /* call the transport message dissector */
        (*pfctParse)(transport_tree, tvb, pinfo, &offset, &metadata);

        /* MSG_MESSAGE and MSG_CLOSESECURECHANNEL can be decrypted.
         * Also handle chunked message reassembly for MSG_MESSAGE.
         */
        if (msgtype == MSG_MESSAGE || msgtype == MSG_CLOSESECURECHANNEL)
        {
            guint8 chunkType = 0;
            guint32 opcua_seqno = 0; /* OPCUA sequence number */
            guint32 opcua_reqid = 0; /* OPCUA request id */
            guint32 opcua_frag_seqnum; /* wireshark reassemble fragment number (zero based) */
            fragment_head *frag_msg = NULL;
            fragment_item *frag_i = NULL;

            bParseService = TRUE;
            offset = 3;
            chunkType = tvb_get_guint8(tvb, offset); offset += 1;
            offset += 4; /* message size */
            offset += 4; /* skip secure channel_id */
            parseSecurityHeader(transport_tree, tvb, &offset, &metadata); /* only token_id (4 byte) */

            if (mode == UA_MessageMode_MaybeEncrypted) {
                /* try to parse ServiceId */
                iServiceId = getServiceNodeId(tvb, offset + 8); /* skip 4 byte SeqNo and 4 byte RequestId */
                const gchar *szServiceName = val_to_str((guint32)iServiceId, g_requesttypes, "not found");
                if (strcmp(szServiceName, "not found") == 0) {
                    mode = UA_MessageMode_SignAndEncrypt;
                } else {
                    mode = UA_MessageMode_Sign;
                }
                store_encryption_info(pinfo, mode, sig_len);
            }

            /* Message Structure:
             *             +-----------------+
             *          /  | Message Header  |   MSGF, MessageSize
             *          |  +-----------------+
             *          |  | Security Header |   SecureChannelId, TokenId
             *          |  +-----------------+
             * Signed  <   | Sequence Header | \ SequenceNumber, RequestId
             *          |  +-----------------+ |
             *          |  | Body            | |
             *          |  +-----------------+  > Encrypted
             *          \  | Padding         | |
             *             +-----------------+ |
             *             | Signature       | /
             *             +-----------------+
             */
            if (mode == UA_MessageMode_SignAndEncrypt) {
                uint32_t channel_id = tvb_get_letohl(tvb, 8);
                uint32_t token_id = tvb_get_letohl(tvb, 12);
                guint cipher_len = tvb_ensure_captured_length_remaining(tvb, 16);
                guint plaintext_len = cipher_len;
                const guint8 *cipher = tvb_get_ptr(tvb, 16, (gint)cipher_len);
                guchar *plaintext = (guchar*)wmem_alloc(pinfo->pool, plaintext_len);

                ret = decrypt_opcua(channel_id, token_id, cipher, cipher_len, plaintext, plaintext_len, &pad_len, &sig_len, from_server);
                if (ret == 0) {
                    /* decrypted */
                    /* to get the payload length we need to subtract the sequence header (8) byte,
                     * the padding (paddin_len+1), and the signature from the plaintext */
                    payload_len = plaintext_len - pad_len - sig_len - 9; /* pad_len 2 = 02 02 02 */
                    /* Now re-setup the tvb buffer to have the new data */
                    decrypted_tvb = tvb_new_child_real_data(tvb, plaintext, (guint)plaintext_len, (gint)plaintext_len);
                    add_new_data_source(pinfo, decrypted_tvb, "Decrypted Data");
                    /* process decrypted_tvb from here */
                    tvb = decrypted_tvb;
                    offset = 0;
                    decrypted = true;
                } else {
                    /* decryption failed */
                    metadata.encrypted = true;
                }
            } else if (mode == UA_MessageMode_Sign) {
                uint32_t channel_id = tvb_get_letohl(tvb, 8);
                uint32_t token_id = tvb_get_letohl(tvb, 12);
                payload_len = tvb_ensure_captured_length_remaining(tvb, 24); /* subtract header */

                ret = opcua_get_footer_info(channel_id, token_id, &sig_len, from_server);
                if (ret != 0) {
                    debugprintf("Processing security footer of signed message failed.\n");
                } else {
                    /* signed only messages habe no padding, so the payload is the message size
                     * without 24 byte header and without signature */
                    payload_len -= sig_len;
                }
                /* store the current tvb as decrypted tvb, because we need this to parse the signature
                 * at the end, and tvb gets replaces with the reassembled UA message if the message was chunked.
                 */
                decrypted_tvb = tvb;
            } else {
                /* no padding, no signature, just payload */
                payload_len = tvb_ensure_captured_length_remaining(tvb, 16);
                pad_len= 0;
                sig_len = 0;
            }

            opcua_seqno = tvb_get_letohl(tvb, offset); /* Sequence.Sequence Number */
            opcua_reqid = tvb_get_letohl(tvb, offset + 4); /* Sequence.RequestId */
            parseSequenceHeader(transport_tree, tvb, &offset, &metadata);

            if (chunkType == 'A')
            {
                /* cancel chunk reassembly */
                fragment_delete(&opcua_reassembly_table, pinfo, opcua_reqid, NULL);

                col_clear_fence(pinfo->cinfo, COL_INFO);
                col_set_str(pinfo->cinfo, COL_INFO, "Abort message");

                offset = 0;
                (*pfctParse)(transport_tree, tvb, pinfo, &offset, &metadata);
                parseAbort(transport_tree, tvb, pinfo, &offset, &metadata);

                return tvb_reported_length(tvb);
            }

            /* check if tvb is part of a chunked message:
               the UA protocol does not tell us that, so we look into
               opcua_reassembly_table if the opcua_reqid belongs to a
               chunked message */
            frag_msg = fragment_get(&opcua_reassembly_table, pinfo, opcua_reqid, NULL);
            if (frag_msg == NULL)
            {
                frag_msg = fragment_get_reassembled_id(&opcua_reassembly_table, pinfo, opcua_reqid);
            }

            if (frag_msg != NULL || chunkType == 'C')
            {
                gboolean bSaveFragmented = pinfo->fragmented;
                gboolean bMoreFragments = TRUE;
                tvbuff_t *reassembled_tvb = NULL;

                pinfo->fragmented = TRUE;

                if (frag_msg == NULL)
                {
                    /* first fragment */
                    opcua_frag_seqnum = 0;
                }
                else
                {
                    /* the UA protocol does not number the chunks beginning from 0 but from a
                       arbitrary value, so we have to fake the numbers in the stored fragments.
                       this way Wireshark reassembles the message, as it expects the fragment
                       sequence numbers to start at 0 */
                    for (frag_i = frag_msg->next; frag_i && frag_i->next; frag_i = frag_i->next); /* get last fragment */
                    if (frag_i) {
                        opcua_frag_seqnum = frag_i->offset + 1; /* offset contains fragment number */
                    } else {
                        /* We should never have a fragment head with no fragment items, but
                         * just in case.
                         */
                        opcua_frag_seqnum = 0;
                    }

                    if (chunkType == 'F')
                    {
                        bMoreFragments = FALSE;
                    }
                }

                frag_msg = fragment_add_seq_check(&opcua_reassembly_table,
                                                  tvb,
                                                  offset,
                                                  pinfo,
                                                  opcua_reqid, /* ID for fragments belonging together */
                                                  NULL,
                                                  opcua_frag_seqnum, /* fragment sequence number */
                                                  payload_len,
                                                  bMoreFragments); /* More fragments? */

                reassembled_tvb = process_reassembled_data(tvb,
                                                   offset,
                                                   pinfo,
                                                   "Reassembled UA Message",
                                                   frag_msg,
                                                   &opcua_frag_items,
                                                   NULL,
                                                   transport_tree);

                if (reassembled_tvb)
                {
                    /* Reassembled */
                    bIsFinalChunk = TRUE;
                    /* take it all */
                    tvb = reassembled_tvb;
                    /* new tvb starts at payload */
                    offset = 0;
                }
                else
                {
                    /* Not last packet of reassembled UA message */
                    col_append_fstr(pinfo->cinfo, COL_INFO, " (Message fragment %u)", opcua_seqno);
                    /* only show transport header */
                    bParseService = FALSE;
                    tvb = tvb_new_subset_remaining(tvb, 0);
                }

                pinfo->fragmented = bSaveFragmented;
            }
        }

        /* parse payload if not encrypted */
        if (!metadata.encrypted && bParseService) {
            if (msgtype == MSG_CLOSESECURECHANNEL) {
                iServiceId = parseService(transport_tree, tvb, pinfo, &offset, &metadata);
                if (iServiceId == OpcUaId_CloseSecureChannelRequest_Encoding_DefaultBinary) {
                    col_append_str(pinfo->cinfo, COL_INFO, ": CloseSecureChannelRequest");
                } else if (iServiceId == OpcUaId_CloseSecureChannelResponse_Encoding_DefaultBinary) {
                    col_append_str(pinfo->cinfo, COL_INFO, ": CloseSecureChannelResponse");
                } else {
                    const gchar *szServiceName = val_to_str((guint32)iServiceId, g_requesttypes, "ServiceId %d");
                    col_append_fstr(pinfo->cinfo, COL_INFO, ": %s (Wrong ServiceId)", szServiceName);
                }
            } else if (msgtype == MSG_MESSAGE) {
                /* parse the service if not chunked or message was reassembled */
                iServiceId = parseService(transport_tree, tvb, pinfo, &offset, &metadata);

                /* display the service type in addition to the message type */
                if (iServiceId != -1)
                {
                    const gchar *szServiceName = val_to_str((guint32)iServiceId, g_requesttypes, "ServiceId %d");

                    if (bIsFinalChunk == FALSE)
                    {
                        /* normal message in one chunk */
                        col_append_fstr(pinfo->cinfo, COL_INFO, ": %s", szServiceName);
                    }
                    else
                    {
                        /* reassembled message from multiple chunks */
                        col_append_fstr(pinfo->cinfo, COL_INFO, ": %s (Message Reassembled)", szServiceName);
                    }
                }
            }
            if (mode == UA_MessageMode_SignAndEncrypt && decrypted) {
                /* parse padding and signature */
                parseSecurityFooterSAE(transport_tree, decrypted_tvb, 8 + payload_len, pad_len, sig_len);
            } else if (mode == UA_MessageMode_Sign) {
                /* parse signature */
                parseSecurityFooterSO(transport_tree, decrypted_tvb, 24 + payload_len, sig_len);
            }
        }
        if (metadata.encrypted) {
            col_append_str(pinfo->cinfo, COL_INFO, " (encrypted)");
        } else if (mode == UA_MessageMode_SignAndEncrypt) {
            col_append_str(pinfo->cinfo, COL_INFO, " (decrypted)");
        }
    }

    return tvb_reported_length(tvb);
}

/** The main OpcUa dissector functions.
  * It uses tcp_dissect_pdus from packet-tcp.h
  * to reassemble the TCP data.
  */
static int dissect_opcua(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
    tcp_dissect_pdus(tvb, pinfo, tree, TRUE, FRAME_HEADER_LEN,
                     get_opcua_message_len, dissect_opcua_message, data);
    return tvb_reported_length(tvb);
}

/** Init plugin resources */
void proto_init_opcua(void)
{
    debugprintf("proto_init_opcua called.\n");
    ua_keysets_init();
    load_keysets(g_opcua_debug_file_name);
}

/** Cleanup plugin resources */
void proto_cleanup_opcua(void)
{
    debugprintf("proto_cleanup_opcua called.\n");
    ua_keysets_clear();
}

/** plugin entry functions.
 * This registers the OpcUa protocol.
 */
void proto_register_opcua(void)
{
    static hf_register_info hf[] =
        {
            /* id                                    full name                                              abbreviation                        type            display     strings bitmask blurb HFILL */
            {&hf_opcua_fragments,                   {"Message fragments",                                   "opcua.fragments",                  FT_NONE,        BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment,                    {"Message fragment",                                    "opcua.fragment",                   FT_FRAMENUM,    BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_overlap,            {"Message fragment overlap",                            "opcua.fragment.overlap",           FT_BOOLEAN,     BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_overlap_conflicts,  {"Message fragment overlapping with conflicting data",  "opcua.fragment.overlap.conflicts", FT_BOOLEAN,     BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_multiple_tails,     {"Message has multiple tail fragments",                 "opcua.fragment.multiple_tails",    FT_BOOLEAN,     BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_too_long_fragment,  {"Message fragment too long",                           "opcua.fragment.too_long_fragment", FT_BOOLEAN,     BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_error,              {"Message defragmentation error",                       "opcua.fragment.error",             FT_FRAMENUM,    BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_fragment_count,              {"Message fragment count",                              "opcua.fragment.count",             FT_UINT32,      BASE_DEC,   NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_reassembled_in,              {"Reassembled in",                                      "opcua.reassembled.in",             FT_FRAMENUM,    BASE_NONE,  NULL,   0x00,   NULL, HFILL}},
            {&hf_opcua_reassembled_length,          {"Reassembled length",                                  "opcua.reassembled.length",         FT_UINT32,      BASE_DEC,   NULL,   0x00,   NULL, HFILL}}
        };

    /** Setup protocol subtree array */
    static gint *ett[] =
        {
            &ett_opcua_extensionobject,
            &ett_opcua_nodeid,
            &ett_opcua_transport,
            &ett_opcua_fragment,
            &ett_opcua_fragments
        };

    proto_opcua = proto_register_protocol("OpcUa Binary Protocol", "OpcUa", "opcua");
    opcua_handle = register_dissector("opcua", dissect_opcua, proto_opcua);

    register_init_routine(proto_init_opcua);
    register_cleanup_routine(proto_cleanup_opcua);

    opcua_module = prefs_register_protocol(proto_opcua, proto_reg_handoff_opcua);
    prefs_register_filename_preference(opcua_module, "debug_file", "OPCUA debug file",
            "Redirect OPC UA Secure Conversion session keys to the file specified to enable decryption.",
            &g_opcua_debug_file_name, FALSE);

    registerTransportLayerTypes(proto_opcua);
    registerSecurityLayerTypes(proto_opcua);
    registerSequenceLayerTypes(proto_opcua);
    registerApplicationLayerTypes(proto_opcua);
    registerSimpleTypes(proto_opcua);
    registerEnumTypes(proto_opcua);
    registerComplexTypes();
    registerServiceTypes();
    registerFieldTypes(proto_opcua);

    proto_register_subtree_array(ett, array_length(ett));
    proto_register_field_array(proto_opcua, hf, array_length(hf));

    reassembly_table_register(&opcua_reassembly_table,
                          &addresses_reassembly_table_functions);
}

void proto_reg_handoff_opcua(void)
{
    dissector_add_uint_range_with_preference("tcp.port", OPCUA_PORT_RANGE, opcua_handle);
}

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */