Скачать презентацию NET Security By R S Security Скачать презентацию NET Security By R S Security

9377ff1f377c6c7eb0f89521319d336c.ppt

  • Количество слайдов: 67

. NET Security By R. S . NET Security By R. S

Security What is Security ? Security in general means freedom from risk and Danger. Security What is Security ? Security in general means freedom from risk and Danger. So What does Security in Software field means? Software security is the effort to create a secure computing platform, designed so that agents (users or programs) can only perform actions that have been allowed. Simply put, protecting hardware and software from being misused or corrupted. As a software engineer/programmer what should I know about software security ? Risks

Risks ? When Software Security is breached, what risks do I have and what Risks ? When Software Security is breached, what risks do I have and what is the importance of identifying these risks? Risks may vary depending on q Whether I am user working on my personal computer/laptop or I am a company employee working on my company computer. q What permissions do I have on the machine that I am working on (Admin, power user, normal user, domain user etc) § In case 1, I am risking my home computer’s integrity , my personal information, etc § Case 2, as a company Employee , I am risking everything , including my Job …… Importance : Prevent loss and misery of any kind.

Software Security Breach and Nightmares in an organization • Irrespective of what an organization’s Software Security Breach and Nightmares in an organization • Irrespective of what an organization’s business is, security breach could potentially cause a lot of loss to the organization starting from customers to $$$. • Think about somebody hacking into an online bank where you have saved all your money and getting hold of your account. • Now the bank has to go through a lot trying to comfort its other customers who wants to end their business with them , bare the $$ loss , fire people that didn’t do their job right in providing security , fix loop holes in the system to make it more secured etc ….

What to Do ? § Alright, Software security breach doesn’t sounds good. So we What to Do ? § Alright, Software security breach doesn’t sounds good. So we decided to enforce security. § The Question is WHERE and HOW ? § Security is not a single entity , rather is a connection of several entities , like a Chain. § Remember , The strength of a Chain depends on its weakest link…. § Simple Example : A house with multiple doors. § Securing all the doors and windows is not sufficient.

How much should I secure? • Securing every inch of your house of course How much should I secure? • Securing every inch of your house of course provides closer to 100% security. • It also increases the cost of living, maintenance , stress etc. Answer is : Think if its really worth providing so much of security. Don’t have to spend $50 a month to protect your 3 month old tooth brush.

Where to Start ? • Most likely from the weakest link…… • Securing an Where to Start ? • Most likely from the weakest link…… • Securing an organization involves securing its networks, different applications that it uses/creates , securing the servers , databases , securing the development machines etc including securing the premise of the organization itself. • Identify and make a list of areas that easily opens the door for a malicious user. • Prioritize the list • Delegate the tasks to the individual groups responsible • Team Work ?

Where do we come into play ? • Where does the software programmers role Where do we come into play ? • Where does the software programmers role begins ? • What do we have to offer to our organization? • What are our tools ?

Contd. • • Our role as software engineers begins from understanding the organizations operations. Contd. • • Our role as software engineers begins from understanding the organizations operations. Once we know that , we have a solid ground to stand on to make suggestions on what the company needs to do to ensure security. The suggestions could be modifying an existing application’s modules to increase security or redesigning the entire application to cope up with the current security trends. Don’t be afraid to express yourself, you are only trying to help the company. Always have proofs to support your claims. In other words , Don’t try to redesign the application to ensure your job security instead of the company security. Be a Good team player. Understand your team mates and their approaches. This has a lot to do with being more efficient programmers and building trust among the team members. If you don’t trust your team , how can you expect the company to trust you and how can you expect the end users to trust the application created by your team ? ?

Teams Role • A software team should identify existing problems and loop holes within Teams Role • A software team should identify existing problems and loop holes within an existing system. • Recommend solutions for those problems. • Should undertake software projects approved by the organization • Should have a solid strategy for developing and implementing the project. • Must have knowledge of the developing trends of the platform they use. • Must have knowledge of the current security threats. • Must have the knowledge about available tools , no matter , whether the tool is a software/Graphics design tool to aid them in implementing their project or a security tool that will help them to secure their project. • The team must have a solid understanding of the environment where the application will be deployed. Last but not least , a software team must know what they are trying to accomplish through their project.

