Search This Blog

Thursday, November 26, 2009

Credit Card Validation

"""
    Provides functions & Fields for validating credit card numbers
    Thanks to David Shaw for the Luhn Checksum code 
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/172845)
"""

import re        
from django import newforms as forms

import datetime
        
def ValidateLuhnChecksum(number_as_string):
    """ checks to make sure that the card passes a luhn mod-10 checksum """

    sum = 0

    num_digits = len(number_as_string)
    oddeven = num_digits & 1

    for i in range(0, num_digits):
        digit = int(number_as_string[i])

        if not (( i & 1 ) ^ oddeven ):

            digit = digit * 2
        if digit > 9:

            digit = digit - 9

        sum = sum + digit

        
    return ( (sum % 10) == 0 )

# Regex for valid card numbers
CC_PATTERNS = {
    'mastercard':   '^5[12345]([0-9]{14})$',
    'visa':         '^4([0-9]{12,15})$',

}

def ValidateCharacters(number):
    """ Checks to make sure string only contains valid characters """
    return re.compile('^[0-9 ]*$').match(number) != None

        
def StripToNumbers(number):
    """ remove spaces from the number """
    if ValidateCharacters(number):

        result = ''
        rx = re.compile('^[0-9]$')

        for d in number:
            if rx.match(d):

                result += d
        return result
    else:
        raise Exception('Number has invalid digits')

def ValidateDigits(type, number):
    """ Checks to make sure that the Digits match the CC pattern """
    regex = CC_PATTERNS.get(type.lower(), False)

    if regex:
        return re.compile(regex).match(number) != None

    else:
        return False

def ValidateCreditCard(type, number):

    """ Check that a credit card number matches the type and validates the Luhn Checksum """
    type = type.strip().lower()
    if ValidateCharacters(number):

        number = StripToNumbers(number)
        if CC_PATTERNS.has_key(type):

            return ValidateDigits(type, number)
            return ValidateLuhnChecksum(number)

    return False

class CreditCardNumberField(forms.CharField):
    """ A newforms widget for a creditcard number """

    def clean(self, value):
        
        value = forms.CharField.clean(self, value)

        if not ValidateCharacters(value):
            raise forms.ValidationError('Can only contain numbers and spaces.')

        value = StripToNumbers(value)
        if not ValidateLuhnChecksum(value):

            raise forms.ValidationError('Not a valid credit card number.')
        
        return value


class CreditCardExpiryField(forms.CharField):
    """ A newforms widget for a creditcard expiry date """
    def clean(self, value):     
        value = forms.CharField.clean(self, value.strip())

        
        # Just check MM/YY Pattern
        r = re.compile('^([0-9][0-9])/([0-9][0-9])$')
        m = r.match(value)

        if m == None:
            raise forms.ValidationError('Must be in the format MM/YY. i.e. "11/10" for Nov 2010.')

        
        # Check that the month is 1-12
        month = int(m.groups()[0])

        if month < 1 or month > 12:
            raise forms.ValidationError('Month must be in the range 1 - 12.')

        
        # Check that the year is not too far into the future
        year = int(m.groups()[1])

        curr_year = datetime.datetime.now().year % 100

        max_year = curr_year + 10
        if year > max_year or year < curr_year:

            raise forms.ValidationError('Year must be in the range %s - %s.' % (str(curr_year).zfill(2), str(max_year).zfill(2),))

        return value   

# An example Form based on ModelForm.
class PaymentForm(forms.ModelForm):    
    cc_number = creditcards.CreditCardNumberField(required=False)

    cc_expiry = creditcards.CreditCardExpiryField()
   
    class Meta:
        model = Payment 
    
    """

        This function checks that the card number matches the card type.  
        If you don't want to do this, comment out this function.
    """
    def clean(self):

        if self.cleaned_data:
            if len(self.cleaned_data.items()) == len(self.fields):      
                if self.cleaned_data['method'] == 'cc':

                    the_type = self.cleaned_data.get('cc_type', '')

                    number = self.cleaned_data.get('cc_number', '')

                    if not ValidateDigits(the_type, number):
                        raise forms.ValidationError('Card Number is not a valid ' + the_type.upper() + ' card number.')

                    if not self.instance.is_payment_valid():
                        raise forms.ValidationError('Credit card payment could not be processed.  Reason is %s.  Check that card details are correct and try again.  If you still receive this error, check with your financial institution.' % (self.instance.gateway_resptxt))

        return self.cleaned_data

Tuesday, November 3, 2009

Snort

Snort is a versatile, lightweight and very useful intrusion detection system. In this article we will look at Snort as a backup Intrusion Detection System for your enterprise network and see whether it can really scale up to the requirements of your enterprise networks.

Our failure establishes only this,
that our determination to succeed
wasn't strong enough.
--Bovee


The main distribution site for Snort is http://www.snort.org. Snort is distributed under the GNU GPL license by the author Martin Roesch. Snort is a lightweight network IDS, capable of performing real-time traffic analysis and packet logging on IP networks. It can perform protocol analysis, content searching/matching. It can be used to detect a variety of attacks and probes, such as buffer overflows, stealth port scans, CGI attacks, SMB probes, OS fingerprinting attempts, and more. Snort uses a flexible rules language to describe traffic that it should collect or pass, and includes a detection engine utilizing a modular plug-in architecture. Snort has real-time alerting capability as well, incorporating alerting mechanisms for Syslog, user- specified files, a UNIX socket, or WinPopup messages to Windows clients using Samba's smbclient. Snort has three primary uses. It can be used as a straight packet sniffer like tcpdump or as a packet logger that is useful for network traffic debugging. It can also be used as a full blown network intrusion detection system.
Snort logs packets in either tcpdump binary format or in Snort's decoded ASCII format to logging directories that are named based on the IP address of the foreign host.
Plug-ins allow the detection and reporting subsystems to be extended. Available plug-ins include database logging, small fragment detection, portscan detection, and HTTP URI normalization.

The ground that we will be covering with respect to Snort will be
- Snort as a straight packet sniffer like tcpdump.
- Snort as a packet logger. Useful for network traffic debugging etc.
- Snort as a full blown network intrusion detection system.

Compiling and installing Snort
Having downloaded Snort, untar the archive with the following command.
bash# tar -xvzf snort-1.6.3.tar.gz

This should do the trick and get it untarred into a directory snort-1.6.3. Having done this, next on the cards is a dependency check for various libraries and header files that Snort needs. You'll need to ensure that you have the sources for libcap. If not, you can download it from ftp://ftp.ee.lbl.gov/libpcap.tar.Z.
Download the libcap headers and untar the archive using the tar command with the similar switches as mentioned above. Enter the directory and carry out the following steps.
bash# ./configure
bash# make
Though we do not need any of the binaries, this is just a precautionary measure. Now, we'll compile Snort. Change into the directory in which Snort lies and issue the following command.
bash# ./configure --with-libpcap-includes=/path/to/your/libcap/headers
bash# make
bash# make install
Using
Now Snort is installed on your system. Let's start using Snort on your system. We'll start with the basics of using Snort as a Packet Sniffer and a Packet Analyser. Apart from running in a promiscuous mode, we will also discover rules that will help us log alerts to our Snort logs or redirect them to syslog.
Using Snort as a packet sniffer and packet analyzer is a pretty simple process. The man pages are very helpful as far as information regarding using Snort is concerned. Let's basically start with a simple command that makes Snort display all the command switches and then exit.
bash# snort -?

