Presentation is loading. Please wait.

Presentation is loading. Please wait.

.NET Framework Application Security Overview

Similar presentations


Presentation on theme: ".NET Framework Application Security Overview"— Presentation transcript:

1 .NET Framework Application Security Overview
Session Prereqs – Level 300 Development experience with Microsoft Visual Basic®, Microsoft Visual C++®, or C# Experience building Microsoft Windows® or Web applications using the .NET Framework Gunther Beersaerts Microsoft Corporation

2 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will introduce application security by using the Microsoft .NET Framework. Specifically, we will discuss: Security 101 .NET Framework security features. Code access security. Role-based security. Cryptography. Securing Microsoft ASP.NET Web applications. Securing ASP.NET Web services.

3 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will review security technologies. Specifically, we will discuss: Encryption. Hashing. Digital signatures. Digital certificates. Secure communication. Authentication. Authorization. Firewalls. Auditing. Service Packs and Updates.

4 Security 101 Overview of Security Technologies
Developers need to understand, use and apply: Encryption Hashing Digital signatures Digital certificates Secure communication Authentication Authorization Firewalls Auditing Service packs and updates This section of the presentation reviews the different security technologies that are available. A broad understanding of these technologies is important for you as a developer, so that you have the grounding you need to take part in threat modelling, develop secure software, and to perform effective code reviews.

5 Security 101 Encryption Encryption is the process of encoding data
To protect a user’s identity or data from being read To protect data from being altered To verify that data originates from a particular user Encryption can be: Asymmetric Symmetric Encryption protects data from being viewed or modified, and provides secure channels of communication over otherwise insecure channels. For example, data can be encrypted by using a cryptographic algorithm, transmitted in an encrypted state, and later decrypted by the intended party. If a third party intercepts the encrypted data, it is difficult to decipher the data. Encryption is used for: Confidentiality: Protect a user’s identity or data from being read. Data integrity: Protect data from being altered. Authentication: Verify that data originates from a particular party. There are two basic types of encryption: Symmetric. Asymmetric. These types of encryption are described in the following slide.

6 Security 101 Symmetric vs Asymmetric Encryption
Algorithm Type Description Symmetric Uses one key to: Encrypt the data Decrypt the data Is fast and efficient Asymmetric Uses two mathematically related keys: Public key to encrypt the data Private key to decrypt the data Is more secure than symmetric encryption Is slower than symmetric encryption Symmetric encryption performs a transformation on data, preventing third parties from reading the data. This type of encryption uses a single shared, secret key to encrypt and decrypt data. Symmetric encryption is very fast and does not consume a tremendous amount of resources. Common algorithms for symmetric encryption include: Data Encryption Standard (DES) Triple DES. Advanced Encryption Standard (AES). International Data Encryption Algorithm (IDEA). RC2. Asymmetric encryption also performs a transformation on data, preventing third parties from reading the data. With this type of encryption, a key pair is used to encrypt and decrypt data. A key pair consists of two parts: a public key and a private key. These two keys are mathematically related. Although asymmetric encryption consumes more resources than symmetric encryption, it is a far more secure approach. Common algorithms for asymmetric encryption include: Rivest, Shamir, and Adleman (RSA). Diffie-Helman. Digital Signature Algorithm (DSA)

7 Security 101 Verifying Data Integrity with Hashes
User A User B Data Hash Value Hash Algorithm If hash values match, data is valid User A sends data and hash value to User B Hashing differs from encryption. Put simply, encryption is the process of encoding data so that at some point it will be decrypted. Hashed data, on the other hand is not designed to be decrypted. Instead, the hashed values are simply used to verify that that the data is valid. A hash is a unique, fixed-length string of bits. Hashing data involves matching an arbitrarily long string of bits with a fixed-length string of bits. For example, matching a 50-kilobyte file with a 160-bit hash value. Hashes must be one-way operations and collision-resistant. To be a one-way operation, it must be computationally unfeasible to determine the input data from just the hash value. To be collision-resistant, it must be computationally unfeasible to find two sets of input data that result in the same hash value. As shown on the slide, when User A sends the hash value and the original data, User B can verify the validity of the data by applying the same hash algorithm to the data and then comparing the resulting hash value to the hash value that is sent with the data. If the hash values match, User B can be assured that nobody has tampered with the data since it was first sent. Common hash functions include: Message Digest 4 (MD4). Message Digest 5 (MD5) Secure Hash Standard (SHA-1)

8 Security 101 Digital Signatures
User A User B Data Hash Algorithm Data Hash Algorithm User A Public Key Hash Value Hash Value Digital signing ensures that data originates from a specific party by creating a digital signature that is unique to that party. This process also uses hash functions. Put simply, digital signatures combine hashing (for the validation of the signature data) with asymmetric encryption for encoding that signature data. The following occurs when data is signed with a digital signature: A hash algorithm is applied to the data to create a hash value. The hash value is encrypted with User A’s private key, thereby creating the digital signature. The digital signature and the data are sent to User B. The following occurs when digitally signed data is decrypted: User B decrypts the signature by using User A’s public key and then recovers the hash value. If the signature can be decrypted, User B knows that the data came from User A (or the owner of the private key). The hash algorithm is applied to the data to create a second hash value. The two hash values are compared. If the hash values match, User B knows that the data has not been modified. User A Private key Hash Value If hash values match, data came from the owner of the private key and is valid