Preparing Yourself • Learn about different kinds of threats , old or new. • Preparing Yourself • Learn about different kinds of threats , old or new. • Find out how those threats are put to sleep. • Learn about the software updates, what’s new in it , how it solves an existing problem/vulnerability. • Understand your platform , its pros and cons , its vulnerability in particular if any. Example : Do you know of any disadvantages of programming in C++ or C#? ? C++ - Pointers C# - Ability to regenerate the entire source code from the exe file using reflection.

. NET and Security • There are many technologies used to build. NET applications. . NET and Security • There are many technologies used to build. NET applications. To build effective application-level authentication and authorization strategies, you need to understand how to fine-tune the various security features within each product and technology area, and how to make them work together to provide an effective, defense-indepth security strategy. • Know the available. NET tools first then learn what those tools can do for you.

Contd. . • What are the typical deployment patterns adopted by. NET Web applications? Contd. . • What are the typical deployment patterns adopted by. NET Web applications? • What security features are provided by the various technologies that I use to build . NET Web applications? • What gatekeepers should I be aware of and how do I use them to provide a defense-in-depth security strategy?

The Design Phase • Though the requirement phase comes first, the actual role of The Design Phase • Though the requirement phase comes first, the actual role of the software programmers begins (except in special conditions) from the design phase. • With the requirements at hand , the design phase can begin. • This is when you can design your project flow, identify different objects required , their importance, functionalities , properties etc • This is also where you can identify different areas where your projects needs to be secured, possible loop holes etc… • But this is just the beginning …….

Contd. . • Once after identifying required objects and areas that needs to be Contd. . • Once after identifying required objects and areas that needs to be secured , you are ready to prepare a game plan that would help you secure your project. • What is the game plan ? • Do some research and find out if there any current security threats that your application may fall a victim for. • Find out if there any available solutions, updates for your hosting platform that would help you take care of the threat from the operating system level. • Make sure to have all the latest updates on your development machines. • Next , Analyze the Security tools that. NET offers.

Contd. . • After analyzing the available tools carefully and in depth, pick the Contd. . • After analyzing the available tools carefully and in depth, pick the ones that you think will help you improve the security of your application. • Since you already know where to secure your application, this shouldn’t be a tough task. • Please keep in mind that you don’t want to do too much of anything. Just what is required to ensure security.

3 Most Important areas to Secure • As a software engineers , we should 3 Most Important areas to Secure • As a software engineers , we should worry about the following three areas. • The Code which includes your code/class design , design documents , source control etc • The Databases used by the code (application) • The communication layer in a distributed application environment (Why ? ? )

Creating Secured Code § Assume the architectural design is completed and presented to the Creating Secured Code § Assume the architectural design is completed and presented to the programmers. This means you already know where to secure and what to secure. § Concentrate on creating secured code based on the design using the tools provided by. NET.

Restrict Class and Member visibility • Restrict access to the members and methods of Restrict Class and Member visibility • Restrict access to the members and methods of a class( or object). • Private, protected , internal etc • Sealed classes are safer • Seal virtual methods in derived classes which also improves performance through in lining.

Sealed class Example • A Sealed Class. . public sealed class File. Modifier. Class Sealed class Example • A Sealed Class. . public sealed class File. Modifier. Class { public File. Modifier. Class() { } } This class cannot be inherited…

Sealed Method example • Only methods in derived classes can be sealed. public class Sealed Method example • Only methods in derived classes can be sealed. public class Parent. File. Modifier. Class { public File. Modifier. Class() { } public virtual void Modify() { } } public sealed class File. Modifier. Class { public File. Modifier. Class() { } sealed override public void Modify() { } } Classes inheriting File. Modifier. Class will not be able to override the Modify method.

