.NET Security - PowerPoint PPT Presentation

About This Presentation
Title:

.NET Security

Description:

.NET Security By R.S ... NET Framework 2.0 provides a set of managed classes in the System.Net.Security namespace to enable secure ... Code Access Security CAS is a ... – PowerPoint PPT presentation

Number of Views:174
Avg rating:3.0/5.0
Slides: 68
Provided by: sank50
Learn more at: https://www.cs.odu.edu
Category:
Tags: net | net | security

less

Transcript and Presenter's Notes

Title: .NET Security


1
.NET Security
  • By
  • R.S

2
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

3
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
  • Whether I am user working on my personal
    computer/laptop or I am a company employee
    working on my company computer.
  • 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 computers
    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.

4
Software Security Breach and Nightmares in an
organization
  • Irrespective of what an organizations 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 didnt do their job right in
    providing security ,fix loop holes in the system
    to make it more secured etc .

5
What to Do ?
  • Alright, Software security breach doesnt 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 .

6
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 .
  • Dont have to spend 50 a month to protect your 3
    month old tooth brush.

7
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 ?

8
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 ?

9
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
    applications modules to increase security or
    redesigning the entire application to cope up
    with the current security trends.
  • Dont be afraid to express yourself, you are only
    trying to help the company.
  • Always have proofs to support your claims . In
    other words , Dont 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 dont 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 ????

10
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.

11
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, whats new in
    it , how it solves an existing problem/vulnerabili
    ty.
  • 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.

12
.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-in-depth security strategy.
  • Know the available .NET tools first then learn
    what those tools can do for you .

13
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?

14
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 .

15
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 are any
    current security threats that your application
    may fall a victim for.
  • Find out if there are 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.

16
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 shouldnt be a tough task.
  • Please keep in mind that you dont want to do too
    much of anything. Just what is required to ensure
    security .

17
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 ??)

18
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.

19
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.

20
Sealed class Example
  • A Sealed Class ..
  • public sealed class FileModifierClass
  • public FileModifierClass()
  • This class cannot be inherited

21
Sealed Method example
  • Only methods in derived classes can be sealed.
  • public class ParentFileModifierClass
  • public FileModifierClass()
  • public virtual void Modify()
  • public sealed class FileModifierClass
  • public FileModifierClass()
  • sealed override public void Modify()
  • Classes inheriting FileModifierClass will not be
    able to override the Modify method.

22
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.

23
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.

24
Contd.
  • Use GetfullPath on a windows application.
  • GetFullPath performs the following checks
  • It checks that the file name does not contain any
    invalid characters, as defined by
    Path.InvalidPathChars.
  • 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 LPT1, COM1, 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.MapPath on a server.
  • Note The MapPath property potentially contains
    sensitive information about the hosting
    environment. The return value should not be
    displayed to users.

25
Contd..
  • Validate Input from All Sources Like QueryString,
    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.

26
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.

27
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. 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.

28
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

29
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 ( ltbgt
    , ltigt, etc) and eliminate other HTML tags.
  • How and where to enable request validation ?
  • In Machine.Config and Web.Config as follows
  • ltpages validateRequest"true" ... /gt
  • 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.

