1. Use Session Cookies (not Cookieless sessions)
As Session Cookies store on Server side. Cookless ones mean hackers can get around through URL manipulation.
2. Use Server.HtmlEncode() method to encode any user input:
While this vulnerability has been hot-fixed, it is nevertheless important that you employ added precaution. One good method is to use the Server.HtmlEncode() method to encode all user inputs into HTML-encode strings:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
lblMessage.Text = Server.HtmlEncode(txtName.Text)
End Sub
3. SQL Injection. If you pass username straight to where clause then hacker can display all users:
They can enter into the password:
xyz' union select @@servername, @@servicename, @@version --
or xyz' or UserId like '%
correct method:
Private Sub btnLogin_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnsecureLogin.Click SqlConnection1.Open() Dim str As String = "SELECT * FROM Users WHERE " & _ "UserID=@userID AND Password=@password" Dim comm As New SqlCommand(str, SqlConnection1) comm.Parameters.Add("@userID", txtName.Text) comm.Parameters.Add("@password", txtPassword.Text)
Dim reader As SqlDataReader = comm.ExecuteReader() If Not reader.HasRows Then _ Response.Write("Login failed. Please try again") While reader.Read() Response.Write("Hello " & reader("UserName")) End WhileEnd Sub
As Session Cookies store on Server side. Cookless ones mean hackers can get around through URL manipulation.
2. Use Server.HtmlEncode() method to encode any user input:
While this vulnerability has been hot-fixed, it is nevertheless important that you employ added precaution. One good method is to use the Server.HtmlEncode() method to encode all user inputs into HTML-encode strings:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
lblMessage.Text = Server.HtmlEncode(txtName.Text)
End Sub
3. SQL Injection. If you pass username straight to where clause then hacker can display all users:
They can enter into the password:
xyz' union select @@servername, @@servicename, @@version --
or xyz' or UserId like '%
correct method:
Private Sub btnLogin_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnsecureLogin.Click SqlConnection1.Open() Dim str As String = "SELECT * FROM Users WHERE " & _ "UserID=@userID AND Password=@password" Dim comm As New SqlCommand(str, SqlConnection1) comm.Parameters.Add("@userID", txtName.Text) comm.Parameters.Add("@password", txtPassword.Text)
Dim reader As SqlDataReader = comm.ExecuteReader() If Not reader.HasRows Then _ Response.Write("Login failed. Please try again") While reader.Read() Response.Write("Hello " & reader("UserName")) End WhileEnd Sub
4. Validate user inputs
Always check for length and wildcard characters.
5. Use hashing to store password:
A much better way to store passwords in your database is to use hashing. Hashing is a one-way process of mapping data (plain text) of any length to a unique fixed-length byte sequence. This fixed-length byte sequence is called a hash. Statistically, two different pieces of data would not generate the same hash. And a hash cannot be used to reverse-generate the plain text. In the case of saving passwords in the database, saving the hash value of each password is preferred over the saving the plain password. When a user logs in, the hash value of the password is computed and then compared to the hash value stored in the database. In this case, even if the database server is compromised, the hackers have no way of knowing the users’ real passwords (though he could still alter the hash value of a user’s password to one he generated himself and gain illegal access).
The following function shows how to use the SHA1 hash algorithm implementation in the .NET Framework:
Public Function ComputeHashValue(ByVal data() As Byte) As Byte()
Dim hashAlg As SHA1 = SHA1.Create
Dim hashvalue() As Byte = hashAlg.ComputeHash(data)
Return hashvalue
End Function
You could derive the hash value of a password like this:
Dim hashValue() As Byte
hashValue = ComputeHashValue(Encoding.ASCII.GetBytes(txtPassword.Text))
The hash value could then be stored in place of the user’s password.
Tip 5—Encrypt Sensitive DataASP.NET Web developers know that it is sometimes useful to store information such as database connection strings in the Web.config file rather than hardcode them in the application. Doing so allows the database server to be changed without modifying and recompiling the application. However, storing sensitive information such as the connection string (which may contain user information and password) in plain text format in Web.config file is not a very good idea, as Web.config is an XML document stored as a text file and thus easily accessed.
So, a safer way would be to encrypt the sensitive information and store the ciphertext into the Web.config file. There are two types of encryption algorithms that you can use:
Symmetric
Asymmetric Symmetric algorithms encrypt and decrypt information using a common key. It is a simple and efficient way of encrypting/decrypting information. However the use of a common key makes it less secure if more than one party needs to know the key.
Asymmetric algorithms encrypt and decrypt information using a pair of keys. This pair of keys is made up of a private and a public key. Data encrypted using the public key can only be decrypted using the private key and vice versa. Asymmetric algorithms are much more complex and are computationally expensive. However, it is also much more secure than symmetric algorithms.
Listing 1 shows the use of the Rijndael symmetric encryption algorithm implementation in .NET. Listing 2 shows the RSA asymmetric encryption algorithm implementation in .NET.
The functions shown in Listings 1 and 2 will allow you encrypt the sensitive data in your Web application, especially configuration and XML files. Listing 3 shows the supporting function used by the functions in Listings 1 and 2. The supporting function converts a string to a byte array. For example, it converts a string "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16" to a byte array of {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}.
For asymmetric encryption, you need to first create the pair of private and public keys:
'===========For Asymmetric use=============
Dim publicKey, privateKey As String
Dim RSA As New RSACryptoServiceProvider()
publicKey = RSA.ToXmlString(False) ' get public key
privateKey = RSA.ToXmlString(True) ' get private key
'===========Asymmetric Encryption=============
Dim cipherText as String = AsymmetricEncryption _
(txtAsyPlainText.Text, publicKey)
'===========Asymmetric Decryption=============
Dim plainText as String = AsymmetricDecryption _
(txtAsyCipherText.Text, privateKey)
For symmetric encryption, you need a 16-byte key and Initialization Vector (IV):
'===========Symmetric=============
Dim Key, IV as String
Key="1234567890123456"
IV ="1234567890123456"
Dim cipherText As String = SymmetricEncryption _
(txtSyPlainText.Text, Key, IV)
'===========Symmetric=============
Dim plainText as String = SymmetricDecryption _
(txtSyCipherText.Text, Key, IV)
Because SOAP messages are sent in plain text, Web services could also benefit from encryption. Instead of using SSL to protect the entire communication path (which is overkill), you could use encryption to protect sensitive information such as credit card numbers from prying eyes.
6. *Store secure information in registry (DB connection string UN and Password):
1. Download the aspnet_setreg.exe utility from http://support.microsoft.com/default.aspx?scid=kb;en-us;Q329290.
2. Create a new user account in your Windows machine. I have called it ASPNETUSER with a password of “secret.”

