Security (C# Programming Guide)

Security is a necessary aspect of every C# application, and it must be considered at every phase of development, not only when design and implementation are completed.

C# Specific Security Recommendations

This list is not an exhaustive list of potential security problems. It highlights some common issues for C# developers.

  • Use the checked keyword to control the overflow-checking context for integral-type arithmetic operations and conversions.

  • Always use the most restrictive data type for parameters. For example, when you pass a value to a method that describes the size of a data structure, use unsigned integer rather than integer.

  • Do not make decisions based on file names. File names can be expressed in many different ways, and your test for a particular file may be bypassed.

  • Never, ever hardcode passwords or other sensitive information into your application.

  • Always validate input that is used to generate SQL queries.

  • Validate all inputs into your methods. The regular expression methods in the System.Text.RegularExpressions namespace are useful for confirming that input is of the correct form, such as an e-mail address.

  • Do not display exception information: it provides any would-be attacker with valuable clues.

  • Ensure that your application works while running with the least possible permissions. Few applications require that a user be logged in as an administrator.

  • Do not use your own encryption algorithms. Use the System.Security.Cryptography classes.

  • Give your assemblies strong names.

  • Do not store sensitive information in XML or other configuration files.

  • Check managed code that wraps native code carefully. Confirm that the native code is secure.

  • Use caution when you use delegates passed from outside your application.

  • Run the Visual Studio code analysis tool on your assemblies to ensure compliance with Microsoft .NET Framework Design Guidelines. This tool can also find and warn against over 200 code defects. For more information, see Detecting and Correcting Managed Code Defects.

Other Security Resources

The following Microsoft Internet Web sites provide in-depth information about creating secure, reliable software.

Security in C# 3.0 Cookbook, Third Edition: More than 250 solutions for C# 3.0 programmers

See Also

Concepts

C# Programming Guide

Security Tools

Other Resources

Security in Native and .NET Framework Code

Secure Coding Guidelines