The output of the command is as follows.
-*> Snort! <*-
Version 1.6.3
By Martin Roesch (roesch@clark.net, www.snort.org)
USAGE: snort [-options]
Options:
-A Set alert mode: fast, full, or none (alert file alerts only)
'unsock' enables UNIX socket logging (experimental).
-a Display ARP packets
-b Log packets in tcpdump format (much faster!)
-c Use Rules File
-C Print out payloads with character data only (no hex)
-d Dump the Application Layer
-D Run Snort in background (daemon) mode
-e Display the second layer header info
-F Read BPF filters from file
-g Run snort gid as 'gname' user or uid after initialization
-h Home network =
-i Listen on interface
-l Log to directory
-n Exit after receiving packets
-N Turn off logging (alerts still work)
-o Change the rule testing order to Pass|Alert|Log
-O Obfuscate the logged IP addresses
-p Disable promiscuous mode sniffing
-P set explicit snaplen of packet (default: 1514)
-q Quiet. Don't show banner and status report
-r Read and process tcpdump file
-s Log alert messages to syslog
-S Set rules file variable n equal to value v
-t Chroots process to after initialisaton
-u Run snort uid as 'uname' user (or uid) after initialization
-v Be verbose
-V Show version number
-? Show this information
are standard BPF options, as seen in TCPDump

Let's check out the next command wherein we set Snort to a verbose display of the packets sniffed and analyzed. The '-v' switch elicits a verbose response to Stdout. The '-d' switch elicits dumping the decoded application layer data and while '-e' shows the decoded ethernet headers. The '-i' switch specifies the interface to be monitored for packet analysis. The '-h' switch specifies which class of network packets has to be captured. e.g. - The command given below captures all the packets belonging to the class C internal IP's of the type 192.168.1.*.
freeos:~ # snort -v -d -e -i eth0 -h 192.168.1.0/24

If we wanted to generate alerts, the '-A' switch is of importance to us.
-A - Alert using the specified alert-mode. Valid alert modes include 'fast', 'full', 'none', and 'unsock'. Fast, writes alerts to the default 'alert' file in a single-line, syslog style alert message. Full, writes the alert to the 'alert' file with the full decoded header as well as the alert message. The command will then change to the following.
freeos:~ # snort -v -d -e -i eth0 -h 192.168.1.0/24 -A fast

Instead, if you wanted to send alert messages to the syslog daemon, you could use the '-s' switch instead.
-s - Send alert messages to Syslog. On Linux boxes, they will appear in /var/log/secure or /var/log/messages on many other platforms.
freeos:~ # snort -v -d -e -i eth0 -h 192.168.1.0/24 -s
Until now we haven't seen any actual logging taking place. All the packets sniffed and analyzed were just dumped to your screen. To have Snort dump the packets sniffed and analyzed to your logs, you will use the "-l" switch. That dumps all the data, regarding the packets analysed, to the directory log in the current path. You will have to create this directory. Do not expect Snort to create it at runtime.
freeos:~ # snort -v -d -e -i eth0 -h 192.168.1.0/24 -A full -l ./log
But, there is an inherent drawback to this type of packet analysis and reporting. One of the foremost problems that may be encountered can be visualized as follows. Assuming that you are using Snort on your Gigabit ethernet. The speed at which data will be flowing across the network is too much for your NIC working in promiscous mode. Many packets will be dumped because it may not be possible to keep up the pace of analyzing the large amount of high speed data transfers across your network segment. Thus, instead if using the "-l" switch you should use the "-b" switch. This will log packets in tcpdump format and produce minimal alerts. For example:
freeos:~ # snort -b -i eth0 -A fast -h 192.168.1.0/24 -s -l ./log
In this configuration, Snort has been able to log multiple simultaneous probes and attacks on a 100 Mbps LAN running at a saturation level of approximately 80 Mbps. In this configuration the logs are written in binary format to log in tcpdump format. To read this file back and break out the data in the familiar Snort format, just re-run Snort on the data file with the "-r" option and the other options you would normally use.

freeos:~ # snort -i eth0 -l ./log -h 192.168.1.0/24 -A fast -r ./log/snort-123@1016.log
This command deciphers the tcpdump-formatted log file ./log/snort-0123@1016.log and dumps the output in the normal Snort log format in the ./log directory.

This kind of packet sniffing and analysis causes Snort to log all the packets on your network segment. But what if you wanted to log only certain type of packets. Yes, of course, there is a way out. Snort allows you to define your own rules for packet analysis. Use the '-c' command switch for this.
freeos:~ # snort -b -i eth0 -A fast -h 192.168.1.0/24 -s -l ./log -c ./rules.snort
For various rulesets that could be used along with Snort, take a look at http://www.snort.org/snort_rules.html.
Here ends our look at Snort. Following up will be another article that will help you ascertain the dangers that your system logs are prone to and the security measures you can put into place to prevent tampering of your precious system logs in case of a security breach.

Don't let life discourage you;
Everyone who got where he is
had to begin where he was.
-Richard L Evans

tmpwatch - removes files which haven't been accessed for a period of time

tmpwatch recursively removes files which haven't been accessed for a given number of hours. Normally, it's used to clean up directories which are used for temporary holding space such as /tmp.
When changing directories, tmpwatch is very sensitive to possible race conditions and will exit with an error if one is detected. It does not follow symbolic links in the directories it's cleaning (even if a symbolic link is given as its argument), will not switch filesystems,
 and only removes empty directories and regular files. 
By default, tmpwatch dates files by their atime (access time), not their mtime (modification time). If files aren't being removed when ls -l implies they should be, use ls -u to examine their atime to see if that explains the problem.
If the --atime, --ctime or --mtime options are used in combination, the decision about deleting a file will be based on the maximum of this times.
The hours parameter defines the threshold for removing files. If the file has not been accessed for hours hours, the file is removed. Following this, one or more directories may be given for tmpwatch to clean up.

 

OPTIONS

-u, --atime
Make the decision about deleting a file based on the file's atime (access time). This is the default.
 
-m, --mtime
Make the decision about deleting a file based on the file's mtime (modification time) instead of the atime.
-c, --ctime
Make the decision about deleting a file based on the file's ctime (inode change time) instead of the atime; for directories, make the decision based on the mtime.
-a, --all
Remove all file types, not just regular files and directories.
-d, --nodirs
Do not attempt to remove directories, even if they are empty.
-f, --force
Remove files even if root doesn't have write access (akin to rm -f).
-t, --test
Doesn't remove files, but goes through the motions of removing them. This implies -v.
-s, --fuser
Attempt to use the "fuser" command to see if a file is already open before removing it. Not enabled by default. Does help in some circumstances, but not all. Dependent on fuser being installed in /sbin.
-v, --verbose
Print a verbose display. Two levels of verboseness are available -- use this option twice to get the most verbose output.
 

SEE ALSO

cron(1), ls(1), rm(1), fuser(1)
 
Example:
You may need to use a command called tmpwatch which removes files which haven’t been accessed for a period of time. Normally, it’s used to clean up directories which are used for temporary holding space such as /tmp. Following code will remove all files/dirs from /tmp if they are not accessed in last 2 weeks (24 * 14 days = 336)
Code:
tmpwatch --mtime --all 336 /tmp
 

Saturday, October 24, 2009

Send an HTML email with embedded image and plain text alternate

Recipe 473810: Send an HTML email with embedded image and plain text alternate




HTML is the method of choice for those wishing to send emails with rich text, layout and graphics. Often it is desirable to embed the graphics within the message so recipients can display the message directly, without further downloads.

Some mail agents don't support HTML or their users prefer to receive plain text messages. Senders of HTML messages should include a plain text message as an alternate for these users.

This recipe sends a short HTML message with a single embedded image and an alternate plain text message.





Python
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.

from email.MIMEMultipart import MIMEMultipart

from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

# Define these once; use them twice!
strFrom = 'from@example.com'
strTo = 'to@example.com'

# Create the root message and fill in the from, to, and subject headers

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'

msgRoot['From'] = strFrom
msgRoot['To'] = strTo

msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')

msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')

msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')

msgAlternative.attach(msgText)

# This example assumes the image is in the current directory
fp = open('test.jpg', 'rb')

msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.example.com')

smtp.login('exampleuser', 'examplepass')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())

smtp.quit()




Discussion



While the practice of embedding images within the message provides a better experience for many users than linking to web-hosted images does it is important to consider the impact this has on message size and consequently on message download time.