3. Add the !appSettings! element into your Web.config file. This setting saves the database connection string into Web.config:
!configuration!
!appSettings!
!add key="Distributor" value="workstation id=F16;packet size=4096;integrated security=SSPI;data
source=F16;persist security info=True;initial catalog=Distributor" /!
!configuration!
!appSettings!
!add key="Distributor" value="workstation id=F16;packet size=4096;integrated security=SSPI;data
source=F16;persist security info=True;initial catalog=Distributor" /!
!/appSettings!
4. In your code, you can retrieve the connection string defined in your Web.config file using:
Dim connStr As String = _
ConfigurationSettings.AppSettings("Distributor")
Dim Conn As New SqlConnection(connStr)
Dim connStr As String = _
ConfigurationSettings.AppSettings("Distributor")
Dim Conn As New SqlConnection(connStr)
5. Next, use the aspnet_setreg.exe utility to add the username and password of the user account that your ASP.NET application will impersonate, into the registry:
C:\>aspnet_setreg -k:Software\ASPNetApp\Identity -u:ASPNETUSER -p:secret
6. When you do that, Windows will print a long message to the screen. The text of the message is shown below. In particular, look for two lines denoted in bold. You will need to save the two lines in a text file.
Please edit your configuration to contain the following:
userName="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,password"
The DACL on the registry key grants Full Control to System, Administrators, and Creator Owner.
If you have encrypted credentials for the configuration section, or a connection string for the
!sessionState/! configuration section, ensure that the process identity has Read access to the
registry key. Furthermore, if you have configured IIS to access content on a UNC share, the account used to
access the share will need Read access to the registry key.
Regedt32.exe may be used to view/modify registry key permissions.
You may rename the registry subkey and registry value in order to prevent discovery.
Please edit your configuration to contain the following:
userName="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,password"
The DACL on the registry key grants Full Control to System, Administrators, and Creator Owner.
If you have encrypted credentials for the
!sessionState/! configuration section, ensure that the process identity has Read access to the
registry key. Furthermore, if you have configured IIS to access content on a UNC share, the account used to
access the share will need Read access to the registry key.
Regedt32.exe may be used to view/modify registry key permissions.
You may rename the registry subkey and registry value in order to prevent discovery.
7. Locate the Machine.config file at: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG and modify the !identity! element in Machine.config file to:
!identity impersonate="true"
userName="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,password"
/!
!identity impersonate="true"
userName="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,password"
/!
8. Launch the registry editor and navigate to My Computer/HKEY_LOCAL_MACHINE/SOFTWARE/ASPNetApp/Identity/ASPNET_SETREG (use regedt32)
9. Right-click on the ASPNET_SETREG registry key and select Permissions. Add the user account ASPNET and set it to Read permission
10. Give the user account ASPNETUSER FULL CONTROL access rights to the “Temporary ASP.NET Files” folder located in C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.
11. That’s it! Your application will now run under the impersonation of ASPNETUSER. And the credentials of the user can be securely retrieved from the registry.
7. Web.config before deployment
a. Turn trace off:
!trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /!
b. Turn debug off:
!compilation defaultLanguage="vb" debug="false" /!
c. Set customErrors to RemoteOnly:
!customErrors mode="RemoteOnly" /!
The mode attribute has three possible values:
>"On" always display custom (friendly) messages
>"Off" always display detailed ASP.NET error information.
>"RemoteOnly" displays custom (friendly) messages only to users not running on the local Web server. This setting is recommended for security purposes, so that you do not display application detail information to remote clients.
d. Remove Solution and Project files from your deployment server.
Reference: http://www.devx.com/security/Article/20898
a. Turn trace off:
!trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /!
b. Turn debug off:
!compilation defaultLanguage="vb" debug="false" /!
c. Set customErrors to RemoteOnly:
!customErrors mode="RemoteOnly" /!
The mode attribute has three possible values:
>"On" always display custom (friendly) messages
>"Off" always display detailed ASP.NET error information.
>"RemoteOnly" displays custom (friendly) messages only to users not running on the local Web server. This setting is recommended for security purposes, so that you do not display application detail information to remote clients.
d. Remove Solution and Project files from your deployment server.
Reference: http://www.devx.com/security/Article/20898
No comments:
Post a Comment