N342 Security and Risk

Modified

There are two sides to security from a Web developers viewpoint, the client and the server.

The client side issues fall into the following categories:

The server issues are generally:

Secure access

The success of many attacks is due to program flaws or poor implementation of security.

Securing access to data commonly includes verification of some form of user credentials, such as a login/password.

Further measures should include preventing common methods used to breach program or data integrity.

SQL Injection - http://en.wikipedia.org/wiki/SQL_injection

SQL injection can occur whenever user input, such as from a form, is directly used to construct a SQL statement.

Suppose the CartCommit.asp script accepted user entered text in an SQL statement:

username = Request("username");

rs = conn.Execute("SELECT * FROM Cart where ID='"+username+"'");

Ray as input results in SQL of:

SELECT * FROM Cart where ID='Ray'

O'Brien as input results in SQL of:

SELECT * FROM Cart where ID='O'Brien'

causing the SQL to fail and probably crash the program.

Other inputs could delete all the table records, note that -- is an SQL comment:

x'; DELETE FROM TRADER;--

SELECT * FROM Cart where ID='x'; DELETE FROM TRADER;--'

Attackers can easily determine if your programs are subject to SQL injection by making them fail. A little more effort and some lucky guesses can accomplish serious damage.

Note that the following, because no user input is used to construct the SQL statement, is not subject to SQL injection.

conn.Execute("DELETE FROM Portfolio WHERE SHARES=0");

The following seems safe because Session("trader") is a cookie, there is no direct user input.

conn.Execute("DELETE FROM Cart WHERE ID='"+Session("trader")+"'");

However, if user input was used directly when registering the trader SQL injection is still possible.

 

Variable binding

To deter injection, the fixed and variable parts of the SQL can be separated by the following:

var cmd = Server.CreateObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = "SELECT * FROM Cart WHERE ID = ?";
cmd.CommandType = 1;

// name, type, direction, size, value
cmd.Parameters.Append( cmd.CreateParameter ("ID", 200, 1, username.length, username));

rs = cmd.Execute();

See CreateParameters for further information.

The SQL is defined as the command text where the ? acts as a formal parameter in:

cmd.CommandText = "SELECT * FROM Cart WHERE ID = ?";

The user input is defined as an actual parameter username that replaces the ? at execution:

cmd.Parameters.Append( cmd.CreateParameter ("ID", 200, 1, username.length, username));

User input of:

'; DELETE FROM TRADER;--

would cause no issues, being processed as the ID value with quotes part of the value not delimiters, as:

SELECT * FROM Cart WHERE ID = '; DELETE FROM TRADER;--

 

Microsoft Access

Microsoft Access does not allow multiple SQL statements in a single input.

While preventing execution of:

SELECT * FROM Cart where ID='x'; DELETE FROM TRADER;--'

the statement would fail in Access and potentially crash the application.

 

Security Overview

Security consists of three interdependent elements:

·   Authentication as proof of identity.

We need to know a site claiming to be www.search.com actually is www.search.com.

Generally, we require some trusted third-party authority that can not only verify an identity but also ensure that the verification is trustworthy.

·   Encryption transforms an easily read message into a form that, without knowledge of the transformation, is more difficult to read.

Decryption transforms the encrypted message back to a readable form.

Caesar's Cipher is based on substituting each letter with one a fixed distance in the alphabet. For a distance of 2, the message: ABCD would be encrypted as:  CDEF

·   Verification determines whether the message has been received as it was sent; no tampering has occurred.

 

Resources:

 

VERIFICATION

    Hashing - Used to verify that the message sent is the message received.

A hash maps input (such as a message text) to some number.

For example, a modulus 256 hash could operate by:

Sum the byte values of the message, the sum will be a value between 0-255.

SHA-1 (Secure Hash Algorithm 1) developed by NSA processes 512-bit blocks to produce a 160-bit hash. Very difficult to change the message and produce the same hash.

Verification process:

Sender computes hash of message and sends along with message.

Receiver recomputes hash, if agree with sent hash assumed message verified.

    Verification by Hashing (Message Digest) - Used to verify that the message sent is the message received.

Sum the byte values of the message.

The hash (sum) will be a value between 0-255.

Sender computes hash of message and sends along with message.

Receiver recomputes hash of message, if agrees with sent hash assumed message verified.

 

    Microsoft File Checksum Integrity Verifier (FCIV) Utility

File Checksum Integrity Verifier (FCIV) is command-line utility that computes and generates MD5 or SHA-1 cryptographic hash values for files to compare the values against a known good value to verify that the files have not been changed.

Features of the FCIV utility:

  • Supports MD5 or SHA1 hash algorithms (The default is MD5.)
     
  • Can output hash values to the console or store the hash value and file name in an XML file.
     
  • Can recursively generate hash values for all files in a directory and in all subdirectories (for example, fciv.exe c:\ -r)
     
  • Supplies an exception list to specify files or directories to hash.
     
  • Can store hash values for a file with or without the full path of the file.

To display the MD5 hash of a file named readme.txt, type the following command at a command prompt:

fciv.exe readme.txt

79ac8d043dc8739f661c45cc33fc07ac readme.txt

To display the SHA-1 hash of a file, use the following command:

fciv.exe -sha1 readme.txt

2fe398f1ebced166087362626241b95efeaab407 readme.txt

 

Readme.txt

Microsoft (R) File Checksum Integrity Verifier V2.05 README file
================================================================

1.What is File Checksum Integrity Verifier (FCIV)?
2.Features.
3.Syntax.
4.Database storage format.
5.Verification.


1.What is fciv?
---------------
Fciv is a command line utility that computes and verifies hashes of files.

It computes a MD5 or SHA1 cryptographic hash of the content of the file.
If the file is modified, the hash is different.

With fciv, you can compute hashes of all your sensitive files.
When you suspect that your system has been compromised, you can run a verification to determine which files have been modified.
You can also schedule verifications regularily.

2.Features:
-----------
- Hash algorithm: MD5 , SHA1 or both ( default MD5).
- Display to screen or store hash and filename in a xml file.
- Can recursively browse a directory ( ex fciv.exe c:\ -r ).
- Exception list to specify files or directories that should not be computed.
- Database listing.
- hashes and signature verifications.
- store filename with or without full path.

3.Syntax:
---------
Usage:  fciv.exe [Commands] 

Commands: ( Default -add )

        -add     : Compute hash and send to output (default screen).

                dir options:
                -r       : recursive.
                -type    : ex: -type *.exe.
                -exc file: list of directories that should not be computed.
                -wp      : Without full path name. ( Default store full path)
                -bp      : base path. The base path is removed from the path name of each entry

        -list            : List entries in the database.

        -v               : Verify hashes.
                         : Option: -bp basepath.

        -? -h -help      : Extended Help.

Options:
        -md5 | -sha1 | -both    : Specify hashtype, default md5.
        -xml db                 : Specify database format and name.

To display the MD5 hash of a file, type fciv.exe filename

Compute hashes:
        fciv.exe c:\mydir\myfile.dll
        fciv.exe c:\ -r -exc exceptions.txt -sha1 -xml dbsha.xml
        fciv.exe c:\mydir -type *.exe
        fciv.exe c:\mydir -wp -both -xml db.xml

List hashes stored in database:
        fciv.exe -list -sha1 -xml db.xml

Verifications:
        fciv.exe -v -sha1 -xml db.xml
        fciv.exe -v -bp c:\mydir -sha1 -xml db.xml
        
4.Database storage format:
--------------------------
xml file.

The hash is stored in base 64.

5.Verification:
---------------
You can build a hash database of your sensitive files and verify them regularly or when you suspect that your system
has been compromised.