9 Security 101 How Digital Certificates work?
Private Key User Private/Public Key Pair Computer Public Key Although digital signatures ensures that data originates from a party who have access to a private key, it does not guarantee that party's identity. For example, an attacker might have obtained a private key that belongs to Microsoft. They could then use that key along with a standard hashing algorithm to sign some data, implying that the source of the data is Microsoft. A digital certificate prevents this electronic identity theft by verifying that the signature does indeed belong to the publisher. The data and signature can now be verified as belonging to the authorized publisher because the trusted CA has verified the publisher owns both the public and private key. The following process occurs with digital certificates: A user, computer, service, or application creates the public/private key pair. The public key is transmitted to the certification authority (CA) by using a secure network connection. The certified administrator reviews the certificate request to verify the information. Upon approval, the certified administrator signs the public key with the private key of the CA. Common uses of certificates include: 802.1x wireless communication Digital certificates Encryption File System (EFS) Internet authentication IP Security (IPSec) Secure Smart card logon Software code signing Software restriction policy Service Application Certification Authority Certified Administrator

10 Security 101 Secure Communication Technologies
Technologies include: IPSec SSL TLS RPC encryption SSL/TLS IPSec RPC Encryption Secure communication technologies are proven solutions that use encryption techniques to protect privacy and integrity of data across a network. The following technologies and standards protect data across networks: IPSec (Internet Protocol security). IPSec is a framework of open standards that you can use to ensure secure, private communications over IP networks by using a combination of cryptographic security services that are negotiated between the client and server. IPSec is built by using other encryption standards, including symmetric algorithms such as DES, Triple DES, and RC5, and hashes such as MD5 and SHA-1. IPSec provides a transport-level secure communication solution and can be used to secure the data that is sent between two computers, such as an application server and a database server. SSL (Secure Sockets Layer). The advantage of SSL is that it lends itself to applications that require a trust relationship, because each request or response is validated by the authority of the certificate. When you use SSL, either the server or the client has a digital certificate that they have obtained from a third party. This certificate is passed to your application with requests. TLS (Transport Layer Security). TLS is the only security option available when servers need to prove their identity to anonymous clients. This is important for websites that want to participate in e-commerce, because it allows the secure transmission of sensitive information, such as credit card numbers. TLS requires that all servers prove their identity to clients. Additionally, TLS provides the option of having clients prove their identity to servers. This mutual authentication can be used to restrict who has access to certain Web pages in a large corporate intranet. TLS is the best choice for environments where you want the highest level of security for the data in transit. Remote Procedure Call (RPC) Encryption protocol. Distributed Component Object Model (DCOM) used RPC protocol to provide packet-level privacy authentication, which causes every packet of data sent between client and server to be encrypted. The RPC runtime stubs and libraries manage most of the details relating to network protocols and communication. This enables you to focus on the details related to the application rather than the details related to the network.

11 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will introduce the .NET Framework security features. Specifically, we will discuss: .NET managed execution. A type-safe system. Buffer overrun protection. Arithmetic error trapping. Strong-named assemblies. Isolated storage.

12 .NET Framework Security In General
.NET CLR controls execution of managed code .NET Framework Security is part of the CLR .NET Framework Security includes many features: Managed Execution Type-Safe System Buffer Overrun Protection Arithmetic Error Trapping Strong-Named Assemblies Isolated Storage ... Important: Complements Windows Security The .NET common language runtime controls the execution of .NET code. The .NET Framework security system is part of the common language runtime. The .NET Framework includes many features that you will learn about in this presentation, such as type checking for safe type-conversions, secure exception management, and code access security control. .NET Framework security is designed to complement the security provided by Microsoft Windows®. It does not override Windows-based security. For example, if a Windows access control list (ACL) restricts access to a file, the .NET Framework does not override this security.

13 .NET Framework Security Type Safety System
Type-safe code: Prevents buffer overruns Restricts access to authorized memory locations Allows multiple assemblies to run in same process App Domains provide: Increased performance Increased code security Don't confuse this type safety with data type-verification in most programming languages. In a .NET security context, type safe means preventing programs from accessing memory outside the bounds of an object's public properties. Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot directly read values from another object's private fields or code areas. It accesses types only in well-defined, allowable ways, thereby circumventing certain popular overrun security breaches. During just-in-time compilation, an optional verification process examines the metadata and intermediate language of a method to verify that they are type-safe. If the code has permission to bypass verification, then this process is skipped. Although verification of type-safety is not mandatory for managed code, type-safety is important for assembly isolation and security enforcement. When code is type- safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability. Type-safe components can execute safely in the same process even if they are trusted at different levels. Type-safety verification is the cornerstone of .NET Framework security because it prevents access to unauthorized memory locations. This allows you to consistently enforce security policy. For example, code cannot overrun a buffer and cause execution to jump to an arbitrary memory location. Type-safety verification allows the common language runtime to run more than one type-safe assembly in the same process. These sub-processes are called application domains. Application domains, which are represented by AppDomain objects, help provide isolation, unloading, and security boundaries for executing managed code. Multiple application domains can run in a single process. Application domains are especially useful in server scenarios in which the overhead of using many processes may slow system performance. In the past, the use of dynamic-link library (DLL)-based components was preferred for efficiency reasons, because EXE-based components were seen to be more secure and robust (due to the Microsoft Win32® virtual address space architecture). However, .NET supports the concept of an App Domain. An App Domain can be thought of as a process within a process, which provides good performance (like a DLL-based component), excellent security, and robustness.

14 .NET Framework Security Buffer Overrun Protection
Managed Code does not deal with raw pointers (char *,…) Instead, .NET CLR uses Framework Classes System.String .NET System.String objects are immutable System.Text.StringBuilder System.Text.StringBuilder class checks buffer bounds Throws exception if attempts to overwrite internal buffer Type-verification prevents arbitrary memory overwrites void CopyString (string src) { stringDest = src; } Managed code typically does not deal with raw pointers (such as a char *). Instead, the .NET runtime uses classes such as System.String and System.Text.StringBuilder, which are managed by .NET type-verification checks. A String is an immutable object, which vastly alleviates the buffer overrun issue. Consider the following code: void CopyString (string src) { stringDest = src; } When the code executes, a new resultant string object will be created, and the reference stringDest will be altered to refer to that string. Therefore, a buffer overrun is not possible. Another string class found in the .NET Framework is StringBuilder. StringBuilder is also a robust class and will throw an exception if an attempt is made to overwrite its internal buffer.

