Особые исключения в.net

Similar documents
Exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running

The code for all of this is relatively straightforward. The full listing using SEH is shown below: #include <Windows.h>

Reversed Buffer Overflow Cross Stack Attacks. Kris Kaspersky Endeavor Security, Inc.

.Net Technologies. Components of.net Framework

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

C#: framework overview and in-the-small features

Introduce C# as Object Oriented programming language. Explain, tokens,

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Question And Answer.

Exercise Session Week 8

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exercise Session Week 8

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Multithreading. Multithreading. HIS CHAPTER DISCUSSES how to write multithreaded code. To do this, Another Thread

SA31675 / CVE

Introduction to C# Applications

{ JSL } phone +44 (0)

Framework Design Guidelines

Key Switch Control Software Windows driver software for Touch Panel Classembly Devices

State of the.net Performance

CS313D: ADVANCED PROGRAMMING LANGUAGE

Platform SDK Developer's Guide. Management Layer

Programming II (CS300)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Programming in.net. Microsoft Development Center Serbia programming course. Lesson 8 Parallelism and Threading in.net

Programming II (CS300)

Expert C++/CLI:.NET for Visual C++ Programmers

Concurrent and Real-Time Programming in Java

Modeling the.net CLR Exception Handling Mechanism for a Mathematical Analysis

Final Exam. Fall Semester 2016 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

CS 241 Honors Concurrent Data Structures

Threads are lightweight processes responsible for multitasking within a single application.

Table of Contents Preface Bare Necessities... 17

EXCEPTIONS. Prof. Chris Jermaine

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Malware Analysis and Antivirus Technologies: Using Debuggers to Analyze Malware

What goes inside when you declare a variable?

Understanding Undefined Behavior

G Programming Languages - Fall 2012

Variation of Pointers

Runtime Defenses against Memory Corruption

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

T Using debuggers to analyze malware. Antti Tikkanen, F-Secure Corporation

About INtime Win32 and real time extension system calls

Problems.Net. Обра. Анатолий Крыжановский

CS 222: Pointers and Manual Memory Management

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Computer Components. Software{ User Programs. Operating System. Hardware

Contents. Error Handling Strategies (cont d) Error handling strategies: error code, assert(), throw-try-catch

SIMATIC Industrial software Readme SIMATIC S7-PLCSIM Advanced V2.0 SP1 Readme

Question And Answer.

Threading in C# The mere mention of multithreading can strike fear in the hearts of some programmers. For others,

Exceptions. Why Exception Handling?

Future Trends in Computing X10 Basics Distributed Programming

SPUR: A Trace-Based JIT Compiler for CIL

Level: M.Ed. Credit Hour: 3 (2+1) Semester: Third Teaching Hour: 80(32+48)

Towards a Real-Time Implementation of the ECMA Common Language Infrastructure

Program Flow. Instructions and Memory. Why are these 16 bits? C code. Memory. a = b + c. Machine Code. Memory. Assembly Code.

Is Exploitation Over? Bypassing Memory Protections in Windows 7

Pointers, Dynamic Data, and Reference Types

Excep&ons and Threads

Final Exam. Fall Semester 2016 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Third Midterm Exam April 24, 2017 CS162 Operating Systems

C16b: Exception Handling

SEH overwrite and its exploitability. Shuichiro Suzuki Fourteenforty Research Institute Inc. Research Engineer

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

Application Architecture Using Generics C#.Net 2.0

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context

Beyond Stack Smashing: Recent Advances in Exploiting. Jonathan Pincus(MSR) and Brandon Baker (MS)

Course Hours

Fun facts about recursion

Assertions and Exceptions

Lecture 21: Concurrency in Other Environments (Part 2)

Contents. I Introductory Examples. Topic 06 -Exception Handling

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

LoadDataToDataGrid();

OPC UA Protocol Stack

File Systems: Consistency Issues

Exceptions, Case Study-Exception handling in C++.

Software Exception Flow Analysis for WPF C# Asynchronous Programs Using Microsoft Visual Studio

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

Error Handling. Exceptions

5 When a program calls a function, in which type of data structure is memory allocated for the variables in that function?

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued)

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

CSCE : Computer Systems Homework #1 Part 1 (25 pts) Due date: 1/24/19

C Programming Basics II

FAT (32 KB) 216 * 215 = 231 = 2GB

2018/2/5 话费券企业客户接入文档 语雀

Object Oriented Programming Exception Handling

StackwalkerAPI Programmer s Guide

Transparent Pointer Compression for Linked Data Structures

Threads & Networking

PES INSTITUTE OF TECHNOLOGY