30
ASP.NET Validators
  • Text Fields RegularExpressionValidator
  • ltform id"WebForm" method"post" runat"server"gt
  • ltaspTextBox id"txtName" runat"server"gtlt/aspTex
    tBoxgt ltaspRegularExpressionValidator
    id"nameRegex" runat"server" ControlToValidate"t
    xtName" ValidationExpression"a-zA-Z'.\s1,40
    " ErrorMessage"Invalid name"gt lt/aspregularexpres
    sionvalidatorgt
  • lt/formgt
  • Regex Class
  • // Instance method
  • Regex reg new Regex(_at_"a-zA-Z'.\s1,40")
    Response.Write(reg.IsMatch(txtName.Text)) //
    Static method
  • if (!Regex.IsMatch(txtName.Text,_at_"a-zA-Z'.\s1
    ,40"))
  • // Name does not match expression

31
Contd..
  • Numeric Fields Range Validator
  • ltaspRangeValidator ID"RangeValidator1"
    Runat"server" ErrorMessage"Invalid range.
    Number must be between 0 and 255."
    ControlToValidate"rangeInput" MaximumValue"255"
    MinimumValue"0" Type"Integer" /gt
  • Test in your Code for range as follows (only in
    Framework 2.0)
  • Int32 i
  • if (Int32.TryParse(txtInput.Text, out i)
    false) // Conversion failed
  • (Older versions of Framework , use
    Int32.TryParse or Convert.ToInt32 inside a try
    catch bolck. Catch any formatexception inside the
    catch block and throw an exception to the user.)

32
CustomValidator
  • lt_at_ Page Language"C" gt
  • ltscript runat"server"gt
  • void ValidateDateInFuture(object source,
    ServerValidateEventArgs args)
  • DateTime dt // Check for valid date and that
    the date is in the future if ((DateTime.TryParse(a
    rgs.Value, out dt) false) (dt lt
    DateTime.Today)) args.IsValid false
  • lt/scriptgt
  • lthtmlgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • ltaspLabel ID"Label1" Runat"server"
    Text"Future Date"gtlt/aspLabelgt ltaspTextBox
    ID"futureDatetxt" Runat"server"gtlt/aspTextBoxgt
    ltaspCustomValidator ID"CustomValidator1"
    Runat"server" ErrorMessage"Invalid date. Enter
    a date in the future." ControlToValidate"futureDa
    tetxt" OnServerValidate"ValidateDateInFuture"gt
    lt/aspCustomValidatorgt ltbr /gt ltaspButton
    ID"submitBtn" Runat"server" Text"Submit" /gt
    lt/divgt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

33
Html Encode
  • void submitBtn_Click(object sender, EventArgs e)
  • // Encode the string input
  • StringBuilder sb new StringBuilder(
    HttpUtility.HtmlEncode(htmlInputTxt.Text))
  • // Selectively allow and ltigt
  • sb.Replace("ltbgt", "ltbgt")
  • sb.Replace("lt/bgt", "")
  • sb.Replace("ltigt", "ltigt")
  • sb.Replace("lt/igt", "")
  • Response.Write(sb.ToString())

34
Query String Validation
  • void Page_Load(object sender, EventArgs e)
  • if (!System.Text.RegularExpressions.Regex.IsMatch(
    Request.QueryString"Name", _at_"a-zA-Z'.\s1,40
    ")) Response.Write("Invalid name parameter")
  • else
  • Response.Write("Name is " Request.QueryString"
    Name")

35
Request.MapPath
  • Use the Overloaded Request.MapPath method to read
    file paths.
  • Try
  • string mappedPath Request.MapPath(
    inputPath.Text, Request.ApplicationPath, false)
  • catch (HttpException 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.MapPathSecure
    method to retrieve the physical path .
    Control.MapPathSecure uses code access security
    and throws an HttpException 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.
  • lttrust levelmedium/gt (Web.Config or
    machine.Config)

36
Validating Urls
  • Use Regular expressions..
  • (?httphttpsftp)//a-zA-Z0-9\.\-(?\\d1,5
    )?(?A-Za-z0-9\.\\\_at_\\\\\,\?/u0-9A-Fa-f
    40-9A-Fa-f2)
  • Use HttpUtility.HtmlEncode and
    HttpUtility.UrlEncode( urlString ) 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 .

37
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 .

38
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 Passwordpassword.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 11--
  • Password.Textpassword
  • Select from Users where Username
    username.Text and Passwordpassword.Text
  • The code generated on the fly will now look like
  • Select from Users where Usernamesomething or
    11-- and Passwordpassword
  • 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.

39
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 dont provide
    protection against SQL Injection.

40
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, SqlParameterCollection) 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.

41
SQLParameterCollection sample
  • using System.Data
  • using System.Data.SqlClient
  • using (SqlConnection connection new
    SqlConnection(connectionString))
  • DataSet userDataset new DataSet()
  • SqlDataAdapter myAdapter new SqlDataAdapter(
  • "LoginStoredProcedure", connection)
  • myAdapter.SelectCommand.CommandType
    CommandType.StoredProcedure
  • myAdapter.SelectCommand.Parameters.Add("_at_au_id",
    SqlDbType.VarChar, 11)
  • myAdapter.SelectCommand.Parameters"_at_au_id".Val
    ue SSN.Text
  • myAdapter.Fill(userDataset)

42
SQlParameters with Dynamic SQL
  • using System.Data
  • using System.Data.SqlClient
  • using (SqlConnection connection new
    SqlConnection(connectionString))
  • DataSet userDataset new DataSet()
  • SqlDataAdapter myDataAdapter new
    SqlDataAdapter(
  • "SELECT au_lname, au_fname FROM Authors
    WHERE au_id _at_au_id",
  • connection)
  • myDataAdapter.SelectCommand.Parameters.Add("_at_au_
    id", SqlDbType.VarChar, 11)
  • myDataAdapter.SelectCommand.Parameters"_at_au_id"
    .Value SSN.Text
  • myDataAdapter.Fill(userDataset)

43
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.

44
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.

45
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

46
Membership Providers
  • ActiveDirectoryMembershipProvider
  • SqlMembershipProvider

47
ActiveDirectoryMembershipProvider
  • ActiveDirectoryMembershipProvider 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.
  • ltauthentication mode"Forms"gt
  • ltforms loginUrl"Login.aspx"
  • protection"All"
  • timeout"30"
  • name"AppNameCookie"
  • path"/FormsAuth"
  • requireSSL"false"
  • slidingExpiration"true"
  • defaultUrl"default.aspx"
  • cookieless"UseCookies"
  • enableCrossAppRedirects"false"/gt
  • lt/authenticationgt
  • ltauthorizationgt
  • ltdeny users"?" /gt
  • ltallow users"" /gt
  • lt/authorizationgt

48
Contd (Step 2)
  • Configure the ActiveDirectoryMembershipProvider
    as follows ,
  • ltconnectionStringsgt
  • ltadd name"ADConnectionString"
  • connectionString
  • "LDAP//domain.testing.com/CNUsers,DCdomain,
    DCtesting,DCcom" /gt
  • lt/connectionStringsgt
  • ltsystem.webgt
  • ...
  • ltmembership defaultProvider"MembershipADProvider
    "gt
  • ltprovidersgt
  • ltadd
  • name"MembershipADProvider"
  • type"System.Web.Security.ActiveDirectoryMem
    bershipProvider, System.Web,
  • Version2.0.0.0, Cultureneutral,
    PublicKeyTokenb03f5f7f11d50a3a"
  • connectionStringName"ADConnection
    String"
  • connectionUsername"ltdomainNamegt\a
    dministrator"
  • connectionPassword"password"/gt
  • lt/providersgt

49
Creating Users
  • Using Website administration tool (ASP.NET
    configuration) in visual Studio 2005 toolbar.
  • CreateUserWizard Control on a web page.
  • Membership API (to create users programmatically)
    .
  • Membership.CreateUser("UserName_at_DomainName",
    "P_at_ssw0rd", "userName_at_emailAddress")

50
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.validateUser
    to authenticate users.
  • if (Membership.ValidateUser(userName.Text,
    password.Text))
  • if (Request.QueryString"ReturnUrl" ! null)
  • FormsAuthentication.RedirectFromLoginPage(user
    Name.Text, false) )//false to prevent creating
    persistant cookies
  • else
  • FormsAuthentication.SetAuthCookie(userName.Tex
    t, false
  • else
  • Response.Write("Invalid UserID and Password")

51
SQLMembershipProvider
  • Used for applications facing internet where users
    dont 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 SqlMembershipProvider.
  • Create users.
  • Authenticate users.

52
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.

53
Configure the SqlMembershipProvider
  • ltconnectionStringsgt
  • ltadd name"MySqlConnection" connectionString"Da
    ta SourceMySqlServerInitial CatalogaspnetdbInt
    egrated SecuritySSPI" /gt
  • lt/connectionStringsgt
  • ltsystem.webgt
  • ...
  • ltmembership defaultProvider"SqlProvider"
    userIsOnlineTimeWindow"15"gt
  • ltprovidersgt
  • ltclear /gt
  • ltadd
  • name"SqlProvider"
  • type"System.Web.Security.SqlMembershipPro
    vider"
  • connectionStringName"MySqlConnection"
  • applicationName"MyApplication"
  • enablePasswordRetrieval"false"
  • enablePasswordReset"true"
  • requiresQuestionAndAnswer"true"
  • requiresUniqueEmail"true"
  • passwordFormat"Hashed" /gt
  • lt/providersgt

54
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.
  • Use Medium trust in shared hosting environments
  • CAS policy is defined by applications trust level
    .
  • lttrust level"FullHighMediumLowMinimal" /gt
  • Be wary about choosing a trust level for your
    application. Remember that , at full trust, CAs
    always succeeds.

55
CAS Example
  • // Allow only this code to read files from
    c\YourAppDir
  • FileIOPermission(SecurityAction.PermitOnly,Read_at_
    "c\YourAppDir\") FileIOPermission(SecurityActio
    n.PermitOnly, PathDiscovery_at_"c\YourAppDir\")
  • public static string ReadFile(string filename)
  • // Use Path.GetFullPath() to canonicalize the
    file name
  • // Use FileStream.OpenRead to open the file
  • // Use FileStream.Read to access and return the
    data
  • The above code will allow the users to read a
    file from the c\YourAppDir and only from that
    directory using this method .

56
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 doesnt describes the content of
    the files. (for example , a file containing
    password should not be named as passwords
    especially if they are plain text).

57
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.

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

59
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.

60
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.

61
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.

62
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.

63
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.

64
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 propertiesincludin
    g 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 ReflectionPermission, 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
    assembliesfor 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 assembliesfor example, by using
    System.Reflection.MethodInfo.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 ReflectionOnlyLoadFrom if you only need to
    inspect code.

65
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.

66
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. 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.

67
References
  • http//en.wikipedia.org/wiki/Software_security
  • http//support.microsoft.com/kb/910443
  • http//msdn2.microsoft.com/en-us/library/aa292118(
    VS.71).aspx
  • http//msdn2.microsoft.com/en-us/library/aa302381.
    aspx
  • http//msdn2.microsoft.com/en-us/library/ms998372.
    aspx
  • http//msdn2.microsoft.com/en-us/library/bb355989.
    aspx
  • http//www.unixwiz.net/techtips/sql-injection.html
  • http//msdn2.microsoft.com/en-us/library/ms998258.
    aspx
  • http//msdn2.microsoft.com/en-us/library/ms998258.
    aspx
  • http//msdn2.microsoft.com/en-us/library/ms998264.
    aspx
Write a Comment
User Comments (0)
About PowerShow.com