public void ThrowsGuardException_ForDelegatesCreatedFromMethodsWithRewriters(string code)
        {
            var compiled = TestHelper.Compile(@"
                using System;
                using System.Linq.Expressions;
                class C {
                    void M() { " + code + @" }
                }"
                                              );
            var policy = ApiPolicy.SafeDefault()
                         .Namespace("System.Linq.Expressions", ApiAccess.Allowed)
                         .Namespace("System.Reflection", ApiAccess.Allowed);

            Assert.Throws <AssemblyGuardException>(
                () => AssemblyGuard.Rewrite(compiled, new MemoryStream(), new AssemblyGuardSettings {
                ApiPolicy = policy
            })
                );
        }
Beispiel #2
0
        public ExecutionResult Execute(CompilationStreamPair streams, IWorkSession session)
        {
            var readerParameters = new ReaderParameters {
                ReadSymbols          = streams.SymbolStream != null,
                SymbolStream         = streams.SymbolStream,
                AssemblyResolver     = _assemblyResolver,
                SymbolReaderProvider = streams.SymbolStream != null ? _symbolReaderProvider : null
            };

            using (streams)
                using (var definition = AssemblyDefinition.ReadAssembly(streams.AssemblyStream, readerParameters)) {
                    AssemblyLog.Log("1.Initial", definition);

                    foreach (var rewriter in _rewriters)
                    {
                        rewriter.Rewrite(definition, session);
                    }
                    PerformanceLog.Checkpoint("Executor.Rewrite.Flow.End");

                    AssemblyLog.Log("2.WithFlow", definition);
                    if (definition.EntryPoint == null)
                    {
                        throw new ArgumentException("Failed to find an entry point (Main?) in assembly.", nameof(streams));
                    }

                    var guardToken = AssemblyGuard.Rewrite(definition, _guardSettings);
                    using (var rewrittenStream = _memoryStreamManager.GetStream()) {
                        definition.Write(rewrittenStream);

                        AssemblyLog.Log("3.Unbreakable", definition);

                        rewrittenStream.Seek(0, SeekOrigin.Begin);
                        PerformanceLog.Checkpoint("Executor.Rewrite.Unbreakable.End");
                        using (var context = new CustomAssemblyLoadContext(shouldShareAssembly: ShouldShareAssembly)) {
                            var assembly = context.LoadFromStream(rewrittenStream);
                            PerformanceLog.Checkpoint("Executor.AssemblyLoad.End");

                            return(Execute(assembly, guardToken, session));
                        }
                    }
                }
        }
Beispiel #3
0
        public void DoesNotEnforceApiPolicy_ForUserCode()
        {
            var compiled = TestHelper.Compile(@"
                namespace N {
                    class C1 {
                        void M(C2 c2) { c2.M(); }
                    }

                    class C2 {
                        public void M() {}
                    }
                }
            ");

            var exception = Record.Exception(() => AssemblyGuard.Rewrite(compiled, new MemoryStream(), new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault().Namespace("N", ApiAccess.Denied)
            }));

            Assert.Null(exception);
        }