the gamedesigninitiative at cornell university Lecture 10 Memory Management

Pierce Ch. 3, 8, 11, 15. Type Systems

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Transcription:

Особые исключения в.net Евгений Пешков e-mail: peshkov@kontur.ru telegram/twitter/vk: @epeshk 1

ПЛАН Поведение исключений в.net AccessViolationException ThreadAbortException OutOfMemoryException StackOverflowException Обработка исключений в Windows и хаки SEH/VEH Обработка StackOverflowException 2

ACCESS VIOLATION try { Marshal.WriteByte((IntPtr) 1000, 42); catch (AccessViolationException) {... 3

ACCESS VIOLATION try { var bytes = new byte[] {42; Marshal.Copy(bytes, 0, (IntPtr) 1000, bytes.length); catch (AccessViolationException) {... 4

ACCESS VIOLATION Marshal.Copy(bytes, 0, (IntPtr) 1000, bytes.length); Marshal.WriteByte((IntPtr) 1000, 42); 5

ACCESS VIOLATION static void Copy(...) { Marshal.CopyToNative( (object) source, startindex, destination, length); [MethodImpl(MethodImplOptions.InternalCall)] static extern void CopyToNative( object source, int startindex, IntPtr destination, int length); 6

ACCESS VIOLATION unsafe static void WriteByte(IntPtr ptr, byte val) { try { *(byte*) ptr = val; catch (NullReferenceException) { throw new AccessViolationException(); Все исключения, выброшенные throw - обрабатываемые 7

ACCESS VIOLATION unsafe static void WriteByte(IntPtr ptr, byte val) { try { *(byte*) ptr = val; catch (NullReferenceException) { throw new AccessViolationException(); *(byte*) 1000 = 42; 8

NULL REFERENCE 0-2 16 Virtual address space Null Reference Access Violation 9

NULL REFERENCE Virtual address space class A Field A a = null; Console.WriteLine(a.Field); movzx eax,byte ptr [rdx+48h] 10

NULL REFERENCE Large class Virtual address space Field 11

ACCESS VIOLATION [StructLayout(LayoutKind.Explicit)] public class LargeClass { public byte A; [FieldOffset(64 * 1024)] public byte B; void GetA(LargeClass c) { return c.a; void GetB(LargeClass c) { return c.b; movzx eax,byte ptr [rdx+8h] cmp dword ptr [rdx],edx movzx eax,byte ptr [rdx+10008h] 12

ACCESS VIOLATION Code/Address < 64 KB >= 64 KB Managed Null Reference Access Violation Native Access Violation Access Violation 13

ACCESS VIOLATION Версия.NET Поведение Native Access Violation 1.0 NullReferenceException 2.0, 3.5 Обрабатываемый AV 4.0 и выше Обрабатываемый AV*.NET Core Необрабатываемый AV [HandleProcessCorruptedStateExceptions] App.config legacynullreferenceexceptionpolicy legacycorruptedstateexceptionspolicy 14

ACCESS VIOLATION.NET 4 Runtime.NET 4.7.1 Application.NET 3.5 Library 15

ACCESS VIOLATION while (isrunning) { try { action(); catch (Exception e) { log.error(e); WaitForNextExecution(...); 16

ACCESS VIOLATION Native/managed Обработка зависит от Target Framework и настроек рантайма 17

THREAD ABORT var thread = new Thread(() => { try {... catch (ThreadAbortException e) {... );... throw; thread.abort(); 18

THREAD ABORT var thread = new Thread(() => { try {... catch (ThreadAbortException e) {... );... Thread.ResetAbort(); thread.abort(); 19

FINALLY var thread = new Thread(() => { try { ); catch { // <-- No ThreadAbortException in catch finally { // <-- No ThreadAbortException in finally Thread.Sleep(-1); thread.start();... thread.abort(); // Never returns 20

THREAD ABORT NET CORE thread.abort() throws PlatformNotSupportedException 21

OUT OF MEMORY var arr4gb = new int[int.maxvalue/2]; App.config: gcallowverylargeobjects var largearr = new int[int.maxvalue]; Max array index: byte arrays 0x7FFFFFC7 other arrays 0X7FEFFFFF 22

OUT OF MEMORY static string Concat(params string[] values) { int totallength = 0; string[] sargs = new string[values.length]; for (int index = 0; index < values.length; ++index) { string str = values[index]; sargs[index] = str == null? string.empty : str; totallength += sargs[index].length; if (totallength < 0) throw new OutOfMemoryException(); return string.concatarray(sargs, totallength); 23

OUT OF MEMORY LimitMemory(64.Mb()); try { while (true) list.add(new byte[size]); catch (OutOfMemoryException e) { Console.WriteLine(e); 24

OUT OF MEMORY Исключение обработается Процесс упадёт Зайдём в catch, но исключение вылетит снова Зайдём в catch, но вылетит StackOverflow 25

OUT OF MEMORY Ответ 26

OUT OF MEMORY Исключение обработается Процесс упадёт Зайдём в catch, но исключение вылетит снова Зайдём в catch, но вылетит StackOverflow 27

OUT OF MEMORY LimitMemory(64.Mb()); try { while (true) list.add(new byte[size]); catch (OutOfMemoryException e) { Console.WriteLine(e); 28

ОТКУДА STACKOVERFLOW Virtual address space RAM + Swap Reserved Committed 29

ОТКУДА STACKOVERFLOW Reserved pages MethodB Committed pages MethodA 30

ОТКУДА STACKOVERFLOW new Thread(() => F(), 4*1024*1024).Start(); 31

ОТКУДА STACKOVERFLOW <disablecommitthreadstack enabled="false"/> «The default behavior of the common language runtime is to commit the full thread stack when a thread is started» - MSDN https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/disablecommitthreadstack-element 32

STACK OVERFLOW try { InfiniteRecursion(); catch (Exception) {... try { throw new StackOverflowException(); catch (Exception) {... 33

STACK OVERFLOW «You cannot catch stack overflow exceptions, because the exception-handling code may require the stack. Instead, when a stack overflow occurs in a normal application, the Common Language Runtime (CLR) terminates the process.» - MSDN https://msdn.microsoft.com/en-us/library/w6sxk224.aspx 34

КАК ИЗБЕЖАТЬ STACK OVERFLOW RuntimeHelpers.EnsureSufficientExecutionStack(); «Ensures that the remaining stack space is large enough to execute the average.net Framework function.» - MSDN InsufficientExecutionStackException 512 KB x86, AnyCPU, 2 MB x64 (half of stack size) 64/128 KB -.NET Core Check only stack address space RuntimeHelpers.TryEnsureSufficientExecutionStack(); https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimehelpers.ensuresufficientexecutionstack https://github.com/dotnet/coreclr/issues/9167 35

КАК ИЗБЕЖАТЬ STACK OVERFLOW Span<byte> span; if (CanAllocateOnStack(size)) span = stackalloc byte[size]; else span = new byte[size]; 36

КАК ИЗБЕЖАТЬ STACK OVERFLOW RuntimeHelpers.TryForSufficientStack(size); trystackalloc https://github.com/dotnet/corefx/issues/26954 37

STACK OVERFLOW «You cannot catch stack overflow exceptions, because the exception-handling code may require the stack. Instead, when a stack overflow occurs in a normal application, the Common Language Runtime (CLR) terminates the process.» - MSDN https://msdn.microsoft.com/en-us/library/w6sxk224.aspx 38

НА УРОВЕНЬ НИЖЕ Managed exceptions Managed app CLR Windows 39

CLR HOSTING «An application that hosts the CLR can change the default behavior and specify that the CLR unload the application domain where the exception occurs, but lets the process continue.» - MSDN StackOverflowException AppDomainUnloadedException https://msdn.microsoft.com/en-us/library/w6sxk224.aspx 40

CLR HOSTING ICLRPolicyManager *policymgr; pclrcontrol->getclrmanager( IID_ICLRPolicyManager, (void**)(&policymgr)); policymgr->setactiononfailure( FAIL_StackOverflow, erudeunloadappdomain); erudeexitprocess erudeunloadappdomain 41

CLR HOSTING try { var appd = AppDomain.CreateDomain(... ); appd.docallback(() => { var thread = new Thread(() => InfiniteRecursion()); thread.start(); thread.join(); ); AppDomain.Unload(appd); catch (AppDomainUnloadedException) { 42

APP DOMAINS public class CustomException : Exception { var appd = AppDomain.CreateDomain("..."); appd.docallback(() => throw new CustomException()); System.Runtime.Serialization.SerializationException: Type 'CustomException' is not marked as serializable. at System.AppDomain.DoCallBack(CrossAppDomainDelegate callbackdelegate) 43

APP DOMAINS (SERIALIZATION EXCEPTION) [Serializable] public class CustomException : Exception { public CustomException(){ public CustomException( SerializationInfo info, StreamingContext ctx) : base(info, context){ var appd = AppDomain.CreateDomain("..."); appd.docallback(() => throw new CustomException()); 44

НА УРОВЕНЬ НИЖЕ Managed exceptions Managed app CLR Windows SEH exceptions 45

SEH SEH Structured Exception Handling Механизм обработки исключений в Windows Единообразная обработка software и hardware исключений C# исключения реализованы поверх SEH 46

SEH MANAGED EXCEPTION_STACK_OVERFLOW Crash EXCEPTION_ACCESS_VIOLATION AccessViolationException EXCEPTION_ACCESS_VIOLATION NullReferenceException EXCEPTION_INT_DIVIDE_BY_ZERO DivideByZeroException Unknown SEH exceptions SEHException 47

RAISE SEH [DllImport("kernel32.dll")] static extern void RaiseException( uint dwexceptioncode, uint dwexceptionflags, uint nnumberofarguments, IntPtr lparguments); 48

RAISE SEH // DivideByZeroException RaiseException(0xc0000094, 0, 0, IntPtr.Zero); // Stack overflow RaiseException(0xc00000fd, 0, 0, IntPtr.Zero); 49

THROW & SEH throw RaiseException(0xe0434f4d,...) SEH СLR Exception Managed exception SEH СLR Exception Managed exception 50

VEH VEH Vectored Exception Handling Расширение SEH Работает на уровне процесса Позволяет изменить SEH исключение до обработки 51

ПЕРЕХВАТ STACK OVERFLOW Managed exceptions Managed app CLR Windows Handler SEH exceptions 52

VEH [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr AddVectoredExceptionHandler( IntPtr FirstHandler, PVECTORED_EXCEPTION_HANDLER VectoredHandler); 53

VEH delegate VEH PVECTORED_EXCEPTION_HANDLER( ref EXCEPTION_POINTERS exceptionpointers); public enum VEH : long { EXCEPTION_CONTINUE_SEARCH = 0, EXCEPTION_EXECUTE_HANDLER = 1, EXCEPTION_CONTINUE_EXECUTION = -1 54

VEH delegate VEH PVECTORED_EXCEPTION_HANDLER( ref EXCEPTION_POINTERS exceptionpointers); [StructLayout(LayoutKind.Sequential)] unsafe struct EXCEPTION_POINTERS { public EXCEPTION_RECORD* ExceptionRecord; public IntPtr Context; 55

VEH delegate VEH PVECTORED_EXCEPTION_HANDLER( ref EXCEPTION_POINTERS exceptionpointers); [StructLayout(LayoutKind.Sequential)] unsafe struct EXCEPTION_RECORD { public uint ExceptionCode;... 56

ПЕРЕХВАТ STACK OVERFLOW static unsafe VEH Handler(ref EXCEPTION_POINTERS e) { if (e.exceptionrecord == null) return VEH.EXCEPTION_CONTINUE_SEARCH; var record = e.exceptionrecord; if (record->exceptioncode!= ExceptionStackOverflow) return VEH.EXCEPTION_CONTINUE_SEARCH; record->exceptioncode = 0x01234567; return VEH.EXCEPTION_EXECUTE_HANDLER; 57

ПЕРЕХВАТ STACK OVERFLOW HandleSO(() => InfiniteRecursion()); 58

ПЕРЕХВАТ STACK OVERFLOW static T HandleSO<T>(Func<T> action) { Kernel32.AddVectoredExceptionHandler( IntPtr.Zero, new PVECTORED_EXCEPTION_HANDLER(Handler)); Kernel32.SetThreadStackGuarantee(ref size); try { return action(); catch (Exception e) when ((uint) Marshal.GetExceptionCode() == 0x01234567) { return default(t); 59

ПЕРЕХВАТ STACK OVERFLOW HandleSO(() => InfiniteRecursion()); HandleSO(() => InfiniteRecursion()); AccessViolationException 60

ПЕРЕХВАТ STACK OVERFLOW Guard page STATUS_GUARD_PAGE_VIOLATION MethodC MethodB MethodA 61

ВОССТАНОВЛЕНИЕ GUARD PAGE [DllImport("msvcrt.dll")] static extern int _resetstkoflw(); 62

ПЕРЕХВАТ AV В NET CORE Kernel32.AddVectoredExceptionHandler( IntPtr.Zero, handler); Kernel32.AddVectoredExceptionHandler( (IntPtr) 1, handler); 63

ВЫВОДЫ Исключения не так просты, как кажутся Не все исключения обрабатываются одинаково Обработка исключений происходит на разных уровнях абстракции Можно вмешаться в процесс обработки исключений 64

LINKS Samples https://github.com/epeshk/dotnext-2018-exceptions Exceptional Exceptions in.net https://www.youtube.com/watch?v=u92ts53win4 65

ВОПРОСЫ Евгений Пешков e-mail: peshkov@kontur.ru telegram/twitter/vk: @epeshk 66