Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

January 26, 2009

Protecting cookie

XSS attacks can be used to hack cookie information. Following code is demonstrates simple steps to hack unprotected cookie values.
Create Javascript file “getMe.js” with just one line

alert(document.cookie);

Create hackMe.htm file as shown

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/javascript" src="http://someHost/myDir/getMe.js">
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Now you can use hackme.htm to perform XSS attack.

To protect cookie attacks set HttpOnly flag to true as shown.

MyCookie = Request.Cookies("MyID")   
if MyCookie is Nothing then
MyCookie = New HttpCookie("MyID")
MyCookie.HttpOnly = true
Response.AppendCookie(MyCookie)
end if
MyCookie.Value = sAppId & sSessionId
Response.Cookies.Set(MyCookie)
Or
Response.Cookies("MyID") = “MySecId”
Response.Cookies("MyID").HttpOnly=true 

You can get more info -
http://en.wikipedia.org/wiki/HTTP_cookie
http://www.codinghorror.com/blog/archives/001167.html

September 29, 2008

Proxy tools for thin & thick client

Thin client

Thick client

  • Echo Mirage
  • Holodeck
  • Wpepro
  • August 19, 2008

    All about WCF Security

    All about WCF Security can be found here

    Patterns & practices: Improving Web Services Security

    This guide shows you how to make the most of WCF (Windows Communication Foundation) with end-to-end application scenarios, it shows you how to design and implement authentication and authorization in WCF, how to improve the security of your WCF services through prescriptive guidance including guidelines, Q&A, practices at a glance, and step-by-step how tos.

    February 07, 2006

    Setting Security Preferences (SSL)

    You can set a number of system-wide preferences for SSL. To do so, choose Server Preferences|Encryption Preferences in the Server Manager. After you make your changes, click OK and confirm your changes. You can configure settings for SSL version, client certificates, and ciphers

    SSL Version

    You can specify which versions of SSL your server can communicate with. The latest and most secure version is SSL version 3, but many older clients use only SSL version 2. You will probably want to enable your server to use both versions.

    Client Certificates

    You can refuse any client that doesn't have a client certificate from a trusted CA. If your server is running on an internal company intranet, you might have an internal CA. If so, all your clients would have certificates issued by the internal CA. In this case you would allow only people with client certificates to connect to your server.

    Ciphers

    A cipher is an algorithm used in encryption. Some ciphers are more secure, or stronger, than others. Generally speaking, the more bits a cipher uses during encryption, the harder it is to decrypt the data. The list of available ciphers doesn't appear on the Encryption Preferences form unless you've enabled SSL.

    When initiating an SSL connection with a server, a client lets the server know what ciphers it prefers for encrypting information. In any two-way encryption process, both parties must use the same ciphers. Because a number of ciphers are available, your server needs to be able to use the most popular ones.

    You can choose ciphers from the SSL 2 protocol, as well as from SSL 3. To specify which ciphers your server can use, check them in the list. Unless you have a compelling reason not to use a specific cipher, you should check them all.

    The SSL 2.0 ciphers are:

    • RC4 cipher with 128-bit encryption and MD5 message authentication. RC4 ciphers are the fastest ciphers. This cipher, because it has 128-bit encryption, is the second strongest cipher next to Triple DES (Data Encryption Standard) with 168-bit encryption. It has approximately 3.4 * 1038 possible keys, making it very difficult to crack. As added security, all SSL 2.0 ciphers use MD5 (Message Digest 5) message authentication. MD5 message authentication detects attempts to modify data while it is in transit.
    • RC4 cipher with 40-bit encryption and MD5 message authentication. This cipher is also an RC4 cipher, making it one of the fastest available ciphers. It has 40-bit encryption, which has approximately 1.1 * 1012 (a trillion) possible keys, making it easier to crack than encryption with more possible keys, such as 128-bit encryption. This cipher also uses MD5 message authentication to detect attempts to modify data in transit.
    • RC2 cipher with 128-bit encryption and MD5 message authentication. The RC2 ciphers are slower than the RC4 ciphers. This RC2 cipher, because it has 128-bit encryption, is the second strongest cipher next to Triple DES with 168-bit. It has approximately 3.4 * 1038 possible keys, making it very difficult to crack. This cipher also uses MD5 message authentication to detect attempts to modify data in transit.
    • RC2 cipher with 40-bit encryption and MD5 message authentication. This cipher is also an RC2 cipher, making it is slower than the RC4 cipher. It has 40-bit encryption, which is not as strong as 168-bit, 128-bit, or 56-bit encryption. 40-bit encryption has approximately 1.1 * 1012 (a trillion) possible keys. This cipher also uses MD5 message authentication to detect attempts to modify data in transit.
    • DES with 56-bit encryption and MD5 message authentication. DES (Data Encryption Standard) is a U.S. government standard for data encryption. This cipher does not have as many possible keys as does 128-bit encryption, and therefore is not as strong. 56-bit encryption has approximately 7.2 * 1016 possible keys. This cipher also uses MD5 message authentication to detect attempts to modify data in transit.
    • Triple DES with 168-bit encryption and MD5 message authentication. Triple DES is the strongest cipher available, but it is not as fast as RC4. Triple DES uses a key three times as long as the key for standard DES. Because the key size is so large, there are more possible keys than for any other cipher - approximately 3.7 * 1050. This cipher also uses MD5 message authentication to detect attempts to modify data in transit.

    The SSL 3.0 ciphers are:

    • RC4 with 128-bit encryption and MD5 message authentication. This cipher is the same as the SSL 2.0 version of RC4 with 128-bit encryption but uses a more secure implementation of MD5 message authentication to detect attempts to modify data in transit.
    • RC4 with 40-bit encryption and MD5 message authentication. This cipher is the same as the SSL 2.0 version of RC4 with 40-bit encryption but uses a more secure implementation of MD5 message authentication to detect attempts to modify data in transit.
    • Triple DES with 168-bit encryption and SHA message authentication. This cipher is the same as the SSL 2.0 version of Triple DES with 168-bit encryption, but uses SHA (Secure Hash Algorithm) message authentication instead of MD5 message authentication. SHA is a government standardized algorithm that is used to construct a message authentication code that detects attempts to modify data while it is in transit. SHA is slower than MD5, but it is stronger.
    • DES with 56-bit encryption and SHA message authentication. This cipher is the same as the SSL 2.0 version of DES with 56-bit encryption but uses SHA message authentication instead of MD5 message authentication.
    • RC2 with 40-bit encryption and MD5 message authentication. This cipher is the same as the SSL 2.0 version of RC2 with 40-bit encryption but uses a more secure implementation of MD5 message authentication to detect attempts to modify data in transit.
    • No encryption, only MD5 message authentication. This cipher uses only MD5 message authentication to secure data. Any data sent using this cipher is not encrypted. The data is protected from modification, but it can be viewed by eavesdroppers.

    December 17, 2004

    Cryptography and security

    http://www.interhack.net/pubs/

    April 14, 2003

    Strong Encryption/Decryption and hash implementation in C#

    Following code snippet provides methods for strong Encryption/Decryption and hash implementation (as compare to last code)

    (Tip: Not better for performance)

    /// <summary>
    /// Strong Encryption/Decryption methods and hash implementation
    /// </summary>
    internal class StrongSecurity {

    private const int SHA1_HASH_SIZE = 160; // Size of hash without salt. Do not change this size.
    private static string HASH_ALGORITHM = "SHA1";// can be "MD5"
    private static int PASSWORD_ITERATIONS = 1;
    private static int KEY_SIZE = 128;

    /// <summary>
    /// Decrypt Input Message
    /// </summary>
    /// <param name="strEncryptedMessage">Encrypted Message</param>
    /// <param name="btSalt">Salt</param>
    /// <param name="strKey">Key</param>
    /// <param name="strHashAlgorithm">Hash Algorithm</param>
    /// <returns>Decrypted Message</returns>
    internal static string decryptMessage(string strEncryptedMessage, byte[] btSalt,string strKey) {
    PasswordDeriveBytes password = null;
    RijndaelManaged symmetricKey = null;
    ICryptoTransform decryptor = null;
    MemoryStream memoryStream = null;
    CryptoStream cryptoStream = null;
    try{
    // Convert strings defining encryption key characteristics into byte arrays.
    byte[] btIV = btSalt;

    byte[] btEncryptedDataBytes = Convert.FromBase64String(strEncryptedMessage);

    //Create password using salt and key
    password = new PasswordDeriveBytes(
    strKey,
    btSalt,
    HASH_ALGORITHM,
    PASSWORD_ITERATIONS);

    // Use the password to generate pseudo-random bytes for the encryption
    // key. Specify the size of the key in bytes (instead of bits).
    byte[] keyBytes = password.GetBytes(KEY_SIZE / 8);

    symmetricKey = new RijndaelManaged();

    // Set encryption mode to Cipher Block Chaining (CBC)
    symmetricKey.Mode = CipherMode.CBC;

    // Generate encryptor from the existing key bytes and IV
    decryptor = symmetricKey.CreateDecryptor(
    keyBytes,
    btIV);

    // Memory stream to hold encrypted data.
    memoryStream = new MemoryStream(btEncryptedDataBytes);

    // Define cryptographic stream
    cryptoStream = new CryptoStream(memoryStream,
    decryptor,
    CryptoStreamMode.Read);

    byte[] plainTextBytes = new byte[btEncryptedDataBytes.Length];

    // Start decrypting.
    int decryptedByteCount = cryptoStream.Read(plainTextBytes,
    0,
    plainTextBytes.Length);

    // Convert decrypted data into a string.
    string plainText = Encoding.UTF8.GetString(plainTextBytes,
    0,
    decryptedByteCount);

    // Return decrypted string.
    return plainText;
    }
    finally{
    password = null;
    symmetricKey = null;
    decryptor = null;
    memoryStream.Close();
    memoryStream = null;
    cryptoStream.Close();
    cryptoStream = null;
    }
    }

    /// <summary>
    /// Encrypts the Message
    /// </summary>
    /// <param name="strMessage">Message to Encrypt</param>
    /// <param name="btSalt">Salt</param>
    /// <param name="strKey">Key</param>
    /// <param name="strHashAlgorithm">Hash Algorithm</param>
    /// <returns>Encrypted Message</returns>
    internal static string encryptMessage(string strMessage, byte[] btSalt, string strKey) {
    PasswordDeriveBytes password = null;
    RijndaelManaged symmetricKey = null;
    ICryptoTransform encryptor = null;
    MemoryStream memoryStream = null;
    CryptoStream cryptoStream = null;

    try{
    // Convert strings into byte arrays.
    byte[] btIV = btSalt;
    byte[] btInputData = Encoding.UTF8.GetBytes(strMessage);

    // Create password using salt,password phrase
    password = new PasswordDeriveBytes(
    strKey,
    btSalt,
    HASH_ALGORITHM,
    PASSWORD_ITERATIONS);

    // Use the password to generate pseudo-random bytes for the encryption
    // key. Specify the size of the key in bytes (instead of bits).
    byte[] keyBytes = password.GetBytes(KEY_SIZE / 8);

    symmetricKey = new RijndaelManaged();

    // Set encryption mode to Cipher Block Chaining (CBC)
    symmetricKey.Mode = CipherMode.CBC;

    // Generate encryptor from the existing key bytes and IV
    encryptor = symmetricKey.CreateEncryptor(
    keyBytes,
    btIV);

    // Memory stream to hold encrypted data.
    memoryStream = new MemoryStream();

    // Define cryptographic stream
    cryptoStream = new CryptoStream(memoryStream,
    encryptor,
    CryptoStreamMode.Write);
    // Start encrypting.
    cryptoStream.Write(btInputData, 0, btInputData.Length);

    // Finish encrypting.
    cryptoStream.FlushFinalBlock();

    // Convert our encrypted data from a memory stream into a byte array.
    byte[] btEncryptedDataBytes = memoryStream.ToArray();

    // Convert encrypted data into a base64-encoded string.
    string strEncryptedData = Convert.ToBase64String(btEncryptedDataBytes);

    // Return encrypted string.
    return strEncryptedData;
    }
    finally{
    password = null;
    symmetricKey = null;
    encryptor = null;
    memoryStream.Close();
    memoryStream = null;
    cryptoStream.Close();
    cryptoStream = null;
    }
    }

    /// <summary>
    /// Verifies Hash received from the client
    /// </summary>
    /// <param name="hashValue">Hash Value to Verify</param>
    /// <param name="strKey">Server side Key to generate the hash</param>
    /// <returns>If hash is correct then return the salt bytes else null</returns>
    internal static byte[] VerifyHash(string strHashValue,string strKey) {
    int intHashSizeInBits, intHashSizeInBytes;

    // Convert base64-encoded hash value into a byte array.
    byte[] btHashWithSalt = Convert.FromBase64String(strHashValue);

    // Size of hash without salt.
    intHashSizeInBits = SHA1_HASH_SIZE;

    // Convert size of hash from bits to bytes.
    intHashSizeInBytes = intHashSizeInBits / 8;

    // Make sure that the specified hash value is long enough.
    if (btHashWithSalt.Length < intHashSizeInBytes)
    return null;

    // Allocate array to hold original salt bytes retrieved from hash.
    byte[] btSalt = new byte[btHashWithSalt.Length -
    intHashSizeInBytes];

    // Copy salt from the end of the hash to the new array.
    for (int i=0; i < btSalt.Length; i++)
    btSalt[i] = btHashWithSalt[intHashSizeInBytes + i];

    // Compute a new hash string.
    string strExpectedHashString =
    computeHash(btSalt,strKey);

    // If the computed hash matches the specified hash,
    // the secrete key must be correct.
    if (strHashValue == strExpectedHashString)
    return btSalt;
    else
    return null;
    }

    /// <summary>
    /// Computes hash of the key and salt
    /// </summary>
    /// <param name="btSalt">Salt</param>
    /// <param name="strKey">Key</param>
    /// <returns>Computed Hash</returns>
    internal static string computeHash(byte [] btSalt, string strKey) {

    // Convert plain text into a byte array.
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(strKey);

    // Allocate array, which will hold plain text and salt.
    byte[] plainTextWithSaltBytes =
    new byte[plainTextBytes.Length + btSalt.Length];

    // Copy plain text bytes into resulting array.
    for (int i=0; i < plainTextBytes.Length; i++)
    plainTextWithSaltBytes[i] = plainTextBytes[i];

    // Append salt bytes to the resulting array.
    for (int i=0; i < btSalt.Length; i++)
    plainTextWithSaltBytes[plainTextBytes.Length + i] = btSalt[i];

    // Specify hashing algorithm
    HashAlgorithm hash = new SHA1Managed();

    // Compute hash value of our plain text with appended salt.
    byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

    // Create array which will hold hash and original salt bytes.
    byte[] hashWithSaltBytes = new byte[hashBytes.Length +
    btSalt.Length];

    // Copy hash bytes into resulting array.
    for (int i=0; i < hashBytes.Length; i++)
    hashWithSaltBytes[i] = hashBytes[i];

    // Append salt bytes to the result.
    for (int i=0; i < btSalt.Length; i++)
    hashWithSaltBytes[hashBytes.Length + i] = btSalt[i];

    // Convert result into a base64-encoded string.
    string hashValue = Convert.ToBase64String(hashWithSaltBytes);

    // Return the result.
    return hashValue;
    }
    }

    April 12, 2003

    Encryption/Decryption/hash implementation in C#

    Following is code snippet for Encryption/Decryption/hash implementation

    /// <summary>
    /// Encryption/Decryption/hash implementation
    /// </summary>
    internal class Security {

    private static int KEY_SIZE = 128;
    private static int KEY_SKIP_SIZE = 64;

    /// <summary>
    /// Encrypts the Message
    /// </summary>
    /// <param name="strMessageToEncrypt">Message to Encrypt</param>
    /// <param name="btSalt">Salt</param>
    /// <param name="strKey">Key</param>
    /// <param name="strHashAlgorithm">Hash Algorithm</param>
    /// <returns>Encrypted Message</returns>
    internal static string encryptMessage(string strMessageToEncrypt, byte[] btSalt, string strKey) {

    // Get input message in bytes
    byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(strMessageToEncrypt);

    // create a MemoryStream so that the process can be done without I/O files
    System.IO.MemoryStream ms = new System.IO.MemoryStream();

    // Get proper size key require for encryption
    byte[] bytKey = GetProperKey(strKey);

    RijndaelManaged objCryptoService = new RijndaelManaged();

    // set the private key and init vector
    objCryptoService.Key = bytKey;
    objCryptoService.IV = btSalt;

    // create an Encryptor from the Provider Service instance
    ICryptoTransform encrypto = objCryptoService.CreateEncryptor();

    // create Crypto Stream that transforms a stream using the encryption
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

    // write out encrypted content into MemoryStream
    cs.Write(bytIn, 0, bytIn.Length);
    cs.FlushFinalBlock();

    // convert into Base64 so that the result can be used in xml
    return System.Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
    }


    /// <summary>
    /// Decrypt Input Message
    /// </summary>
    /// <param name="strEncryptedMessage">Encrypted Message</param>
    /// <param name="btSalt">Salt</param>
    /// <param name="strKey">Key</param>
    /// <param name="strHashAlgorithm">Hash Algorithm</param>
    /// <returns>Decrypted Message</returns>
    internal static string decryptMessage(string strEncryptedMessage, byte[] btSalt,string strKey) {
    // convert from Base64 to binary
    byte[] bytIn = System.Convert.FromBase64String(strEncryptedMessage);
    // create a MemoryStream with the input
    System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);

    byte[] bytKey = GetProperKey(strKey);
    RijndaelManaged objCryptoService = new RijndaelManaged();
    // set the private key
    objCryptoService.Key = bytKey;
    objCryptoService.IV = btSalt;

    // create a Decryptor from the Provider Service instance
    ICryptoTransform encrypto = objCryptoService.CreateDecryptor();

    // create Crypto Stream that transforms a stream using the decryption
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);

    // read out the result from the Crypto Stream
    System.IO.StreamReader sr = new System.IO.StreamReader( cs );
    return sr.ReadToEnd();
    }

    /// <summary>
    /// Manipulates key size required for Encryption/Decryption algorithm
    /// </summary>
    /// <param name="Key">Sec Key</param>
    /// <returns>Fix size bytes require as a key</returns>
    private static byte[] GetProperKey(string Key) {
    string sTemp;
    int i = 0, reqSize = KEY_SIZE;
    // key sizes are in bits
    while (Key.Length * 8 > reqSize) {
    i = reqSize;
    reqSize += KEY_SKIP_SIZE;
    }
    sTemp = Key.PadRight(reqSize / 8, '*');

    // convert the secret key to byte array
    return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }

    }

    May 29, 2001

    Cryptography in .NET

    Secret-key encryption (symmetric cryptography)

    Performs a transformation on data, keeping the data from being read by third parties. This type of encryption uses a single shared, secret key to encrypt and decrypt data.

    .NET provides following Symmetric cAlgorithms (System.Security.Cryptography.SymmetricAlgorithm)


    • System.Security.Cryptography.DES
    • System.Security.Cryptography.RC2
    • System.Security.Cryptography.Rijndael
    • System.Security.Cryptography.TripleDES

    Public-key encryption (asymmetric cryptography)

    Performs a transformation on data, keeping the data from being read by third parties. This type of encryption uses a public/private key pair to encrypt and decrypt data.

    In .NET System.Security.Cryptography provides RSA and DSA asymmetric algorithms

    Digital Signatures

    Helps verify that data originates from a specific party by creating a digital signature that is unique to that party. This process also uses hash functions.

    The .NET Framework provides the following classes that implement digital signature algorithms:

    • DSACryptoServiceProvider
    • RSACryptoServiceProvider
    Cryptographic hashes

    Maps data from any length to a fixed-length byte sequence. Hashes are statistically unique; a different two-byte sequence will not hash to the same value.

    Message authentication code (MAC) hash functions are commonly used with digital signatures to sign data, while message detection code (MDC) hash functions are used for data integrity.

    The .NET Framework provides the following classes for hashing algorithms:
    • HMACSHA1
    • MACTripleDES
    • MD5CryptoServiceProvider
    • SHA1
    • Managed
    • SHA256Managed
    • SHA384Managed
    • SHA512 Managed