15 Buffer Overrun Buffer overruns are primarily a C+/C++ problem because the languages are one notch above the “metal”. Buffer overruns exist in other languages but they thend to be bugs in the run-time engine of libraries, rather then in user code. Visual C++.NET has a new feature, called the /GS switch = buffer security check. /GS inserts special code into certain functions’ prolog and epilog code. (= code located at the start and end of a function call) Prolog code had random cookie data or canarie code and a call to __security_check_cookie at the end of the function = epilog. When the function returns, the cookie is checked. If it is changed, it halts the process. Note: /GS only works for stack-based buffer overruns, it does not detect heap-based buffer overruns.

16 .NET Framework Security Arithmetic Error Trapping
Arithmetic error trapping is achieved by using: The checked keyword Project settings byte b=0; while (true) { Console.WriteLine (b); checked b++; } } Trapping arithmetic errors in unmanaged code (for example, Visual C++) is very difficult. However, with managed code, spotting arithmetic runtime errors is easier. For example, the Visual C# compiler enables automatic checking for arithmetic overflows and underflows. By default, the arithmetic error trapping feature is turned off (for optimization reasons). However, you can easily turn on this feature either from the project properties or by using the checked keyword in your code. If you have turned arithmetic checking on at the project level, you can override the settings by using the unchecked keyword in your code. This is useful if you are certain that arithmetic errors cannot occur in specific blocks of code and you want to optimize those blocks when your code is compiled.

17 Type Safety System Investigating .NET Data-Type Safety
Using the checked keyword In this demonstration, you will see: How .NET data-type safety works. How to use the checked keyword.

18 .NET Framework Security Strong Named Assemblies
Strong names are: Unique identifiers (containing a public key) Used to digitally sign assemblies Why strong-named assemblies? Prevent tampering Confirm the identity of the assembly’s publisher Allow side-by-side components sn –k MyFullKey.snk Strong names are unique identifiers for your assemblies. You can generate strong names and then use them to digitally sign your assemblies. Strong-naming solves problems (such as version control and backward compatibility issues) that are caused when components are shared by multiple applications. In effect, strong names associate a distinct build of a component assembly with the client application. A distinct build is indicated by a combination of a version number and a special value that is called the publicKeyToken. You can generate a public/private key pair for signing your assembly by using the Strong Name tool (Sn.exe). When you have a private key, you can specify the key file and the version number to be assigned when you compile the assembly, using attributes as shown: [assembly: System.Reflection.AssemblyVersion(" ")] [assembly: System.Reflection.AssemblyKeyFile("orgKey.snk")] A strong-named assembly prevents attackers from tampering with the assembly's code, and allows confirmation of the assembly publisher's identity. Strong-named assemblies also allow side-by-side components to co-exist, which aids version control and backward compatibility.

19 .NET Framework Security Isolated Storage
Provides a virtual file system Allows quotas Implements file system isolation based on: Application identity User identity For some applications, such as downloaded Web applications and code that may come from sources that are not trusted, the basic file system does not provide the necessary isolation and safety. Isolated storage is a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data. This provides the capability to store things such as application state and user preference information. Windows Applications traditionally place application data in Windows .INI files and Windows Registry settings but now developers can also use isolated storage. Administrators can use tools that are designed to manipulate isolated storage to configure file storage space, set security policies, and to delete unused data. With isolated storage, developers no longer have to invent unique paths to specify safe locations in the file system. Developers can now access safe locations by using either the application's identity or the user's identity. The code sample on the slide show an example of how to access the isolated storage based on a user's identity. IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForAssembly();

20 .NET Framework Security What did we learn?
Use managed code ! Type-Safe System Buffer Overrun Protection Arithmetic Error Trapping Strong-Named Assemblies Isolated Storage

21 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will introduce code access security. Specifically, we will discuss: Evidence-based security. Security policies. Security checks. Using security checks. Permission requests. Partial trust applications. Sandboxing privileged Code.

22 Code Access Security Evidence-Based Security
Evidence works on top of Win32 security .NET Framework Collects info about an Assembly Presents info to the Security system CLR decides if code is allowed to execute Evidence Assessed when assembly is loaded Determines permissions for assembly Evidence can include assembly’s: Strong name information URL Zone Authenticode signature In contrast to many security systems, the .NET Framework security policy is based on assembly identity, rather than user identity. Win32 security works on the principal of user authentication and authorization. For example, if a user places a floppy disk into the computer, lists the directory, and chooses to execute the file ‘trustme.exe’, the operating system will oblige, and run the application in the security context of the logged on user. Therefore, the application (which may be malicious) will have all of the system privileges granted to the user in question. .NET provides you with the concept of evidence-based security. This security works on top of Win32 security; it does not replace it. Irrespective of the logged on user, the .NET Framework collects evidence about an assembly and presents it to the security system. After the evidence has been gathered, the runtime will decide on whether or not the code will be allowed to complete all of the tasks that it requests. Some evidence is considered stronger by the runtime than other evidence. For example, strong names and Authenticode signatures are considered stronger than URL or zone evidence, because it is more difficult for an attacker to fake values for these elements. Developers can create their own unique evidence. For example, they can create evidence that indicates an assembly was developed internally and reviewed by the IT department for security flaws.