Use properties to expose fields • Using properties facilitates validating a value to be Use properties to expose fields • Using properties facilitates validating a value to be set to a field. • Permission can also be demanded for these fields. • Use Read/Write and read-Only properties to access fields. • Private fields are enforced during compile time. Code running in fully trusted environment can bypass this property using reflection and unmanaged pointers.

Do Not Trust user inputs • • Do not trust user input. Never!!!!! Validate Do Not Trust user inputs • • Do not trust user input. Never!!!!! Validate for type , length format and range Use Regular Expressions to validate user inputs Avoid un trusted input for file names and file paths. • If you accept file names, validate them. • Use absolute file paths where you can. • Consider constraining file I/O within your application's context.

Contd…. • Use Getfull. Path on a windows application. • Get. Full. Path performs Contd…. • Use Getfull. Path on a windows application. • Get. Full. Path performs the following checks: • It checks that the file name does not contain any invalid characters, as defined by Path. Invalid. Path. Chars. • It checks that the file name represents a file and not another device type, such as a physical drive, a named pipe, a mail slot, or a DOS device such as LPT 1, COM 1, AUX, and other devices. • It checks that the combined path and file name is not too long. • It removes redundant characters such as trailing dots. • It rejects file names that use the //? / format. • Use Request. Map. Path on a server. • Note : The Map. Path property potentially contains sensitive information about the hosting environment. The return value should not be displayed to users.

Contd. . • Validate Input from All Sources Like Query. String, Cookies, and HTML Contd. . • Validate Input from All Sources Like Query. String, Cookies, and HTML Controls • These validation can help prevent injection attacks. • Prefer server side validation to client side validation. If required, combine the client side validation with the server side validation. • Prevent using user input for file names and path inputs.

Injection Attacks • Injection attacks are attacks initiated by a user using malicious input Injection Attacks • Injection attacks are attacks initiated by a user using malicious input which was not validated by the application in context. • These attacks can vary from injecting such malicious inputs into applications to change their behavior or into a database to corrupt or read sensitive data.

Most common Injection Attacks • SQL injection. If you generate dynamic SQL queries based Most common Injection Attacks • SQL injection. If you generate dynamic SQL queries based on user input, an attacker could inject malicious SQL commands that can be executed by the database. • Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. This code is subsequently sent to an unsuspecting user's computer and executed on the browser. Because the browser downloads the script code from a trusted site, the browser has no way of determining whether the code is legitimate. • Unauthorized file access. If your code accepts input from a caller, a malicious user could potentially manipulate your code's file operations, such as accessing a file they should not access or exploiting your code by injecting bad data.

Preventing Injection Attacks in ASP. NET • Simple Rule : Accept good input, reject Preventing Injection Attacks in ASP. NET • Simple Rule : Accept good input, reject bad input • If your application accepts user inputs, assume that , every input is invalid and malicious and validate them n the server side. • Define valid input for every field. This means that, define the range, format length and type of the input. • Verify the input against the list of acceptable characters • HTML encode the html outputs before displaying

Contd. . • Follow these steps to validate user input. • Constrain: Check for Contd. . • Follow these steps to validate user input. • Constrain: Check for type, length , range and format. Use Asp. NET Validator on server controls. For other resources, use regular expressions. • Reject: Reject any data that failed validation • Sanitize: Change potentially malicious input to good input. Example : Allow few HTML tags ( , , etc) and eliminate other HTML tags. • How and where to enable request validation ? • In Machine. Config and Web. Config as follows • • Confirm that you have not disabled request validation by overriding the default settings in your server's Machine. config file or your application's Web. config file.

ASP. NET Validators • Text Fields : Regular. Expression. Validator <form id= ASP. NET Validators • Text Fields : Regular. Expression. Validator

