├── .gitignore
├── App.config
├── FodyWeavers.xml
├── ModifiedVulnerableBinaryFormatters
├── AdvancedBinaryFormatterParser.cs
├── BinaryFormatterMinifier.cs
├── Environment.cs
├── ObjectExtensions.cs
├── SerTrace.cs
├── SimpleBinaryFormatterParser.cs
├── SimpleObjectLosFormatter.cs
├── binarycommonclasses.cs
├── binaryconverter.cs
├── binaryenums.cs
├── binaryformatter.cs
├── binaryformatterwriter.cs
├── binarymethodmessage.cs
├── binaryobjectinfo.cs
├── binaryobjectreader.cs
├── binaryobjectwriter.cs
├── binaryparser.cs
└── binaryutilclasses.cs
├── Program.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── packages.config
├── suo_exploit_test.csproj
└── suo_exploit_test.sln
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
--------------------------------------------------------------------------------
/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/FodyWeavers.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/ModifiedVulnerableBinaryFormatters/AdvancedBinaryFormatterParser.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Runtime.Serialization.Formatters;
5 | using System.Runtime.Serialization;
6 | using System.Text;
7 | using System.Text.RegularExpressions;
8 |
9 | namespace suo_exploit_test.Helpers.ModifiedVulnerableBinaryFormatters
10 | {
11 | public class AdvancedBinaryFormatterParser
12 | {
13 | public static String StreamToJson(Stream serializationStream)
14 | {
15 | return StreamToJson(serializationStream, false, false, true);
16 | }
17 |
18 | public static String StreamToJson(Stream serializationStream, bool ignoreErrors, bool enableIndent, bool keepInfoFields)
19 | {
20 | return AdvancedBinaryFormatterObjectToJson(StreamToAdvancedBinaryFormatterObject(serializationStream, ignoreErrors), enableIndent, keepInfoFields);
21 | }
22 |
23 | public static List StreamToAdvancedBinaryFormatterObject(Stream serializationStream)
24 | {
25 | return StreamToAdvancedBinaryFormatterObject(serializationStream, false);
26 | }
27 |
28 | public static List StreamToAdvancedBinaryFormatterObject(Stream serializationStream, bool ignoreErrors)
29 | {
30 | if (serializationStream.CanRead)
31 | serializationStream.Position = 0;
32 |
33 | InternalFE formatterEnums = new InternalFE();
34 | formatterEnums.FEtypeFormat = FormatterTypeStyle.TypesAlways;
35 | formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary;
36 | formatterEnums.FEassemblyFormat = FormatterAssemblyStyle.Simple;
37 | formatterEnums.FEsecurityLevel = TypeFilterLevel.Low;
38 | ISurrogateSelector m_surrogates = null;
39 | StreamingContext m_context = new StreamingContext(StreamingContextStates.All);
40 | SerializationBinder m_binder = null;
41 | //bool fCheck = false;
42 | //HeaderHandler handler = null;
43 |
44 | ObjectReader objectReader = new ObjectReader(serializationStream, m_surrogates, m_context, formatterEnums, m_binder);
45 | __BinaryParser serParser = new __BinaryParser(serializationStream, objectReader);
46 | //BinaryReader dataReader = new BinaryReader(serializationStream, new UTF8Encoding(false, true));
47 |
48 | return serParser.RunModifiedAdvanced(ignoreErrors);
49 | }
50 |
51 |
52 | public static MemoryStream AdvancedBinaryFormatterObjectToStream(List abfoList)
53 | {
54 | MemoryStream resultMS = new MemoryStream();
55 |
56 | InternalFE formatterEnums = new InternalFE();
57 | formatterEnums.FEtypeFormat = FormatterTypeStyle.TypesAlways;
58 | formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary;
59 | formatterEnums.FEassemblyFormat = FormatterAssemblyStyle.Simple;
60 | formatterEnums.FEsecurityLevel = TypeFilterLevel.Low;
61 | ISurrogateSelector m_surrogates = null;
62 | StreamingContext m_context = new StreamingContext(StreamingContextStates.All);
63 | SerializationBinder m_binder = null;
64 | //bool fCheck = false;
65 | //HeaderHandler handler = null;
66 |
67 | ObjectWriter objectWriter = new ObjectWriter(m_surrogates, m_context, formatterEnums, m_binder);
68 | __BinaryWriter binaryWriter = new __BinaryWriter(resultMS, objectWriter, formatterEnums.FEtypeFormat);
69 |
70 | List asmArray = new List();
71 | foreach (AdvancedBinaryFormatterObject abfo in abfoList)
72 | {
73 | var currentObjInfo = abfo.Data;
74 | if(currentObjInfo.GetType() == typeof(BinaryObjectWithMapTyped))
75 | {
76 | if (currentObjInfo.binaryHeaderEnum == BinaryHeaderEnum.ObjectWithMapTypedAssemId)
77 | {
78 | if (asmArray.IndexOf(currentObjInfo.assemId) == -1 && currentObjInfo.assemId != 0)
79 | {
80 | asmArray.Add(currentObjInfo.assemId);
81 | }
82 | else
83 | {
84 | currentObjInfo.assemId = 0;
85 | }
86 | }
87 | }
88 |
89 | currentObjInfo.Write(binaryWriter);
90 | if(abfo.ArrayBytes != null)
91 | {
92 | // this is for arrays when we have more data:
93 | /*
94 | BinaryHeaderEnum.Array:
95 | BinaryHeaderEnum.ArraySinglePrimitive:
96 | BinaryHeaderEnum.ArraySingleObject:
97 | BinaryHeaderEnum.ArraySingleString:
98 | */
99 | binaryWriter.WriteBytes(abfo.ArrayBytes);
100 |
101 | }
102 | }
103 | return resultMS;
104 | }
105 |
106 | public static MemoryStream JsonToStream(String jsonNet_str)
107 | {
108 |
109 | String currentNameSpace = typeof(AdvancedBinaryFormatterParser).Namespace;
110 | String mainAssembly = typeof(AdvancedBinaryFormatterParser).Assembly.GetName().Name;
111 |
112 | String pattern = @"([""']\$type[""']:\s*[""'])([^\""'\.\[\] ,=]+)([\""'])";
113 | jsonNet_str = Regex.Replace(jsonNet_str, pattern, "$1"+ currentNameSpace + ".$2, " + mainAssembly + "$3");
114 |
115 | List deserialized_obj = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonNet_str, typeof(List), new Newtonsoft.Json.JsonSerializerSettings
116 | {
117 | TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
118 | });
119 |
120 | return AdvancedBinaryFormatterObjectToStream(deserialized_obj);
121 | }
122 |
123 | public static String AdvancedBinaryFormatterObjectToJson(List abfoList)
124 | {
125 | return AdvancedBinaryFormatterObjectToJson(abfoList, false, true);
126 | }
127 |
128 | public static String AdvancedBinaryFormatterObjectToJson(List abfoList, bool enableIndent, bool keepInfoFields)
129 | {
130 | var defaultFormatting = Newtonsoft.Json.Formatting.None;
131 | if (enableIndent)
132 | {
133 | defaultFormatting = Newtonsoft.Json.Formatting.Indented;
134 | }
135 |
136 | if (!keepInfoFields)
137 | {
138 | foreach(AdvancedBinaryFormatterObject abfo in abfoList)
139 | {
140 | abfo.KeepInfoFieldsForJson = false;
141 | }
142 | }
143 |
144 | String jsonNetStr = Newtonsoft.Json.JsonConvert.SerializeObject(abfoList, typeof(List), defaultFormatting, new Newtonsoft.Json.JsonSerializerSettings
145 | {
146 | TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
147 | });
148 |
149 | String currentNameSpace = typeof(AdvancedBinaryFormatterParser).Namespace.Replace(".",@"\.");
150 | String mainAssembly = typeof(AdvancedBinaryFormatterParser).Assembly.GetName().Name.Replace(".", @"\.");
151 |
152 | String pattern = @"(""\$type"":\s*"")" + currentNameSpace + @"\.([^,]+),\s*" + mainAssembly;
153 | jsonNetStr = Regex.Replace(jsonNetStr, pattern, "$1$2");
154 |
155 | if (enableIndent)
156 | {
157 | // removing spaces between array items
158 | jsonNetStr = Regex.Replace(jsonNetStr, @"\:\s*\[[a-z\sA-Z0-9\,\[\]""'\+\._`]+\],", delegate (Match m) {
159 | String finalVal = m.Value;
160 | finalVal = Regex.Replace(finalVal, @"\s+", "");
161 | return finalVal;
162 | });
163 |
164 | // removing spaces between non-alphanumerical characters at the beginning of each clause
165 | jsonNetStr = Regex.Replace(jsonNetStr, @"^\s*([^\w""':. ][^\w""']+)+", delegate (Match m) {
166 | String finalVal = m.Value;
167 | finalVal = Regex.Replace(finalVal, @"\s+", "");
168 | return finalVal;
169 | }, RegexOptions.Multiline);
170 | }
171 | return jsonNetStr;
172 | }
173 |
174 | public static byte[] Calculate7BitEncodedInt(int value)
175 | {
176 | // it cannot be more than 5 bytes according to [MS-NRBF]
177 | byte[] output = new byte[1];
178 | // Similar to Write7BitEncodedInt from System.IO.BinaryWriter
179 | uint v = (uint)value;
180 | int counter = 0;
181 |
182 | while (v >= 0x80)
183 | {
184 | if (counter > 1)
185 | Array.Resize(ref output, counter + 1);
186 |
187 | output[counter] = ((byte)(v | 0x80));
188 | v >>= 7;
189 | counter++;
190 | }
191 |
192 | if (counter > 0)
193 | Array.Resize(ref output, counter + 1);
194 |
195 | output[counter] = ((byte)v);
196 |
197 | return output;
198 | }
199 |
200 | public static byte[] Create7bitLengthObjectString(string strInput)
201 | {
202 | byte[] size = Calculate7BitEncodedInt(strInput.Length);
203 | byte[] value = Encoding.UTF8.GetBytes(strInput);
204 | return ConcatTwoByteArrays(size, value);
205 | }
206 |
207 | public static byte[] ConcatTwoByteArrays(byte[] arr1, byte[] arr2)
208 | {
209 | byte[] result = new byte[arr1.Length + arr2.Length];
210 | Array.Copy(arr1, 0, result, 0, arr1.Length);
211 | Array.Copy(arr2, 0, result, arr1.Length, arr2.Length);
212 | return result;
213 | }
214 | }
215 |
216 | [Serializable]
217 | // The Data property is the only one that matters for serialization/deserialization
218 | public class AdvancedBinaryFormatterObject
219 | {
220 | public AdvancedBinaryFormatterObject() { }
221 |
222 | public AdvancedBinaryFormatterObject(string strType) {
223 | expectedTypeName = strType;
224 | }
225 |
226 | // We keep this in serialization so we can easily point to an item - not needed in reconstruction
227 | public int Id = -1;
228 |
229 | // Not needed in reconstruction but good for information
230 | public string TypeName = "";
231 |
232 | // Not needed in reconstruction but good for information
233 | public bool IsPrimitive = false;
234 |
235 | [NonSerialized]
236 | // This field can be used to minimize the Json.Net output
237 | // It will not serialize informational items when it is set to false
238 | public bool KeepInfoFieldsForJson = true;
239 |
240 | [NonSerialized]
241 | private dynamic _data;
242 |
243 | // This is for information when debugging
244 | [NonSerialized]
245 | public SimpleBinaryFormatterObject simpleBinaryFormatterObject;
246 |
247 | // This is for information when debugging
248 | [NonSerialized]
249 | public String expectedTypeName;
250 |
251 | // This is for information when debugging as well as being used during reading a binary formatted object
252 | [NonSerialized]
253 | public int ArrayBytesDataRecordLength;
254 |
255 | // this and Data are the only important ones for deserialization really
256 | public byte[] ArrayBytes;
257 |
258 | // This and ArrayBytes are the only important ones for deserialization really
259 | public dynamic Data
260 | {
261 | get
262 | {
263 | return _data;
264 | }
265 |
266 | set
267 | {
268 | //*
269 | object obj = value;
270 | using (var ms = new MemoryStream())
271 | {
272 | var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
273 | formatter.Serialize(ms, obj);
274 | ms.Position = 0;
275 |
276 | obj = formatter.Deserialize(ms);
277 | }
278 |
279 | _data = obj;
280 |
281 | //*/
282 | //_data = ObjectExtensions.Copy(value);
283 | }
284 | }
285 |
286 | public bool ShouldSerializeIsPrimitive()
287 | {
288 | // don't serialize IsPrimitive when it is not primitive or when KeepInfoFieldsForJson == false
289 | return (IsPrimitive && KeepInfoFieldsForJson);
290 | }
291 |
292 | public bool ShouldSerializeArrayBytes()
293 | {
294 | // don't serialize IsPrimitive when it is not primitive or when KeepInfoFieldsForJson == false
295 | return (ArrayBytes != null);
296 | }
297 |
298 | public bool ShouldSerializeTypeName()
299 | {
300 | // don't serialize IsPrimitive when it is not primitive or when KeepInfoFieldsForJson == false
301 | return (!String.IsNullOrEmpty(TypeName) && KeepInfoFieldsForJson);
302 | }
303 |
304 | public bool ShouldSerializeId()
305 | {
306 | // don't serialize Id when KeepInfoFieldsForJson == false
307 | return (KeepInfoFieldsForJson);
308 | }
309 |
310 | public AdvancedBinaryFormatterObject DeepClone()
311 | {
312 | AdvancedBinaryFormatterObject newAbfo = new AdvancedBinaryFormatterObject();
313 |
314 | newAbfo.Data = this.Data;
315 | newAbfo.expectedTypeName = this.expectedTypeName;
316 | newAbfo.Id = this.Id;
317 | newAbfo.IsPrimitive = this.IsPrimitive;
318 | newAbfo.simpleBinaryFormatterObject = this.simpleBinaryFormatterObject;
319 | newAbfo.TypeName = this.TypeName;
320 | newAbfo.ArrayBytes = this.ArrayBytes;
321 | newAbfo.ArrayBytesDataRecordLength = this.ArrayBytesDataRecordLength;
322 | return newAbfo;
323 | }
324 |
325 | }
326 | }
327 |
--------------------------------------------------------------------------------
/ModifiedVulnerableBinaryFormatters/BinaryFormatterMinifier.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json.Linq;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.IO;
6 | using System.Linq;
7 | using System.Reflection;
8 | using System.Text;
9 | using System.Text.RegularExpressions;
10 | using System.Threading.Tasks;
11 | using suo_exploit_test.Helpers.ModifiedVulnerableBinaryFormatters;
12 |
13 | namespace suo_exploit_test.Helpers
14 | {
15 | public class BinaryFormatterMinifier
16 | {
17 | public static string FullTypeNameMinifier(string strFullTypeName, string strAssemblyName)
18 | {
19 | if (strAssemblyName == null || strFullTypeName == null)
20 | return strFullTypeName;
21 |
22 | // replacing spaces between things like:
23 | // Foo, Microsoft.IdentityModel, Version=3.5.0.0, PublicKeyToken=31bf3856ad364e35
24 | // clr-namespace:System.Diagnostics; assembly=system
25 | string strFullTypeName_noSpace = System.Text.RegularExpressions.Regex.Replace(strFullTypeName, @"([^\w])[\s]+([\w])", "$1$2");
26 | strFullTypeName_noSpace = System.Text.RegularExpressions.Regex.Replace(strFullTypeName_noSpace, @"([\w])[\s]+([^\w])", "$1$2");
27 | strFullTypeName_noSpace = System.Text.RegularExpressions.Regex.Replace(strFullTypeName_noSpace, @"([^\w])[\s]+([^\w])", "$1$2");
28 |
29 |
30 | string shortenedFullTypeName = System.Text.RegularExpressions.Regex.Replace(strFullTypeName_noSpace, @"\s*,\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
31 |
32 | try
33 | {
34 | var asm = Assembly.Load(strAssemblyName);
35 | if (asm.GetType(shortenedFullTypeName) !=null)
36 | {
37 | strFullTypeName = shortenedFullTypeName;
38 | }
39 |
40 | }
41 | catch
42 | {
43 | strFullTypeName = strFullTypeName_noSpace;
44 | }
45 |
46 | return strFullTypeName;
47 | }
48 |
49 | public static string AssemblyOrTypeNameMinifier(string strInput)
50 | {
51 | if (strInput == null)
52 | return strInput;
53 |
54 | if (!System.Text.RegularExpressions.Regex.IsMatch(strInput, @"[,]\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}"))
55 | {
56 | // does not contain an assembly name
57 | return strInput;
58 | }
59 |
60 | bool isAssemblyString = false;
61 | if (System.Text.RegularExpressions.Regex.IsMatch(strInput, @"^[^,]+\s*[,]\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}$",System.Text.RegularExpressions.RegexOptions.IgnoreCase| System.Text.RegularExpressions.RegexOptions.Multiline))
62 | {
63 | isAssemblyString = true;
64 | }
65 |
66 | // replacing spaces between things like:
67 | // Microsoft.IdentityModel, Version=3.5.0.0, PublicKeyToken=31bf3856ad364e35
68 | // clr-namespace:System.Diagnostics; assembly=system
69 | string strInput_noSpace = System.Text.RegularExpressions.Regex.Replace(strInput, @"([^\w])[\s]+([\w])", "$1$2");
70 | strInput_noSpace = System.Text.RegularExpressions.Regex.Replace(strInput_noSpace, @"([\w])[\s]+([^\w])", "$1$2");
71 | strInput_noSpace = System.Text.RegularExpressions.Regex.Replace(strInput_noSpace, @"([^\w])[\s]+([^\w])", "$1$2");
72 |
73 | if(IsValid(strInput_noSpace, isAssemblyString))
74 | {
75 | strInput = strInput_noSpace;
76 | }
77 |
78 |
79 | string strInput_simpleAsm = System.Text.RegularExpressions.Regex.Replace(strInput, @"[,]\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
80 |
81 | if (IsValid(strInput_simpleAsm, isAssemblyString))
82 | {
83 | strInput = strInput_simpleAsm;
84 | }else if (!isAssemblyString && strInput.Contains("mscorlib"))
85 | {
86 | // we know mscorlib can be used a lot
87 | string strInput_simpleCorlibAsm = System.Text.RegularExpressions.Regex.Replace(strInput, @"mscorlib\s*,\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}", "mscorlib", System.Text.RegularExpressions.RegexOptions.IgnoreCase| System.Text.RegularExpressions.RegexOptions.Multiline);
88 |
89 | if (IsValid(strInput_simpleCorlibAsm, isAssemblyString))
90 | strInput = strInput_simpleCorlibAsm;
91 | }
92 |
93 | if (strInput.Contains(",mscorlib"))
94 | {
95 | string strInput_removedMSCORLIB = strInput.Replace(",mscorlib", "");
96 |
97 | if (IsValid(strInput_removedMSCORLIB, isAssemblyString))
98 | strInput = strInput_removedMSCORLIB;
99 | }
100 |
101 | return strInput;
102 | }
103 |
104 | private static bool IsValid(string strInput, bool isAssemblyString)
105 | {
106 | bool result = false;
107 |
108 | if (isAssemblyString)
109 | {
110 | try
111 | {
112 | if (Assembly.Load(strInput) != null)
113 | result = true;
114 | }
115 | catch { }
116 | }
117 | else
118 | {
119 | try
120 | {
121 | if (Type.GetType(strInput) != null)
122 | result = true;
123 | }
124 | catch { }
125 |
126 | }
127 |
128 | return result;
129 | }
130 |
131 |
132 |
133 | private static StringBuilder DataObjectRemovalTester(ref JArray jsonJArrayObj, string myApp, bool isErrOk, bool showInfo)
134 | {
135 | JArray origJsonJArrayObj = new JArray(jsonJArrayObj.ToList().ToArray());
136 | string json_shortened = origJsonJArrayObj.ToString();
137 | bool ruleComplete = false;
138 |
139 | StringBuilder sbSuccessResult = new StringBuilder();
140 |
141 | // remove a Data object
142 | ruleComplete = false;
143 | int externalCounter = 0;
144 | while (!ruleComplete)
145 | {
146 | int internalCounter = 0;
147 |
148 | foreach (JObject item in origJsonJArrayObj)
149 | {
150 | internalCounter++;
151 | JToken dataItem = item["Data"];
152 | foreach (JProperty subDataItem in dataItem)
153 | {
154 | string subDataItemName = subDataItem.Name;
155 | JToken subDataItemValue = subDataItem.Value;
156 | JTokenType subDataItemType = subDataItem.Value.Type;
157 | if (subDataItemName.Equals("$type"))
158 | {
159 | if (subDataItemValue.ToString().Equals("MessageEnd"))
160 | {
161 | ruleComplete = true;
162 | }
163 | break;
164 | }
165 | }
166 |
167 | if (!ruleComplete && internalCounter > externalCounter)
168 | {
169 | var currentObjId = item["Data"]["objectId"];
170 |
171 | string tempValue = item.ToString();
172 | item.Remove();
173 |
174 | if (currentObjId != null)
175 | {
176 | // we want to remove objects that have idRef == objectId of our removed item
177 | List refRremovalList = new List();
178 | foreach (JObject otherItems in origJsonJArrayObj)
179 | {
180 | if (otherItems["Data"]["idRef"] != null)
181 | {
182 | if ((int)otherItems["Data"]["idRef"] == (int)currentObjId)
183 | {
184 | refRremovalList.Add(otherItems);
185 | }
186 | }
187 | }
188 |
189 | foreach (JObject refObject in refRremovalList)
190 | {
191 | refObject.Remove();
192 | }
193 | }
194 |
195 | if (CheckIfSuccess(origJsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
196 | {
197 | // it is a success so we can remove it!
198 | // we have to start from the beginning!
199 | externalCounter = 0;
200 | jsonJArrayObj = new JArray(origJsonJArrayObj.ToList().ToArray());
201 | sbSuccessResult.AppendLine("Successful in removing:" + tempValue);
202 | }
203 | else
204 | {
205 | // we should not remove it
206 | externalCounter = internalCounter;
207 | origJsonJArrayObj = new JArray(jsonJArrayObj.ToList().ToArray());
208 | }
209 |
210 | break;
211 | }
212 | }
213 | }
214 |
215 |
216 | return sbSuccessResult;
217 | }
218 |
219 | private static StringBuilder DataObjectNullifyTester(ref JArray jsonJArrayObj, string myApp, bool isErrOk, List valueExclusionList, bool showInfo)
220 | {
221 |
222 | JArray origJsonJArrayObj = new JArray(jsonJArrayObj.ToList().ToArray());
223 | string json_shortened = origJsonJArrayObj.ToString();
224 | bool ruleComplete = false;
225 |
226 | StringBuilder sbSuccessResult = new StringBuilder();
227 |
228 | JObject nullJObject = JObject.Parse(@"{'Id': 0,
229 | 'TypeName': 'ObjectNull',
230 | 'Data': {
231 | '$type': 'ObjectNull',
232 | 'nullCount': 0
233 | }}");
234 | // remove a Data object
235 | ruleComplete = false;
236 | int externalCounter = 0;
237 | while (!ruleComplete)
238 | {
239 | int internalCounter = 0;
240 |
241 | foreach (JObject item in origJsonJArrayObj)
242 | {
243 | internalCounter++;
244 | bool isExcluded = false;
245 | JToken dataItem = item["Data"];
246 | foreach (JProperty subDataItem in dataItem)
247 | {
248 | string subDataItemName = subDataItem.Name;
249 | JToken subDataItemValue = subDataItem.Value;
250 | JTokenType subDataItemType = subDataItem.Value.Type;
251 | if (subDataItemName.Equals("$type"))
252 | {
253 | if (subDataItemValue.ToString().Equals("MessageEnd"))
254 | {
255 | ruleComplete = true;
256 | }
257 | else if (subDataItemValue.ToString().Equals("ObjectNull"))
258 | {
259 | isExcluded = true;
260 | }
261 | break;
262 | }
263 | }
264 |
265 | string subDataItemValueStringValue = "";
266 |
267 | if (item["Data"]["value"] != null)
268 | {
269 | subDataItemValueStringValue = (string)item["Data"]["value"];
270 | }
271 |
272 | if (isExcluded || valueExclusionList.Contains(subDataItemValueStringValue))
273 | continue;
274 |
275 | if (!ruleComplete && internalCounter > externalCounter)
276 | {
277 | var currentObjId = item["Data"]["objectId"];
278 |
279 | string tempValue = item.ToString();
280 | item.AddAfterSelf(nullJObject);
281 | item.Remove();
282 |
283 | if (currentObjId != null)
284 | {
285 | // we want to remove objects that have idRef == objectId of our removed item
286 | List refRremovalList = new List();
287 | foreach (JObject otherItems in origJsonJArrayObj)
288 | {
289 | if (otherItems["Data"]["idRef"] != null)
290 | {
291 | if ((int)otherItems["Data"]["idRef"] == (int)currentObjId)
292 | {
293 | refRremovalList.Add(otherItems);
294 | }
295 | }
296 | }
297 |
298 | foreach (JObject refObject in refRremovalList)
299 | {
300 | refObject.AddAfterSelf(nullJObject);
301 | refObject.Remove();
302 | }
303 | }
304 |
305 | if (CheckIfSuccess(origJsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
306 | {
307 | // it is a success so we can remove it!
308 | // we have to start from the beginning!
309 | externalCounter = 0;
310 | jsonJArrayObj = new JArray(origJsonJArrayObj.ToList().ToArray());
311 | sbSuccessResult.AppendLine("Successful in nullifying:" + tempValue);
312 | }
313 | else
314 | {
315 | // we should not remove it
316 | externalCounter = internalCounter;
317 | origJsonJArrayObj = new JArray(jsonJArrayObj.ToList().ToArray());
318 | }
319 |
320 | break;
321 | }
322 | }
323 | }
324 |
325 |
326 | return sbSuccessResult;
327 | }
328 |
329 | private static StringBuilder RulesRunner(ref JArray jsonJArrayObj, JProperty currentPropItem, string myApp, bool isErrOk, bool showInfo)
330 | {
331 | return RulesRunner(ref jsonJArrayObj, currentPropItem, -1, myApp, isErrOk, showInfo);
332 | }
333 |
334 | private static StringBuilder RulesRunner(ref JArray jsonJArrayObj, JProperty currentPropItem, int arrNum, string myApp, bool isErrOk, bool showInfo)
335 | {
336 | StringBuilder sbSuccessResult = new StringBuilder();
337 | var origCurrentItem = currentPropItem.Value.DeepClone();
338 | JTokenType currentItemType = currentPropItem.Value.Type;
339 |
340 | if (currentItemType == JTokenType.Array)
341 | {
342 | if ((arrNum) > -1)
343 | {
344 | // we are dealing with an array item
345 | currentItemType = currentPropItem.Value[arrNum].Type;
346 | }
347 | }
348 |
349 | switch (currentItemType)
350 | {
351 | case JTokenType.String:
352 | string origValue = currentPropItem.Value.ToString();
353 |
354 | if (arrNum > -1)
355 | {
356 | origValue = currentPropItem.Value[arrNum].ToString();
357 | }
358 |
359 | // replace a string with null
360 | if (arrNum == -1)
361 | {
362 | currentPropItem.Value = null;
363 | }
364 | else
365 | {
366 | currentPropItem.Value[arrNum] = null;
367 | }
368 |
369 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
370 | {
371 | //success
372 | sbSuccessResult.AppendLine("String replaced with null: " + origValue);
373 | break;
374 | }
375 |
376 | // undo
377 | currentPropItem.Value = origCurrentItem.DeepClone();
378 |
379 | if (!string.IsNullOrEmpty(origValue))
380 | {
381 | // replace a non empty string with an empty string ('')
382 | if (arrNum == -1)
383 | {
384 | currentPropItem.Value = "";
385 | }
386 | else
387 | {
388 | currentPropItem.Value[arrNum] = "";
389 | }
390 |
391 |
392 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
393 | {
394 | //success
395 | sbSuccessResult.AppendLine("String replaced with empty: " + origValue);
396 | break;
397 | }
398 |
399 | // undo
400 | currentPropItem.Value = origCurrentItem.DeepClone();
401 |
402 | if (origValue.Length > 1)
403 | {
404 | // replace a non empty string greater than one character with one character ('x')
405 | if (arrNum == -1)
406 | {
407 | currentPropItem.Value = "x";
408 | }
409 | else
410 | {
411 | currentPropItem.Value[arrNum] = "x";
412 | }
413 |
414 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
415 | {
416 | //success
417 | sbSuccessResult.AppendLine("String replaced with 'x': " + origValue);
418 | break;
419 | }
420 |
421 | // undo
422 | currentPropItem.Value = origCurrentItem.DeepClone();
423 |
424 | if (origValue.Contains(" "))
425 | {
426 | // replace space in string if it contains a space
427 | if (arrNum == -1)
428 | {
429 | currentPropItem.Value = origValue.Replace(" ", "");
430 | }
431 | else
432 | {
433 | currentPropItem.Value[arrNum] = origValue.Replace(" ", "");
434 | }
435 |
436 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
437 | {
438 | //success
439 | origValue = currentPropItem.Value.ToString();
440 |
441 | if (arrNum > -1)
442 | {
443 | origValue = currentPropItem.Value[arrNum].ToString();
444 | }
445 | sbSuccessResult.AppendLine("Space characters removed from: " + origValue);
446 | // we shouldn't break here! we have things to do!
447 | }
448 | else
449 | {
450 | // undo
451 | currentPropItem.Value = origCurrentItem.DeepClone();
452 | }
453 | }
454 |
455 | origCurrentItem = currentPropItem.Value.DeepClone();
456 |
457 | string newValue = origValue;
458 |
459 | // replace a full class or assembly string to only keep then class and assembly
460 | Regex asmSection = new Regex(@"([^,]+)\s*[,]\s*Version=[^,]+,\s*Culture=[^,]+,\s*PublicKeyToken=[a-z0-9]{16}", RegexOptions.IgnoreCase);
461 |
462 | foreach (Match match in asmSection.Matches(origValue))
463 | {
464 | if (arrNum == -1)
465 | {
466 | currentPropItem.Value = newValue.Replace(match.Value, match.Groups[1].Value);
467 | }
468 | else
469 | {
470 | currentPropItem.Value[arrNum] = newValue.Replace(match.Value, match.Groups[1].Value);
471 | }
472 |
473 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
474 | {
475 | // success
476 | newValue = currentPropItem.Value.ToString();
477 | if (arrNum > -1)
478 | {
479 | newValue = currentPropItem.Value[arrNum].ToString();
480 | }
481 | sbSuccessResult.AppendLine("A class or an assembly string became shorter: " + origValue);
482 | origCurrentItem = currentPropItem.Value.DeepClone();
483 | }
484 | }
485 |
486 | // undo
487 | if (newValue.Equals(origValue))
488 | {
489 | // failure
490 | currentPropItem.Value = origCurrentItem.DeepClone();
491 | }
492 | else
493 | {
494 | origValue = newValue;
495 | }
496 |
497 | origCurrentItem = currentPropItem.Value.DeepClone();
498 |
499 | // replace a full class or assembly string to only keep class
500 | Regex classRegex = new Regex(@"([a-z0-9\.\+_\$`]+)\s*[;,]\s*[a-z0-9\.\+_\$`]+", RegexOptions.IgnoreCase);
501 |
502 | newValue = origValue;
503 |
504 | foreach (Match match in classRegex.Matches(origValue))
505 | {
506 | if (arrNum == -1)
507 | {
508 | currentPropItem.Value = newValue.Replace(match.Value, match.Groups[1].Value);
509 | }
510 | else
511 | {
512 | currentPropItem.Value[arrNum] = newValue.Replace(match.Value, match.Groups[1].Value);
513 | }
514 |
515 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
516 | {
517 | // success
518 | newValue = currentPropItem.Value.ToString();
519 | if (arrNum > -1)
520 | {
521 | newValue = currentPropItem.Value[arrNum].ToString();
522 | }
523 | sbSuccessResult.AppendLine("A class or an assembly string became shorter: " + origValue);
524 | origCurrentItem = currentPropItem.Value.DeepClone();
525 | }
526 | }
527 |
528 | // undo if failed
529 | if (arrNum == -1 && !newValue.Equals(currentPropItem.Value.ToString()))
530 | {
531 | currentPropItem.Value = origCurrentItem.DeepClone();
532 | }
533 | else if (arrNum > -1 && !newValue.Equals(currentPropItem.Value[arrNum].ToString()))
534 | {
535 | currentPropItem.Value = origCurrentItem.DeepClone();
536 | }
537 |
538 | }
539 | }
540 |
541 | break;
542 | case JTokenType.Integer:
543 | // replace an integer with 0 to N - when int is M and N < M && N < 20 (we need a limit)
544 | var origItemValue = currentPropItem.Value.DeepClone();
545 | int origIntValue = 0;
546 |
547 | if (arrNum == -1)
548 | {
549 | int.TryParse(currentPropItem.Value.ToString(), out origIntValue);
550 | }
551 | else
552 | {
553 | int.TryParse(currentPropItem.Value[arrNum].ToString(), out origIntValue);
554 | }
555 |
556 |
557 | if (origIntValue > 0)
558 | {
559 | int intCounter = 0;
560 |
561 | while (intCounter < origIntValue && intCounter < 20)
562 | {
563 |
564 | if (arrNum == -1)
565 | {
566 | currentPropItem.Value = intCounter;
567 | }
568 | else
569 | {
570 | currentPropItem.Value[arrNum] = intCounter;
571 | }
572 |
573 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
574 | {
575 | //success
576 | sbSuccessResult.AppendLine("A number was changed from: " + origIntValue + " to: " + intCounter);
577 | break;
578 | }
579 | else
580 | {
581 | currentPropItem.Value = origItemValue.DeepClone();
582 | }
583 |
584 | intCounter++;
585 | }
586 | }
587 | break;
588 | default:
589 | // convert to null
590 | currentPropItem.Value = null;
591 | if (CheckIfSuccess(jsonJArrayObj.ToString(), myApp, isErrOk, showInfo))
592 | {
593 | //success
594 | sbSuccessResult.AppendLine("An item was replaced with null: " + origCurrentItem.ToString());
595 | break;
596 | }
597 | // undo
598 | currentPropItem.Value = origCurrentItem.DeepClone();
599 | break;
600 | }
601 |
602 | return sbSuccessResult;
603 | }
604 |
605 | private static bool CheckIfSuccess(string strJson, string myApp, bool isErrOk, bool showInfo)
606 | {
607 | bool result = true;
608 |
609 | try
610 | {
611 | if (!BinaryFormatterDeserializeABFJson(strJson, showInfo))
612 | {
613 | if (!isErrOk)
614 | {
615 | // we have error but we don't like errors
616 | result = false;
617 | }
618 | }
619 | }
620 | catch
621 | {
622 | if (!isErrOk)
623 | {
624 | // we have error but we don't like errors
625 | result = false;
626 | }
627 | }
628 |
629 |
630 | if (!KillMyProcess(myApp))
631 | {
632 | // no app was found so the code exec did not work
633 | result = false;
634 | }
635 |
636 | return result;
637 | }
638 | public static object BinaryFormatter_deserialize(byte[] byteArray)
639 | {
640 | MemoryStream ms = new MemoryStream(byteArray);
641 | return BinaryFormatter_deserialize(ms);
642 | }
643 | public static object BinaryFormatter_deserialize(MemoryStream ms)
644 | {
645 | ms.Position = 0;
646 | System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
647 | return bf.Deserialize(ms);
648 | }
649 | private static bool BinaryFormatterDeserializeABFJson(string strJson, bool showInfo)
650 | {
651 | bool noError = true;
652 | try
653 | {
654 | MemoryStream ms = AdvancedBinaryFormatterParser.JsonToStream(strJson);
655 |
656 | /*
657 | ms.Position = 0;
658 | BinaryFormatter bf = new BinaryFormatter();
659 | var task = Task.Run(() => bf.Deserialize(ms));
660 | //*/
661 |
662 | var task = Task.Run(() => { try { BinaryFormatter_deserialize(ms.ToArray()); } catch (Exception e) { noError = false; } });
663 |
664 | if (!task.Wait(TimeSpan.FromSeconds(5)))
665 | {
666 | noError = false;
667 | if(showInfo)
668 | Console.WriteLine("The formatter is not responding - infinite loop because of parameters.");
669 | }
670 |
671 |
672 |
673 | }
674 | catch (Exception e)
675 | {
676 | noError = false;
677 | }
678 |
679 | return noError;
680 | }
681 |
682 | private static bool KillMyProcess(string myprocess)
683 | {
684 | bool processFound = false;
685 | foreach (Process myp in Process.GetProcessesByName(myprocess))
686 | {
687 | // It has worked
688 | processFound = true;
689 | // killing any existing TestConsoleApp_YSONET to be ready
690 | try
691 | {
692 | myp.Kill();
693 | }
694 | catch
695 | {
696 | // hopefully it is just a race condition and all has been closed!!!
697 | // just to be on the safe side:
698 | processFound = KillMyProcess(myprocess);
699 | }
700 |
701 | }
702 |
703 | return processFound;
704 | }
705 | }
706 | }
707 |
--------------------------------------------------------------------------------
/ModifiedVulnerableBinaryFormatters/Environment.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.IO;
4 |
5 | namespace suo_exploit_test.Helpers.ModifiedVulnerableBinaryFormatters
6 | {
7 | public static class Environment
8 | {
9 | public static String GetResourceString(string str)
10 | {
11 | return str;
12 | }
13 |
14 | public static String GetResourceString(String key, params Object[] values)
15 | {
16 | String s = GetResourceString(key);
17 | return String.Format(CultureInfo.CurrentCulture, s, values);
18 | }
19 |
20 | public static void GetResourceString(string str, out Object test)
21 | {
22 | test = str;
23 | }
24 |
25 | public static Exception GetResourceString(string str, Stream test)
26 | {
27 | return new Exception(str);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/ModifiedVulnerableBinaryFormatters/ObjectExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Reflection;
3 | using System.ArrayExtensions;
4 |
5 | // from https://github.com/Burtsev-Alexey/net-object-deep-copy
6 |
7 | namespace System
8 | {
9 | public static class ObjectExtensions
10 | {
11 | private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
12 |
13 | public static bool IsPrimitive(this Type type)
14 | {
15 | if (type == typeof(String)) return true;
16 | return (type.IsValueType & type.IsPrimitive);
17 | }
18 |
19 | public static Object Copy(this Object originalObject)
20 | {
21 | return InternalCopy(originalObject, new Dictionary