It checks each entry stored in the db and verify that the checksum was not modified.

 

    Using a hash (digest) to send a password to a server

  1. Create a message digest value from the clear-text password but do not send the password.

    An attacker could just steal the digest value, of course.

    Add some other data to the digest as well so that only the server, knowing the password, can recreate the same digest value.
     

  2. Client generates a timestamp and a random number and, along with the user name and the password, creates the message digest .
     
  3. Client sends the clear-text user name, the timestamp, the random number, and the digest value to the server.

    It does not send the password as clear-text, but the password was used to calculate the digest value.

     

  4. The server takes the user name and looks up the corresponding password (possibly a hash), which should be stored securely in a file or a database.

    The server repeats the client process, creating a digest value of the user name, password, timestamp, and random number.

     

  5. If the digest value created on the server matches the digest value sent by the client, then the server knows that only the user could have typed in the right password.

 

Question: Why the random number?

 


    Replay attacks

Replay attacks can occur when a man-in-the-middle captures a valid login sequence and later replays to the server.

The server needs some logic to prevent replay attacks.

Specifically, the server should reject login attempts that use timestamps and random numbers that have been used before with that login by:

  1. Save the timestamp of each user’s last login attempt.
     
  2. For each subsequent login attempt, the server looks up the saved timestamp.
     
  3. If the timestamp on the current attempt is more recent than the saved timestamp, the attempt is allowed.
     
  4. The current attempt’s timestamp replaces the saved timestamp for this user.
Question: What is to prevent the man-in-the-middle from changing the time-stamp?

 

ENCRYPTION/DECRYPTION

 

    Secret-key Cryptography - Used for secure data communications.

The same symmetric key encrypts and decrypts plain text message.

A secret-key example is Data Encryption Standard (DES) with a key length of 56 bits, considered too short for modern code breaking methods. Work is under way to improve its security.

The same symmetric key encrypts and decrypts plain text message.

Problem is that both sender and receiver must possess same key.

KDC

Kerberos protocol

 

Question: Why is a temporary session key used for networked communication?

 

Key Distribution Center from Microsoft

The Key Distribution Center (KDC) is implemented as a domain service. It uses the Active Directory as its account database and the Global Catalog for directing referrals to KDCs in other domains.

As in other implementations of the Kerberos protocol, the KDC is a single process that provides two services:

  • Authentication Service (AS)

    This service issues ticket-granting tickets (TGTs) for connection to the ticket-granting service in its own domain or in any trusted domain. Before a client can ask for a ticket to another computer, it must request a TGT from the authentication service in the client's account domain. The authentication service returns a TGT for the ticket-granting service in the target computer's domain. The TGT can be reused until it expires, but the first access to any domain's ticket-granting service always requires a trip to the authentication service in the client's account domain.

  • Ticket-Granting Service (TGS)

    This service issues tickets for connection to computers in its own domain. When clients want access to a computer, they contact the ticket-granting service in the target computer's domain, present a TGT, and ask for a ticket to the computer. The ticket can be reused until it expires, but the first access to any computer always requires a trip to the ticket-granting service in the target computer's account domain.

The KDC for a domain is located on a domain controller, as is the Active Directory for the domain. Both services are started automatically by the domain controller's Local Security Authority (LSA) and run as part of the LSA's process. Neither service can be stopped. If the KDC is unavailable to network clients, then the Active Directory is also unavailable—and the domain controller is no longer controlling the domain. The system ensures availability of these and other domain services by allowing each domain to have several domain controllers, all peers. Any domain controller can accept authentication requests and ticket-granting requests addressed to the domain's KDC.

The security principal name used by the KDC in any domain is "krbtgt", as specified by RFC 1510. An account for this security principal is created automatically when a new domain is created. The account cannot be deleted, nor can the name be changed. A password is assigned to the account automatically and is changed on a regular schedule, as are the passwords assigned to domain trust accounts. The password for the KDC's account is used to derive a cryptographic key for encrypting and decrypting the TGTs that it issues. The password for a domain trust account is used to derive an inter-realm key for encrypting referral tickets.