An alternative implementation for sending HTML messages is provided in this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083, though it doesn't address embedding images and was written before the email package was incorporated into Python. The email package and its MIME-handling capabilities significantly reduce the amount of code required.



Thursday, October 8, 2009

CAPTCHA: "Completely Automated Public Turing test to Tell Computers and Humans Apart"

CAPTCHA: Telling Humans and Computers Apart Automatically


A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown below, but current computer programs can't:


The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.


Get a Free CAPTCHA For Your Site


A free, secure and accessible CAPTCHA implementation is available from the reCAPTCHA project. Easy to install plugins and controls are available for WordPress, MediaWiki, PHP, ASP.NET, Perl, Python, Java, and many other environments. reCAPTCHA also comes with an audio test to ensure that blind users can freely navigate your site. reCAPTCHA is our officially recommended CAPTCHA implementation.

Test Drive a CAPTCHA

  • reCAPTCHA. Stop spam and help digitize books at the same time! The words shown come directly from old books that are being digitized.
  • SQUIGL-PIX. Our newest CAPTCHA!
  • ESP-PIX. A CAPTCHA script that's close to our hearts. Instead of typing letters, you authenticate yourself as a human by recognizing what object is common in a set of images. This was the first example of a CAPTCHA based on image recognition.

    Below is an example for Embedding a sample Captcha in a CGi FIle.


    #!/usr/bin/env python

    ######### don't change the following three lines: ###########
    import cgi
    import cgitb;cgitb.enable()
    import time
    from recaptcha.client import captcha

    publickey = "<publickey>"
    privatekey = "<privatekey>"


    print "Content-Type: text/html\n\n"
    print '''
    <html>
    <head>
    <title>NO BOTS</title>
    </head>
    <body>
    <form action="<ur cgi validator>" method="post">
    <h2>Prove you are not a BOT</h2>
    <script type="text/javascript" src="http://api.recaptcha.net/challenge?k=''' + publickey + '''"></script>
    <noscript>
    <iframe src="http://api.recaptcha.net/noscript?k=''' + publickey + '''" height="300" width="500" frameborder="0"></iframe><br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
    </textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
    </noscript>
    <input type = "submit" value = "Go">
    </form>
    </body>
    </html>
    '''


    Below is an example for validating a Captcha in a CGi FIle.


    #!/usr/bin/env python

    ######### don't change the following three lines: ###########
    import cgi
    import cgitb;cgitb.enable()
    import time
    from recaptcha.client import captcha


    publickey = "<publickey>"
    privatekey = "<privatekey>"

    print "Content-Type: text/html\n\n"
    form = cgi.FieldStorage()

    response = captcha.submit(
            form.getvalue("recaptcha_challenge_field"),
            form.getvalue('recaptcha_response_field'),
            privatekey,
            "192.168.20.68",
            )

    if not response.is_valid:
            print '''
            <html>
                    <head>
                            <title>U BOTS</title>
                    </head>
                    <body>
                            <form action="<cgi captcha validator>" method="post">
                            <h2>YOU ARE A BOT!!!!!!!!!!!!!!</h2>
                            <h3>Else Try Again</h3>
                            <script type="text/javascript" src="http://api.recaptcha.net/challenge?k=''' + publickey + '''"></script>
                            <noscript>
                                    <iframe src="http://api.recaptcha.net/noscript?k=''' + publickey + '''" height="300" width="500" frameborder="0"></iframe><br>
                                    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
                                    </textarea>
                                    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
                            </noscript>
                            <input type = "submit" value = "Go">
                            </form>
                    </body>
            </html>
            '''
    else:
            print '''
            <html>
                    <head>
                            <title>Hurray ur not a BOT </title>
                    </head>
                    <body>
                            <form action="<cgi captcha validator>" method="post">
                            <h2>Hurray!!!!!!!!!!!!!!<br> :) you are A Human ;-)</h2>
                            <h3>You can Try Again Human</h3>
                            <script type="text/javascript" src="http://api.recaptcha.net/challenge?k=''' + publickey + '''"></script>
                            <noscript>
                                    <iframe src="http://api.recaptcha.net/noscript?k=''' + publickey + '''" height="300" width="500" frameborder="0"></iframe><br>
                                    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
                                    </textarea>
                                    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
                            </noscript>
                            <input type = "submit" value = "Go">
                            </form>
                    </body>
            </html>
            '''



Thursday, August 20, 2009

Introduction to Public-Key Cryptography

Introduction to Public-Key Cryptography

Public-key cryptography and related standards and techniques underlie security features of many Netscape products, including signed and encrypted email, form signing, object signing, single sign-on, and the Secure Sockets Layer (SSL) protocol. This document introduces the basic concepts of public-key cryptography

Internet Security Issues

Encryption and Decryption

Digital Signatures

Certificates and Authentication

Managing Certificates

Internet Security Issues All communication over the Internet uses the Transmission Control Protocol/Internet Protocol (TCP/IP). TCP/IP allows information to be sent from one computer to another through a variety of intermediate computers and separate networks before it reaches its destination. The great flexibility of TCP/IP has led to its worldwide acceptance as the basic Internet and intranet communications protocol. At the same time, the fact that TCP/IP allows information to pass through intermediate computers makes it possible for a third party to interfere with communications in the following ways:
  • Eavesdropping. Information remains intact, but its privacy is compromised. For example, someone could learn your credit card number, record a sensitive conversation, or intercept classified information.
  • Tampering. Information in transit is changed or replaced and then sent on to the recipient. For example, someone could alter an order for goods or change a person's resume.
  • Impersonation. Information passes to a person who poses as the intended recipient. Impersonation can take two forms:
    • Spoofing. A person can pretend to be someone else. For example, a person can pretend to have the email address
    • jdoe@mozilla.com, or a computer can identify itself as a site called www.mozilla.com when it is not. This type of impersonation is known as spoofing.
    • Misrepresentation. A person or organization can misrepresent itself. For example, suppose the site
    • www.mozilla.com pretends to be a furniture store when it is really just a site that takes credit-card payments but never sends any goods.
Normally, users of the many cooperating computers that make up the Internet or other networks don't monitor or interfere with the network traffic that continuously passes through their machines. However, many sensitive personal and business communications over the Internet require precautions that address the threats listed above. Fortunately, a set of well-established techniques and standards known as public-key cryptography make it relatively easy to take such precautions.

Public-key cryptography facilitates the following tasks:

  • Encryption and decryption allow two communicating parties to disguise information they send to each other. The sender encrypts, or scrambles, information before sending it. The receiver decrypts, or unscrambles, the information after receiving it. While in transit, the encrypted information is unintelligible to an intruder.
  • Tamper detection allows the recipient of information to verify that it has not been modified in transit. Any attempt to modify data or substitute a false message for a legitimate one will be detected.
  • Authentication allows the recipient of information to determine its origin--that is, to confirm the sender's identity.
  • Nonrepudiation prevents the sender of information from claiming at a later date that the information was never sent.
The sections that follow introduce the concepts of public-key cryptography that underlie these capabilities.

Encryption and Decryption

Encryption is the process of transforming information so it is unintelligible to anyone but the intended recipient. Decryption is the process of transforming encrypted information so that it is intelligible again. A cryptographic algorithm, also called a cipher, is a mathematical function used for encryption or decryption. In most cases, two related functions are employed, one for encryption and the other for decryption. With most modern cryptography, the ability to keep encrypted information secret is based not on the cryptographic algorithm, which is widely known, but on a number called a key that must be used with the algorithm to produce an encrypted result or to decrypt previously encrypted information. Decryption with the correct key is simple. Decryption without the correct key is very difficult, and in some cases impossible for all practical purposes. The sections that follow introduce the use of keys for encryption and decryption. Symmetric-Key Encryption Public-Key Encryption Key Length and Encryption Strength

Symmetric-Key Encryption

With symmetric-key encryption, the encryption key can be calculated from the decryption key and vice versa. With most symmetric algorithms, the same key is used for both encryption and decryption, as shown in Figure 1.