23 Code Access Security Security Policies
Security Entity Description Policy Is set by administrators Is enforced at runtime Simplifies administration Contains permissions Contains code groups Code Group Associates similar components Is evidence based Is linked to permission set(s) Permission Set Is a set of granted permissions In contrast to many security systems, the .NET Framework security policy is based on assembly identity, rather than user identity. Security policies map assembly evidence to permissions that are granted for that assembly. Security policies use code groups and policy levels to achieve this mapping. The .NET Framework includes multiple levels of policy configuration, including enterprise, machine, and user settings. Developers use an intersection of different policy settings when determining permissions. Code groups and policy levels give administrators fine-grained control over security policy. Administrators can configure policies to grant a set of permissions for the assembly based on a variety of evidence. Administrators can use Active Directory to ease the deployment of security policies.

24 Code Access Security Security Check Stack Walk
Call Stack 1. An assembly requests access to a method in your assembly 2. Your assembly passes the request to a .NET Framework assembly 3. The security system ensures that all callers in the stack have the required permissions 4. The security system grants access or throws an exception SomeAssembly Grant: Execute Call to ReadFile YourAssembly Grant: ReadFile When the code accessing a protected resource demands a permission, a stack walk is performed. The security system checks the permission granted to each caller. If each caller is granted the permission, the demand succeeds, otherwise a security exception is thrown. This approach prevents an assembly without permissions, using your assemblies to perform unauthorized actions. Call to ReadFile Permission Demand Security System .NET Framework Assembly Grant access? Security exception Access denied Grant: ReadFile

25 Code Access Security Types of Security Checks
Imperative security checks Create Permission objects Call Permission methods (Demand,…) Declarative security checks Use Permission attributes Apply to methods or classes Overriding security checks Use the Assert method Prevent the stack walk Imperative security checks involve creating instances of Permission objects at run time and invoking methods on them, such as the Demand method. For example, the developer may create an instance of the FileIOPermission object, and demand the Read permission for a specific file. If the call to the Demand method succeeds, execution continues, otherwise, a security exception is thrown. With declarative security checks, permissions are specified by using attributes instead of creating Permission objects at run time. At design time, developers specify permissions (such as the FileIOPermission Read access permission for a specific file) by including the attributes in class definitions or individual methods. Although the same types of permission can be managed as with the imperative approach, the declarative process makes it easier to review the required permissions for a class or method. However, because the permissions apply only to classes or methods, this approach is slightly less flexible than imperative checking. While obtaining evidence for both imperative and declarative security checks, the runtime will walk the stack, assuring that less privileged code further up the stack is not trying to execute code for which it does not normally have permission. However, you can use the Assert method to change the behavior of the stack walk. When the method in which you call Assert is reached, the stack walk stops. This means that permissions for the callers of your code are not checked. The Assert method is most useful when your code needs access to a protected resource, but your code does not give access to that resource to its callers.

26 Code Access Security Permissions Requests
Used by developers to state required permissions Implemented by attributes Prevents an assembly from loading When minimum permissions are not available Rather than wait for unauthorized operation Developers use permission requests to state the permission requirements of their assemblies. Permission requests are implemented as assembly attributes. Using permission requests makes it easier to run code with least privilege. If an assembly does not receive its minimum permission request at load time, it does not load, rather than waiting until an unauthorized operation is attempted and then failing. In the slide example, an assembly requests the Unmanaged code permission. If that permission is denied at load time, the assembly will not continue. //I will only run if I can call unmanaged code [assembly:SecurityPermission (SecurityAction.RequestMinimum, UnmanagedCode=true)]

27 Code Access Security Using the .NET Framework Configuration Tool
Performing Security Checks Requesting Permissions In this demonstration, you will see how to: Use the .NET Framework Configuration Tool to configure permissions. Perform security checks in your code. Requesting permissions for your code.

28 Code Access Security Partial Trust Applications
.NET Framework 1.0 All ASP.NET web applications ran with full trust  No CAS could be applied .NET Framework 1.1 Provides partial trust levels to ASP.NET  Full High Medium Low Minimal Prior to the .NET Framework 1.1, all ASP.NET Web applications ran with full trust, which meant that code access security could not be applied to them. ASP.NET Web Applications under .NET 1.0 run with FullTrust privileges (i.e. They are no way constrained by CAS). The concept of the “trust“ element simply did NOT exist in 1.0.  Only .NET 1.1 will allow you to run ASP.NET Web Applications under a partial trust scenario. The basic concept behind AllowPartiallyTrustedCallersAttribute (APTCA) is that: - An assembly that has a strong name cannot, by default, be called by a partial trust assembly (i.e. an assembly that has not been granted Full Trust privileges). So by default, an ASP.NET Web Application that is running in a partial trust scenario cannot call a strongly named assembly. - The only way a partial trust assembly/ASP.NET Web App running under partial trust can call an assembly with a strong name is if the strong named assembly is marked with the APTCA. The .NET Framework 1.1 allows an administrator to define the trust levels for all Web applications within the machine.config file, thereby gaining control on what code access is available. Five trust levels are available, as follows: Full. Unrestricted permissions enable applications to access any resource that is subject to operating system security, and all privileged operations are supported. High. Cannot call unmanaged code, message queues, serviced components, or OLE DB data sources. Medium. Can only access its own directory structure, and cannot access the registry. Low. Cannot access Microsoft SQL Server™, and no assertion permission. Minimal. Execute permission only. Each of these trust levels can be customized with its own .config file.