Regex Class : // Instance method: Regex reg = new Regex(@"^[a-z. A-Z'. s]{1, 40}$"); Response. Write(reg. Is. Match(txt. Name. Text)); // Static method: if (!Regex. Is. Match(txt. Name. Text, @"^[a-z. A-Z'. s]{1, 40}$")) { // Name does not match expression }

Contd. . • Numeric Fields : Range Validator <asp: Range. Validator ID= Contd. . • Numeric Fields : Range Validator Test in your Code for range as follows (only in Framework 2. 0) Int 32 i; if (Int 32. Try. Parse(txt. Input. Text, out i) == false) { // Conversion failed } (Older versions of Framework , use Int 32. Try. Parse or Convert. To. Int 32 inside a try catch bolck. Catch any formatexception inside the catch block and throw an exception to the user. )


Html Encode void submit. Btn_Click(object sender, Event. Args e) { // Encode the string Html Encode void submit. Btn_Click(object sender, Event. Args e) { // Encode the string input String. Builder sb = new String. Builder( Http. Utility. Html. Encode(html. Input. Txt. Text)); // Selectively allow and sb. Replace("< b> ", ""); sb. Replace("< /b> ", ""); sb. Replace("< i> ", ""); sb. Replace("< /i> ", ""); Response. Write(sb. To. String()); }

Query String Validation void Page_Load(object sender, Event. Args e) { if (!System. Text. Regular. Query String Validation void Page_Load(object sender, Event. Args e) { if (!System. Text. Regular. Expressions. Regex. Is. Match( Request. Query. String["Name"], @"^[a-z. A-Z'. s]{1, 40}$")) Response. Write("Invalid name parameter"); else Response. Write("Name is " + Request. Query. String["Name"]); }

Request. Map. Path • Use the Overloaded Request. Map. Path method to read file Request. Map. Path • Use the Overloaded Request. Map. Path method to read file paths. Try { string mapped. Path = Request. Map. Path( input. Path. Text, Request. Application. Path, false); } catch (Http. Exception ex) { // Cross-application mapping attempted } The false parameter will prevent the user from using file paths that contains “. . ” to traverse outside your app directory. For server controls, use the Control. Map. Path. Secure method to retrieve the physical path. Control. Map. Path. Secure uses code access security and throws an Http. Exception if the server control does not have permissions to read the resulting mapped file. NOTE : An Applications trust level can be set to medium by an administrator if he/she wants to restrict its File I/O to its own virtual directory. (Web. Config or machine. Config)

Validating Urls • Use Regular expressions. . ^(? : http|https|ftp): //[a-z. A-Z 0 -9. Validating Urls • Use Regular expressions. . ^(? : http|https|ftp): //[a-z. A-Z 0 -9. -]+(? : : d{1, 5})? (? : [A-Za-z 0 -9. ; : @&=+$, ? /]|%u[0 -9 AFa-f]{4}|%[0 -9 A-Fa-f]{2})*$ Use Http. Utility. Html. Encode and Http. Utility. Url. Encode( url. String ) to putput html output and URL output respectively; Note : Get yourself familiar with Regular expressions if you are planning to specialize in security oriented programming.

SQL Injection • • SQL Injection • • "SQL Injection" is subset of the unverified/unsanitized user input vulnerability ("buffer overflows" are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it's straightforward to create some real surprises. Is it that bad ? ? ? Of course. If you loose the integrity of your database, you loose everything. If the database gets corrupted, I can guarantee that 100% of the users will be affected. This statement is not true when it comes to a corrupted client side script.

SQL Injection Example • SQL injection is caused mainly by inputs that are not SQL Injection Example • SQL injection is caused mainly by inputs that are not sanitized. Consider the following Query, “Select * from Users where Username =‘”+username. Text+”’ and Password=‘”+password. Text+”’”; What is wrong with this query and how can I inject code into this SQL statement ? Nothing wrong , untill I enter the following values for Username. Text and Password. Text, Username. Text= something’ or ‘ 1’=‘ 1’; -Password. Text=password “Select * from Users where Username =‘”+username. Text+”’ and Password=‘”+password. Text+”’” The code generated on the fly will now look like Select * from Users where Username=‘something’ or ‘ 1’=‘ 1’; -- and Password=‘password’; This condition in the statement will always result in true returning all the rows from the users table. If the inputs in the Username and password field are validated and sanitized this injection could have been prevented.

Contd… • We can also inject a complete SQL statement in the fields to Contd… • We can also inject a complete SQL statement in the fields to drop tables, insert records into the tables etc. • You can guess the table names, fields, passwords etc or any other valuable information. • Using Stored procedures necessarily don’t provide protection against SQL Injection.

Data Access Tips • • Do not hard code connection strings. Consider encrypting connection Data Access Tips • • Do not hard code connection strings. Consider encrypting connection strings. Do not generate dynamic SQL queries To help prevent SQL injection, you should validate input and use parameterized stored procedures for data access. The use of parameters (for example, Sql. Parameter. Collection) ensures that input values are checked for type and length and values outside the range throw an exception. Parameters are also treated as safe literal values and not as executable code within the database. Avoid stored procedures that accept a single parameter as an executable query. Instead, pass query parameters only. Use structured exception handling to catch errors that occur during database access, and prevent them from being returned to the client. A detailed error message may reveal valuable information such as the connection string, SQL server name, or table and database naming conventions. Attackers can use this information to construct more precise attacks. As an additional precaution, use a least privileged account to access the database, so that even if your application is compromised, the impact will be reduced.

SQLParameter. Collection sample using System. Data; using System. Data. Sql. Client; using (Sql. Connection SQLParameter. Collection sample using System. Data; using System. Data. Sql. Client; using (Sql. Connection connection = new Sql. Connection(connection. String)) { Data. Set user. Dataset = new Data. Set(); Sql. Data. Adapter my. Adapter = new Sql. Data. Adapter( "Login. Stored. Procedure", connection); my. Adapter. Select. Command. Type = Command. Type. Stored. Procedure; my. Adapter. Select. Command. Parameters. Add("@au_id", Sql. Db. Type. Var. Char, 11); my. Adapter. Select. Command. Parameters["@au_id"]. Value = SSN. Text; my. Adapter. Fill(user. Dataset); }

SQl. Parameters with Dynamic SQL using System. Data; using System. Data. Sql. Client; using SQl. Parameters with Dynamic SQL using System. Data; using System. Data. Sql. Client; using (Sql. Connection connection = new Sql. Connection(connection. String)) { Data. Set user. Dataset = new Data. Set(); Sql. Data. Adapter my. Data. Adapter = new Sql. Data. Adapter( "SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", connection); my. Data. Adapter. Select. Command. Parameters. Add("@au_id", Sql. Db. Type. Var. Char, 11); my. Data. Adapter. Select. Command. Parameters["@au_id"]. Value = SSN. Text; my. Data. Adapter. Fill(user. Dataset); }

Exceptions • Please keep in mind not to give any valuable information when you Exceptions • Please keep in mind not to give any valuable information when you throw exceptions to the user. Prefer giving a generic error rather than returning the exception stack which would actually let the malicious user guess more about your database. • Example: In this specific scenario , if submitting the form with the injected code return a server error , it Indicates your query is malformed. But this gives away the truth that you are constructing your query on the fly which would encourage a malicious user to keep on trying with his attacks until he finds something useful.

Authentication • Forms Authentication : Cookie based authentication system where username and password are Authentication • Forms Authentication : Cookie based authentication system where username and password are stored in XML/Text file or in the database. • Passport authentication : Single Authentication point through Microsoft. • Windows Authentication: Authentication mode that uses local/domain windows users. Web. Config file is used to tells the web application which mode of authentication should be used.

Forms Authentication • Prefer Membership providers over custom authentication. • Communication through SSL should Forms Authentication • Prefer Membership providers over custom authentication. • Communication through SSL should be preferred while using Forms authentication. • Use strong passwords. • Encrypt username passwords in the user store. • Do not persist cookies

Membership Providers • Active. Directory. Membership. Provider • Sql. Membership. Provider Membership Providers • Active. Directory. Membership. Provider • Sql. Membership. Provider

Active. Directory. Membership. Provider • Active. Directory. Membership. Provider: Uses Microsoft Active Directory directory Active. Directory. Membership. Provider • Active. Directory. Membership. Provider: Uses Microsoft Active Directory directory service to maintain user information. Used in Intranet applications. To use this provider , first, configure the forms authentication using the web. config as follows.

Contd… (Step 2) • Configure the Active. Directory. Membership. Provider as follows , <connection. Contd… (Step 2) • Configure the Active. Directory. Membership. Provider as follows , . . . . . . LDAP : Light. Weight Directory Access protocol. LDAP Connectionstring Format : LDAP: //server/userdn/ Server ; name or IP address of the server using the directory Userdn is the unique name of the active directory user store.

Creating Users • Using Website administration tool (ASP. NET configuration) in visual Studio 2005 Creating Users • Using Website administration tool (ASP. NET configuration) in visual Studio 2005 toolbar. • Create. User. Wizard Control on a web page. • Membership API (to create users programmatically). Membership. Create. User("User. [email protected] Na me", "[email protected] 0 rd", "user. [email protected] Address");

Authenticating Users • Using Login Control in ASP. NET 2. 0 (uses membership providers Authenticating Users • Using Login Control in ASP. NET 2. 0 (uses membership providers by default without writing any additional code) • Custom login page : call Membership. validate. User to authenticate users. if (Membership. Validate. User(user. Name. Text, password. Text)) { if (Request. Query. String["Return. Url"] != null) { Forms. Authentication. Redirect. From. Login. Page(user. Name. Text, false); ); //false to prevent creating persistant cookies } else { Forms. Authentication. Set. Auth. Cookie(user. Name. Text, false } } else { Response. Write("Invalid User. ID and Password"); }

SQLMembership. Provider • Used for applications facing internet where users don’t have Active directory SQLMembership. Provider • Used for applications facing internet where users don’t have Active directory account. User credentials are stored in the database. Steps: § Configure forms authentication. (Same as for ADMP) § Install the membership database. § Configure the Sql. Membership. Provider. § Create users. § Authenticate users.

Install Membership database • Log on to SQLServer with a database admin account. • Install Membership database • Log on to SQLServer with a database admin account. • Run the following command aspnet_regsql. exe -E -S localhost -A m § -E indicates authenticate using the Windows credentials of the currently logged on user. § -S (server) indicates the name of the server where the database will be installed or is already installed. § -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Configure the Sql. Membership. Provider <connection. Strings> <add name= Configure the Sql. Membership. Provider . . . • Note : Make sure the ASP. NET user account has enough permissions on the SQL server database. • Encrypt the database connection string in the config file. • Creating and authenticating users is same as for ADMP.

Code Access Security CAS is a resource constraint model responsible for restricting the types Code Access Security CAS is a resource constraint model responsible for restricting the types of system resources code can access. CAS provides application level isolation in a shared environment. Ø Consider code access security for partial trust applications. Ø Choose a trust level that does not exceed your application's requirements. Ø Create a custom trust policy if your application needs additional permissions. CAS policy is defined by applications trust level. Ø Use Medium trust in shared hosting environments Be wary about choosing a trust level for your application. Remember that , at full trust, CAs always succeeds.

CAS Example • // Allow only this code to read files from c: Your. CAS Example • // Allow only this code to read files from c: Your. App. Dir [File. IOPermission(Security. Action. Permit. Only, [email protected]"c: Your. App. Dir")] [File. IOPermission(Security. Action. Permit. Only, Path. [email protected]"c: Your. App. Dir")] public static string Read. File(string filename) { // Use Path. Get. Full. Path() to canonicalize the file name // Use File. Stream. Open. Read to open the file // Use File. Stream. Read to access and return the data The above code will allow the users to read a file from the c: Your. App. Dir and only from that directory using this method. }

Saving sensitive Information on a computer • Saving sensitive information on a machine is Saving sensitive Information on a computer • Saving sensitive information on a machine is not recommended. • Never save sensitive information in plain text(text files, xml files etc). • Encrypt the data using the hashing algorithms before saving them. • Protect the folders and files that has the sensitive data. (using permission control) • Use names that doesn’t describes the content of the files. (for example , a file containing password should not be named as passwords especially if they are plain text).

Use Registry • Sometimes, Registry can also be used to save sensitive data. • Use Registry • Sometimes, Registry can also be used to save sensitive data. • Encrypt these data before saving the registry in HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER keys. • Saving under KKEY_CURRENT_USER provides much better security as it only gives permission to the current logged in user.

Protecting your Assemblies • Assemblies must be protected from being accessed or executed by Protecting your Assemblies • Assemblies must be protected from being accessed or executed by malicious users. • Assemblies are vulnerable through. NET’s own Reflection class. • Reverse Engineering add to the misery • Obfuscators provide a cure

Strong Names Strong name signatures provide a unique identity for code, and they cannot Strong Names Strong name signatures provide a unique identity for code, and they cannot be spoofed. The identity associated with the signature can be used to make security decisions. For example, you could set code access security policy to trust assemblies signed with your company's strong name when the assemblies come from a server you control. Consider the following guidelines for strong names: • Evaluate whether you need strong names. • Do not expect strong names to make your assembly tamper proof. • Use delay signing appropriately. • Use. pfx files to protect your private key if you do not use delay signing. • Do not depend on strong name identity permissions in full trust scenarios.

Do Strong Name tamper proof my assembly ? • • Do Not Expect Strong Do Strong Name tamper proof my assembly ? • • Do Not Expect Strong Names to Make Your Assembly Tamper Proof By adding a strong name to an assembly, you ensure that it cannot be modified and still retain your strong name signature. The strong name does not make your assembly tamper proof. It is still possible to remove a strong name, modify the IL code, and then reapply a different strong name. However, an attacker cannot recreate a valid signature from your original publisher's key unless your publisher's private key has been compromised. Because the key is part of the strong name identity, if an attacker strips a strong name signature, signs the code, and then installs the code in the global assembly cache, the code will have a different identity. Any callers looking for the original assembly will not bind to an assembly signed with a different private key. Strong names prevent this type of substitution attack. Note Both Authenticode and strong name signing ensure that if the signed code is tampered with, the signature will be invalidated. However, neither technology prevents an attacker from stripping off the signature, modifying the IL, and signing the code with the attacker's key.

Communication Security • If your application passes sensitive data over networks, consider the threats Communication Security • If your application passes sensitive data over networks, consider the threats of eavesdropping, tampering, and unauthorized callers accessing your end point. • . NET Framework 2. 0 provides a set of managed classes in the System. Net. Security namespace to enable secure communication between hosts when you are using remoting or raw-sockets based communication. • This allows you to implement both client and server-side secure channels using SSPI or SSL. These classes support mutual authentication, data encryption, and data signing.

Transport Level Encryption • If your servers are not inside a physically secure data Transport Level Encryption • If your servers are not inside a physically secure data center where the network eavesdropping threat is considered insignificant, you need to use an encrypted communication channel to protect data sent between servers. • You can use SSL or IPSec to encrypt traffic and help protect communication between servers. Use SSL when you need granular channel protection for a particular application, instead of protection for all applications and services running on a computer. • Use IPSec to help protect the communication channel between two servers and to restrict the computers that can communicate with each other. • For example, you can help protect a database server by establishing a policy that permits requests only from a trusted client computer, such as an application or Web server. You can also restrict communication to specific IP protocols and TCP/UDP ports.

Event Log • When you write event logging code, consider the threats of tampering Event Log • When you write event logging code, consider the threats of tampering and information disclosure. For example, can an attacker retrieve sensitive data by accessing the event logs? Can an attacker cover tracks by deleting the logs or erasing particular records? • Windows security restricts direct access to the event logs using system administration tools, such as the Event Viewer. Your main concern should be to ensure that the event logging code you write cannot be used by a malicious user for unauthorized access to the event log. • Do not log sensitive data. • Do not expose event log data to unauthorized users.

Reflection • • • • Reflection. NET reflection is a feature that allows running Reflection • • • • Reflection. NET reflection is a feature that allows running code to dynamically discover, load, and generate assemblies. With reflection, you can enumerate an assembly's types, methods, and properties—including those marked as private. By using Reflection. Emit, you can generate a new assembly dynamically at run time and invoke its members. Reflection is a powerful feature that has a number of security implications: If your code has the Reflection. Permission, it can enumerate and invoke non-public members or types in other assemblies. If you do not use code access security permission demands to authorize calling code, an attacker could gain access to code that would otherwise be inaccessible. By using reflection, you can dynamically load assemblies—for example, by using System. Reflection. Assembly. Load. If you allow untrusted code or data to influence which assembly is loaded, an attacker could trick your code into loading and executing malicious code. By using reflection, you can dynamically invoke methods on assemblies—for example, by using System. Reflection. Method. Info. Invoke. If you allow untrusted code or data to influence the method invocation, an attacker could trick your code into making unexpected and potentially malicious method calls. With Reflection. Emit, your code can dynamically generate and execute code at run time. If you allow untrusted code or data to influence the code generation, an attacker could coerce your application into generating malicious code. When you use reflection, consider the following guidelines: Use full assembly names when you dynamically load assemblies. Avoid letting untrusted code or data control run-time assembly load decisions. Avoid letting untrusted code or data control Reflection. Emit. Consider restricting the permissions of dynamically generated assemblies. Only persist dynamically created assemblies if necessary. Use Reflection. Only. Load. From if you only need to inspect code.

Summary : What should you know? ? • • Know When, Where and how Summary : What should you know? ? • • Know When, Where and how to authenticate Know When , Where and how to authorize How to Secure communication ? Common issues ? How to avoid them? Top Risks ? How to avoid them ? Never bypass security to get things to work. Always follow the best practices starting from design to implementation and testing.

Terminologies • • • Authentication. Positively identifying the clients of your application; clients might Terminologies • • • Authentication. Positively identifying the clients of your application; clients might include end-users, services, processes or computers. Authorization. Defining what authenticated clients are allowed to see and do within the application. Secure Communications. Ensuring that messages remain private and unaltered as they cross networks. Impersonation. This is the technique used by a server application to access resources on behalf of a client. The client's security context is used for access checks performed by the server. Delegation. An extended form of impersonation that allows a server process that is performing work on behalf of a client, to access resources on a remote computer. Security Context. Security context is a generic term used to refer to the collection of security settings that affect the security-related behavior of a process or thread. The attributes from a process' logon session and access token combine to form the security context of the process. Identity refers to a characteristic of a user or service that can uniquely identify it. For example, this is often a display name, which often takes the form authority/user name.

References http: //en. wikipedia. org/wiki/Software_security http: //support. microsoft. com/kb/910443 http: //msdn 2. microsoft. com/enus/library/aa References http: //en. wikipedia. org/wiki/Software_security http: //support. microsoft. com/kb/910443 http: //msdn 2. microsoft. com/enus/library/aa 292118(VS. 71). aspx http: //msdn 2. microsoft. com/en-us/library/aa 302381. aspx http: //msdn 2. microsoft. com/en-us/library/ms 998372. aspx http: //msdn 2. microsoft. com/en-us/library/bb 355989. aspx http: //www. unixwiz. net/techtips/sql-injection. html http: //msdn 2. microsoft. com/en-us/library/ms 998258. aspx http: //msdn 2. microsoft. com/en-us/library/ms 998264. aspx