-
Notifications
You must be signed in to change notification settings - Fork 9
/
JSON2dotnetBinaryFormatter.py
350 lines (300 loc) · 10.7 KB
/
JSON2dotnetBinaryFormatter.py
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
# -*- coding: utf-8 -*-
import sys
import json
import struct
import argparse
import base64
import urllib
myClasses = {}
def Length(string):
value = len(string)
ret = ''
while value >= 0x80:
ret += chr((value | 0x80)&0xff)
value >>= 7
ret += chr(value)
return ret
def LengthPrefixedString(string, options=''):
ret = Length(string.encode('utf8'))+string.encode('utf8')
return ret
def ClassInfo(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += LengthPrefixedString(s['Name'])
ret += struct.pack('<I', s['MemberCount'])
for m in range(s['MemberCount']):
ret += LengthPrefixedString(s['MemberNames'][m])
return ret
def date(s, options):
return s.decode("hex")
def pack_value(s, options):
return struct.pack(options[1], s)
def none(s):
return ''
PrimitiveTypeEnumeration = {
'Boolean':[1,pack_value, [1, '<B']],
'Byte':[2, pack_value, [1, '<B']],
'Char':[3, pack_value, [1, '<b']],
'Decimal':[5, LengthPrefixedString, 0],
'Double':[6, pack_value, [8, '<Q']],
'Int16':[7, pack_value, [2, '<h']],
'Int32':[8, pack_value, [4, '<i']],
'Int64':[9, pack_value, [8, '<q']],
'SByte':[10, pack_value, [1, '<B']],
'Single':[11, pack_value, [4, '<I']],
'TimeSpan':[12, date, [8, '<Q']],
'DateTime':[13, date, [8, '<Q']],
'UInt16':[14, pack_value, [2, '<H']],
'UInt32':[15, pack_value, [4, '<I']],
'UInt64':[16, pack_value, [8, '<Q']],
'Null':[17, pack_value, [1, '<B']],
'String':[18, LengthPrefixedString, 0]
}
def Primitive(s):
ret = ''
ret += struct.pack('<B', PrimitiveTypeEnumeration[s][0])
return ret
def SystemClass(s):
return LengthPrefixedString(s)
def ClassTypeInfo(s):
ret = ''
ret += LengthPrefixedString(s['TypeName'])
ret += struct.pack('<I', s['LibraryId'])
return ret
BinaryTypeEnumeration = {
'Primitive':[0, Primitive],
'String':[1, none],
'Object':[2, none],
'SystemClass':[3, SystemClass],
'Class':[4, ClassTypeInfo],
'ObjectArray':[5, none],
'StringArray':[6, none],
'PrimitiveArray':[7, Primitive]
}
def MemberTypeInfo(s, c):
ret = ''
for i in range(c):
ret += struct.pack('<B', BinaryTypeEnumeration[s['BinaryTypeEnums'][i]][0])
for i in range(c):
ret += BinaryTypeEnumeration[s['BinaryTypeEnums'][i]][1](s['AdditionalInfos'][i][1])
return ret
def parse_value(val, typeEnum, info):
ret = ''
if typeEnum == 'Primitive':
ret += PrimitiveTypeEnumeration[info[1]][1](val, PrimitiveTypeEnumeration[info[1]][2])
else:
RecordType = RecordTypeEnum[val[0]]
ret += struct.pack('<B', RecordType[0])
ret += RecordType[1](val[1])
return ret
def parse_values(s, type, c):
ret = ''
for i in range(c):
ret += parse_value(s[i][1], type['BinaryTypeEnums'][i], type['AdditionalInfos'][i])
return ret
def ClassWithMembersAndTypes(s):
global myClasses
ret = ''
ret += ClassInfo(s['ClassInfo'])
ret += MemberTypeInfo(s['MemberTypeInfo'], s['ClassInfo']['MemberCount'])
ret += struct.pack('<I', s['LibraryId'])
myClasses[s['ClassInfo']['ObjectId']]={'Name': s['ClassInfo']['Name'], 'MemberTypeInfo': s['MemberTypeInfo'], 'MemberCount': s['ClassInfo']['MemberCount']}
ret += parse_values(s['Values'], s['MemberTypeInfo'], s['ClassInfo']['MemberCount'])
return ret
def SystemClassWithMembersAndTypes(s):
global myClasses
ret = ''
ret += ClassInfo(s['ClassInfo'])
ret += MemberTypeInfo(s['MemberTypeInfo'], s['ClassInfo']['MemberCount'])
myClasses[s['ClassInfo']['ObjectId']]={'Name': s['ClassInfo']['Name'], 'MemberTypeInfo': s['MemberTypeInfo'], 'MemberCount': s['ClassInfo']['MemberCount']}
ret += parse_values(s['Values'], s['MemberTypeInfo'], s['ClassInfo']['MemberCount'])
return ret
def MemberReference(s):
return struct.pack('<I', s['IdRef'])
def BinaryLibrary(s):
ret = ''
ret += struct.pack('<I', s['LibraryId'])
ret += LengthPrefixedString(s['LibraryName'])
return ret
def SerializedStreamHeader(s):
return struct.pack('<IIII', s['RootId'], s['HeaderId'], s['MajorVersion'], s['MinorVersion'])
BinaryArrayTypeEnumeration = {
'Single':[0],
'Jagged':[1],
'Rectangular':[2],
'SingleOffset':[3],
'JaggedOffset':[4],
'RectangularOffset':[5]
}
def BinaryArray(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<B', BinaryArrayTypeEnumeration[s['BinaryArrayTypeEnum']][0])
ret += struct.pack('<I', s['Rank'])
for i in range(s['Rank']):
ret += struct.pack('<I', s['Lengths'][i])
if 'Offset' in s['BinaryArrayTypeEnum']:
for i in range(s['Rank']):
ret += struct.pack('<I', s['LowerBounds'][i])
ret += struct.pack('<B', BinaryTypeEnumeration[s['TypeEnum']][0])
ret += BinaryTypeEnumeration[s['TypeEnum']][1](s['AdditionalTypeInfo'])
return ret
def BinaryObjectString(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += LengthPrefixedString(s['Value'])
return ret
def ClassWithId(s):
global myClasses
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<I', s['MetadataId'])
theclass = myClasses[s['MetadataId']]
ret += parse_values(s['Values'], theclass['MemberTypeInfo'], theclass['MemberCount'])
return ret
def ArraySingleObject(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<I', s['Length'])
for o in range(s['Length']):
ret += parse_value(s['Values'][o], '', '')
return ret
def ArraySingleString(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<I', s['Length'])
for o in range(s['Length']):
ret += parse_value(s['Values'][o], '', '')
return ret
def ArraySinglePrimitive(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<I', s['Length'])
ret += struct.pack('<B', PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][0])
for o in range(s['Length']):
ret += PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][1](s['Values'][o], PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][2])
return ret
def ArraySinglePrimitiveBig(s):
ret = ''
ret += struct.pack('<I', s['ObjectId'])
ret += struct.pack('<I', s['Length'])
ret += struct.pack('<B', PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][0])
ret += s['Values']
return ret
def MemberPrimitiveTyped(s):
memberPrimitiveTyped = {}
primitive = Primitive(s)
value = primitive[1](s, primitive[2])
memberPrimitiveTyped['PrimitiveTypeEnum'] = primitive[0]
memberPrimitiveTyped['Value'] = value
return memberPrimitiveTyped
def ObjectNullMultiple256(s):
ret = ''
ret += struct.pack('<B', s['NullCount'])
return ret
def ObjectNullMultiple(s):
ret = ''
ret += struct.pack('<I', s['NullCount'])
return ret
def MemberPrimitiveTyped(s):
ret = ''
ret += struct.pack('<B', PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][0])
ret += PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][1](s['Value'], PrimitiveTypeEnumeration[s['PrimitiveTypeEnum']][2])
return ret
def MethodCall(s):
ret = ''
ret += struct.pack('<I', s['MessageEnum'])
ret += StringValueWithCode(s['MethodName'])
ret += StringValueWithCode(s['TypeName'])
if s['MessageEnum'] & MessageFlagsEnum['NoContext'] == 0:
ret += StringValueWithCode(s['CallContext'])
if s['MessageEnum'] & MessageFlagsEnum['NoArgs'] == 0:
ret += ArrayOfValueWithCode(s['Args'])
return ret
def MethodReturn(s):
ret = ''
ret += struct.pack('<I', s['MessageEnum'])
ret += StringValueWithCode(s['MethodName'])
ret += StringValueWithCode(s['TypeName'])
if s['MessageEnum'] & MessageFlagsEnum['NoContext'] == 0:
ret += StringValueWithCode(s['CallContext'])
if s['MessageEnum'] & MessageFlagsEnum['NoArgs'] == 0:
ret += ArrayOfValueWithCode(s['Args'])
return ret
def ArrayOfValueWithCode(s):
ret = ''
ret += struct.pack('<I', s['Length'])
for v in s['ListOfValueWithCode']:
ret += struct.pack('<B', PrimitiveTypeEnumeration[v['PrimitiveTypeEnum']][0])
ret += PrimitiveTypeEnumeration[v['PrimitiveTypeEnum']][1](v['Value'], PrimitiveTypeEnumeration[v['PrimitiveTypeEnum']][2])
return ret
def StringValueWithCode(s):
ret = ''
ret += struct.pack('<B', PrimitiveTypeEnumeration['String'][0])
ret += LengthPrefixedString(s)
return ret
MessageFlagsEnum = {
'NoArgs': 0x00000001,
'ArgsInline': 0x00000002,
'ArgsIsArray': 0x00000004,
'ArgsInArray': 0x00000008,
'NoContext': 0x00000010,
'ContextInline': 0x00000020,
'ContextInArray': 0x00000040,
'MethodSignatureInArray': 0x00000080,
'PropertiesInArray': 0x00000100,
'NoReturnValue': 0x00000200,
'ReturnValueVoid': 0x00000400,
'ReturnValueInline': 0x00000800,
'ReturnValueInArray': 0x00001000,
'ExceptionInArray': 0x00002000,
'GenericMethod': 0x00008000
}
RecordTypeEnum = {
'SerializedStreamHeader':[0, SerializedStreamHeader],
'ClassWithId':[1, ClassWithId],
'SystemClassWithMembers':[2, ],
'ClassWithMembers':[3, ],
'SystemClassWithMembersAndTypes':[4, SystemClassWithMembersAndTypes],
'ClassWithMembersAndTypes':[5, ClassWithMembersAndTypes],
'BinaryObjectString':[6, BinaryObjectString],
'BinaryArray':[7, BinaryArray],
'MemberPrimitiveTyped':[8, MemberPrimitiveTyped],
'MemberReference':[9, MemberReference],
'ObjectNull':[10, none],
'MessageEnd':[11, none],
'BinaryLibrary':[12, BinaryLibrary],
'ObjectNullMultiple256':[13, ObjectNullMultiple256],
'ObjectNullMultiple':[14, ObjectNullMultiple],
'ArraySinglePrimitive':[15, ArraySinglePrimitive],
'ArraySinglePrimitiveBig':[15, ArraySinglePrimitiveBig],
'ArraySingleObject':[16, ArraySingleObject],
'ArraySingleString':[17, ArraySingleString],
'MethodCall':[21, MethodCall],
'MethodReturn':[22, MethodReturn]
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Convert json to dotnet binary formatter')
parser.add_argument('-i', dest='inputFile', required=True)
parser.add_argument('-o', dest='outputFile', required=False)
parser.add_argument('-e', dest='encode', help='Url and base64 encode the output binary', required=False, action='store_true')
parser.add_argument('-v', dest='verbose', help='Verbose mode', required=False, action='store_true')
args = parser.parse_args()
f=open(args.inputFile)
myObject = json.loads(f.read())
f.close()
binary = ''
for o in range(len(myObject)):
RecordType = RecordTypeEnum[myObject[str(o)][0]]
if args.verbose:
print myObject[str(o)][0]
binary += struct.pack('<B', RecordType[0])
binary += RecordType[1](myObject[str(o)][1])
if args.encode:
binary = urllib.quote(base64.b64encode(binary))
if args.outputFile:
f = open(args.outputFile, 'w')
f.write(binary)
f.close()
else:
print binary