29 Code Access Security Sandboxing Privileged Code
Permissions Demanded / Asserted AllowPartiallyTrustedCallers attribute added Assembly installed into the Global Assembly Cache Resource Access Partial Trust Web Application Secured Resource Rather than allowing a whole application maximum privileges, it is possible to sandbox privileged code while retaining partial trust for the Web application as a whole. The .NET sandboxing approach is as follows: Encapsulate the resource access in a wrapper assembly. Demand and then assert the relevant permission prior to accessing the resource. Add the AllowPartiallyTrustedCallersAttribute to the assembly. This is necessary to allow it to be called from a partial-trust Web application. Install the wrapper assembly in the global assembly cache (GAC). This automatically assigns the assembly full trust. Configure the Web application to use an appropriate trust level. Wrapper Assembly <trust level_”Medium” originUri_--/> Sandboxed Code

30 Code Access Security What did we learn?
Use managed code ! Evidence is Assembly based Security Stack Walk Types of Security Checks Imperative, Declarative, Overridable Partially Trusted Applications

31 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will introduce role-based security. Specifically, we will discuss: Authentication and authorization. Identities and principals. Creating Windows identities and principals. Creating generic identities and principals. Performing security checks. Imperative and declarative security checks.

32 Role-Based Security Authentication & Authorization
Authentication asks: "Who are you?" "Am I sure you are who you say you are?“ Authorization asks: "Are you allowed to … ?" Authentication is the process of obtaining identification credentials, such as a name and a password, from a user and then validating those credentials against some authority, such as a database. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. For example, all users must provide a user name and password every time they log on to a network. These credentials are then validated against an authority, such as a database or a Windows-based domain server. After an identity has been authenticated, the authorization process determines whether that identity has access to a specified resource. The authorization process limits access rights by granting or denying specific permissions to an authenticated identity. For example, you can authorize one user to access the color printer, but deny access to another user. Similarly, you can authorize only the users of a group to access the color printer and deny access to the rest of the users. Role-based security in the .NET Framework mostly involves authorization.

33 Role-Based Security Identities and Principals
Identity Contains information about a user Example: Logon name Principal Contains role information about a user or computer .NET Framework provides: WindowsIdentity and WindowsPrincipal objects GenericIdentity and GenericPrincipal objects An identity contains information about the user’s identity, such as their logon name and whether the user is authenticated. A principal contains information about the role membership for a user or computer. The .NET Framework implements two major types of identities and principals. WindowsIdentity and WindowsPrincipal objects provide information about the Windows credentials for a user. GenericIdentity and GenericPrincipal objects enable the developer to implement their own authentication technique. The following slides show how to create Windows and Generic principals and identities, and then demonstrates how to use them to make role-based security checks.

34 Role-Based Security Creating Windows Identities and Principals
Use WindowsIdentity and WindowsPrincipal For Single validation WindowsIdentity myIdent = WindowsIdentity.GetCurrent(); WindowsPrincipal myPrin = new WindowsPrincipal(myIdent); For Repeated validation You can create Windows identities and principals for users based on their Windows credentials. You can use either of the approaches that are shown on the slide to achieve this, but the first code sample is more efficient, if the principal and identity are retrieved for a single check, whereas the second sample is more efficient if multiple checks will be made. After you have created Windows identities and principals, you can use them to perform security checks. The Framework provides a WindowsIdentity class that represents an authenticated Windows user and a WindowsPrincipal class that encapsulates the WindowsIdentity and information about the user's role memberships. These objects representing the current user are accessible in one of two ways: using a static property on the Thread object or a static method on the WindowsIdentity object. Notice that before accessing the current principal, a call to SetPrincipalPolicy is made. This is noteworthy because without it the principal returned would be a GenericPrincipal containing no user information. As the call to SetPrincipalPolicy requires the ControlPrincipal SecurityPermission (one not normally given out to less than fully trusted code) this prevents semi-trusted code (such as that running off the Internet) from gaining access to a user's account name. AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal myPrin = System.Threading.Thread.CurrentPrincipal;

35 Role-Based Security Creating Generic Identities and Principals
Create a GenericIdentity and a GenericPrincipal GenericIdentity myIdent = new GenericIdentity("User1"); string[] roles = {"Manager", "Teller"}; GenericPrincipal myPrin = new GenericPrincipal(myIdent, roles); Attach the GenericPrincipal to the current thread Creating GenericIdentity and GenericPrincipal objects is useful when you want to implement custom authentication techniques, such as finding credentials in a database, rather than perform authentication based on a user's Windows credentials. The slide shows sample code for creating Generic identities and principals. After you have created generic identities and principals, you can use them to perform security checks, as we will discuss next. System.Threading.Thread.CurrentPrincipal = myPrin;