All instances of the KDC within a domain use the domain account for the security principal "krbtgt". Clients address messages to a domain's KDC by including both the service's principal name, "krbtgt", and the name of the domain. Both items of information are also used in tickets to identify the issuing authority. For information on name forms and addressing conventions, see RFC 1510.

 

    Public-key Cryptography - Avoids the secret-key problem of exchanging a common key. Diagram of encryption and decryption

Based on a private key and an inverse public key.

The public key is used by the sender to encrypt a message to the receiver, the receiver applies their private key to decrypt the message.

An example public key might be to square each piece of a message, the private key would be the inverse, to take the square root of each piece. For example, square to encrypt the message 2 3 4 as 4 9 16 and send, decrypt 4 9 16 using the square root as 2 3 4.

Generally a key is generated as the composition of two large prime numbers which are needed for encryption and are difficult to determine given the key itself.

When both sender and receiver have public keys, the sender can sign a message using their private key and the receiver decrypt the signature using the sender's public key to verify the origin.

Problem:

Third party could intercept messages, replace with own. Receiver needs to verify message was not tampered.

Solution:

Sender computes message hash, signs hash with private key. Sends message and hash.

Receiver applies sender's public key to hash, recomputes hash of message, if agree message verified. Note that only the sender could have signed a hash readable using their public key.

Example

x = f(x)1/2 = (x2)1/2
 

Keys

Generally a public key is generated as the composition of two large prime numbers which are needed for encryption and are difficult to determine given the key itself.

Signing

Both sender and receiver have public keys.

Sender can sign a message using their private key.

Sender encrypts message and signature using receiver's public key.

Receiver decrypts message using their private key.

Receiver reads signature using the sender's public key to verify the origin.

Verification

Third party could intercept messages, replace with own using receiver's public key.

Receiver needs to verify message was not tampered.

Sender computes message hash, signs hash with private key.

Receiver applies sender's public key to hash, recomputes hash of message, if agree message verified.

   

    Certification Authorities (CA) - Certify that one is who they claim, that a public key is associated with a given site. 

  1. site's public key
     
  2. a hash of the certificate
     
  3. CA's own signature generated using the CA's private key

 

Data Security

Protection of personal or sensitive data is commonly required by law. There are several basic approaches to protecting data on the server or personal machine:

  1. Restrict access of directories containing sensitive files to only those users or applications requiring access.
  2. Encrypt data. Most operating systems (including Microsoft) support data encryption.

    Microsoft

Files or folders can be encrypted and automatically decrypted by the owner, non-owners must supply the encryption key. Details are at: http://www.microsoft.com/windowsxp/using/security/learnmore/encryptdata.mspx

    PGP

PGP (Pretty Good Privacy) originated as public-domain software to encrypt/decrypt communications and file encryption using public/private and symmetric and asymmetric keys. A freeware version is available at: http://www.pgp.com/downloads/index.html 

 

Network Security

    Security Holes

    Security Protocols

Secure Socket Layer (SSL) is a standard protocol based on public key technology, certificates and secret-keys.

Transport Layer Security (TLS) succeeded SSL.

Hypertext Transfer Protocol Secure (HTTPS)

A Secure Transaction

Public key cryptography keys must be long for security, since attackers have lots of time and public keys must not change often.

Encryption/decryption is slow using long keys.

Using a one-time, smaller secret key for encryption allows for a faster conversion.

Still computationally difficult for attackers to determine message.

To conduct a secure transaction:

  1. a customer contacts a commercial site server and sends a random number
     
  2. site sends own random number and its certificate containing public key
     
  3. the customer verifies the certificate authenticity through a CA, often the CA verification data is stored on customer computer.
     
  4. negotiates a new secret key with the server using the public key
    • the customer sends a 384-bit premaster key encrypted by site's public key.
    • secret-key derived using the two random numbers and premaster key.
       
  5. Secure communication is then conducted using the shared secret-key for encryption/decryption and a hash for message integrity.

