-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmessages.py
More file actions
442 lines (372 loc) · 14.1 KB
/
messages.py
File metadata and controls
442 lines (372 loc) · 14.1 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
from message_fields import *
from abc import ABC
import struct
from typing import *
from dataclasses import dataclass
# Exception signifying rgar a CloseSecureChannelRequest was received when expecting something else.
class ClientClosedChannel(Exception):
pass
# Main "outer" messages.
class OpcMessage(ABC):
def __init__(self, **field_values):
for name, ftype in self.fields:
setattr(self, name, field_values.get(name, ftype.default_value))
@property
@abstractmethod
def messagetype() -> str:
...
@property
@abstractmethod
def fields() -> list[tuple[str, FieldType]]:
...
def to_bytes(self, final_chunk : bool = True) -> bytes:
mtype = self.messagetype.encode()
chunkmarker = b'F' if final_chunk else b'C'
assert len(mtype) == 3
body = b''
for name, ftype in self.fields:
value = getattr(self, name)
body += ftype.to_bytes(value)
return mtype + chunkmarker + struct.pack('<I', len(body) + 8) + body
def from_bytes(self, reader : BinaryIO, allow_chunking : bool = False) -> bool:
# Note: when this throws a ServerError the message is still consumed in its entirety from the reader.
# Returns whether this is the final chunk.
mtype = reader.read(3)
decodecheck(len(mtype) == 3, 'Connection unexpectedly terminated.')
decodecheck(mtype == self.messagetype.encode() or mtype in [b'ERR',b'CLO'], 'Unexpected message type')
ctype = reader.read(1)
decodecheck(ctype == b'F' or ctype == b'C')
decodecheck(ctype == b'F' or allow_chunking, f'Unexpected chunked message.')
bodylen = struct.unpack('<I', reader.read(4))[0] - 8
body = reader.read(bodylen)
if mtype == b'ERR' and self.messagetype != 'ERR':
# Unexpected server error. Parse for exception.
errorcode, tail = IntField().from_bytes(body)
reason, _ = StringField().from_bytes(tail)
raise ServerError(errorcode, reason)
if mtype == b'CLO' and self.messagetype != 'CLO':
# Unexpected client channel closure.
raise ClientClosedChannel()
for name, ftype in self.fields:
value, body = ftype.from_bytes(body)
setattr(self, name, value)
return ctype == b'F'
def get_field_location(self, fieldname : str) -> int:
'''Returns binary (offset, length) of a specific field within the result of self.to_bytes()'''
offset = 8
for name, ftype in self.fields:
value = getattr(self, name)
valsize = len(ftype.to_bytes(value))
if name == fieldname:
return offset, valsize
else:
offset += valsize
raise Exception(f'Field {fieldname} does not exist.')
def sign_and_encrypt(self,
signer : Callable[[bytes], bytes], encrypter : Optional[Callable[[bytes], bytes]],
plainblocksize : int, cipherblocksize : int, sigsize : int
):
'''Applies OPC's weird padding scheme and sign/encrypt combo to TrailingBytes of the message.'''
trailname, trailtype = self.fields[-1]
assert isinstance(trailtype, TrailingBytes)
plaintext = getattr(self, trailname)
# Length calculations.
padbyte = plainblocksize - (len(plaintext) + 1 + sigsize) % plainblocksize
if padbyte < 256:
padding = (padbyte + 1) * bytes([padbyte])
else:
padding = (padbyte + 1) * bytes([padbyte % 256]) + bytes([padbyte // 256])
ptextsize = len(plaintext) + len(padding) + sigsize
ctextsize = (ptextsize // plainblocksize) * cipherblocksize
# Add padding and adjust length to obtain signature input.
setattr(self, trailname, plaintext + padding)
siginput = self.to_bytes()
siginput = siginput[:4] + IntField().to_bytes(len(siginput) - len(plaintext) - len(padding) + ctextsize) + siginput[8:]
signature = signer(siginput)
# Encrypt plaintext, padding and signature.
ciphertext = encrypter(plaintext + padding + signature)
assert len(ciphertext) == ctextsize
setattr(self, trailname, ciphertext)
assert(len(self.to_bytes()) == len(siginput) - len(plaintext) - len(padding) + ctextsize)
def sign(self, signer : Callable[[bytes], bytes], sigsize : int):
'''Message signing without encryption and padding.'''
trailname, trailtype = self.fields[-1]
assert isinstance(trailtype, TrailingBytes)
siginput = self.to_bytes()
siginput = siginput[:4] + IntField().to_bytes(len(siginput) + sigsize) + siginput[8:]
signature = signer(siginput)
setattr(self, trailname, getattr(self, trailname) + signature)
# Messages.
class HelloMessage(OpcMessage):
messagetype = 'HEL'
fields = [
('version', IntField()),
('receiveBufferSize', IntField()),
('sendBufferSize', IntField()),
('maxMessageSize', IntField()),
('maxChunkCount', IntField()),
('endpointUrl', StringField()),
]
class AckMessage(OpcMessage):
messagetype = 'ACK'
fields = [
('version', IntField()),
('receiveBufferSize', IntField()),
('sendBufferSize', IntField()),
('maxMessageSize', IntField()),
('maxChunkCount', IntField()),
]
class OpenSecureChannelMessage(OpcMessage):
messagetype = 'OPN'
fields = [
('secureChannelId', IntField()),
('securityPolicyUri', SecurityPolicyField()),
('senderCertificate', ByteStringField()),
('receiverCertificateThumbprint', ByteStringField()),
('encodedPart', TrailingBytes()),
]
class ConversationMessage(OpcMessage):
messagetype = 'MSG'
fields = [
('secureChannelId', IntField()),
('tokenId', IntField()),
('encodedPart', TrailingBytes())
]
class ReverseHelloMessage(OpcMessage):
messagetype = 'RHE'
fields = [
('serverUri', StringField()),
('endpointUrl', StringField()),
]
encodedConversation = ObjectField('EncodedConversation', [
('sequenceNumber', IntField()),
('requestId', IntField()),
('requestOrResponse', TrailingBytes()),
])
# Enumerations.
class SecurityTokenRequestType(IntEnum):
ISSUE = 0
RENEW = 1
class MessageSecurityMode(IntEnum):
INVALID = 0
NONE = 1
SIGN = 2
SIGN_AND_ENCRYPT = 3
class ApplicationType(IntEnum):
SERVER = 0
CLIENT = 1
CLIENTANDSERVER = 2
DISCOVERYSERVER = 3
class UserTokenType(IntEnum):
ANONYMOUS = 0
USERNAME = 1
CERTIFICATE = 2
ISSUEDTOKEN = 3
class TimestampsToReturn(IntEnum):
SOURCE = 0
SERVER = 1
BOTH = 2
NEITHER = 3
INVALID = 4
class BrowseDirection(IntEnum):
FORWARD = 0
INVERSE = 1
BOTH = 2
INVALID = 3
class NodeClass(IntEnum):
UNSPECIFIED = 0
OBJECT = 1
VARIABLE = 2
METHOD = 4
OBJECTTYPE = 8
VARIABLETYPE = 16
REFERENCETYPE = 32
DATATYPE = 64
VIEW = 128
# Encoded requests and responses. Based on UA-.NETStandard/Stack/Opc.Ua.Core/Schema/{NodeIds.csv,Opc.Ua.Types.bsd}
# and UA-.NETStandard/Stack/Opc.Ua.Core/Types/Encoders/BinaryEncoder.cs
requestHeader = ObjectField('RequestHeader', [
('authenticationToken', NodeIdField()),
('timeStamp', DateTimeField()),
('requestHandle', IntField()),
('returnDiagnostics', IntField()),
('auditEntryId', StringField()),
('timeoutHint', IntField()),
('additionalHeader', ExtensionObjectField()),
])
responseHeader = ObjectField('ResponseHeader', [
('timeStamp', DateTimeField()),
('requestHandle', IntField()),
('serviceResult', IntField()),
('serviceDiagnostics', FixedBytes(b'\x00')), # Just assume this stays empty for now.
('stringTable', ArrayField(StringField())),
('additionalHeader', ExtensionObjectField()),
])
applicationDescription = ObjectField('ApplicationDescription', [
('applicationUri', StringField()),
('productUri', StringField()),
('applicationName', LocalizedTextField()),
('applicationType', EnumField(ApplicationType)),
('gatewayServerUri', StringField()),
('discoveryProfileUri', StringField()),
('discoveryUrls', ArrayField(StringField())),
])
openSecureChannelRequest = EncodableObjectField('OpenSecureChannelRequest', 446, [
('requestHeader', requestHeader),
('clientProtocolVersion', IntField()),
('requestType', EnumField(SecurityTokenRequestType)),
('securityMode', EnumField(MessageSecurityMode)),
('clientNonce', ByteStringField()),
('requestedLifetime', IntField()),
])
channelSecurityToken = ObjectField('ChannelSecurityToken', [
('channelId', IntField()),
('tokenId', IntField()),
('createdAt', DateTimeField()),
('revisedLifetime', IntField()),
])
openSecureChannelResponse = EncodableObjectField('OpenSecureChannelResponse', 449, [
('responseHeader', responseHeader),
('serverProtocolVersion', IntField()),
('securityToken', channelSecurityToken),
('serverNonce', ByteStringField()),
])
createSessionRequest = EncodableObjectField('CreateSessionRequest', 461, [
('requestHeader', requestHeader),
('clientDescription', applicationDescription),
('serverUri', StringField()),
('endpointUrl', StringField()),
('sessionName', StringField()),
('clientNonce', ByteStringField()),
('clientCertificate', ByteStringField()),
('requestedSessionTimeout', DoubleField()),
('maxResponseMessageSize', IntField()),
])
userTokenPolicy = ObjectField('UserTokenPolicy', [
('policyId', StringField()),
('tokenType', EnumField(UserTokenType)),
('issuedTokenType', StringField()),
('issuerEndpointUrl', StringField()),
('securityPolicyUri', SecurityPolicyField()),
])
endpointDescription = ObjectField('EndpointDescription', [
('endpointUrl', StringField()),
('server', applicationDescription),
('serverCertificate', ByteStringField()),
('securityMode', EnumField(MessageSecurityMode)),
('securityPolicyUri', SecurityPolicyField()),
('userIdentityTokens', ArrayField(userTokenPolicy)),
('transportProfileUri', StringField()),
('securityLevel', IntField('<B')),
])
signedSoftwareCertificate = ObjectField('SignedSoftwareCertificate', [
('certificateData', ByteStringField()),
('signature', ByteStringField()),
])
signatureData = ObjectField('SignatureData', [
('algorithm', StringField()),
('signature', ByteStringField()),
])
createSessionResponse = EncodableObjectField('CreateSessionResponse', 464, [
('responseHeader', responseHeader),
('sessionId', NodeIdField()),
('authenticationToken', NodeIdField()),
('revisedSessionTimeout', DoubleField()),
('serverNonce', ByteStringField()),
('serverCertificate', ByteStringField()),
('serverEndpoints', ArrayField(endpointDescription)),
('serverSoftwareCertificates', ArrayField(signedSoftwareCertificate)),
('serverSignature', signatureData),
('maxRequestMessageSize', IntField()),
])
activateSessionRequest = EncodableObjectField('ActivateSessionRequest', 467, [
('requestHeader', requestHeader),
('clientSignature', signatureData),
('clientSoftwareCertificates', ArrayField(signedSoftwareCertificate)),
('localeIds', ArrayField(StringField())),
('userIdentityToken', ExtensionObjectField()),
('userTokenSignature', signatureData),
])
activateSessionResponse = EncodableObjectField('ActivateSessionResponse', 470, [
('responseHeader', responseHeader),
('serverNonce', ByteStringField()),
('results', ArrayField(IntField())),
('diagnosticInfos', TrailingBytes()), # Not bothering to parse this
])
readValueId = ObjectField('ReadValueId', [
('nodeId', NodeIdField()),
('attributeId', IntField()),
('indexRange', StringField()),
('dataEncoding', QualifiedNameField()),
])
getEndpointsRequest = EncodableObjectField('GetEndpointsRequest', 428, [
('requestHeader', requestHeader),
('endpointUrl', StringField()),
('localeIds', ArrayField(StringField())),
('profileUris', ArrayField(StringField())),
])
getEndpointsResponse = EncodableObjectField('GetEndpointsResponse', 431, [
('responseHeader', responseHeader),
('endpoints', ArrayField(endpointDescription)),
])
readRequest = EncodableObjectField('ReadRequest', 631, [
('requestHeader', requestHeader),
('maxAge', DoubleField()),
('timestampsToReturn', EnumField(TimestampsToReturn)),
('nodesToRead', ArrayField(readValueId)),
])
readResponse = EncodableObjectField('ReadResponse', 634, [
('responseHeader', responseHeader),
('results', ArrayField(DataValueField())),
('diagnosticInfos', TrailingBytes()),
])
viewDescription = ObjectField('ViewDescription', [
('viewId', NodeIdField()),
('timestamp', DateTimeField()),
('viewVersion', IntField()),
])
browseDescription = ObjectField('BrowseDescription', [
('nodeId', NodeIdField()),
('browseDirection', EnumField(BrowseDirection)),
('referenceTypeId', NodeIdField()),
('includeSubtypes', BooleanField()),
('nodeClassMask', IntField()),
('resultMask', IntField()),
])
browseRequest = EncodableObjectField('BrowseRequest', 527, [
('requestHeader', requestHeader),
('view', viewDescription),
('requestedMaxReferencesPerNode', IntField()),
('nodesToBrowse', ArrayField(browseDescription)),
])
browseResponse = EncodableObjectField('BrowseResponse', 530, [
('responseHeader', responseHeader),
('results', ArrayField(ObjectField('BrowseResult', [
('statusCode', IntField()),
('continuationPoint', ByteStringField()),
('references', ArrayField(ObjectField('ReferenceDescription', [
('referenceTypeId', NodeIdField()),
('isForward', BooleanField()),
('nodeId', ExpandedNodeIdField()),
('browseName', QualifiedNameField()),
('displayName', LocalizedTextField()),
('nodeClass', EnumField(NodeClass)),
('typeDefinition', ExpandedNodeIdField()),
]))),
]))),
('diagnosticInfos', TrailingBytes()),
])
# Supported extension objects.
anonymousIdentityToken = ExtensionObjectField.register('AnonymousIdentityToken', 321, [
('policyId', StringField()),
])
userNameIdentityToken = ExtensionObjectField.register('UserNameIdentityToken', 324, [
('policyId', StringField()),
('userName', StringField()),
('password', ByteStringField()),
('encryptionAlgorithm', StringField()),
])
x509IdentityToken = ExtensionObjectField.register('X509IdentityToken', 327, [
('policyId', StringField()),
('certificateData', ByteStringField()),
])