Figure 1 Symmetric-key encryption

Implementations of symmetric-key encryption can be highly efficient, so that users do not experience any significant time delay as a result of the encryption and decryption. Symmetric-key encryption also provides a degree of authentication, since information encrypted with one symmetric key cannot be decrypted with any other symmetric key. Thus, as long as the symmetric key is kept secret by the two parties using it to encrypt communications, each party can be sure that it is communicating with the other as long as the decrypted messages continue to make sense. Symmetric-key encryption is effective only if the symmetric key is kept secret by the two parties involved. If anyone else discovers the key, it affects both confidentiality and authentication. A person with an unauthorized symmetric key not only can decrypt messages sent with that key, but can encrypt new messages and send them as if they came from one of the two parties who were originally using the key. Symmetric-key encryption plays an important role in the SSL protocol, which is widely used for authentication, tamper detection, and encryption over TCP/IP networks. SSL also uses techniques of public-key encryption, which is described in the next section.

Public-Key Encryption

The most commonly used implementations of public-key encryption are based on algorithms patented by RSA Data Security. Therefore, this section describes the RSA approach to public-key encryption. Public-key encryption (also called asymmetric encryption) involves a pair of keys--a public key and a private key--associated with an entity that needs to authenticate its identity electronically or to sign or encrypt data. Each public key is published, and the corresponding private key is kept secret. (For more information about the way public keys are published, see Certificates and Authentication) Data encrypted with your public key can be decrypted only with your private key. Figure 2 shows a simplified view of the way public-key encryption works.

Figure 2 Public-key encryption

The scheme shown in Figure 2 lets you freely distribute a public key, and only you will be able to read data encrypted using this key. In general, to send encrypted data to someone, you encrypt the data with that person's public key, and the person receiving the encrypted data decrypts it with the corresponding private key. Compared with symmetric-key encryption, public-key encryption requires more computation and is therefore not always appropriate for large amounts of data. However, it's possible to use public-key encryption to send a symmetric key, which can then be used to encrypt additional data. This is the approach used by the SSL protocol. As it happens, the reverse of the scheme shown in Figure 2 also works: data encrypted with your private key can be decrypted only with your public key. This would not be a desirable way to encrypt sensitive data, however, because it means that anyone with your public key, which is by definition published, could decrypt the data. Nevertheless, private-key encryption is useful, because it means you can use your private key to sign data with your digital signature--an important requirement for electronic commerce and other commercial applications of cryptography. Client software such as Communicator can then use your public key to confirm that the message was signed with your private key and that it hasn't been tampered with since being signed. Digital Signatures and subsequent sections describe how this confirmation process works.

Key Length and Encryption Strength

In general, the strength of encryption is related to the difficulty of discovering the key, which in turn depends on both the cipher used and the length of the key. For example, the difficulty of discovering the key for the RSA cipher most commonly used for public-key encryption depends on the difficulty of factoring large numbers, a well-known mathematical problem. Encryption strength is often described in terms of the size of the keys used to perform the encryption: in general, longer keys provide stronger encryption. Key length is measured in bits. For example, 128-bit keys for use with the RC4 symmetric-key cipher supported by SSL provide significantly better cryptographic protection than 40-bit keys for use with the same cipher. Roughly speaking, 128-bit RC4 encryption is 3 x 1026 times stronger than 40-bit RC4 encryption. (For more information about RC4 and other ciphers used with SSL, see Introduction to SSL.) Different ciphers may require different key lengths to achieve the same level of encryption strength. The RSA cipher used for public-key encryption, for example, can use only a subset of all possible values for a key of a given length, due to the nature of the mathematical problem on which it is based. Other ciphers, such as those used for symmetric key encryption, can use all possible values for a key of a given length, rather than a subset of those values. Thus a 128-bit key for use with a symmetric-key encryption cipher would provide stronger encryption than a 128-bit key for use with the RSA public-key encryption cipher. This difference explains why the RSA public-key encryption cipher must use a 512-bit key (or longer) to be considered cryptographically strong, whereas symmetric key ciphers can achieve approximately the same level of strength with a 64-bit key. Even this level of strength may be vulnerable to attacks in the near future. Because the ability to surreptitiously intercept and decrypt encrypted information has historically been a significant military asset, the U.S. Government restricts export of cryptographic software, including most software that permits use of symmetric encryption keys longer than 40 bits. For detailed information about these restrictions as they apply to Netscape products, see Export Restrictions on International Sales. [Top]

Digital Signatures

Encryption and decryption address the problem of eavesdropping, one of the three Internet security issues mentioned at the beginning of this document. But encryption and decryption, by themselves, do not address the other two problems mentioned in Internet Security Issues: tampering and impersonation. This section describes how public-key cryptography addresses the problem of tampering. The sections that follow describe how it addresses the problem of impersonation. Tamper detection and related authentication techniques rely on a mathematical function called a one-way hash (also called a message digest). A one-way hash is a number of fixed length with the following characteristics:
  • The value of the hash is unique for the hashed data. Any change in the data, even deleting or altering a single character, results in a different value.
  • The content of the hashed data cannot, for all practical purposes, be deduced from the hash--which is why it is called "one-way."
As mentioned in Public-Key Encryption, it's possible to use your private key for encryption and your public key for decryption. Although this is not desirable when you are encrypting sensitive information, it is a crucial part of digitally signing any data. Instead of encrypting the data itself, the signing software creates a one-way hash of the data, then uses your private key to encrypt the hash. The encrypted hash, along with other information, such as the hashing algorithm, is known as a digital signature. Figure 3 shows a simplified view of the way a digital signature can be used to validate the integrity of signed data.

Figure 3 Using a digital signature to validate data integrity