TLS Handshake - from http://en.wikipedia.org/wiki/Secure_Sockets_Layer

A TLS client and server negotiate a stateful connection by using a handshaking procedure.

During this handshake, the client and server agree on various parameters used to establish the connection's security.

  • The handshake begins when a client connects to a TLS-enabled server requesting a secure connection, and presents a list of supported ciphers and hash functions.
     
  • From this list, the server picks the strongest cipher and hash function that it also supports and notifies the client of the decision.
     
  • The server sends back its identification in the form of a digital certificate.
     
  • The certificate usually contains the server name, the trusted certificate authority (CA), and the server's public encryption key.

The client may contact the server that issued the certificate (the trusted CA as above) and confirm that the certificate is authentic before proceeding.

  • In order to generate the session keys used for the secure connection, the client encrypts a random number (RN) with the server's public key (PbK), and sends the result to the server.
     
  • Only the server can decrypt it (with its private key (PvK)): this is the one fact that makes the keys hidden from third parties, since only the server and the client have access to this data.
     
  • The client knows PbK and RN, and the server knows PvK and (after decryption of the client's message) the RN.
     
  • A third party may only know PbK, unless PvK has been compromised.
     
  • From the random number, both parties generate symmetric key for encryption and decryption using the agreed upon cipher.

This concludes the handshake and begins the secured connection, which is encrypted and decrypted with the symmetric key until the connection closes.

If any one of the above steps fails, the TLS handshake fails, and the connection is not created.

 

    HTTPS - HTTP over Secure connection

HTTP over a secure connection such as TLS.

Client authentication

Question:
  1. What port is used for HTTP?
     
  2. What port is used for HTTPS?
     
  3. Are URLs encrypted under HTTPS?
     
  4. Must login data be encrypted when sent over HTTP?
     
  5. Must login data be encrypted when sent over HTTPS?

Strong encryption

Message-driven applications

Example

In establishing a secure connection, IE attempts to verify the certificate. On failure, it displays this familiar popup.

 

About Encryption

Excerpted from Microsoft IIS 5.1 Documentation

Sensitive information transmitted across an unsecured network can potentially be intercepted by a computer vandal. For this reason, if you plan to provide users with access to Web sites that process sensitive financial or personal information, you need to protect your network links with encryption.

    How Encryption Works

Encryption is the process of scrambling information by applying a mathematical function in such a way that it is extremely difficult for anyone other than an intended recipient to retrieve the original information. Central to this process is a mathematical value, called a key, which is used by the function to scramble the information in a unique and complex way.

Your Web server uses essentially the same encryption process to secure communication links with users. After establishing a secure link, a special session key is used by both your Web server and the user's Web browser to both encrypt and decrypt information. For example, when an authenticated user attempts to download a file from a Web site requiring a secure channel, your Web server uses a session key to encrypt the file and related HTTP headers. After receiving the encrypted file, the Web browser then uses a copy of the same session key to recover the file.

This method of encryption, although secure, has an inherent drawback: During the process of creating a secure link, a copy of the session key might be transmitted across an unsecured network. This means that a computer vandal intent on compromising the link need only intercept and steal the session key. To safeguard against this possibility, however, your Web server implements an additional method of encryption.

    Public Key Encryption

Your Web server's Secure Sockets Layer (SSL) security feature utilizes a technique known as public key encryption to shield the session key from interception during transmission. Public key encryption, which involves the use of two additional keys, a private and a public key, works in the following manner:

  1. The user's Web browser establishes a secure (https://) communication link with your Web server.
  2. The user's Web browser and your server engage in negotiation to determine the degree of encryption to use for securing communications.
  3. Your Web server sends the browser its public key.
  4. The Web browser encrypts information used in generating a session key with the server's public key and sends it to the server.
  5. Using the private key, your server decrypts the message, generates a session key, encrypts it with the public key, and sends it to the browser.
  6. Your Web server and the browser both use the session key to encrypt and decrypt transmitted data.

Diagram of encryption and decryption

Notice that the private key serves an important role in ensuring that your communication link remains secure. You should take every reasonable precaution to protect the private key from loss or theft. You can back up your certificate by copying it to floppy disk and keeping it in a safe place. Likewise, if you suspect that your private key has been compromised, notify your certification authority, use the Web Server Certificate Wizard to create a new certificate request, and then obtain a new server certificate.

    Session Key Encryption Strength

A session key's strength is proportional to the number of binary bits comprising the session key file. This means that session keys with a greater number of bits have a greater degree of security, and are considerably more difficult to forcibly decode.

When a user attempts to establish a secure communication channel with your Web server, the user's browser must negotiate the strongest possible level of encryption, or session key strength, that can be used to secure communications over that channel. This means that both your Web server and the user's browser must be equipped with compatible session key encryption and decryption capabilities. For example, when you configure your Web server to require a session key with a minimum 40-bit (default) encryption strength, a user attempting to secure a connection must have a Web browser capable of processing information with a 40-bit session key.

 

How to use makecert.exe to create a self-signed test certificate that can be used with IIS for SSL

Problem: Special options must be specified with makecert.exe, to create a self-signed certificate that can be used with IIS (Microsoft Internet Information Server).

Note: Microsoft recommends to install and use the "Certificate Server" to generate an SSL test certificate (Q216907), instead of using makecert.exe. But using makecert is simpler.

Solution:

The following command can be used to create and import a self-signed SSL test certificate:

makecert -r -pe -n "CN=www.yourserver.com" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

To install this certificate in IIS 5.0, open the IIS "Web Site Properties", "Directory Security", "Server Certificate...", "Assign an existing certificate" and select the new certificate from the list.

Note: Older versions of makecert.exe do not support the "-pe" option, which makes the private key exportable. If you have an old version of makecert.exe, you can omit the "-pe" option, but then the certificate cannot be exported including the private key.

(Visual Studio contains makecert.exe (5.131) that supports the "-pe" option. The .NET Framework SDK 1.0 of 2002-03-19 contains an old version of makecert.exe that does not support the "-pe" option).

If the private key is exportable, you can export the certificate together with the private key into a PFX (PKCS #12) file as described in Q232136.

Note: SSL server certificates for IIS are stored in the "Personal" ("My") certificate store of the "computer account" ("localMachine"). The "Certificates" snap-in of the Microsoft Management Console (mmc.exe) must be used to manage these certificates. The normal certificate management window (accessible via "Internet Properties" / "Content" / "Certificates" or via "Control Panel" / "Users and Passwords" / "Advanced" / "Certificates") cannot be used.

Note: To create a key with more than 512 bits, use the "-len" parameter of makecert.exe.

Author: Christian d'Heureuse (chdh@inventec.ch)

Exercise 0 - SSL

The following will install and test the use of SSL using self-signed certificates.

  1. The makecert.exe utility is installed with .NET SDK.
  2. Open a Command prompt window and enter:
    makecert -r -pe -n "CN=localhost" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
  3. To install this certificate in IIS 5.0:
    • Start | Run | Control | Administration Tools | Internet Information Services | Default Web Site Properties |
      Directory Security | Server Certificate | Assign an existing certificate... | Select the new certificate from the list
  4. To test that SSL is in use between the server and browser, enter in the browser address bar:
    • https://localhost/project/Welcome.xml
 

Servers

Server configuration is an administration problem that varies from one server to another, setting promiscuous access rights to files or directories can compromise the system. There are security scanners available that probe for known holes in server software, since intruders also probe potential victims with the same scanners, its advisable to check it yourself before someone else does. Popular scanners are: COPS, TAMU, SATAN (from an IU CSCI dropout), and ISS.

Hosts