Beispiel #4
0
        public void ThrowsGuardException_ForFieldReadsThatExceedSizeLimit()
        {
            // found by Tereza Tomcova (@the-ress)
            var compiled = TestHelper.Compile(@"
                using System;
                using System.Collections.Generic;

                struct A_1 { public int A; public int B; }
                struct A_2 { public A_1 A; public A_1 B; }
                struct A_3 { public A_2 A; public A_2 B; }
                struct A_4 { public A_3 A; public A_3 B; }
                struct A_5 { public A_4 A; public A_4 B; }
                struct A_6 { public A_5 A; public A_5 B; }
                struct A_7 { public A_6 A; public A_6 B; }
                struct A_8 { public A_7 A; public A_7 B; }
                struct A_9 { public A_8 A; public A_8 B; }
                struct A_10 { public A_9 A; public A_9 B; }
                struct A_11 { public A_10 A; public A_10 B; }
                struct A_12 { public A_11 A; public A_11 B; }
                struct A_13 { public A_12 A; public A_12 B; }
                struct A_14 { public A_13 A; public A_13 B; }
                struct A_15 { public A_14 A; public A_14 B; }
                struct A_16 { public A_15 A; public A_15 B; }
                struct A_17 { public A_16 A; public A_16 B; }
                struct A_18 { public A_17 A; public A_17 B; }

                class C {
                    static readonly A_18 Value = default(A_18);

                    int M() {
                        var d = new Dictionary<int, A_18>();
                        d.Add(0, Value);
                        return 0;
                    }
                }
            ");

            Assert.Throws <AssemblyGuardException>(
                () => AssemblyGuard.Rewrite(compiled, new MemoryStream())
                );
        }
Beispiel #5
0
        public ExecutionResult Execute(Stream assemblyStream, Stream symbolStream, IWorkSession session)
        {
            var readerParameters = new ReaderParameters {
                ReadSymbols          = symbolStream != null,
                SymbolStream         = symbolStream,
                AssemblyResolver     = _assemblyResolver,
                SymbolReaderProvider = symbolStream != null ? _symbolReaderProvider : null
            };

            using (assemblyStream)
                using (symbolStream)
                    using (var assembly = AssemblyDefinition.ReadAssembly(assemblyStream, readerParameters)) {
                        /*
                         #if DEBUG
                         * assembly.Write(@"d:\Temp\assembly\" + DateTime.Now.Ticks + "-before-rewrite.dll");
                         #endif
                         */
                        foreach (var rewriter in _rewriters)
                        {
                            rewriter.Rewrite(assembly, session);
                        }
                        if (assembly.EntryPoint == null)
                        {
                            throw new ArgumentException("Failed to find an entry point (Main?) in assembly.", nameof(assemblyStream));
                        }

                        var guardToken = AssemblyGuard.Rewrite(assembly, GuardSettings);
                        using (var rewrittenStream = _memoryStreamManager.GetStream()) {
                            assembly.Write(rewrittenStream);

                            /*
                             #if DEBUG
                             * assembly.Write(@"d:\Temp\assembly\" + DateTime.Now.Ticks + ".dll");
                             #endif
                             */
                            rewrittenStream.Seek(0, SeekOrigin.Begin);

                            return(ExecuteInAppDomain(rewrittenStream, guardToken, session));
                        }
                    }
        }
        private static Assembly RewriteNewtonsoftJson()
        {
            var assemblyPath = typeof(JsonSerializer).Assembly.GetAssemblyFileFromCodeBase().FullName;
            var definition   = AssemblyDefinition.ReadAssembly(assemblyPath);

            definition.Name.HasPublicKey      = false;
            definition.Name.PublicKey         = new byte[0];
            definition.Name.HashAlgorithm     = AssemblyHashAlgorithm.None;
            definition.MainModule.Attributes &= ~ModuleAttributes.StrongNameSigned;
            AssemblyGuard.Rewrite(definition, new AssemblyGuardSettings {
                ApiPolicy                = ApiRules,
                MethodLocalsSizeLimit    = IntPtr.Size * 40,
                MethodStackPushSizeLimit = 120,
                AllowExplicitLayoutInTypesMatchingPattern = new Regex("<PrivateImplementationDetails>")
            });

            var assemblyStream = new MemoryStream();

            definition.Write(assemblyStream);
            definition.Write(Path.Combine(Path.GetDirectoryName(assemblyPath) !, "Newtonsoft.Json.Rewritten.dll"));
            return(Assembly.Load(assemblyStream.ToArray()));
        }
Beispiel #7
0
        public static Invoke RewriteAndGetMethodWrappedInScope(
            string code, string typeName, string methodName,
            AssemblyGuardSettings?assemblyGuardSettings = null,
            RuntimeGuardSettings?runtimeGuardSettings   = null
            )
        {
            runtimeGuardSettings ??= new RuntimeGuardSettings {
                TimeLimit = TimeSpan.FromMilliseconds(1000)
            };

            var assemblySourceStream = Compile(code);
            var assemblyTargetStream = new MemoryStream();

            var token = AssemblyGuard.Rewrite(assemblySourceStream, assemblyTargetStream, assemblyGuardSettings);

            return(args => {
                using (token.Scope(runtimeGuardSettings)) {
                    var method = GetInstanceMethod(assemblyTargetStream, typeName, methodName);
                    return method(args);
                }
            });
        }
Beispiel #8
0
        public ExecutionResult Execute(CompilationStreamPair streams, IWorkSession session)
        {
            var readerParameters = new ReaderParameters {
                ReadSymbols          = streams.SymbolStream != null,
                SymbolStream         = streams.SymbolStream,
                AssemblyResolver     = _assemblyResolver,
                SymbolReaderProvider = streams.SymbolStream != null ? _symbolReaderProvider : null
            };

            using (streams)
                using (var definition = AssemblyDefinition.ReadAssembly(streams.AssemblyStream, readerParameters)) {
                    AssemblyLog.Log("1.Initial", definition);

                    foreach (var rewriter in _rewriters)
                    {
                        rewriter.Rewrite(definition, session);
                    }
                    AssemblyLog.Log("2.WithFlow", definition);
                    if (definition.EntryPoint == null)
                    {
                        throw new ArgumentException("Failed to find an entry point (Main?) in assembly.", nameof(streams));
                    }

                    var guardToken = AssemblyGuard.Rewrite(definition, _guardSettings);
                    using (var rewrittenStream = _memoryStreamManager.GetStream()) {
                        definition.Write(rewrittenStream);
                        AssemblyLog.Log("3.Unbreakable", definition);

                        rewrittenStream.Seek(0, SeekOrigin.Begin);
                        var(result, exception) = ExecuteWithIsolation(rewrittenStream, guardToken, session);
                        if (ShouldMonitorException(exception))
                        {
                            _monitor.Exception(exception !, session);
                        }

                        return(result);
                    }
                }
        }
Beispiel #9
0
 public static RuntimeGuardToken Rewrite(Stream source, Stream target)
 {
     return(AssemblyGuard.Rewrite(source, target, CreateGuardSettings()));
 }