/
client_secure_channel.go
1897 lines (1724 loc) · 59.3 KB
/
client_secure_channel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Converter Systems LLC. All rights reserved.
package client
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/binary"
"encoding/json"
"fmt"
"hash"
"io"
"log"
"math"
"net"
"net/url"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/awcullen/opcua/ua"
"github.com/djherbis/buffer"
)
const (
// defaultTimeoutHint is the default number of milliseconds before a request is cancelled. (15 sec)
defaultTimeoutHint uint32 = 15000
// defaultDiagnosticsHint is the default diagnostic hint that is sent in a request. (None)
defaultDiagnosticsHint uint32 = 0x00000000
// defaultTokenRequestedLifetime is the default number of milliseconds before a security token is expired. (60 min)
defaultTokenRequestedLifetime uint32 = 3600000
// defaultConnectTimeout is the default number of milliseconds to wait for a connection response. (15 sec)
defaultConnectTimeout int64 = 15000
// defaultSessionTimeout the default number of milliseconds that the session will remain open without activity. (2 min)
defaultSessionTimeout float64 = 120 * 1000
// protocolVersion documents the version of binary protocol that this library supports.
protocolVersion uint32 = 0
// defaultMaxBufferSize is the default limit on the size of the send and receive buffers.
defaultMaxBufferSize uint32 = 64 * 1024
// defaultMaxMessageSize is the default limit on the size of messages that may be accepted.
defaultMaxMessageSize uint32 = 64 * 1024 * 1024
// defaultMaxChunkCount is the default limit on the number of message chunks that may be accepted.
defaultMaxChunkCount uint32 = 4 * 1024
// sequenceHeaderSize is the size of the sequence header
sequenceHeaderSize int = 8
// the length of nonce in bytes.
nonceLength int = 32
)
// clientSecureChannel implements a secure channel for binary data over Tcp.
type clientSecureChannel struct {
sync.RWMutex
localDescription ua.ApplicationDescription
timeoutHint uint32
diagnosticsHint uint32
tokenRequestedLifetime uint32
endpointURL string
receiveBufferSize uint32
sendBufferSize uint32
maxRequestMessageSize uint32
maxRequestChunkCount uint32
maxResponseMessageSize uint32
maxResponseChunkCount uint32
conn net.Conn
connectTimeout int64
trustedCertsPath string
trustedCRLsPath string
issuerCertsPath string
issuerCRLsPath string
rejectedCertsPath string
suppressHostNameInvalid bool
suppressCertificateExpired bool
suppressCertificateChainIncomplete bool
suppressCertificateRevocationUnknown bool
//
localCertificate []byte
remoteCertificate []byte
localPrivateKey *rsa.PrivateKey
remotePublicKey *rsa.PublicKey
localPrivateKeySize int
remotePublicKeySize int
localNonce []byte
remoteNonce []byte
channelID uint32
tokenID uint32
tokenLock sync.RWMutex
authenticationToken ua.NodeID
securityPolicyURI string
securityPolicy ua.SecurityPolicy
securityMode ua.MessageSecurityMode
namespaceURIs []string
serverURIs []string
closed chan struct{}
statusCode ua.StatusCode
sendingSemaphore sync.Mutex
receivingSemaphore sync.Mutex
pendingResponseCh chan *ua.ServiceOperation
pendingResponses map[uint32]*ua.ServiceOperation
closing bool
requestHandle uint32
sequenceNumber uint32
sendingTokenID uint32
receivingTokenID uint32
localSigningKey []byte
localEncryptingKey []byte
localInitializationVector []byte
remoteSigningKey []byte
remoteEncryptingKey []byte
remoteInitializationVector []byte
tokenRenewalTime time.Time
symSignHMAC hash.Hash
symVerifyHMAC hash.Hash
symEncryptingBlockCipher cipher.Block
symDecryptingBlockCipher cipher.Block
bytesPool sync.Pool
bufferPool buffer.PoolAt
trace bool
}
// newClientSecureChannel initializes a new instance of the secure channel.
func newClientSecureChannel(
localDescription ua.ApplicationDescription,
localCertificate []byte,
localPrivateKey *rsa.PrivateKey,
endpointURL string,
securityPolicyURI string,
securityMode ua.MessageSecurityMode,
remoteCertificate []byte,
connectTimeout int64,
trustedCertsPath string,
trustedCRLsPath string,
issuerCertsPath string,
issuerCRLsPath string,
rejectedCertsPath string,
suppressHostNameInvalid bool,
suppressCertificateExpired bool,
suppressCertificateChainIncomplete bool,
suppressCertificateRevocationUnknown bool,
timeoutHint uint32,
diagnosticsHint uint32,
tokenLifetime uint32,
maxBufferSize uint32,
maxMessageSize uint32,
maxChunkCount uint32,
trace bool,
) *clientSecureChannel {
ch := &clientSecureChannel{
localDescription: localDescription,
endpointURL: endpointURL,
securityPolicyURI: securityPolicyURI,
securityMode: securityMode,
localCertificate: localCertificate,
localPrivateKey: localPrivateKey,
remoteCertificate: remoteCertificate,
namespaceURIs: []string{"http://opcfoundation.org/UA/"},
serverURIs: []string{},
connectTimeout: connectTimeout,
trustedCertsPath: trustedCertsPath,
trustedCRLsPath: trustedCRLsPath,
issuerCertsPath: issuerCertsPath,
issuerCRLsPath: issuerCRLsPath,
rejectedCertsPath: rejectedCertsPath,
suppressHostNameInvalid: suppressHostNameInvalid,
suppressCertificateExpired: suppressCertificateExpired,
suppressCertificateChainIncomplete: suppressCertificateChainIncomplete,
suppressCertificateRevocationUnknown: suppressCertificateRevocationUnknown,
timeoutHint: timeoutHint,
diagnosticsHint: diagnosticsHint,
tokenRequestedLifetime: tokenLifetime,
receiveBufferSize: maxBufferSize,
sendBufferSize: maxBufferSize,
maxResponseMessageSize: maxMessageSize,
maxResponseChunkCount: maxChunkCount,
bytesPool: sync.Pool{New: func() any { s := make([]byte, maxBufferSize); return &s }},
bufferPool: buffer.NewMemPoolAt(int64(maxBufferSize)),
trace: trace,
}
if cert, err := x509.ParseCertificate(ch.remoteCertificate); err == nil {
ch.remotePublicKey = cert.PublicKey.(*rsa.PublicKey)
}
return ch
}
// EndpointURL gets the URL of the remote endpoint.
func (ch *clientSecureChannel) EndpointURL() string {
return ch.endpointURL
}
// SetAuthenticationToken sets the authentication token.
func (ch *clientSecureChannel) SetAuthenticationToken(value ua.NodeID) {
ch.Lock()
defer ch.Unlock()
ch.authenticationToken = value
}
// NamespaceURIs gets the namespace uris.
func (ch *clientSecureChannel) NamespaceURIs() []string {
ch.RLock()
defer ch.RUnlock()
return ch.namespaceURIs
}
// SetNamespaceURIs sets the namespace uris.
func (ch *clientSecureChannel) SetNamespaceURIs(value []string) {
ch.Lock()
defer ch.Unlock()
ch.namespaceURIs = value
}
// ServerURIs gets the server uris.
func (ch *clientSecureChannel) ServerURIs() []string {
ch.RLock()
defer ch.RUnlock()
return ch.serverURIs
}
// SetServerURIs sets the server uris.
func (ch *clientSecureChannel) SetServerURIs(value []string) {
ch.Lock()
defer ch.Unlock()
ch.serverURIs = value
}
// Request sends a service request to the server and returns the response.
func (ch *clientSecureChannel) Request(ctx context.Context, req ua.ServiceRequest) (ua.ServiceResponse, error) {
header := req.Header()
header.Timestamp = time.Now()
header.RequestHandle = ch.getNextRequestHandle()
header.AuthenticationToken = ch.authenticationToken
if header.TimeoutHint == 0 {
header.TimeoutHint = defaultTimeoutHint
}
var operation = ua.NewServiceOperation(req, make(chan ua.ServiceResponse, 1))
ch.pendingResponseCh <- operation
ctx, cancel := context.WithDeadline(ctx, header.Timestamp.Add(time.Duration(header.TimeoutHint)*time.Millisecond))
err := ch.sendRequest(ctx, operation)
if err != nil {
cancel()
return nil, err
}
select {
case res := <-operation.ResponseCh():
cancel()
if sr := res.Header().ServiceResult; sr != ua.Good {
return nil, sr
}
return res, nil
case <-ctx.Done():
cancel()
return nil, ua.BadRequestTimeout
case <-ch.closed:
cancel()
return nil, ua.BadSecureChannelClosed
}
}
// Open opens the channel.
func (ch *clientSecureChannel) Open(ctx context.Context) error {
ch.Lock()
defer ch.Unlock()
remoteURL, err := url.Parse(ch.endpointURL)
if err != nil {
return err
}
if len(ch.remoteCertificate) > 0 {
cert, err := x509.ParseCertificate(ch.remoteCertificate)
if err != nil {
return ua.BadSecurityChecksFailed
}
err = ua.ValidateCertificate(
cert,
[]x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
remoteURL.Hostname(),
ch.trustedCertsPath,
ch.trustedCRLsPath,
ch.issuerCertsPath,
ch.issuerCRLsPath,
ch.rejectedCertsPath,
ch.suppressHostNameInvalid,
ch.suppressCertificateExpired,
ch.suppressCertificateChainIncomplete,
ch.suppressCertificateRevocationUnknown,
)
if err != nil {
return err
}
}
ch.conn, err = net.DialTimeout("tcp", remoteURL.Host, time.Duration(ch.connectTimeout)*time.Millisecond)
if err != nil {
return err
}
buf := *(ch.bytesPool.Get().(*[]byte))
defer ch.bytesPool.Put(&buf)
var writer = ua.NewWriter(buf)
var enc = ua.NewBinaryEncoder(writer, ch)
enc.WriteUInt32(ua.MessageTypeHello)
enc.WriteUInt32(uint32(32 + len(ch.endpointURL)))
enc.WriteUInt32(protocolVersion)
enc.WriteUInt32(ch.receiveBufferSize)
enc.WriteUInt32(ch.sendBufferSize)
enc.WriteUInt32(ch.maxResponseMessageSize)
enc.WriteUInt32(ch.maxResponseChunkCount)
enc.WriteString(ch.endpointURL)
_, err = ch.Write(writer.Bytes())
if err != nil {
return err
}
// if ch.trace {
// log.Printf("Hello{\"Version\":%d,\"ReceiveBufferSize\":%d,\"SendBufferSize\":%d,\"MaxMessageSize\":%d,\"MaxChunkCount\":%d,\"EndpointURL\":\"%s\"}\n", protocolVersion, ch.receiveBufferSize, ch.sendBufferSize, ch.maxResMessageSize, ch.maxResChunkCount, ch.endpointURL)
// }
_, err = ch.Read(buf)
if err != nil {
return err
}
var reader = bytes.NewReader(buf)
var dec = ua.NewBinaryDecoder(reader, ch)
var msgType uint32
if err := dec.ReadUInt32(&msgType); err != nil {
return err
}
var msgLen uint32
if err := dec.ReadUInt32(&msgLen); err != nil {
return err
}
switch msgType {
case ua.MessageTypeAck:
if msgLen < 28 {
return ua.BadDecodingError
}
var remoteProtocolVersion uint32
if err := dec.ReadUInt32(&remoteProtocolVersion); err != nil {
return err
}
if remoteProtocolVersion < protocolVersion {
return ua.BadProtocolVersionUnsupported
}
// read the remote receiveBufferSize into the local sendBufferSize
if err := dec.ReadUInt32(&ch.sendBufferSize); err != nil {
return err
}
// read the remote sendBufferSize into the local receiveBufferSize
if err := dec.ReadUInt32(&ch.receiveBufferSize); err != nil {
return err
}
if err := dec.ReadUInt32(&ch.maxRequestMessageSize); err != nil {
return err
}
if err := dec.ReadUInt32(&ch.maxRequestChunkCount); err != nil {
return err
}
// if ch.trace {
// log.Printf("Ack{\"Version\":%d,\"ReceiveBufferSize\":%d,\"SendBufferSize\":%d,\"MaxMessageSize\":%d,\"MaxChunkCount\":%d}\n", remoteProtocolVersion, ch.sendBufferSize, ch.receiveBufferSize, ch.maxReqMessageSize, ch.maxReqChunkCount)
// }
case ua.MessageTypeError:
if msgLen < 16 {
return ua.BadDecodingError
}
var remoteCode uint32
if err := dec.ReadUInt32(&remoteCode); err != nil {
return err
}
var unused string
if err = dec.ReadString(&unused); err != nil {
return err
}
return ua.StatusCode(remoteCode)
default:
return ua.BadDecodingError
}
// setSecurityPolicy
switch ch.securityPolicyURI {
case ua.SecurityPolicyURINone:
ch.securityPolicy = new(ua.SecurityPolicyNone)
case ua.SecurityPolicyURIBasic128Rsa15:
ch.securityPolicy = new(ua.SecurityPolicyBasic128Rsa15)
case ua.SecurityPolicyURIBasic256:
ch.securityPolicy = new(ua.SecurityPolicyBasic256)
case ua.SecurityPolicyURIBasic256Sha256:
ch.securityPolicy = new(ua.SecurityPolicyBasic256Sha256)
case ua.SecurityPolicyURIAes128Sha256RsaOaep:
ch.securityPolicy = new(ua.SecurityPolicyAes128Sha256RsaOaep)
case ua.SecurityPolicyURIAes256Sha256RsaPss:
ch.securityPolicy = new(ua.SecurityPolicyAes256Sha256RsaPss)
default:
return ua.BadSecurityPolicyRejected
}
ch.localSigningKey = make([]byte, ch.securityPolicy.SymSignatureKeySize())
ch.localEncryptingKey = make([]byte, ch.securityPolicy.SymEncryptionKeySize())
ch.localInitializationVector = make([]byte, ch.securityPolicy.SymEncryptionBlockSize())
ch.remoteSigningKey = make([]byte, ch.securityPolicy.SymSignatureKeySize())
ch.remoteEncryptingKey = make([]byte, ch.securityPolicy.SymEncryptionKeySize())
ch.remoteInitializationVector = make([]byte, ch.securityPolicy.SymEncryptionBlockSize())
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
if ch.localPrivateKey == nil {
return ua.BadSecurityChecksFailed
}
ch.localPrivateKeySize = ch.localPrivateKey.Size()
if ch.remotePublicKey == nil {
return ua.BadSecurityChecksFailed
}
ch.remotePublicKeySize = ch.remotePublicKey.Size()
}
ch.pendingResponseCh = make(chan *ua.ServiceOperation, 32)
ch.pendingResponses = make(map[uint32]*ua.ServiceOperation)
ch.closed = make(chan struct{})
ch.channelID = 0
ch.tokenID = 0
ch.sendingTokenID = 0
ch.receivingTokenID = 0
go ch.responseWorker()
request := &ua.OpenSecureChannelRequest{
ClientProtocolVersion: protocolVersion,
RequestType: ua.SecurityTokenRequestTypeIssue,
SecurityMode: ch.securityMode,
ClientNonce: ua.ByteString(getNextNonce(ch.securityPolicy.NonceSize())),
RequestedLifetime: ch.tokenRequestedLifetime,
}
res, err := ch.Request(ctx, request)
if err != nil {
return err
}
response := res.(*ua.OpenSecureChannelResponse)
if response.ServerProtocolVersion < protocolVersion {
return ua.BadProtocolVersionUnsupported
}
ch.tokenLock.Lock()
ch.tokenRenewalTime = time.Now().Add(time.Duration(response.SecurityToken.RevisedLifetime*75/100) * time.Millisecond)
ch.channelID = response.SecurityToken.ChannelID
ch.tokenID = response.SecurityToken.TokenID
ch.localNonce = []byte(request.ClientNonce)
ch.remoteNonce = []byte(response.ServerNonce)
ch.tokenLock.Unlock()
return nil
}
// Close closes the channel.
func (ch *clientSecureChannel) Close(ctx context.Context) error {
ch.Lock()
defer ch.Unlock()
ch.closing = true
_, err := ch.Request(ctx, &ua.CloseSecureChannelRequest{})
if err != nil {
return err
}
if ch.conn != nil {
ch.conn.Close()
}
return nil
}
// Abort closes the channel abruptly.
func (ch *clientSecureChannel) Abort(ctx context.Context) error {
ch.Lock()
defer ch.Unlock()
ch.closing = true
if ch.conn != nil {
ch.conn.Close()
}
return nil
}
// IsClosing returns true when the channel is closing.
func (ch *clientSecureChannel) IsClosing() bool {
ch.Lock()
defer ch.Unlock()
return ch.closing
}
// sendRequest sends the service request on transport channel.
func (ch *clientSecureChannel) sendRequest(ctx context.Context, op *ua.ServiceOperation) error {
// Check if time to renew security token.
if !ch.tokenRenewalTime.IsZero() && time.Now().After(ch.tokenRenewalTime) {
ch.tokenRenewalTime = ch.tokenRenewalTime.Add(60000 * time.Millisecond)
ch.renewToken(ctx)
}
ch.sendingSemaphore.Lock()
defer ch.sendingSemaphore.Unlock()
req := op.Request()
if ch.trace {
b, _ := json.MarshalIndent(req, "", " ")
log.Printf("%s%s", reflect.TypeOf(req).Elem().Name(), b)
}
switch req := req.(type) {
case *ua.OpenSecureChannelRequest:
err := ch.sendOpenSecureChannelRequest(ctx, req)
if err != nil {
return err
}
case *ua.CloseSecureChannelRequest:
err := ch.sendCloseSecureChannelRequest(ctx, req)
if err != nil {
return err
}
// send a success response to ourselves (the server will just close it's socket).
select {
case op.ResponseCh() <- &ua.CloseSecureChannelResponse{ResponseHeader: ua.ResponseHeader{RequestHandle: req.RequestHandle, Timestamp: time.Now()}}:
default:
}
default:
err := ch.sendServiceRequest(ctx, req)
if err != nil {
return err
}
}
return nil
}
// sendOpenSecureChannelRequest sends open secure channel service request on transport channel.
func (ch *clientSecureChannel) sendOpenSecureChannelRequest(ctx context.Context, request *ua.OpenSecureChannelRequest) error {
var bodyStream = buffer.NewPartitionAt(ch.bufferPool)
defer bodyStream.Reset()
var sendBuffer = *(ch.bytesPool.Get().(*[]byte))
defer ch.bytesPool.Put(&sendBuffer)
var bodyEncoder = ua.NewBinaryEncoder(bodyStream, ch)
if err := bodyEncoder.WriteNodeID(ua.ObjectIDOpenSecureChannelRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(request); err != nil {
return ua.BadEncodingError
}
if i := int64(ch.maxRequestMessageSize); i > 0 && bodyStream.Len() > i {
return ua.BadRequestTooLarge
}
// write chunks
var chunkCount int
var bodyCount = int(bodyStream.Len())
for bodyCount > 0 {
chunkCount++
if i := int(ch.maxRequestChunkCount); i > 0 && chunkCount > i {
return ua.BadRequestTooLarge
}
// plan
var plainHeaderSize int
var signatureSize int
var paddingHeaderSize int
var maxBodySize int
var bodySize int
var paddingSize int
var chunkSize int
var cipherTextBlockSize int
var plainTextBlockSize int
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
plainHeaderSize = 16 + len(ch.securityPolicyURI) + 28 + len(ch.localCertificate)
signatureSize = ch.localPrivateKeySize
cipherTextBlockSize = ch.remotePublicKeySize
plainTextBlockSize = cipherTextBlockSize - ch.securityPolicy.RSAPaddingSize()
if cipherTextBlockSize > 256 {
paddingHeaderSize = 2
} else {
paddingHeaderSize = 1
}
maxBodySize = (((int(ch.sendBufferSize) - plainHeaderSize) / cipherTextBlockSize) * plainTextBlockSize) - sequenceHeaderSize - paddingHeaderSize - signatureSize
if bodyCount < maxBodySize {
bodySize = bodyCount
paddingSize = (plainTextBlockSize - ((sequenceHeaderSize + bodySize + paddingHeaderSize + signatureSize) % plainTextBlockSize)) % plainTextBlockSize
} else {
bodySize = maxBodySize
paddingSize = 0
}
chunkSize = plainHeaderSize + (((sequenceHeaderSize + bodySize + paddingSize + paddingHeaderSize + signatureSize) / plainTextBlockSize) * cipherTextBlockSize)
default:
plainHeaderSize = 16 + len(ch.securityPolicyURI) + 8
signatureSize = 0
cipherTextBlockSize = 1
plainTextBlockSize = 1
paddingHeaderSize = 0
paddingSize = 0
maxBodySize = int(ch.sendBufferSize) - plainHeaderSize - sequenceHeaderSize - paddingHeaderSize - signatureSize
if bodyCount < maxBodySize {
bodySize = bodyCount
} else {
bodySize = maxBodySize
}
chunkSize = plainHeaderSize + sequenceHeaderSize + bodySize + paddingSize + paddingHeaderSize + signatureSize
}
var stream = ua.NewWriter(sendBuffer)
var encoder = ua.NewBinaryEncoder(stream, ch)
// header
encoder.WriteUInt32(ua.MessageTypeOpenFinal)
encoder.WriteUInt32(uint32(chunkSize))
encoder.WriteUInt32(ch.channelID)
// asymmetric security header
encoder.WriteString(ch.securityPolicyURI)
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
encoder.WriteByteArray(ch.localCertificate)
thumbprint := sha1.Sum(ch.remoteCertificate)
encoder.WriteByteArray(thumbprint[:])
default:
encoder.WriteByteArray(nil)
encoder.WriteByteArray(nil)
}
if plainHeaderSize != int(stream.Len()) {
return ua.BadEncodingError
}
// sequence header
encoder.WriteUInt32(ch.getNextSequenceNumber())
encoder.WriteUInt32(request.RequestHandle)
// body
_, err := io.CopyN(stream, bodyStream, int64(bodySize))
if err != nil {
return err
}
bodyCount -= bodySize
// padding
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
paddingByte := byte(paddingSize & 0xFF)
encoder.WriteByte(paddingByte)
for i := int(0); i < paddingSize; i++ {
encoder.WriteByte(paddingByte)
}
if paddingHeaderSize == 2 {
extraPaddingByte := byte((paddingSize >> 8) & 0xFF)
encoder.WriteByte(extraPaddingByte)
}
}
if bodyCount > 0 {
return ua.BadEncodingError
}
// sign
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
signature, err := ch.securityPolicy.RSASign(ch.localPrivateKey, stream.Bytes())
if err != nil {
return err
}
if len(signature) != signatureSize {
return ua.BadEncodingError
}
_, err = stream.Write(signature)
if err != nil {
return err
}
}
// encrypt
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
var encryptionBuffer = *(ch.bytesPool.Get().(*[]byte))
defer ch.bytesPool.Put(&encryptionBuffer)
position := int(stream.Len())
copy(encryptionBuffer, stream.Bytes()[:plainHeaderSize])
plainText := make([]byte, plainTextBlockSize)
jj := plainHeaderSize
for ii := plainHeaderSize; ii < position; ii += plainTextBlockSize {
copy(plainText, stream.Bytes()[ii:])
// encrypt with remote public key.
cipherText, err := ch.securityPolicy.RSAEncrypt(ch.remotePublicKey, plainText)
if err != nil {
return err
}
if len(cipherText) != cipherTextBlockSize {
return ua.BadEncodingError
}
copy(encryptionBuffer[jj:], cipherText)
jj += cipherTextBlockSize
}
if jj != chunkSize {
return ua.BadEncodingError
}
// pass buffer to transport
_, err := ch.Write(encryptionBuffer[:chunkSize])
if err != nil {
return err
}
default:
if stream.Len() != chunkSize {
return ua.BadEncodingError
}
// pass buffer to transport
_, err := ch.Write(stream.Bytes())
if err != nil {
return err
}
}
}
return nil
}
// sendCloseSecureChannelRequest sends the close secure channel request on transport channel.
func (ch *clientSecureChannel) sendCloseSecureChannelRequest(ctx context.Context, request ua.ServiceRequest) error {
var bodyStream = buffer.NewPartitionAt(ch.bufferPool)
defer bodyStream.Reset()
var sendBuffer = *(ch.bytesPool.Get().(*[]byte))
defer ch.bytesPool.Put(&sendBuffer)
var bodyEncoder = ua.NewBinaryEncoder(bodyStream, ch)
switch req := request.(type) {
case *ua.CloseSecureChannelRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDCloseSecureChannelRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
default:
return ua.BadEncodingError
}
if i := int64(ch.maxRequestMessageSize); i > 0 && bodyStream.Len() > i {
return ua.BadRequestTooLarge
}
var chunkCount int
var bodyCount = int(bodyStream.Len())
var signatureSize = ch.securityPolicy.SymSignatureSize()
var encryptionBlockSize = ch.securityPolicy.SymEncryptionBlockSize()
for bodyCount > 0 {
chunkCount++
if i := int(ch.maxRequestChunkCount); i > 0 && chunkCount > i {
return ua.BadRequestTooLarge
}
// plan
var plainHeaderSize int
var paddingHeaderSize int
var maxBodySize int
var bodySize int
var paddingSize int
var chunkSize int
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt:
plainHeaderSize = 16
if encryptionBlockSize > 256 {
paddingHeaderSize = 2
} else {
paddingHeaderSize = 1
}
maxBodySize = (((int(ch.sendBufferSize) - plainHeaderSize) / encryptionBlockSize) * encryptionBlockSize) - sequenceHeaderSize - paddingHeaderSize - signatureSize
if bodyCount < maxBodySize {
bodySize = bodyCount
paddingSize = (encryptionBlockSize - ((sequenceHeaderSize + bodySize + paddingHeaderSize + signatureSize) % encryptionBlockSize)) % encryptionBlockSize
} else {
bodySize = maxBodySize
paddingSize = 0
}
chunkSize = plainHeaderSize + sequenceHeaderSize + bodySize + paddingSize + paddingHeaderSize + signatureSize
default:
plainHeaderSize = 16
paddingHeaderSize = 0
paddingSize = 0
maxBodySize = int(ch.sendBufferSize) - plainHeaderSize - sequenceHeaderSize - paddingHeaderSize - signatureSize
if bodyCount < maxBodySize {
bodySize = bodyCount
} else {
bodySize = maxBodySize
}
chunkSize = plainHeaderSize + sequenceHeaderSize + bodySize + paddingSize + paddingHeaderSize + signatureSize
}
var stream = ua.NewWriter(sendBuffer)
var encoder = ua.NewBinaryEncoder(stream, ch)
// header
if bodyCount > bodySize {
return ua.BadEncodingError
} else {
encoder.WriteUInt32(ua.MessageTypeCloseFinal)
}
encoder.WriteUInt32(uint32(chunkSize))
encoder.WriteUInt32(ch.channelID)
// symmetric security header
encoder.WriteUInt32(ch.tokenID)
// detect new TokenId
ch.tokenLock.RLock()
if ch.tokenID != ch.sendingTokenID {
ch.sendingTokenID = ch.tokenID
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
// (re)create security keys for signing, encrypting
localSecurityKey := calculatePSHA(ch.remoteNonce, ch.localNonce, len(ch.localSigningKey)+len(ch.localEncryptingKey)+len(ch.localInitializationVector), ch.securityPolicyURI)
jj := copy(ch.localSigningKey, localSecurityKey)
jj += copy(ch.localEncryptingKey, localSecurityKey[jj:])
copy(ch.localInitializationVector, localSecurityKey[jj:])
// update signer and encrypter with new symmetric keys
ch.symSignHMAC = ch.securityPolicy.SymHMACFactory(ch.localSigningKey)
if ch.securityMode == ua.MessageSecurityModeSignAndEncrypt {
ch.symEncryptingBlockCipher, _ = aes.NewCipher(ch.localEncryptingKey)
}
}
}
ch.tokenLock.RUnlock()
// sequence header
encoder.WriteUInt32(ch.getNextSequenceNumber())
encoder.WriteUInt32(request.Header().RequestHandle)
// body
_, err := io.CopyN(stream, bodyStream, int64(bodySize))
if err != nil {
return err
}
bodyCount -= bodySize
// padding
if ch.securityMode == ua.MessageSecurityModeSignAndEncrypt {
paddingByte := byte(paddingSize & 0xFF)
encoder.WriteByte(paddingByte)
for i := 0; i < paddingSize; i++ {
encoder.WriteByte(paddingByte)
}
if paddingHeaderSize == 2 {
extraPaddingByte := byte((paddingSize >> 8) & 0xFF)
encoder.WriteByte(extraPaddingByte)
}
}
// sign
switch ch.securityMode {
case ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:
ch.symSignHMAC.Reset()
_, err := ch.symSignHMAC.Write(stream.Bytes())
if err != nil {
return err
}
signature := ch.symSignHMAC.Sum(nil)
stream.Write(signature)
}
// encrypt
if ch.securityMode == ua.MessageSecurityModeSignAndEncrypt {
span := stream.Bytes()[plainHeaderSize:]
if len(span)%ch.symEncryptingBlockCipher.BlockSize() != 0 {
return ua.BadEncodingError
}
cipher.NewCBCEncrypter(ch.symEncryptingBlockCipher, ch.localInitializationVector).CryptBlocks(span, span)
}
// pass buffer to transport
_, err = ch.Write(stream.Bytes())
if err != nil {
return err
}
}
return nil
}
// sendServiceRequest sends the service request on transport channel.
func (ch *clientSecureChannel) sendServiceRequest(ctx context.Context, request ua.ServiceRequest) error {
var bodyStream = buffer.NewPartitionAt(ch.bufferPool)
defer bodyStream.Reset()
var sendBuffer = *(ch.bytesPool.Get().(*[]byte))
defer ch.bytesPool.Put(&sendBuffer)
var bodyEncoder = ua.NewBinaryEncoder(bodyStream, ch)
switch req := request.(type) {
// frequent
case *ua.PublishRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDPublishRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.ReadRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDReadRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.BrowseRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDBrowseRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.BrowseNextRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDBrowseNextRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.TranslateBrowsePathsToNodeIDsRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDTranslateBrowsePathsToNodeIDsRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.WriteRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDWriteRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.CallRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDCallRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.HistoryReadRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDHistoryReadRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
// moderate
case *ua.GetEndpointsRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDGetEndpointsRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.OpenSecureChannelRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDOpenSecureChannelRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}
case *ua.CloseSecureChannelRequest:
if err := bodyEncoder.WriteNodeID(ua.ObjectIDCloseSecureChannelRequestEncodingDefaultBinary); err != nil {
return ua.BadEncodingError
}
if err := bodyEncoder.Encode(req); err != nil {
return ua.BadEncodingError
}