36 Role-Based Security Performing Security Checks
Use Identity and Principal members in code For example, using the Name property of the Identity object to check the user’s logon name if (String.Compare(myPrin.Identity.Name, "DOMAIN\\Gerd", true)==0) { // Perform some action } Now that you have seen how to create identities and principals, you can use them to perform security checks in your code. The slide demonstrates two examples. The first code example performs a case-insensitive string comparison of the current identity’s Name property and a hard-coded string. The second code example uses the IsInRole method to check role membership. In this example, the code checks whether the principal is a member of the built in Administrators group. Example: using IsInRole method of the Principal object to check role membership if (myPrin.IsInRole("BUILTIN\\Administrators")) { // Perform some action }

37 Role-Based Security Imperative and Declarative Security Checks
Use permissions to make role-based security checks Imperative checks PrincipalPermission prinPerm = new PrincipalPermission("Teller", “Manager”, true); try { prinPerm.Demand(); //Does the above match the active principal? } You can also use imperative and declarative approaches for role-based security checks. The first code sample on the slide uses an imperative security check to determine whether the active principal object's permissions match the permissions of the newly created prinPerm object. The call to the Demand method will throw a security exception if the permissions do not match. This approach is useful if you want to secure specific actions within your code. The second sample on the slide uses declarative security. The attribute shown can be applied to a class or an individual method, so that a security check is performed when the class or method is used. Although the same types of check can be performed as with the imperative approach, the declarative process makes it easier to review the required permissions for a class or method. However, because the checks apply only to classes or methods, this approach is slightly less flexible than imperative checking. Declarative checks [PrincipalPermission(SecurityAction.Demand, Role="Teller", Authenticated=true)]

38 Role-Based Security Using Windows Role-Based Security
Using Generic Role-Based Security In this demonstration, you will see how to: Use Windows role-based security in your code. Use Generic role-based security in your code.

39 Role-Based Security What did we learn?
Use managed code ! Authentication vs Authorization Identities vs Principals WindowsIdentity vs GenericIdentity WindowsPrincipal vs GenericPrincipal

40 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will introduce cryptography. Specifically, we will discuss: Cryptography review. Symmetric encryption. Asymmetric encryption. Signing data.

41 The .NET Framework provides classes that implement these operations
Cryptography Review Cryptography Term Description Symmetric Encryption Encrypting and decrypting data with a secret key Asymmetric Encryption Encrypting and decrypting data with a public/private key pair Hashing Mapping a long string of data to a short, fixed-size string of data Digital Signing Hashing data and encrypting the hash value with a private key Symmetric encryption enables you to encrypt and decrypt data by using a single secret key. If the secret key is compromised, all of the data that you used the key to encrypt can be decrypted. Asymmetric encryption enables you to encrypt and decrypt data with a public/private key pair. You can distribute the public key freely, but the private key must be kept secret. Data encrypted with the public key can be decrypted only with the private key and vice versa. Hashing is the process of mapping a longer string of data, such as a file, to a small string of data that is a fixed size, such as a 160-bit hash value. Digital signing is the process of encrypting a hash value with a private key and distributing this signature with the data. When a recipient receives the data, the recipient can decrypt the data with the sender’s public key and compare it with the hash value of the data. If the values match, the integrity of the data is guaranteed. The .NET Framework provides classes that implement these operations

42 Cryptography Using Symmetric Algorithms
Choose an algorithm TripleDESCryptoServiceProvider RijndaelManaged Generate a secret key Use secret key to encrypt and decrypt data: FileStream MemoryStream NetworkStream The basic steps for using symmetric encryption algorithms are: Choose the algorithm you want to use. The .NET Framework provides wrapper classes for working with symmetric encryption, such as the TripleDESCryptoServiceProvider the RijndaelManaged classes. Generate a secret key by using the .NET wrapper class that you have chosen. Symmetric algorithms require this key to encrypt and decrypt data. The class constructor can create these values or you can provide your own. Use the same key to encrypt and decrypt data. You can encrypt data by using any class that derives from the Stream class, including FileStream, MemoryStream, and NetworkStream.

43 Cryptography Using Asymmetric Algorithms
Choose an algorithm RSACryptoServiceProvider DSACryptoServiceProvider Generate a private and public key pair Encrypt or decrypt data The basic steps for using asymmetric encryption algorithms are: Choose the algorithm that you want to use. The .NET Framework provides wrapper classes for working with asymmetric encryption, such as the RSACryptoServiceProvider and the DSACryptoServiceProvider classes. These classes use the well-known algorithms after which they are named Generate public and private keys by using the .NET wrapper class that you have chosen. Asymmetric algorithms use a public key and a private key to perform cryptographic operations. Some operations, such as signature creation and decryption, require a private key. Other operations, such as signature verification and encryption, require a public key. Use the appropriate key when encrypting or decrypting data. For example, if you are encrypting data, you would use the public key, whereas if you are decrypting data you would use the private key. You can encrypt and decrypt data by using any class that derives from the Stream class, including FileStream, MemoryStream, and NetworkStream.

44 Cryptography Signing Data and Verifying Signatures
Action Steps Signing Data Hash the data Encrypt the hash value with a private key Verifying Signatures Decrypt the signature by using sender’s public key Compare the decrypted signature to the hash value Signing data prevents tampering and asserts the identity of the signer. In some situations, you will want to sign data so that other's can be assured of your identity, whereas at other times, you will want to verify a signature so that you are sure that the data originated from a specific source. Signing data and verifying signatures involves: Signing Data. Hash the data, and then use an asymmetric algorithm to create a signature. Verifying the signature. Decrypt the signature, hash the data, and then use an asymmetric algorithm to verify the signature.

45 .NET Framework Encryption
Performing Symmetric Encryption Signing Data In this demonstration, you will see how to: Perform symmetric encryption on data. Sign data programmatically

46 Cryptography What did we learn?
Use managed code ! Symmetric Encryption Assymmetric Encryption Data Signing & Verification

47 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will focus on securing ASP.NET Web applications. Specifically, we will discuss: ASP.NET authentication types. Configuring forms-based authentication. Forms-based authentication enhancements. Validation controls. Types of validation controls.

48 Securing ASP.NET ASP.NET Authentication Types
Advantages Disadvantages Windows Uses existing Windows infrastructure Controls access to sensitive information Does not support all client types Forms Supports all client types Relies on cookies Microsoft Passport Supports single sign-on for many Internet Web sites Allows developers to customize the appearance of the registration page Involves fees ASP.NET supports three types of authentication method: Windows-based authentication Forms-based authentication Microsoft Passport authentication With Windows-based authentication, the ASP.NET Web application relies on the Windows operating system to authenticate the user. ASP.NET uses Windows-based authentication in conjunction with Internet Information Services (IIS) authentication. With Windows-based authentication, the user requests a secure Web page from the Web application, and the request then passes through IIS. If the user's credentials do not match those of an authorized user, IIS rejects the request. The user then has to enter his or her name and password in the logon form. The credentials are again verified by IIS. If these credentials are accepted, IIS directs the original request back to the Web application. The secure Web page is then returned to the user. Forms-based authentication involves non-authenticated requests being redirected to a Hypertext Markup Language (HTML) form. The user provides their credentials and submits the form. If the application validates the credentials on the form, the system issues an authentication cookie to the user. Subsequent requests from the user are issued with the authentication cookie in the request headers, and then the user is authenticated on that basis. You will see how to set up forms-based authentication in the next slide. You will then see the .NET enhancements that are associated with forms-based authentication. Passport authentication is a centralized authentication service, provided by Microsoft, which offers a single logon option and core profile services for member sites. Users who sign up to use Passport are authenticated by Web sites with a single Passport account. Microsoft Passport is an XML Web service, and is an integral part of the .NET Framework.

49 Securing ASP.NET Configuring Form-Based Authentication
Configure IIS to use Anonymous authentication Set forms-based authentication in Web.config Set up authorization in Web.config Build a logon form <system.web> <authentication mode="Forms"> <forms loginUrl="WebForm1.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization> </system.web> Configuring forms authentication for your .NET Web application involves the following four tasks: Configure IIS to use Anonymous authentication so that the user is authenticated by ASP.NET and not by IIS. Set the authentication method to 'Forms' for the application in an <authentication> subsection of the <system.web> section in Web.config, If you set the authentication mode to 'Forms', you must add a <forms> element to the <authentication> section, as shown in the slide example. In the <forms> section, configure the settings of the cookie. Set the name attribute to the suffix to be used for the cookies and the loginUrl attribute to the Uniform Resource Locator (URL) of the page to which unauthenticated requests are redirected. Set up the <authorization> section in Web.config to deny or allow users access to your Web application. You can also mark the entire Web application as needing authorization or specify authorization on a page-by-page basis. Build a logon Web Form. This can be a simple page with two fields for a user name and a password. The page requires the users to enter their user name and password to access to your Web application. Although you can perform these tasks in any order, ensure they are all completed before deploying your solution, otherwise forms-based authentication will not work.

50 Securing ASP.NET Form-Based Authentication Enhancements
Developers can require secure cookies <authentication mode="Forms"> <forms loginUrl="login.aspx" protection="All" requireSSL="true" timeout="10" name="AppNameCookie" path="/FormsAuth" slidingExpiration="true" </forms> </authentication> By default, there is no requirement for the authentication cookie submitted by the client with each request to be encrypted. Encryption is normally performed by implementing SSL across the site; however, this is controlled by the site administrators, rather than developers. Developers can ensure that the cookie is encrypted by adding the attribute requireSSL=”true” to the <forms> element in the web.config file. This will set the HttpCookie.Secure property, such that compliant browsers will only return the cookie over SSL. One consideration with secure cookies is the use of validation and decryption keys. These can be automatically generated for the application. However, it is possible for the same key to be generated for several Web applications on the same computer. To avoid this, developers can use the IsolateApps parameter within the machineKey element in the web.config file. Developer can create application-specific keys

51 Securing ASP.NET Validation Controls
Error Message Client Server User Enters Data Valid? Web Application Processed Yes No Client-side validation Provides instant feedback Reduces postback cycles Server-side validation Repeats all client-side validation Validates against stored data, if required Input validation can take place on both the server and the client. Client-side validation is an option with some browsers. The validation controls in ASP.NET have both client-side and server-side support. Client-side validation uses JavaScript and dynamic HTML (DHTML) scripts. Server-side validation can be written in any .NET-based language. Client-side validation enhances the usability of the Web Form by checking user input as the user enters data. By checking for errors when data is being entered, client-side validation allows errors to be detected on the client before the Web Form is submitted. Writing multiple versions of validation code to support both the server and several different browsers can be extremely time-consuming for developers. ASP.NET validation controls eliminate this problem because the validation logic is encapsulated within the controls. The controls create browser-specific code so that users with client-side script support will have client-side input validation. Browsers that do not support scripts will not receive client-side validation scripts. In browser versions that support input validation, such as Microsoft Internet Explorer 4 or later, client-side validation occurs when the user clicks the Submit button. The page will not be posted back to the server until all client-side validation is true. In Internet Explorer 5 or later, using the TAB key to move from one input control to the next runs the client-side validation for the completed input control. All input validation controls also run on the server side. Client-side validations are repeated on the server side when the page is posted back to the server. This repetition avoids attackers bypassing the client-side script and trying to use provide input.

52 Securing ASP.NET Types of Validation Controls
The ASP.NET page framework includes a number of validation controls: The CompareValidator control compares an input control to another input control, a fixed value, a data type, or a file. The CustomValidator control allows you to write your own code to create the validation expression. For example, this control can be used to verify that the input value is a prime number. The RangeValidator control is similar to the CompareValidator control, but this control can verify that the user input is between two values or the values of other input controls. The RegularExpression control verifies that the entry matches a pattern that has been defined by a regular expression. For example, social security numbers, addresses, telephone numbers, and postal codes. The RequiredFieldValidator control checks whether a value has been entered into a control. This is the only validation control that requires a value. The ValidationSummary control displays a summary of all of the validation errors for all of the validation controls on the page. This control is typically placed near the Submit button to provide immediate feedback on the page input status.

53 Securing ASP.NET Configuring Forms Authentication
Using Validation Controls In this demonstration, you will see how to: Configure forms authentication Use validation controls

54 Securing ASP.NET What did we learn?
Use managed code ! Types of Authentication Windows Authentication Forms-Based Authentication PassPort Authentication Forms-Based Auth Enhancements Validation Controls

55 Agenda Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services In this agenda topic, we will focus on securing ASP.NET Web services. Specifically, we will discuss: Message-level security. Web Service Enhancements.

56 Securing ASP.NET Web Services Message-Level Security
XML messages convey security information Credentials Digital signatures Messages can be encrypted Client Transport Service Any Transport XML Security is independent from transport protocol Message-level security applies to the contents of a Simple Object Access Protocol (SOAP) message. This is extremely useful for XML Web Services, because developers and administrators cannot usually secure both end-points in this type of communication, so the actual message itself needs securing. The World Wide Web Consortium (W3C) have defined a set of specifications called WS-Security, which describe enhancements to SOAP messaging. These specifications define message integrity, message confidentiality, and single message authentication for SOAP messaging. With message-level security, authentication is provided by security tokens, which flow in SOAP headers. The security tokens may include Kerberos tickets, X.509 certificates, or a custom binary token. Secure communication is provided by digital signatures to ensure message integrity and by XML encryption for message confidentiality. WS-Security can be used to construct a framework for exchanging secure messages in a heterogeneous Web services environment. It is ideally suited to heterogeneous environments and scenarios where you are not in direct control of the configuration of both endpoints and intermediate application nodes. Message-level security: Can be independent from the underlying transport. Enables a heterogeneous security architecture. Provides end-to-end security and accommodates message routing through intermediate application nodes. Supports multiple encryption technologies. Supports non-repudiation.

57 Securing ASP.NET Web Services Web Service Enhancements (WSE)
WSE includes: Authentication with SOAP Headers Message encryption Message signing Supports message routing Supports attachments Implemented in Microsoft.Web.Services.dll Assembly Web Services Enhancements for Microsoft .NET (WSE) is a set of tools that can be used to implement security within a SOAP message, rather than relying on security features of other protocols (such as SSL). Microsoft developed WSE to conform with the WS-Security standards. The main security-oriented features of WSE are: Authentication through SOAP headers. This is based either on Username tokens, which are defined in the WS-Security standard, or binary tokens, such as an X.509 Certificate token. On the server-side, you can implement your own mechanism for storing user names and passwords. Message encryption. This is implemented through input and output filters, which allows developers to use both the SOAPWebRequest and SOAPWebResponse, thereby applying whichever encryption mechanism they require to the messages. Message signing. This is a signature element generated from an X509 security token. The signature is added to the security header within the SOAP header. It is possible to control which parts of the header, body, and message the signature applies to. This is useful if the message is routed, because the routing process may modify parts of the header which would otherwise invalidate the signature. Attachments can also be secured with WSE. As a developer, you can access the WSE functionality by using classes exposed in Microsoft.Web.Services.dll.

58 Securing Web Services Analyzing SOAP headers
In this demonstration, you will see how to: Implement security for a Web service.

59 Securing Web Services What did we learn?
Use managed code ! Message-Level Security Transport Independant End-to-End Secure Check out Web Service Enhancements WSE 2.0

60 Session Summary Security 101 .NET Framework Security Features
Code Access Security Role-Based Security Cryptography Securing ASP.NET Web Applications Securing ASP.NET Web Services

61 Resources MSDN Security Developer Center Security Guidance
Sign up for security bulletins: Security Guidance Security Training & Books Writing Secure Code (Howard/Leblanc) ISBN CTEC Security Trainings Feedback, Questions & Tomatoes Next steps include going to the Microsoft Web site to: Get the latest security information. Get additional security training.

62 Thank You !

63 Secure Communication How IPSec Works
Security Association Negotiation TCP Layer IPSec Driver Encrypted IP Packets IPSec Policy The primary goal of IPSec is to protect IP packets. IPSec is based on an end-to-end security model, which means that the sender and the recipient are the only hosts that must know about the IPSec protection. Each computer handles its own security, under the assumption that the medium over which the communication takes place is not secure. IPSec uses symmetric algorithms to encrypt data and transmits symmetric keys by using asymmetric algorithms. When a computer configured with an IPSec policy attempts to communicate with another computer, the following occurs: The two computers agree on a set of algorithms and hashes. The computers then exchange public keys and use them to exchange symmetric key algorithms that are used to encrypt packets at the network layer.

64 Secure Communication How SSL Works
2 Web Server Root Certificate Message Secure Browser Secure Web Server 3 4 HTTPS 1 1 The user browses to a secure Web server by using HTTPS The browser creates a unique session key and encrypts it by using the Web server’s public key, which is generated from the root certificate The Web server receives the session key and decrypts it by using the server’s private key After the connection is established, all communication between the browser and Web server is secure SSL encryption relies on the server’s public key and private key. The private key exists only on the Web server and it is used by the Web server to encrypt and decrypt secure messages. The public key exists on any client computer that has installed a certificate for that Web server. After the public key is installed, the user can send encrypted messages to, and decrypt messages received from, the Web server. When SSL is used, the following occurs: The user browses to the secure Web server’s site. The browser creates a unique session key and encrypts it by using the Web server’s public key, which is generated from the root certificate. Each session key that the Web server’s certificate generates is unique. Therefore, even if an attacker has the same certificate installed on their browser, the attacker cannot decrypt the message. The browser where the encrypted message originated cannot decrypt the message. Only the Web server with the appropriate private key can decrypt the message. The Web server receives the message and decrypts it by using its private key. This phase of SSL communication is often called the SSL handshake. An attacker may intercept a message protected with SSL. However, the attacker cannot decrypt the message, because the attacker does not have the Web server’s private key. After the connection is established, all communication between the browser and the Web server is secure. When the session ends, the session key is destroyed. 2 3 4


Download ppt ".NET Framework Application Security Overview"

Similar presentations


Ads by Google