Figure 3 shows two items transferred to the recipient of some signed data: the original data and the digital signature, which is basically a one-way hash (of the original data) that has been encrypted with the signer's private key. To validate the integrity of the data, the receiving software first uses the signer's public key to decrypt the hash. It then uses the same hashing algorithm that generated the original hash to generate a new one-way hash of the same data. (Information about the hashing algorithm used is sent with the digital signature, although this isn't shown in the figure.) Finally, the receiving software compares the new hash against the original hash. If the two hashes match, the data has not changed since it was signed. If they don't match, the data may have been tampered with since it was signed, or the signature may have been created with a private key that doesn't correspond to the public key presented by the signer. If the two hashes match, the recipient can be certain that the public key used to decrypt the digital signature corresponds to the private key used to create the digital signature. Confirming the identity of the signer, however, also requires some way of confirming that the public key really belongs to a particular person or other entity. For a discussion of the way this works, see Certificates and Authentication. The significance of a digital signature is comparable to the significance of a handwritten signature. Once you have signed some data, it is difficult to deny doing so later--assuming that the private key has not been compromised or out of the owner's control. This quality of digital signatures provides a high degree of nonrepudiation--that is, digital signatures make it difficult for the signer to deny having signed the data. In some situations, a digital signature may be as legally binding as a handwritten signature. [Top]

Certificates and Authentication

A Certificate Identifies Someone or Something Authentication Confirms an Identity How Certificates Are Used Contents of a Certificate How CA Certificates Are Used to Establish Trust

A Certificate Identifies Someone or Something

A certificate is an electronic document used to identify an individual, a server, a company, or some other entity and to associate that identity with a public key. Like a driver's license, a passport, or other commonly used personal IDs, a certificate provides generally recognized proof of a person's identity. Public-key cryptography uses certificates to address the problem of impersonation (see Internet Security Issues). To get a driver's license, you typically apply to a government agency, such as the Department of Motor Vehicles, which verifies your identity, your ability to drive, your address, and other information before issuing the license. To get a student ID, you apply to a school or college, which performs different checks (such as whether you have paid your tuition) before issuing the ID. To get a library card, you may need to provide only your name and a utility bill with your address on it. Certificates work much the same way as any of these familiar forms of identification. Certificate authorities (CAs) are entities that validate identities and issue certificates. They can be either independent third parties or organizations running their own certificate-issuing server software (such as Netscape Certificate Server). The methods used to validate an identity vary depending on the policies of a given CA--just as the methods to validate other forms of identification vary depending on who is issuing the ID and the purpose for which it will be used. In general, before issuing a certificate, the CA must use its published verification procedures for that type of certificate to ensure that an entity requesting a certificate is in fact who it claims to be. The certificate issued by the CA binds a particular public key to the name of the entity the certificate identifies (such as the name of an employee or a server). Certificates help prevent the use of fake public keys for impersonation. Only the public key certified by the certificate will work with the corresponding private key possessed by the entity identified by the certificate. In addition to a public key, a certificate always includes the name of the entity it identifies, an expiration date, the name of the CA that issued the certificate, a serial number, and other information. Most importantly, a certificate always includes the digital signature of the issuing CA. The CA's digital signature allows the certificate to function as a "letter of introduction" for users who know and trust the CA but don't know the entity identified by the certificate. For more information about the role of CAs, see How CA Certificates Are Used to Establish Trust.

Authentication Confirms an Identity

Authentication is the process of confirming an identity. In the context of network interactions, authentication involves the confident identification of one party by another party. Authentication over networks can take many forms. Certificates are one way of supporting authentication. Network interactions typically take place between a client, such as browser software running on a personal computer, and a server, such as the software and hardware used to host a Web site. Client authentication refers to the confident identification of a client by a server (that is, identification of the person assumed to be using the client software). Server authentication refers to the confident identification of a server by a client (that is, identification of the organization assumed to be responsible for the server at a particular network address). Client and server authentication are not the only forms of authentication that certificates support. For example, the digital signature on an email message, combined with the certificate that identifies the sender, provide strong evidence that the person identified by that certificate did indeed send that message. Similarly, a digital signature on an HTML form, combined with a certificate that identifies the signer, can provide evidence, after the fact, that the person identified by that certificate did agree to the contents of the form. In addition to authentication, the digital signature in both cases ensures a degree of nonrepudiation--that is, a digital signature makes it difficult for the signer to claim later not to have sent the email or the form. Client authentication is an essential element of network security within most intranets or extranets. The sections that follow contrast two forms of client authentication:
  • Password-Based Authentication. Almost all server software permits client authentication by means of a name and password. For example, a server might require a user to type a name and password before granting access to the server. The server maintains a list of names and passwords; if a particular name is on the list, and if the user types the correct password, the server grants access.
  • Certificate-Based Authentication. Client authentication based on certificates is part of the SSL protocol. The client digitally signs a randomly generated piece of data and sends both the certificate and the signed data across the network. The server uses techniques of public-key cryptography to validate the signature and confirm the validity of the certificate.

Password-Based Authentication

Figure 4 shows the basic steps involved in authenticating a client by means of a name and password. Figure 4 assumes the following:
  • The user has already decided to trust the server, either without authentication or on the basis of server authentication via SSL.
  • The user has requested a resource controlled by the server.
  • The server requires client authentication before permitting access to the requested resource.

Figure 4 Using a password to authenticate a client to a server

These are the steps shown in Figure 4:
  1. In response to an authentication request from the server, the client displays a dialog box requesting the user's name and password for that server. The user must supply a name and password separately for each new server the user wishes to use during a work session.
  2. The client sends the name and password across the network, either in the clear or over an encrypted SSL connection.
  3. The server looks up the name and password in its local password database and, if they match, accepts them as evidence authenticating the user's identity.
  4. The server determines whether the identified user is permitted to access the requested resource, and if so allows the client to access it.
With this arrangement, the user must supply a new password for each server, and the administrator must keep track of the name and password for each user, typically on separate servers. As shown in the next section, one of the advantages of certificate-based authentication is that it can be used to replace the first three steps in Figure 2 with a mechanism that allows the user to supply just one password (which is not sent across the network) and allows the administrator to control user authentication centrally.

Certificate-Based Authentication

Figure 5 shows how client authentication works using certificates and the SSL Protocol. To authenticate a user to a server, a client digitally signs a randomly generated piece of data and sends both the certificate and the signed data across the network. For the purposes of this discussion, the digital signature associated with some data can be thought of as evidence provided by the client to the server. The server authenticates the user's identity on the strength of this evidence. Like Figure 4, Figure 5 assumes that the user has already decided to trust the server and has requested a resource, and that the server has requested client authentication in the process of evaluating whether to grant access to the requested resource.

Figure 5 Using a certificate to authenticate a client to a server

Unlike the process shown in Figure 4, the process shown in Figure 5 requires the use of SSL. Figure 5 also assumes that the client has a valid certificate that can be used to identify the client to the server. Certificate-based authentication is generally considered preferable to password-based authentication because it is based on what the user has (the private key) as well as what the user knows (the password that protects the private key). However, it's important to note that these two assumptions are true only if unauthorized personnel have not gained access to the user's machine or password, the password for the client software's private key database has been set, and the software is set up to request the password at reasonably frequent intervals.
Important Neither password-based authentication nor certificate-based authentication address security issues related to physical access to individual machines or passwords. Public- key cryptography can only verify that a private key used to sign some data corresponds to the public key in a certificate. It is the user's responsibility to protect a machine's physical security and to keep the private-key password secret.
These are the steps shown in Figure 3:
  1. The client software, such as Communicator, maintains a database of the private keys that correspond to the public keys published in any certificates issued for that client. The client asks for the password to this database the first time the client needs to access it during a given session--for example, the first time the user attempts to access an SSL-enabled server that requires certificate-based client authentication. After entering this password once, the user doesn't need to enter it again for the rest of the session, even when accessing other SSL-enabled servers.
  2. The client unlocks the private-key database, retrieves the private key for the user's certificate, and uses that private key to digitally sign some data that has been randomly generated for this purpose on the basis of input from both the client and the server. This data and the digital signature constitute "evidence" of the private key's validity. The digital signature can be created only with that private key and can be validated with the corresponding public key against the signed data, which is unique to the SSL session.
  3. The client sends both the user's certificate and the evidence (the randomly generated piece of data that has been digitally signed) across the network.
  4. The server uses the certificate and the evidence to authenticate the user's identity. (For a detailed discussion of the way this works, see Introduction to SSL.)
  5. At this point the server may optionally perform other authentication tasks, such as checking that the certificate presented by the client is stored in the user's entry in an LDAP directory. The server then continues to evaluate whether the identified user is permitted to access the requested resource. This evaluation process can employ a variety of standard authorization mechanisms, potentially using additional information in an LDAP directory, company databases, and so on. If the result of the evaluation is positive, the server allows the client to access the requested resource.
As you can see by comparing Figure 5 to Figure 4, certificates replace the authentication portion of the interaction between the client and the server. Instead of requiring a user to send passwords across the network throughout the day, single sign-on requires the user to enter the private-key database password just once, without sending it across the network. For the rest of the session, the client presents the user's certificate to authenticate the user to each new server it encounters. Existing authorization mechanisms based on the authenticated user identity are not affected.

How Certificates Are Used

Types of Certificates SSL Protocol Signed and Encrypted Email Form Signing Single Sign-On Object Signing

Types of Certificates

Five kinds of certificates are commonly used with Netscape products:
  • Client SSL certificates. Used to identify clients to servers via SSL (client authentication). Typically, the identity of the client is assumed to be the same as the identity of a human being, such as an employee in an enterprise. See Certificate-Based Authentication for a description of the way client SSL certificates are used for client authentication. Client SSL certificates can also be used for Form Signing and as part of a Single Sign-On solution.
  • Examples: A bank gives a customer a client SSL certificate that allows the bank's servers to identify that customer and authorize access to the customer's accounts. A company might give a new employee a client SSL certificate that allows the company's servers to identify that employee and authorize access to the company's servers.
  • Server SSL certificates. Used to identify servers to clients via SSL (server authentication). Server authentication may be used with or without client authentication. Server authentication is a requirement for an encrypted SSL session. See SSL Protocol.
  • Example: Internet sites that engage in electronic commerce (commonly known as e-commerce) usually support certificate-based server authentication, at a minimum, to establish an encrypted SSL session and to assure customers that they are dealing with a web site identified with a particular company. The encrypted SSL session ensures that personal information sent over the network, such as credit card numbers, cannot easily be intercepted.
  • S/MIME certificates. Used for signed and encrypted email. As with client SSL certificates, the identity of the client is typically assumed to be the same as the identity of a human being, such as an employee in an enterprise. A single certificate may be used as both an S/MIME certificate and an SSL certificate. See Signed and Encrypted Email. S/MIME certificates can also be used for Form Signing and as part of a Single Sign-On solution.
  • Examples: A company deploys combined S/MIME and SSL certificates solely for the purpose of authenticating employee identities, thus permitting signed email and client SSL authentication but not encrypted email. Another company issues S/MIME certificates solely for the purpose of both signing and encrypting email that deals with sensitive financial or legal matters.
  • Object-signing certificates. Used to identify signers of Java code, JavaScript scripts, or other signed files. See Object Signing.
  • Example: A software company signs software distributed over the Internet to provide users with some assurance that the software is a legitimate product of that company. Using certificates and digital signatures in this manner can also make it possible for users to identify and control the kind of access downloaded software has to their computers.
  • CA certificates. Used to identify CAs. Client and server software use CA certificates to determine what other certificates can be trusted. See How CA Certificates Are Used to Establish Trust.
  • Example: The CA certificates stored in Communicator determine what other certificates that copy of Communicator can authenticate. An administrator can implement some aspects of corporate security policies by controlling the CA certificates stored in each user's copy of Communicator.
The sections that follow describes how certificates are used by Netscape products.

SSL Protocol

The Secure Sockets Layer (SSL) protocol, which was originally developed by Netscape, is a set of rules governing server authentication, client authentication, and encrypted communication between servers and clients. SSL is widely used on the Internet, especially for interactions that involve exchanging confidential information such as credit card numbers. SSL requires a server SSL certificate, at a minimum. As part of the initial "handshake" process, the server presents its certificate to the client to authenticate the server's identity. The authentication process uses Public-Key Encryption and Digital Signatures to confirm that the server is in fact the server it claims to be. Once the server has been authenticated, the client and server use techniques of Symmetric-Key Encryption, which is very fast, to encrypt all the information they exchange for the remainder of the session and to detect any tampering that may have occurred. Servers may optionally be configured to require client authentication as well as server authentication. In this case, after server authentication is successfully completed, the client must also present its certificate to the server to authenticate the client's identity before the encrypted SSL session can be established. For an overview of client authentication over SSL and how it differs from password-based authentication, see Authentication Confirms an Identity. For more detailed information about SSL, see Introduction to SSL.

Signed and Encrypted Email

Some email programs (including Messenger, which is part of Communicator) support digitally signed and encrypted email using a widely accepted protocol known as Secure Multipurpose Internet Mail Extension (S/MIME). Using S/MIME to sign or encrypt email messages requires the sender of the message to have an S/MIME certificate. An email message that includes a digital signature provides some assurance that it was in fact sent by the person whose name appears in the message header, thus providing authentication of the sender. If the digital signature cannot be validated by the email software on the receiving end, the user will be alerted. The digital signature is unique to the message it accompanies. If the message received differs in any way from the message that was sent--even by the addition or deletion of a comma--the digital signature cannot be validated. Therefore, signed email also provides some assurance that the email has not been tampered with. As discussed at the beginning of this document, this kind of assurance is known as nonrepudiation. In other words, signed email makes it very difficult for the sender to deny having sent the message. This is important for many forms of business communication. (For information about the way digital signatures work, see Digital Signatures.) S/MIME also makes it possible to encrypt email messages. This is also important for some business users. However, using encryption for email requires careful planning. If the recipient of encrypted email messages loses his or her private key and does not have access to a backup copy of the key, for example, the encrypted messages can never be decrypted.

Single Sign-On

Network users are frequently required to remember multiple passwords for the various services they use. For example, a user might have to type a different password to log into the network, collect email, use directory services, use the corporate calendar program, and access various servers. Multiple passwords are an ongoing headache for both users and system administrators. Users have difficulty keeping track of different passwords, tend to choose poor ones, and tend to write them down in obvious places. Administrators must keep track of a separate password database on each server and deal with potential security problems related to the fact that passwords are sent over the network routinely and frequently. Solving this problem requires some way for a user to log in once, using a single password, and get authenticated access to all network resources that user is authorized to use--without sending any passwords over the network. This capability is known as single sign-on. Both client SSL certificates and S/MIME certificates can play a significant role in a comprehensive single sign-on solution. For example, one form of single sign-on supported by Netscape products relies on SSL client authentication (see Certificate-Based Authentication). A user can log in once, using a single password to the local client's private-key database, and get authenticated access to all SSL-enabled servers that user is authorized to use--without sending any passwords over the network. This approach simplifies access for users, because they don't need to enter passwords for each new server. It also simplifies network management, since administrators can control access by controlling lists of certificate authorities (CAs) rather than much longer lists of users and passwords. In addition to using certificates, a complete single-sign on solution must address the need to interoperate with enterprise systems, such as the underlying operating system, that rely on passwords or other forms of authentication. For information about the single sign-on support currently provided by Netscape products, see Single Sign-On Deployment Guide.

Form Signing

Many kinds of e-commerce require the ability to provide persistent proof that someone has authorized a transaction. Although SSL provides transient client authentication for the duration of an SSL connection, it does not provide persistent authentication for transactions that may occur during that connection. S/MIME provides persistent authentication for email, but e-commerce often involves filling in a form on a web page rather than sending an email. The Netscape technology known as form signing addresses the need for persistent authentication of financial transactions. Form signing allows a user to associate a digital signature with web-based data generated as the result of a transaction, such as a purchase order or other financial document. The private key associated with either a client SSL certificate or an S/MIME certificate may be used for this purpose. When a user clicks the Submit button on a web-based form that supports form signing, a dialog box appears that displays the exact text to be signed. The form designer can either specify the certificate that should be used or allow the user to select a certificate from among the client SSL and S/MIME certificates that are installed in Communicator. When the user clicks OK, the text is signed, and both the text and the digital signature are submitted to the server. The server can then use a Netscape utility called the Signature Verification Tool to validate the digital signature. For more information about support for form signing in Netscape products, see Netscape Form Signing.

Object Signing

Communicator and other Netscape products support a set of tools and technologies called object signing. Object signing uses standard techniques of public-key cryptography to let users get reliable information about code they download in much the same way they can get reliable information about shrink-wrapped software. Most importantly, object signing helps users and network administrators implement decisions about software distributed over intranets or the Internet--for example, whether to allow Java applets signed by a given entity to use specific computer capabilities on specific users' machines. The "objects" signed with object signing technology can be applets or other Java code, JavaScript scripts, plug-ins, or any kind of file. The "signature" is a digital signature. Signed objects and their signatures are typically stored in a special file called a JAR file. Software developers and others who wish to sign files using object-signing technology must first obtain an object-signing certificate. For more information about support for object signing in Netscape products, see Netscape Object Signing: Establishing Trust for Downloaded Software.

Contents of a Certificate

The contents of certificates supported by Netscape and many other software companies are organized according to the X.509 v3 certificate specification, which has been recommended by the International Telecommunications Union (ITU), an international standards body, since 1988. Users don't usually need to be concerned about the exact contents of a certificate. However, system administrators working with certificates may need some familiarity with the information provided here.

Distinguished Names

An X.509 v3 certificate binds a distinguished name (DN) to a public key. A DN is a series of name-value pairs, such as uid=doe, that uniquely identify an entity--that is, the certificate subject. For example, this might be a typical DN for an employee of Netscape Communications Corporation:
uid=doe,e=doe@netscape.com,cn=John Doe,o=Netscape Communications Corp.,c=US
The abbreviations before each equal sign in this example have these meanings: DNs may include a variety of other name-value pairs. They are used to identify both certificate subjects and entries in directories that support the Lightweight Directory Access Protocol (LDAP). The rules governing the construction of DNs can be quite complex and are beyond the scope of this document. For comprehensive information about DNs, see A String Representation of Distinguished Names.

A Typical Certificate

Every X.509 certificate consists of two sections: Here are the data and signature sections of a certificate in human-readable format:
Certificate:
Data:
Version: v3 (0x2)
Serial Number: 3 (0x3)
Signature Algorithm: PKCS #1 MD5 With RSA Encryption
Issuer: OU=Ace Certificate Authority, O=Ace Industry, C=US
Validity:
 Not Before: Fri Oct 17 18:36:25 1997
 Not  After: Sun Oct 17 18:36:25 1999
Subject: CN=Jane Doe, OU=Finance, O=Ace Industry, C=US
Subject Public Key Info:
 Algorithm: PKCS #1 RSA Encryption
 Public Key:
     Modulus:
         00:ca:fa:79:98:8f:19:f8:d7:de:e4:49:80:48:e6:2a:2a:86:
         ed:27:40:4d:86:b3:05:c0:01:bb:50:15:c9:de:dc:85:19:22:
         43:7d:45:6d:71:4e:17:3d:f0:36:4b:5b:7f:a8:51:a3:a1:00:
         98:ce:7f:47:50:2c:93:36:7c:01:6e:cb:89:06:41:72:b5:e9:
         73:49:38:76:ef:b6:8f:ac:49:bb:63:0f:9b:ff:16:2a:e3:0e:
         9d:3b:af:ce:9a:3e:48:65:de:96:61:d5:0a:11:2a:a2:80:b0:
         7d:d8:99:cb:0c:99:34:c9:ab:25:06:a8:31:ad:8c:4b:aa:54:
         91:f4:15
     Public Exponent: 65537 (0x10001)
Extensions:
 Identifier: Certificate Type
     Critical: no
     Certified Usage:
         SSL Client
 Identifier: Authority Key Identifier
     Critical: no
     Key Identifier:
         f2:f2:06:59:90:18:47:51:f5:89:33:5a:31:7a:e6:5c:fb:36:
         26:c9
Signature:
Algorithm: PKCS #1 MD5 With RSA Encryption
Signature:
 6d:23:af:f3:d3:b6:7a:df:90:df:cd:7e:18:6c:01:69:8e:54:65:fc:06:
 30:43:34:d1:63:1f:06:7d:c3:40:a8:2a:82:c1:a4:83:2a:fb:2e:8f:fb:
 f0:6d:ff:75:a3:78:f7:52:47:46:62:97:1d:d9:c6:11:0a:02:a2:e0:cc:
 2a:75:6c:8b:b6:9b:87:00:7d:7c:84:76:79:ba:f8:b4:d2:62:58:c3:c5:
 b6:c1:43:ac:63:44:42:fd:af:c8:0f:2f:38:85:6d:d6:59:e8:41:42:a5:
 4a:e5:26:38:ff:32:78:a1:38:f1:ed:dc:0d:31:d1:b0:6d:67:e9:46:a8:
  dd:c4
Here is the same certificate displayed in the 64-byte-encoded form interpreted by software:
-----BEGIN CERTIFICATE-----
MIICKzCCAZSgAwIBAgIBAzANBgkqhkiG9w0BAQQFADA3MQswCQYDVQQGEwJVUzER
MA8GA1UEChMITmV0c2NhcGUxFTATBgNVBAsTDFN1cHJpeWEncyBDQTAeFw05NzEw
MTgwMTM2MjVaFw05OTEwMTgwMTM2MjVaMEgxCzAJBgNVBAYTAlVTMREwDwYDVQQK
EwhOZXRzY2FwZTENMAsGA1UECxMEUHViczEXMBUGA1UEAxMOU3Vwcml5YSBTaGV0
dHkwgZ8wDQYJKoZIhvcNAQEFBQADgY0AMIGJAoGBAMr6eZiPGfjX3uRJgEjmKiqG
7SdATYazBcABu1AVyd7chRkiQ31FbXFOGD3wNktbf6hRo6EAmM5/R1AskzZ8AW7L
iQZBcrXpc0k4du+2Q6xJu2MPm/8WKuMOnTuvzpo+SGXelmHVChEqooCwfdiZywyZ
NMmrJgaoMa2MS6pUkfQVAgMBAAGjNjA0MBEGCWCGSAGG+EIBAQQEAwIAgDAfBgNV
HSMEGDAWgBTy8gZZkBhHUfWJM1oxeuZc+zYmyTANBgkqhkiG9w0BAQQFAAOBgQBt
I6/z07Z635DfzX4XbAFpjlRl/AYwQzTSYx8GfcNAqCqCwaSDKvsuj/vwbf91o3j3
UkdGYpcd2cYRCgKi4MwqdWyLtpuHAH18hHZ5uvi00mJYw8W2wUOsY0RC/a/IDy84
hW3WWehBUqVK5SY4/zJ4oTjx7dwNMdGwbWfpRqjd1A==
-----END CERTIFICATE----- 

How CA Certificates Are Used to Establish Trust

Certificate authorities (CAs) are entities that validate identities and issue certificates. They can be either independent third parties or organizations running their own certificate-issuing server software (such as the Netscape Certificate Server). A list of third-party certificate authorities is available at Certificate Authority Services. Any client or server software that supports certificates maintains a collection of trusted CA certificates. These CA certificates determine which other certificates the software can validate--in other words, which issuers of certificates the software can trust. In the simplest case, the software can validate only certificates issued by one of the CAs for which it has a certificate. It's also possible for a trusted CA certificate to be part of a chain of CA certificates, each issued by the CA above it in a certificate hierarchy. The sections that follow explains how certificate hierarchies and certificate chains determine what certificates software can trust. CA Hierarchies Certificate Chains Verifying a Certificate Chain

CA Hierarchies

In large organizations, it may be appropriate to delegate the responsibility for issuing certificates to several different certificate authorities. For example, the number of certificates required may be too large for a single CA to maintain; different organizational units may have different policy requirements; or it may be important for a CA to be physically located in the same geographic area as the people to whom it is issuing certificates. It's possible to delegate certificate-issuing responsibilities to subordinate CAs. The X.509 standard includes a model for setting up a hierarchy of CAs like that shown in Figure 6.

Figure 6 Example of a hierarchy of certificate authorities

In this model, the root CA is at the top of the hierarchy. The root CA's certificate is a self-signed certificate: that is, the certificate is digitally signed by the same entity--the root CA--that the certificate identifies. The CAs that are directly subordinate to the root CA have CA certificates signed by the root CA. CAs under the subordinate CAs in the hierarchy have their CA certificates signed by the higher-level subordinate CAs. Organizations have a great deal of flexibility in terms of the way they set up their CA hierarchies. Figure 6 shows just one example; many other arrangements are possible.

Certificate Chains

CA hierarchies are reflected in certificate chains. A certificate chain is series of certificates issued by successive CAs. Figure 7 shows a certificate chain leading from a certificate that identifies some entity through two subordinate CA certificates to the CA certificate for the root CA (based on the CA hierarchy shown in Figure 6).

Figure 7 Example of a certificate chain

A certificate chain traces a path of certificates from a branch in the hierarchy to the root of the hierarchy. In a certificate chain, the following occur:
  • Each certificate is followed by the certificate of its issuer.
  • Each certificate contains the name (DN) of that certificate's issuer, which is the same as the subject name of the next certificate in the chain.
  • In Figure 7, the Engineering CA certificate contains the DN of the CA (that is, USA CA), that issued that certificate. USA CA's DN is also the subject name of the next certificate in the chain.
  • Each certificate is signed with the private key of its issuer. The signature can be verified with the public key in the issuer's certificate, which is the next certificate in the chain.
  • In Figure 7, the public key in the certificate for the USA CA can be used to verify the USA CA's digital signature on the certificate for the Engineering CA.

Verifying a Certificate Chain

Certificate chain verification is the process of making sure a given certificate chain is well-formed, valid, properly signed, and trustworthy. Netscape software uses the following procedure for forming and verifying a certificate chain, starting with the certificate being presented for authentication:
  1. The certificate validity period is checked against the current time provided by the verifier's system clock.
  2. The issuer's certificate is located. The source can be either the verifier's local certificate database (on that client or server) or the certificate chain provided by the subject (for example, over an SSL connection).
  3. The certificate signature is verified using the public key in the issuer's certificate.
  4. If the issuer's certificate is trusted by the verifier in the verifier's certificate database, verification stops successfully here. Otherwise, the issuer's certificate is checked to make sure it contains the appropriate subordinate CA indication in the Netscape certificate type extension, and chain verification returns to step 1 to start again, but with this new certificate. Figure 8 presents an example of this process.

Figure 8 Verifying a certificate chain all the way to the root CA

Figure 8 shows what happens when only Root CA is included in the verifier's local database. If a certificate for one of the intermediate CAs shown in Figure 8, such as Engineering CA, is found in the verifier's local database, verification stops with that certificate, as shown in Figure 9.

Figure 9 Verifying a certificate chain to an intermediate CA

Expired validity dates, an invalid signature, or the absence of a certificate for the issuing CA at any point in the certificate chain causes authentication to fail. For example, Figure 10 shows how verification fails if neither the Root CA certificate nor any of the intermediate CA certificates are included in the verifier's local database.

Figure 10 A certificate chain that can't be verified

For general information about the way digital signatures work, see Digital Signatures. For a more detailed description of the signature verification process in the context of SSL client and server authentication, see Introduction to SSL. [Top]

Managing Certificates

The set of standards and services that facilitate the use of public-key cryptography and X.509 v3 certificates in a networked environment is called the public key infrastructure (PKI). PKI management is complex topic beyond the scope of this document. The sections that follow introduce some of the specific certificate management issues addressed by Netscape products. Issuing Certificates Certificates and the LDAP Directory Key Management Renewing and Revoking Certificates Registration Authorities

Issuing Certificates

The process for issuing a certificate depends on the certificate authority that issues it and the purpose for which it will be used. The process for issuing nondigital forms of identification varies in similar ways. For example, if you want to get a generic ID card (not a driver's license) from the Department of Motor Vehicles in California, the requirements are straightforward: you need to present some evidence of your identity, such as a utility bill with your address on it and a student identity card. If you want to get a regular driving license, you also need to take a test--a driving test when you first get the license, and a written test when you renew it. If you want to get a commercial license for an eighteen-wheeler, the requirements are much more stringent. If you live in some other state or country, the requirements for various kinds of licenses will differ. Similarly, different CAs have different procedures for issuing different kinds of certificates. In some cases the only requirement may be your email address. In other cases, your Unix or NT login and password may be sufficient. At the other end of the scale, for certificates that identify people who can authorize large expenditures or make other sensitive decisions, the issuing process may require notarized documents, a background check, and a personal interview. Depending on an organization's policies, the process of issuing certificates can range from being completely transparent for the user to requiring significant user participation and complex procedures. In general, processes for issuing certificates should be highly flexible, so organizations can tailor them to their changing needs. The Netscape Certificate Server, part of the Mission Control family of products, allows an organization to set up its own certificate authority and issue certificates. Issuing certificates is one of several managements tasks that can be handled by separate Registration Authorities.

Certificates and the LDAP Directory

The Lightweight Directory Access Protocol (LDAP) for accessing directory services supports great flexibility in the management of certificates within an organization. System administrators can store much of the information required to manage certificates in an LDAP-compliant directory. For example, a CA can use information in a directory to prepopulate a certificate with a new employee's legal name and other information. The CA can leverage directory information in other ways to issue certificates one at a time or in bulk, using a range of different identification techniques depending on the security policies of a given organization. Other routine management tasks, such as Key Management and Renewing and Revoking Certificates, can be partially or fully automated with the aid of the directory. Information stored in the directory can also be used with certificates to control access to various network resources by different users or groups. Issuing certificates and other certificate management tasks can thus be an integral part of user and group management. In general, high-performance directory services are an essential ingredient of any certificate management strategy. The Netscape Directory Server, part of the Mission Control family of products, is fully integrated with the Netscape Certificate Server to provide a comprehensive certificate management solution.

Key Management

Before a certificate can be issued, the public key it contains and the corresponding private key must be generated. Sometimes it may be useful to issue a single person one certificate and key pair for signing operations, and another certificate and key pair for encryption operations. Separate signing and encryption certificates make it possible to keep the private signing key on the local machine only, thus providing maximum nonrepudiation, and to back up the private encryption key in some central location where it can be retrieved in case the user loses the original key or leaves the company. Keys can be generated by client software or generated centrally by the CA and distributed to users via an LDAP directory. There are trade-offs involved in choosing between local and centralized key generation. For example, local key generation provides maximum nonrepudiation, but may involve more participation by the user in the issuing process. Flexible key management capabilities are essential for most organizations. Key recovery, or the ability to retrieve backups of encryption keys under carefully defined conditions, can be a crucial part of certificate management (depending on how an organization uses certificates). Key recovery schemes usually involve an m of n mechanism: for example, m of n managers within an organization might have to agree, and each contribute a special code or key of their own, before a particular person's encryption key can be recovered. This kind of mechanism ensures that several authorized personnel must agree before an encryption key can be recovered.

Renewing and Revoking Certificates

Like a driver's license, a certificate specifies a period of time during which it is valid. Attempts to use a certificate for authentication before or after its validity period will fail. Therefore, mechanisms for managing certificate renewal are essential for any certificate management strategy. For example, an administrator may wish to be notified automatically when a certificate is about to expire, so that an appropriate renewal process can be completed in plenty of time without causing the certificate's subject any inconvenience. The renewal process may involve reusing the same public-private key pair or issuing a new one. A driver's license can be suspended even if it has not expired--for example, as punishment for a serious driving offense. Similarly, it's sometimes necessary to revoke a certificate before it has expired--for example, if an employee leaves a company or moves to a new job within the company. Certificate revocation can be handled in several different ways. For some organizations, it may be sufficient to set up servers so that the authentication process includes checking the directory for the presence of the certificate being presented. When an administrator revokes a certificate, the certificate can be automatically removed from the directory, and subsequent authentication attempts with that certificate will fail even though the certificate remains valid in every other respect. Another approach involves publishing a certificate revocation list (CRL)--that is, a list of revoked certificates--to the directory at regular intervals and checking the list as part of the authentication process. For some organizations, it may be preferable to check directly with the issuing CA each time a certificate is presented for authentication. This procedure is sometimes called real-time status checking.

Registration Authorities

Interactions between entities identified by certificates (sometimes called end entities) and CAs are an essential part of certificate management. These interactions include operations such as registration for certification, certificate retrieval, certificate renewal, certificate revocation, and key backup and recovery. In general, a CA must be able to authenticate the identities of end entities before responding to the requests. In addition, some requests need to be approved by authorized administrators or managers before being services. As previously discussed, the means used by different CAs to verify an identity before issuing a certificate can vary widely, depending on the organization and the purpose for which the certificate will be used. To provide maximum operational flexibility, interactions with end entities can be separated from the other functions of a CA and handled by a separate service called a Registration Authority (RA). An RA acts as a front end to a CA by receiving end entity requests, authenticating them, and forwarding them to the CA. After receiving a response from the CA, the RA notifies the end entity of the results. RAs can be helpful in scaling an PKI across different departments, geographical areas, or other operational units with varying policies and authentication requirements. Future versions of the Netscape Certificate Server will support the creation of customizable registration authorities. [Top]

Last Updated: 10/09/98 10:35:45