-
Notifications
You must be signed in to change notification settings - Fork 389
/
SecureChannel.java
1249 lines (1083 loc) · 61 KB
/
SecureChannel.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.plc4x.java.opcua.context;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
import org.apache.plc4x.java.opcua.config.OpcuaConfiguration;
import org.apache.plc4x.java.opcua.readwrite.*;
import org.apache.plc4x.java.spi.ConversationContext;
import org.apache.plc4x.java.spi.context.DriverContext;
import org.apache.plc4x.java.spi.generation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class SecureChannel {
private static final Logger LOGGER = LoggerFactory.getLogger(SecureChannel.class);
private static final String FINAL_CHUNK = "F";
private static final String CONTINUATION_CHUNK = "C";
private static final String ABORT_CHUNK = "A";
private static final int VERSION = 0;
private static final int DEFAULT_MAX_CHUNK_COUNT = 64;
private static final int DEFAULT_MAX_MESSAGE_SIZE = 2097152;
private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 65535;
private static final int DEFAULT_SEND_BUFFER_SIZE = 65535;
public static final Duration REQUEST_TIMEOUT = Duration.ofMillis(1000000);
public static final long REQUEST_TIMEOUT_LONG = 10000L;
private static final String PASSWORD_ENCRYPTION_ALGORITHM = "http://www.w3.org/2001/04/xmlenc#rsa-oaep";
private static final PascalString SECURITY_POLICY_NONE = new PascalString("http://opcfoundation.org/UA/SecurityPolicy#None");
protected static final PascalString NULL_STRING = new PascalString("");
private static final PascalByteString NULL_BYTE_STRING = new PascalByteString(-1, null);
private static ExpandedNodeId NULL_EXPANDED_NODEID = new ExpandedNodeId(false,
false,
new NodeIdTwoByte((short) 0),
null,
null
);
protected static final ExtensionObject NULL_EXTENSION_OBJECT = new ExtensionObject(
NULL_EXPANDED_NODEID,
new ExtensionObjectEncodingMask(false, false, false),
new NullExtension(), true); // Body
public static final Pattern INET_ADDRESS_PATTERN = Pattern.compile("(.(?<transportCode>tcp))?://" +
"(?<transportHost>[\\w.-]+)(:" +
"(?<transportPort>\\d*))?");
public static final Pattern URI_PATTERN = Pattern.compile("^(?<protocolCode>opc)" +
INET_ADDRESS_PATTERN +
"(?<transportEndpoint>[\\w/=]*)[\\?]?"
);
private static final long EPOCH_OFFSET = 116444736000000000L; //Offset between OPC UA epoch time and linux epoch time.
private static final PascalString APPLICATION_URI = new PascalString("urn:apache:plc4x:client");
private static final PascalString PRODUCT_URI = new PascalString("urn:apache:plc4x:client");
private static final PascalString APPLICATION_TEXT = new PascalString("OPCUA client for the Apache PLC4X:PLC4J project");
private static final long DEFAULT_CONNECTION_LIFETIME = 36000000;
private final String sessionName = "UaSession:" + APPLICATION_TEXT.getStringValue() + ":" + RandomStringUtils.random(20, true, true);
private final byte[] clientNonce = RandomUtils.nextBytes(40);
private final AtomicInteger requestHandleGenerator = new AtomicInteger(1);
private PascalString policyId;
private UserTokenType tokenType;
private boolean discovery;
private String certFile;
private String keyStoreFile;
private CertificateKeyPair ckp;
private final PascalString endpoint;
private final String username;
private final String password;
private final String securityPolicy;
private final PascalByteString publicCertificate;
private final PascalByteString thumbprint;
private final boolean isEncrypted;
private byte[] senderCertificate = null;
private byte[] senderNonce = null;
private PascalByteString certificateThumbprint = null;
private boolean checkedEndpoints = false;
private EncryptionHandler encryptionHandler = null;
private OpcuaConfiguration configuration;
private AtomicInteger channelId = new AtomicInteger(1);
private AtomicInteger tokenId = new AtomicInteger(1);
private NodeIdTypeDefinition authenticationToken = new NodeIdTwoByte((short) 0);
ConversationContext<OpcuaAPU> context;
private SecureChannelTransactionManager channelTransactionManager = new SecureChannelTransactionManager();
private long lifetime = DEFAULT_CONNECTION_LIFETIME;
private CompletableFuture<Void> keepAlive;
private int sendBufferSize;
private int maxMessageSize;
private List<String> endpoints = new ArrayList<>();
private AtomicLong senderSequenceNumber = new AtomicLong();
public SecureChannel(DriverContext driverContext, OpcuaConfiguration configuration) {
this.configuration = configuration;
this.endpoint = new PascalString(configuration.getEndpoint());
this.username = configuration.getUsername();
this.password = configuration.getPassword();
this.securityPolicy = "http://opcfoundation.org/UA/SecurityPolicy#" + configuration.getSecurityPolicy();
CertificateKeyPair ckp = configuration.getCertificateKeyPair();
if (configuration.getSecurityPolicy() != null && configuration.getSecurityPolicy().equals("Basic256Sha256")) {
//Sender Certificate gets populated during the 'discover' phase when encryption is enabled.
this.senderCertificate = configuration.getSenderCertificate();
this.encryptionHandler = new EncryptionHandler(ckp, this.senderCertificate, configuration.getSecurityPolicy());
try {
this.publicCertificate = new PascalByteString(ckp.getCertificate().getEncoded().length, ckp.getCertificate().getEncoded());
this.isEncrypted = true;
} catch (CertificateEncodingException e) {
throw new PlcRuntimeException("Failed to encode the certificate");
}
this.thumbprint = configuration.getThumbprint();
} else {
this.encryptionHandler = new EncryptionHandler(ckp, this.senderCertificate, configuration.getSecurityPolicy());
this.publicCertificate = NULL_BYTE_STRING;
this.thumbprint = NULL_BYTE_STRING;
this.isEncrypted = false;
}
this.keyStoreFile = configuration.getKeyStoreFile();
// Generate a list of endpoints we can use.
try {
InetAddress address = InetAddress.getByName(this.configuration.getHost());
this.endpoints.add(address.getHostAddress());
this.endpoints.add(address.getHostName());
this.endpoints.add(address.getCanonicalHostName());
} catch (UnknownHostException e) {
LOGGER.warn("Unable to resolve host name. Using original host from connection string which may cause issues connecting to server");
this.endpoints.add(this.configuration.getHost());
}
}
public void submit(ConversationContext<OpcuaAPU> context, Consumer<TimeoutException> onTimeout, BiConsumer<OpcuaAPU, Throwable> error, Consumer<byte[]> consumer, WriteBufferByteBased buffer) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
//TODO: We need to split large messages up into chunks if it is larger than the sendBufferSize
// This value is negotiated when opening a channel
OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
channelId.get(),
tokenId.get(),
transactionId,
transactionId,
buffer.getData());
final OpcuaAPU apu;
try {
if (this.isEncrypted) {
apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(messageRequest, buffer.getData()), false);
} else {
apu = new OpcuaAPU(messageRequest, false);
}
} catch (ParseException e) {
throw new PlcRuntimeException("Unable to encrypt message before sending");
}
Consumer<Integer> requestConsumer = t -> {
try {
ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream();
context.sendRequest(apu)
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.onTimeout(onTimeout)
.onError(error)
.unwrap(encryptionHandler::decodeMessage)
.unwrap(OpcuaAPU::getMessage)
.check(OpcuaMessageResponse.class::isInstance)
.unwrap(OpcuaMessageResponse.class::cast)
.check(p -> {
if (p.getRequestId() == transactionId) {
try {
messageBuffer.write(p.getMessage());
if (!(senderSequenceNumber.incrementAndGet() == (p.getSequenceNumber()))) {
LOGGER.error("Sequence number isn't as expected, we might have missed a packet. - {} != {}", senderSequenceNumber.incrementAndGet(), p.getSequenceNumber());
context.fireDisconnected();
}
} catch (IOException e) {
LOGGER.debug("Failed to store incoming message in buffer");
throw new PlcRuntimeException("Error while sending message");
}
return p.getChunk().equals(FINAL_CHUNK);
} else {
return false;
}
})
.handle(opcuaResponse -> {
if (opcuaResponse.getChunk().equals(FINAL_CHUNK)) {
tokenId.set(opcuaResponse.getSecureTokenId());
channelId.set(opcuaResponse.getSecureChannelId());
consumer.accept(messageBuffer.toByteArray());
}
});
} catch (Exception e) {
throw new PlcRuntimeException("Error while sending message");
}
};
LOGGER.debug("Submitting Transaction to TransactionManager {}", transactionId);
channelTransactionManager.submit(requestConsumer, transactionId);
}
public void onConnect(ConversationContext<OpcuaAPU> context) {
// Only the TCP transport supports login.
LOGGER.debug("Opcua Driver running in ACTIVE mode.");
this.context = context;
OpcuaHelloRequest hello = new OpcuaHelloRequest(FINAL_CHUNK,
VERSION,
DEFAULT_RECEIVE_BUFFER_SIZE,
DEFAULT_SEND_BUFFER_SIZE,
DEFAULT_MAX_MESSAGE_SIZE,
DEFAULT_MAX_CHUNK_COUNT,
this.endpoint);
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(hello, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaAcknowledgeResponse)
.unwrap(p -> (OpcuaAcknowledgeResponse) p.getMessage())
.handle(opcuaAcknowledgeResponse -> onConnectOpenSecureChannel(context, opcuaAcknowledgeResponse));
channelTransactionManager.submit(requestConsumer, channelTransactionManager.getTransactionIdentifier());
}
public void onConnectOpenSecureChannel(ConversationContext<OpcuaAPU> context, OpcuaAcknowledgeResponse opcuaAcknowledgeResponse) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
OpenSecureChannelRequest openSecureChannelRequest;
if (this.isEncrypted) {
openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
VERSION,
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeSignAndEncrypt,
new PascalByteString(clientNonce.length, clientNonce),
lifetime);
} else {
openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
VERSION,
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeNone,
NULL_BYTE_STRING,
lifetime);
}
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())),
null,
null);
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
openSecureChannelRequest,
false);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
OpcuaOpenRequest openRequest = new OpcuaOpenRequest(FINAL_CHUNK,
0,
new PascalString(this.securityPolicy),
this.publicCertificate,
this.thumbprint,
transactionId,
transactionId,
buffer.getData());
final OpcuaAPU apu;
if (this.isEncrypted) {
apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(openRequest, buffer.getData()), false);
} else {
apu = new OpcuaAPU(openRequest, false);
}
Consumer<Integer> requestConsumer = t -> context.sendRequest(apu)
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.unwrap(apuMessage -> encryptionHandler.decodeMessage(apuMessage))
.check(p -> p.getMessage() instanceof OpcuaOpenResponse)
.unwrap(p -> (OpcuaOpenResponse) p.getMessage())
.check(p -> p.getRequestId() == transactionId)
.handle(opcuaOpenResponse -> {
try {
ReadBuffer readBuffer = new ReadBufferByteBased(opcuaOpenResponse.getMessage(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
ExtensionObject message = ExtensionObject.staticParse(readBuffer, false);
//Store the initial sequence number from the server. there's no requirement for the server and client to use the same starting number.
senderSequenceNumber.set(opcuaOpenResponse.getSequenceNumber());
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Secure Response Connection Response");
try {
OpenSecureChannelResponse openSecureChannelResponse = (OpenSecureChannelResponse) message.getBody();
tokenId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getTokenId());
channelId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getChannelId());
onConnectCreateSessionRequest(context);
} catch (PlcConnectionException e) {
LOGGER.error("Error occurred while connecting to OPC UA server");
e.printStackTrace();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
});
LOGGER.debug("Submitting OpenSecureChannel with id of {}", transactionId);
channelTransactionManager.submit(requestConsumer, transactionId);
} catch (SerializationException | ParseException e) {
LOGGER.error("Unable to to Parse Open Secure Request");
}
}
public void onConnectCreateSessionRequest(ConversationContext<OpcuaAPU> context) throws PlcConnectionException {
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
LocalizedText applicationName = new LocalizedText(
true,
true,
new PascalString("en"),
APPLICATION_TEXT);
int noOfDiscoveryUrls = -1;
List<PascalString> discoveryUrls = new ArrayList<>(0);
ApplicationDescription clientDescription = new ApplicationDescription(APPLICATION_URI,
PRODUCT_URI,
applicationName,
ApplicationType.applicationTypeClient,
NULL_STRING,
NULL_STRING,
noOfDiscoveryUrls,
discoveryUrls);
CreateSessionRequest createSessionRequest = new CreateSessionRequest(
requestHeader,
clientDescription,
NULL_STRING,
this.endpoint,
new PascalString(sessionName),
new PascalByteString(clientNonce.length, clientNonce),
NULL_BYTE_STRING,
120000L,
0L);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(createSessionRequest.getIdentifier())),
null,
null);
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
createSessionRequest,
false);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
Consumer<byte[]> consumer = opcuaResponse -> {
try {
ExtensionObject message = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false);
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Create Session Response Connection Response");
try {
CreateSessionResponse responseMessage;
ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
if (unknownExtensionObject instanceof CreateSessionResponse) {
responseMessage = (CreateSessionResponse) unknownExtensionObject;
authenticationToken = responseMessage.getAuthenticationToken().getNodeId();
onConnectActivateSessionRequest(context, responseMessage, (CreateSessionResponse) message.getBody());
} else {
ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
}
} catch (PlcConnectionException e) {
LOGGER.error("Error occurred while connecting to OPC UA server");
} catch (ParseException e) {
LOGGER.error("Unable to parse the returned Subscription response");
e.printStackTrace();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
};
Consumer<TimeoutException> timeout = e -> {
LOGGER.error("Timeout while waiting for subscription response");
e.printStackTrace();
};
BiConsumer<OpcuaAPU, Throwable> error = (message, e) -> {
LOGGER.error("Error while waiting for subscription response");
e.printStackTrace();
};
submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.error("Unable to to Parse Create Session Request");
}
}
private void onConnectActivateSessionRequest(ConversationContext<OpcuaAPU> context, CreateSessionResponse opcuaMessageResponse, CreateSessionResponse sessionResponse) throws PlcConnectionException, ParseException {
senderCertificate = sessionResponse.getServerCertificate().getStringValue();
encryptionHandler.setServerCertificate(EncryptionHandler.getCertificateX509(senderCertificate));
this.senderNonce = sessionResponse.getServerNonce().getStringValue();
String[] endpoints = new String[3];
try {
InetAddress address = InetAddress.getByName(this.configuration.getHost());
endpoints[0] = "opc.tcp://" + address.getHostAddress() + ":" + configuration.getPort() + configuration.getTransportEndpoint();
endpoints[1] = "opc.tcp://" + address.getHostName() + ":" + configuration.getPort() + configuration.getTransportEndpoint();
endpoints[2] = "opc.tcp://" + address.getCanonicalHostName() + ":" + configuration.getPort() + configuration.getTransportEndpoint();
} catch (UnknownHostException e) {
e.printStackTrace();
}
selectEndpoint(sessionResponse);
if (this.policyId == null) {
throw new PlcRuntimeException("Unable to find endpoint - " + endpoints[1]);
}
ExtensionObject userIdentityToken = getIdentityToken(this.tokenType, policyId.getStringValue());
int requestHandle = getRequestHandle();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
requestHandle,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
SignatureData clientSignature = new SignatureData(NULL_STRING, NULL_BYTE_STRING);
ActivateSessionRequest activateSessionRequest = new ActivateSessionRequest(
requestHeader,
clientSignature,
0,
null,
0,
null,
userIdentityToken,
clientSignature);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(activateSessionRequest.getIdentifier())),
null,
null);
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
activateSessionRequest,
true);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
Consumer<byte[]> consumer = opcuaResponse -> {
try {
ExtensionObject message = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false);
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Activate Session Response Connection Response");
try {
ActivateSessionResponse responseMessage;
ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
if (unknownExtensionObject instanceof ActivateSessionResponse) {
responseMessage = (ActivateSessionResponse) unknownExtensionObject;
long returnedRequestHandle = ((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle();
if (!(requestHandle == returnedRequestHandle)) {
LOGGER.error("Request handle isn't as expected, we might have missed a packet. {} != {}", requestHandle, returnedRequestHandle);
}
// Send an event that connection setup is complete.
keepAlive();
context.fireConnected();
} else {
ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
}
} catch (ParseException e) {
LOGGER.error("Unable to parse the returned Subscription response");
e.printStackTrace();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
};
Consumer<TimeoutException> timeout = e -> {
LOGGER.error("Timeout while waiting for activate session response");
e.printStackTrace();
};
BiConsumer<OpcuaAPU, Throwable> error = (message, e) -> {
LOGGER.error("Error while waiting for activate session response");
e.printStackTrace();
};
submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.error("Unable to to Parse Activate Session Request");
}
}
public void onDisconnect(ConversationContext<OpcuaAPU> context) {
LOGGER.info("Disconnecting");
int requestHandle = getRequestHandle();
if (keepAlive != null) {
keepAlive.complete(null);
}
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, 473),
null,
null); //Identifier for OpenSecureChannel
RequestHeader requestHeader = new RequestHeader(
new NodeId(authenticationToken),
getCurrentDateTime(),
requestHandle, //RequestHandle
0L,
NULL_STRING,
5000L,
NULL_EXTENSION_OBJECT);
CloseSessionRequest closeSessionRequest = new CloseSessionRequest(
requestHeader,
true);
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
closeSessionRequest,
true);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
Consumer<byte[]> consumer = opcuaResponse -> {
try {
ExtensionObject message = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false);
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Close Session Response Connection Response");
try {
CloseSessionResponse responseMessage;
ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
if (unknownExtensionObject instanceof CloseSessionResponse) {
responseMessage = (CloseSessionResponse) unknownExtensionObject;
LOGGER.trace("Got Close Session Response Connection Response" + responseMessage);
onDisconnectCloseSecureChannel(context);
} else {
ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
}
} catch (ParseException e) {
LOGGER.error("Unable to parse the returned Close Session response");
e.printStackTrace();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
};
Consumer<TimeoutException> timeout = e -> {
LOGGER.error("Timeout while waiting for close session response");
e.printStackTrace();
};
BiConsumer<OpcuaAPU, Throwable> error = (message, e) -> {
LOGGER.error("Error while waiting for close session response");
e.printStackTrace();
};
submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.error("Unable to to Parse Close Session Request");
}
}
private void onDisconnectCloseSecureChannel(ConversationContext<OpcuaAPU> context) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
CloseSecureChannelRequest closeSecureChannelRequest = new CloseSecureChannelRequest(requestHeader);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(closeSecureChannelRequest.getIdentifier())),
null,
null);
OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(FINAL_CHUNK,
channelId.get(),
tokenId.get(),
transactionId,
transactionId,
new ExtensionObject(
expandedNodeId,
null,
closeSecureChannelRequest,
true));
Consumer<Integer> requestConsumer = t -> {
context.sendRequest(new OpcuaAPU(closeRequest, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaMessageResponse)
.unwrap(p -> (OpcuaMessageResponse) p.getMessage())
.check(p -> p.getRequestId() == transactionId)
.handle(opcuaMessageResponse -> LOGGER.trace("Got Close Secure Channel Response" + opcuaMessageResponse.toString()));
context.fireDisconnected();
};
channelTransactionManager.submit(requestConsumer, transactionId);
}
public void onDiscover(ConversationContext<OpcuaAPU> context) {
// Only the TCP transport supports login.
LOGGER.debug("Opcua Driver running in ACTIVE mode, discovering endpoints");
OpcuaHelloRequest hello = new OpcuaHelloRequest(FINAL_CHUNK,
VERSION,
DEFAULT_RECEIVE_BUFFER_SIZE,
DEFAULT_SEND_BUFFER_SIZE,
DEFAULT_MAX_MESSAGE_SIZE,
DEFAULT_MAX_CHUNK_COUNT,
this.endpoint);
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(hello, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaAcknowledgeResponse)
.unwrap(p -> (OpcuaAcknowledgeResponse) p.getMessage())
.handle(opcuaAcknowledgeResponse -> {
LOGGER.debug("Got Hello Response Connection Response");
onDiscoverOpenSecureChannel(context, opcuaAcknowledgeResponse);
});
channelTransactionManager.submit(requestConsumer, 1);
}
public void onDiscoverOpenSecureChannel(ConversationContext<OpcuaAPU> context, OpcuaAcknowledgeResponse opcuaAcknowledgeResponse) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
OpenSecureChannelRequest openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
VERSION,
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeNone,
NULL_BYTE_STRING,
lifetime);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())),
null,
null);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(openSecureChannelRequest.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
new ExtensionObject(
expandedNodeId,
null,
openSecureChannelRequest,
true).serialize(buffer);
OpcuaOpenRequest openRequest = new OpcuaOpenRequest(FINAL_CHUNK,
0,
SECURITY_POLICY_NONE,
NULL_BYTE_STRING,
NULL_BYTE_STRING,
transactionId,
transactionId,
buffer.getData());
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(openRequest, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaOpenResponse)
.unwrap(p -> (OpcuaOpenResponse) p.getMessage())
.check(p -> p.getRequestId() == transactionId)
.handle(opcuaOpenResponse -> {
try {
ExtensionObject message = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaOpenResponse.getMessage(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false);
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Secure Response Connection Response");
try {
onDiscoverGetEndpointsRequest(context, opcuaOpenResponse, (OpenSecureChannelResponse) message.getBody());
} catch (PlcConnectionException e) {
LOGGER.error("Error occurred while connecting to OPC UA server");
}
}
} catch (ParseException e) {
e.printStackTrace();
}
});
channelTransactionManager.submit(requestConsumer, transactionId);
} catch (SerializationException e) {
LOGGER.error("Unable to to Parse Create Session Request");
}
}
public void onDiscoverGetEndpointsRequest(ConversationContext<OpcuaAPU> context, OpcuaOpenResponse opcuaOpenResponse, OpenSecureChannelResponse openSecureChannelResponse) throws PlcConnectionException {
tokenId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getTokenId());
channelId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getChannelId());
int transactionId = channelTransactionManager.getTransactionIdentifier();
int nextSequenceNumber = opcuaOpenResponse.getSequenceNumber() + 1;
int nextRequestId = opcuaOpenResponse.getRequestId() + 1;
if (!(transactionId == nextSequenceNumber)) {
LOGGER.error("Sequence number isn't as expected, we might have missed a packet. - " + transactionId + " != " + nextSequenceNumber);
throw new PlcConnectionException("Sequence number isn't as expected, we might have missed a packet. - " + transactionId + " != " + nextSequenceNumber);
}
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
GetEndpointsRequest endpointsRequest = new GetEndpointsRequest(
requestHeader,
this.endpoint,
0,
null,
0,
null);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(endpointsRequest.getIdentifier())),
null,
null);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(endpointsRequest.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
new ExtensionObject(
expandedNodeId,
null,
endpointsRequest,
true).serialize(buffer);
OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
channelId.get(),
tokenId.get(),
nextSequenceNumber,
nextRequestId,
buffer.getData());
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(messageRequest, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaMessageResponse)
.unwrap(p -> (OpcuaMessageResponse) p.getMessage())
.check(p -> p.getRequestId() == transactionId)
.handle(opcuaMessageResponse -> {
try {
ExtensionObject message = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaMessageResponse.getMessage(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false);
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
} else {
LOGGER.debug("Got Create Session Response Connection Response");
GetEndpointsResponse response = (GetEndpointsResponse) message.getBody();
List<ExtensionObjectDefinition> endpoints = response.getEndpoints();
for (ExtensionObjectDefinition endpoint : endpoints) {
EndpointDescription endpointDescription = (EndpointDescription) endpoint;
if (endpointDescription.getEndpointUrl().getStringValue().equals(this.endpoint.getStringValue()) && endpointDescription.getSecurityPolicyUri().getStringValue().equals(this.securityPolicy)) {
LOGGER.info("Found OPC UA endpoint {}", this.endpoint.getStringValue());
this.configuration.setSenderCertificate(endpointDescription.getServerCertificate().getStringValue());
}
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] digest = messageDigest.digest(this.configuration.getSenderCertificate());
this.configuration.setThumbprint(new PascalByteString(digest.length, digest));
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Failed to find hashing algorithm");
}
onDiscoverCloseSecureChannel(context, response);
}
} catch (ParseException e) {
e.printStackTrace();
}
});
channelTransactionManager.submit(requestConsumer, transactionId);
} catch (SerializationException e) {
LOGGER.error("Unable to to Parse Create Session Request");
}
}
private void onDiscoverCloseSecureChannel(ConversationContext<OpcuaAPU> context, GetEndpointsResponse message) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
CloseSecureChannelRequest closeSecureChannelRequest = new CloseSecureChannelRequest(requestHeader);
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(closeSecureChannelRequest.getIdentifier())),
null,
null);
OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(FINAL_CHUNK,
channelId.get(),
tokenId.get(),
transactionId,
transactionId,
new ExtensionObject(
expandedNodeId,
null,
closeSecureChannelRequest,
true));
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(closeRequest, false))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaMessageResponse)
.unwrap(p -> (OpcuaMessageResponse) p.getMessage())
.check(p -> p.getRequestId() == transactionId)
.handle(opcuaMessageResponse -> {
LOGGER.trace("Got Close Secure Channel Response" + opcuaMessageResponse.toString());
// Send an event that connection setup is complete.
context.fireDiscovered(this.configuration);
});
channelTransactionManager.submit(requestConsumer, transactionId);
}
private void keepAlive() {
keepAlive = CompletableFuture.supplyAsync(() -> {
while (true) {
try {
Thread.sleep((long) Math.ceil(this.lifetime * 0.75f));
} catch (InterruptedException e) {
LOGGER.trace("Interrupted Exception");
}
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
OpenSecureChannelRequest openSecureChannelRequest;
if (this.isEncrypted) {
openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
VERSION,
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeSignAndEncrypt,
new PascalByteString(clientNonce.length, clientNonce),
lifetime);
} else {
openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
VERSION,
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeNone,
NULL_BYTE_STRING,
lifetime);
}
ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())),