.Net Basics & Security erich.ruf@csnc.ch Juli 2004 Pae 1
Aenda Indroduction to.net Framework Basics of C# Lanuae Hello World Sample IL-Decompilation Native Code.Net Security Model Remotin ASP.NET Web Services Juli 2004 Pae 2
Introduction What is.net? Microsoft.NET is a set of software technoloies for connectin information, people, systems, and devices. It s a software platform that offers a lanuae-neutral environment for writin prorams that can easily and securely interoperate..net Framework, the core component: Common Lanuae Runtime (CLR) Base Class Library (BCL) Application Hello World App BCL CLR ASP.NET ADO.NET Web-Services GC Security JIT-Compiler.NET Framework OS Windows Juli 2004 Pae 3
Introduction - Basic Concept Goal: x prorammin lanuae for 1 (x) platforms C#, C++, VB, Java, Perl Sourcecode compiled in Common Intermediate Lanuae (CIL) Common Lanuae Runtime (CLR) compiles CIL with JIT compiler in native code and executes it. C# C++ VB Java Perl compiled Common Intermediate Lanuae (CIL) JIT compiled Native Code executes Windows Juli 2004 Pae 4
Introduction.NET Framework Common Lanuae Infrastructure (CLI) Specifies the CLR and the BCL / FCL ISO Standard since Dec. 2002 (ISO/IEC 23271).NET Framework 1.1 is an implementation of the CLI standard Common Intermediate Lanuae (CIL) Output from.net Compilers 240 Operation Codes are defined Codes in binary form Input for JIT Compiler Juli 2004 Pae 5
Introduction.NET Framework Common Lanuae Runtime (CLR) Runtime Environment for manaed.net Code Contains: - JIT-Compiler - Class Loader - Memory Manaement with Garbae Collection - Basic Classes with System Functions - Code Access Security - Type Checkin and Code Verification - Garbae Collector (GC) Base or Framework Class Library (BCL/FCL) BCL, old Name for FCL, used in Beta Versions of the.net Framework 1.0 FCL is an extension of the BCL Juli 2004 Pae 6
Introduction Assemblies Assembly = Unit for Distribution, Versionin + Security Sample Multi File Assembly Multi File Assembly (MFA) Modul MFA.exe Manifest Metadaten Modul M1.mod Metadaten CIL - Code CIL - Code Modul M2.mod Sound.mp3 Imae.if Metadaten CIL - Code Assembly = loical unit, Module = physical unit Juli 2004 Pae 7
Introduction Assemblies Sample Build-Hierarchy *.cs = Source File *.mod = Module File (Binary File with IL-Code) *.exe = Portable Executable File *.dll = Dynamic Link Library Juli 2004 Pae 8
C# Lanuae Basics of C# Lanuae A short overview Juli 2004 Pae 9
C# Lanuae Introduction C# was developed for the.net framework C# is quite similar to Java It consists of 70% Java, 10% C++, 5% VB, 15% new Features from Java Object Oriented (sinle class inheritance only) Interfaces Exceptions Threads Namespaces (like Packaes) Stron Typechecks Garbae Collection Reflection Dynamic Code Loadin Juli 2004 Pae 10
C# Lanuae Introduction Features from C++ Operator Overloadin Pointers (only in unsafe code) some syntactical details New Features Referenceparameters Objects (Structs) on the stack Blockmatrix Enumerations Deleates Indexers Boxin/Unboxin Versionin some more Juli 2004 Pae 11
Hello World Sample Hello World Sample What we need to build a Hello World proram Juli 2004 Pae 12
Hello World Preconditions What we need to run a.net application Computer with one of the followin OS: - MS Windows 2003 Server - MS Windows XP - MS Windows 2000 / Server - MS Windows ME - MS Windows 98 - MS Windows NT 4.0 (SP 6a) Microsoft.NET Framework Redistributable Packae - Current Version: 1.1 - Free download available on http://www.microsoft.com/downloads (23 MB) - Check if the.net Framework isn t already installed: Start -> Control Panel -> Software Juli 2004 Pae 13
Hello World Preconditions What we need to develop a.net application Computer with one of the followin OS: - MS Windows 2003 Server - MS Windows XP (Professional is required to run ASP.NET) - MS Windows 2000 (SP 2 recommended) Microsoft.NET Framework Software Development Kit (SDK) - Current Version: 1.1 - Free download available on http://www.microsoft.com/downloads (108 MB) - Install first the.net Framework Redistributable Packae -.NET Framework SDK and Redistributable Packae are already included in the Microsoft Visual Studio.NET 2003 Juli 2004 Pae 14
Hello World Developer Tools Available Developer Tools Microsoft Visual Studio.NET 2003 http://msdn.microsoft.com/vstudio/productinfo/ Borland C# Builder http://www.borland.com/csharpbuilder/ Borland Delphi for.net http://www.borland.com/delphi_net/ SharpDevelop - Opensource und Freeware http://www.icsharpcode.net/opensource/sd/ Webmatrix for ASP.NET http://www.asp.net/webmatrix/ Juli 2004 Pae 15
Hello World Developer Tools Hello World Sample with Sharp Develop Juli 2004 Pae 16
IL - Decompilation IL - Decompilation How we can decompile IL code Juli 2004 Pae 17
IL-Decompilation - Tool Decompile.NET IL Code with ildasm.exe Included in.net SDK under..\microsoft.net\sdk\v1.1\bin\ildasm.exe Decompile.NET IL Code into real source code with: Anakrino (open source) http://www.saurik.com/net/exemplar Salamander $1099 http://www.remotesoft.com/salamander/index.html Juli 2004 Pae 18
IL-Decompilation - Countermeasures Possible countermeasures Code obfuscatin IL-Code compile to native code.net Obfuscator Product Samples Dotfuscator PreEmptive Solutions $395 http://www.dotfuscator.com/ Demeanor for.net WiseOwl $799 http://www.wiseowl.com/.net Compiler Product Sample Salamander.NET Protector Remotesoft $1899 http://www.remotesoft.com/salamander/protector.html Juli 2004 Pae 19
Native Code Native Code manaed vs. unmanaed code / native calls Juli 2004 Pae 20
Native Code un-/manaed Code Manaed Code IL Code, Executed by the CLR Contains metadata about the code All.NET lanuaes are compiled in manaed code C++ can be compiled in manaed or unmanaed code Manaed Data Allocated and released by the CLR / Garbae Collector Access only by manaed code Unmanaed Code Native executed Code Unmanaed Data Allocated and released not by the CLR Juli 2004 Pae 21
Native Code un-/manaed Code Unsafe manaed code Only partial manaed by the CLR Manaed C++ code or C# code in an unsafe block is called unsafe manaed code Allows pointers Assembler code ( asm ) not allowed ->native calls Sample: unsafe public void AnUnsafeMethode(int* p) { *p = 5; } public void AMethode() { unsafe //an unsafe block { Console.Writeln(sizeof(int)); } } Juli 2004 Pae 22
Native Code Native Calls Native Calls C# allow calls of native functions The native code is unmanaed and not observed by the CLR! Sample: usin System.Runtime.InteropServices; class Test { [DllImport("user32.dll")] static extern int MessaeBox(int hwnd, strin txt, strin capt, int type); } void Main() { int res = MessaeBox(0, "Isn't that cool?", "", 1); } Juli 2004 Pae 23
Security Model.NET Security Model The mechanism and their confiuration Juli 2004 Pae 24
Security Model Overview Two Security Concepts Code Access Security Role Based Security real permissions Code Access Security: Permission dependin on assembly Role Based Security: Permission dependin on user role Juli 2004 Pae 25
Security Model CAS Code Access Security (CAS) Specify the permissions Policy Levels Assembly X Enterprise Machine User Assembly X Evidence URL Zone Publisher Hash Security Manaer PermissionSet FileIO CodeAccess Reflection Reistry Juli 2004 Pae 26
Security Model CAS Security Policy Level all code Nothin Zone: MyComputer SomeCaution URL: http://www.csnc.ch SSW Zone: Internet Internet URL: file://c:/trusted/* Full Trust Publisher: Microsoft Microsoft Publisher: Microsoft SomeCaution Microsoft (PermissionSet) FileDialoPermission:Open SecurityPermission:Execution Juli 2004 Pae 27
Security Model Confiuration.NET Confiuration Policy Levels PermissionSets Code Groups Juli 2004 Pae 28
Security Model Stack Walk Security Stack Walk Every function have to check the permissions of its callers before it accesses a particular resource. If all callers have the permission ranted, the function continues. If only one of the callers don't have the permission, an exception is thrown Juli 2004 Pae 29
Security Model Stack Walk Stack Walk initiation A stack walk is normally initiated by a Library which access secure critical resources. Sample: public void AMethode() { CodeAccessPermission p; p = new FileIOPermission(FileIOPermissionAccess.Read, c:\\f.txt ); p.demand(); dosomethin(); } or in a declarative way: [ FileIOPermission(SecurityAction.Demand,Read= c:\\f.txt )] public void AMethode() { dosomethin(); } Juli 2004 Pae 30
Security Model Stack Walk Stack Walk Modifiers Developers have the opportunity to modify the stack walk. 3 modifiers are available: - Assert: rants permission to callin code -> abort, positiv - Deny: stack walk will fail -> abort, neativ - PermitOnly: denies everythin except the specified permission -> abort, neativ Sample: static void Main(strin[] ars) { Strin f = @"c:\windows"; FileIOPermission p = new FileIOPermission(FileIOPermissionAccess.Write,f); p.demand(); //ok, if the necessary permissions are ranted p.deny(); p.demand(); //ok, because the Deny has no effect in the current method CheckDeny(p); //failed, because the Deny p.assert(); CheckDeny(p); //failed, because a Deny overwrites an Assert } Juli 2004 Pae 31
Security Model RBS Role Based Security, the second security layer Has Assembly XY the permission to access Drive C:\? Is our user allowed to access Drive C:\?.NET s abstract useridentities and roles IIdentity: Interface which represents a user IPrincipal: Interface which represents the roles Each principal belons to one identity Juli 2004 Pae 32
Security Model RBS Each thread belons to one principal Thread knows his principal -> principal knows his identity Use the classes PrincipalPermission and PrincipalPermissionAttribute to check the permissions: static void Methode1() { } GenericIdentity i = new GenericIdentity("testuser"); strin[] roles = { read", write"}; Thread.CurrentPrincipal = new GenericPrincipal(i, roles); Method2(); [PrincipalPermissionAttribute(SecurityAction.Demand, Name= testuser )] static void Methode2() { PrincipalPermission p = new PrincipalPermission(null, read", true); p.demand(); } Juli 2004 Pae 33
Security Model RBS Implementations of the Interfaces IIdentity and IPrincipal GenericIdentity / GenericPrincipal (Defaultimplementation) WindowsIdentity / WindowsPrincipal (Windows User/Roles) static void Method1() { } AppDomain.CurrentDomain.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal); [PrincipalPermissionAttribute(SecurityAction.Demand, Name=@ TEST\user )] static void Methode2() { } //secret code CustomIdentity / CustomPrincipal (Customized Impl.) Juli 2004 Pae 34
Security Model RBS Chane current User Sample with Win32 Api function LoonUser: static bool SetUser(strin user, strin domain, strin pwd) { int token = 0; if(loonuser(user, domain, pw, 3, 0, out token) == false) { return false; } WindowsIdentity id = new WindowsIdentity(token); Thread.CurrentPrincipal = new WindowsPrincipal(id); return true; } Sample with Impersonate function: static void impersonateidentity(windowsidentity identity) { } identity.impersonate(); //Now the code has the operation system rihts of the user //represented by identity. Juli 2004 Pae 35
Remotin.NET Remotin.NET over the Network Juli 2004 Pae 36
Remotin - AppDomains Application Domains / Processes / Threads CLR abstracts OS-Processes and works with application domains ( virtual processes ) AppDomains are containers for assemblies One AppDomain contains one or more assemblies Juli 2004 Pae 37
Remotin - AppDomains Inter application domain method calls -> Remotin Method calls outside the AppDomain requires marshalin Juli 2004 Pae 38
Remotin Marshalin Marshalin by Reference (MBR) Remote object from class System.MarshalByReference extended Executed only in AppDomain in which it was instantiated (no copy) Client calls methods over a proxy object Client ets the proxy object by the activation Marshalin by Object (MBO) Remote object must be serializable (Attribut [Serializable]) A local copy from the remote object is instantiated Juli 2004 Pae 39
Remotin Architecture Remotin Architecture Juli 2004 Pae 40
Remotin Components Proxy Stub Offers the methods from the remote object to the client Forwards calls from client to the formatter Invokes on the server side the remote object Formatters Serialise / deserialise the data in SOAP or binary format SOAP Formatter (default HTTP Channel) Binary Formatter (default TCP Channel) Channels HTTP Channel TCP Channel Juli 2004 Pae 41
Remotin RO-Classification Server Activated Objects Well-Known Objects Instantiated and published by the Server Sinleton Confiuration: - one object for all clients - synchronized access - -> bad scalability - lobal state Sinle-Call Confiuration: - new object for each call - ood scalability - stateless Juli 2004 Pae 42
Remotin RO-Classification Client Activated Objects The client activates the object on the server Each client has its own remote object on the server Lifetime Lease is defined by the client If the lifetime is expired, the arbae collector will kill the instance Juli 2004 Pae 43
Remotin RO-Classification Client Activated Objects Identification Which objects belons to which client? Solved with objects identifier Below a sample of object activation and invocation of the method SayHello() : Client Server create instance of the class HelloWorld object id: CGUYrSh0zKKkbPEoLNr7P_k_1.rem create object invoke methode SayHello() from object with id: CGUYrSh0zKKkbPEoLNr7P_k_1.rem answer: Hello World invoke method SayHello Juli 2004 Pae 44
Remotin Security Model.NET Remotin doesn t offer an own security model All information are transferred as plain text! For a crypted channel use: IPSec and/or SSL (HTTPS) For authentication and authorisation use: ASP.NET / IIS Hostin Juli 2004 Pae 45
ASP.NET ASP.NET Dynamic web paes in.net / IIS Security Juli 2004 Pae 46
ASP.NET - Overview ASP.NET is a component of the.net framework which supports dynamic websites ASP.NET is comparable to JSP Pae sample: <% @Pae Lanuae= C# Debu= false %> <script runat= server > strin text = Guten ta ; void Pae_Load(Object sender, EventArs e) { int hour = DateTime.Now.Hour; if( hour < 12 ) { text = Guten Moren ; } } </script> <html><head></head><body> <p><font Face= Arial Color= blue > <%= text %> </Font></p> </body> </html> Juli 2004 Pae 47
ASP.NET Pae Request Pae Request cycle Parse ASPX Enine Generate Codebehind class 1. Request fo. Requests ASPX File Instantiate Gen d Pae Class Compile Response Response Pae DLL Instantiate, Process and Render Juli 2004 Pae 48
ASP.NET State Manaement Session State Session identifier: - Cookie - URL Rewritin User data on Server in HttpSessionState Object stored Three possibilities to store session data: - IncPro: data stored on aspnet_wp.exe process - StateServer: WinNT/2000 Service - SQLServer: Microsoft database Application State Application data stored in HttpApplicationState Juli 2004 Pae 49
ASP.NET Object Model ASP.NET Object Model Juli 2004 Pae 50
ASP.NET Authentication Four different authentication possibilities Windows Authentication - Basic Auth - Diest Auth - Interated Windows Auth (NTLM, Kerberos) Forms Authentication - Loin pae - User and password isn t checked on the server but in your own code Passport Authentication - External administration of user and passwords with a MS.NET Passport Server Client Certificate Juli 2004 Pae 51
ASP.NET Controls HTML server controls Objects inside a web formular Executes the actions on server side <% @Pae Lanuae= C# Debu= true %> <script runat= server > void Btn_Click(Object Src, EventArs E) { mylable.text = Hallo Welt"; } </script> <html> <body> <form action= test.aspx runat= server > <asp:button text= OK onclick= Btn_Click runat= server /> <asp:label id= mylable runat= server /> </form> </body> </html> Juli 2004 Pae 52
ASP.NET Input Validation Input Validation with controls There are five predefined controls: RequiredFieldValidation Control - It makes sure that the user inputs a value The CompareValidator Control - It compares two value The RaneValidator Control - Checks if the value is in the iven rane The ReularExpressionValidator Control - Checks if the input matches with the reular expression The CustomValidator Control - Makes it possible to write our own function which validates the input Juli 2004 Pae 53
ASP.NET Input Validation Sample with a ReularExpressionValidator Control: E-mail: <asp:textbox id="textbox1" runat="server"/> <asp:reularexpressionvalidator id="valreex runat="server" ControlToValidate="textbox1" ValidationExpression=.*@.*\..* ErrorMessae="* Not a valid e-mail address." display="dynamic">* </asp:reularexpressionvalidator> Validation Summary Collects all the error messaes of all the non-valid controls and put them in a tidy list. <asp:validationsummary id="valsummary" runat="server" HeaderText="Errors: showsummary="true" DisplayMode="List" /> Juli 2004 Pae 54
Web Services Web Services Overview / Sample / Security Juli 2004 Pae 55
Web Services Overview SOAP (Simple Object Access Protocol) XML based protocol for data transport Uses mostly HTTP as underlyin transport protocol WSDL (Web Service Description Lanuae) Describes a web service: Available methods, Protocol, Ports.. UDDI (Universal Description, Discovery and Interation) Index of available web services DISCO (Discovery of web services) ~ UDDI Microsoft service Juli 2004 Pae 56
Web Services Sample ASP.NET infrastructure supports web services -> MS IIS Create file in the web folder with the extension.asmx Sample TimeService.asmx : <%@WebService Lanuae= C# Class= TimeService %> usin System.Web.Services; [WebService(Namespace= http://dotnet.csnc.ch/time/ )] public class TimeService : WebService { [WebMethod (Description= Returns the current time )] public strin GetTime() { return System.DateTime.Now.ToLonTimeStrin(); } } Juli 2004 Pae 57
Web Services Sample Client proxy eneration based on the WSDL Use the wsdl.exe tool form the.net SDK to enerate the proxy source wsdl.exe option parameters: /l[anuae]: prorammin lanuae /n[amespace]: namespace of the enerated proxy /o[ut]: name of the enerated source file /u[sername]: username for authentication /p[assword]: password for authentication /d[omain]: domain for authentication TimeService proxy eneration sample: wsdl /n:timeclient /o:timeclientproxy.cs http://dotnet.csnc.ch/time/timeservice.asmx?wsdl Juli 2004 Pae 58
Web Services Security Model Transport Level Security (Point to Point) Authentication and authorisation supported from IIS SSL and/or IPSec used for secure transport Application Level Security (Custom) User credentials for authentication in SOAP header SSL and/or IPSec used for secure transport Messae Level Security (End to End) SOAP Messae is encrypted Use diital sinatures (X.509 Certificates, Kerberos tickets) You can use any transport Juli 2004 Pae 59
Web Services Security Spec. Global Web Service Architecture (GXA) New WS security specifications Based on W3C specs. Driven by IBM, Microsoft and others Specs in standardisation process by W3C, Oasis and IETF Specs in buildin block system: WS-Security: base for all security mechanism WS-Policy: framework to define ws policies WS-Trust: trust enine which enforce the policy Web Service Enhancement 2.0 (WSE) Toolkit Partial implementation of GXA specs. Free download for MS Visual Studio.NET Juli 2004 Pae 60
References General references Book: Die.NET-Technoloie, dpunkt.verla 2002, ISBN 3-89864-1740 http://www.microsoft.com/net/ http://msdn.microsoft.com/netframework/ http://msdn.microsoft.com/security/ http://www.developer.com/net/ http://www.otdotnet.com/ Native Code http://www.developer.com/net/cplus/print.php/2197621.net Security Model http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnnetsec/html/netframesecover.asp http://www.onjava.com/pub/a/onjava/2003/11/26/javavsdotnet.html (.NET vs Java Security) Juli 2004 Pae 61
References Remotin http://www.microsoft.com/ermany/ms/security/uidance/modules/secmod11.mspx ASP.NET http://msdn.microsoft.com/asp.net/ http://msdn.microsoft.com/library/default.asp?url=/library/enus/dndotnet/html/hawkremotin.asp http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnaspp/html/aspnet-aspnet-j2ee-struts.asp (ASP.NET vs STRUTS) http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnaspp/html/pdc_userinput.asp http://www.owasp.or/software/dotnet.html http://www.spidynamics.com/products/app_dev/secureobj/index.html Web Services http://msdn.microsoft.com/webservices/ http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnnetsec/html/secnetch10.asp www.microsoft.com/usa/presentations/gxaandwse.ppt Juli 2004 Pae 62