October 02, 2006 12:10 AM

Working with Certificates

Create, Access, and Employ Certificates in Your Applications
DevConnections
Rating: (0)

ASP.NET Under the Hood

LANGUAGES:VB.NET | C#

ASP.NETVERSIONS: 2.0

 

Working with Certificates

Create, Access, and Employ Certificates in Your Applications

 

 

Greetings ASP.NET architects and developers! This time I?mgoing to answer some frequently asked questions about X.509 certificates in thedevelopment environment.

 

I?ve shared a fair number of code samples that requireX.509 certificates for authentication and/or secure messaging. Some examples ofapplications that leverage certificates include:

  • SSL-enabled Web applications
  • SSL-enabled Web services (ASMX)
  • Secure Web services using Web ServicesEnhancements (WSE) and WS-Security protocols
  • Secure Windows Communication Foundation (WCF)services using WS-Security protocols
  • Windows CardSpace applications using SSL and IE7

 

I frequently answer questions about the process of workingwith certificates on the local machine for testing, creating test certificatesfor development, and security issues related to accessing certificates at run time.In this article I?ll provide a summary of answers to those questions to helpyou with your development efforts for any of the above scenarios.

 

Q. Where do I find the Certificates snap-in tool?

 

A. Let?s start with the basics. If you?re going to developapplications that require certificates, you?ll need to know where certificatesare stored, as well as how to navigate the management interface. There is anMMC (Microsoft Management Console) snap-in for Certificates (see Figure 1).From this snap-in interface you can manage your certificates; most typicallyfor the currently logged-in user (Current User store), or the machine account(Local Machine store).

 


Figure 1: The MMC snap-in.

 

Follow these instructions to open the Certificates snap-infor the Current User and Local Machine stores:

  • From the Start menu select Run and type mmc.exe.Click OK to launch the MMC console.
  • From the File menu select Add/Remove Snap-in.Click Add from the dialog and select Certificates from the Add Standalone Snap-indialog.
  • Click Add and select My user account; clickFinish.
  • Click Add again and select Computer account.Click Next, then Finish.
  • Close the Add Standalone Snap-in dialog. ClickOK on the Add/Remove Snap-in dialog. You should see the console shown in Figure1.

 

You can save these Certificates snap-in settings to a file(File | Save; name the file certificates.msc). Simply open certificates.msc thenext time you load the MMC console.

 

If you expand the Certificates node for Current User or(Local Computer), you?ll see several logical certificate stores. The logicalstores you?ll use for the scenarios I?m covering are:

  • Personal.Here you store certificates for which you have the associated private key.
  • TrustedRoot Certification Authorities. This store lists the Third-Party RootCertification Authorities (Thawte, Verisign, etc.), Microsoft rootcertificates, and your own root certificates for self-signed certificates.
  • TrustedPeople. Here you place your trusted certificates (you must also trust theentire chain of certificates).

 

As I answer other common certificate questions, you?lllearn how to use each of these logical stores.

 

Q. How can I generate my own test certificates for SSL Websites or secure Web service messaging?

 

A. This is the most often-asked question I hear. It is notalways easy to find a concise list of steps to follow for creatingcertificates. There are three popular approaches to generating certificates fortesting purposes:

1)     Requesta test certificate from a certificate authority (CA), such as Verisign.

2)     Issueyour own certificates from your Windows Server 2003 CA.

3)     Generatecertificates using makecert.exe (the Certificate Creation Tool).

 

The simplest approach is to use makecert.exe. This commandline tool is installed with your .NET Framework SDK (2.0 and 3.0 each have aversion of this tool).

 

MSDN describes the options you can pass to the commandline (see http://msdn2.microsoft.com/en-us/library/bfsktky3.aspx).Still, when you are new to the tool it is often overwhelming to make sense ofall the possible options. I?ll simplify things by providing some steps thatwill work for SSL certificates and secure messaging.

 

Creating an SSL Certificate

To create a self-signed certificate to install in IIS asthe SSL certificate, you can issue the following makecert.exe command from theVisual Studio 2005 command line:

 

makecert -r -pe -n "CN=localhost" -ss my -srcurrentuser -sky exchange -sp "Microsoft RSA SChannel CryptographicProvider" -sy 12 c:\localhost.cer

 

The subject name ?localhost? makes it possible to browse withouterrors to http://localhost or any path relative to it. The subject name of theSSL certificate must match the domain or machine name used in the path to accessthe site. If you used your machine name to browse to Web sites on your machine,for example http://idesign/, you?d create the certificate with the subject name?CN=idesign?.

 

Creating a Secure Messaging Certificate

To create a certificate for use in Web service messageexchanges, you can give the certificate any relevant name. I tend to use thefollowing names for various samples I create:

  • SubjectKey (for client applications)
  • RPKey (for target service applications)
  • IPKey (for identity provider services such as asecurity token service [STS])

 

You can use subject names that are meaningful to yourapplications. The syntax would be essentially the same for makecert.exe, withthe exception of the subject name and certificate output filename:

 

makecert.exe -r -pe -n "CN=RPKey" -ss my -srcurrentuser -sky exchange -sp "Microsoft RSA SChannel CryptographicProvider" -sy 12 c:\rpkey.cer

 

makecert.exe Options

You only have to understand a subset of makecert.exeoptions to create these certificates. The table in Figure 2 describes them.

 

Option

Description

-n certName

The subject name for the certificate. This is a distinguished name following the X.500 specification. It can be as simple as ?CN=localhost? or include a richer description of the subject with ?CN=localhost, O=IDesign, OU=Architecture, E=mlb@idesign.net?.

-pe

This allows the private key to be exported after generating it. It is a good idea to generate the private key pair and export the certificate to apply password protection, even if it is a test certificate.

-sr

Certificate store location where the key will be generated. It doesn?t matter which store you choose, because you will likely export the key pair, password protect it, and then import it to the correct store for use. Values can be currentuser or localmachine.

-ss

Which logical store will the certificate be installed in? Specify ?My? here; this will place it in the Personal logical store.

-sp

The cryptography provider to use. A list of possible providers can be found here: http://windowssdk.msdn.microsoft.com/en-us/library/ms731160.aspx. The ?Microsoft RSA SChannel Cryptographic Provider? is not subject to government restrictions for usage.

-sy

Cryptography provider type; an integer representative of the provider setting for the -sp option. Use the value 12 for the ?Microsoft RSA SChannel Cryptographic Provider?.

-r

Indicates a self-signed certificate.

-sky certType

Can be signature or exchange. Use exchange for SSL and secure messaging.

Figure 2: A subsetof makecert.exe options.

 

Exporting the Certificate

The goal is to export a .pfx file (the key pair) and a.cer file (the public certificate) for later use. The .cer file is generated inthe directory you specified in the makecert.exe command. The .pfx file can beexported from the Certificates snap-in tool as follows:

  • Because the certificate is generated to enableexporting the private key, you can export it using the Certificates console.Open the Certificates snap-in, expand the CurrentUser | Personal store(assuming it was created in currentuser), and select All Tasks | Export (seeFigure 3).
  • Follow the steps in the wizard and be sure toselect ?Yes, export the private key?, and ?Delete the private key if the exportis successful?. Provide a password to protect the key upon export to the .pfxfile.

 


Figure 3: Exporting a key pair.

 

Now you have a .pfx and .cer file ready to use for SSL orsecure messaging.

 

Q. How do I install and troubleshoot a test SSLcertificate?

 

A. During development you may need to test applicationsthat require SSL. If you create a certificate using makecert.exe, you can usethe resulting key pair as the SSL certificate. Here are the steps to accomplishthis:

1)     Importthe localhost.pfx certificate to the Local Machine | Personal store. You can dothis from the Certificates snap-in by right-clicking on the Personal store andselecting Import. You?ll be asked to provide the key pair password you usedwhen exporting earlier.

2)     Next,open the console for Internet Information Services (IIS) from Control Panel | AdministrativeTools.

3)     Openthe Properties dialog for the default Web site and select Server Certificatefrom the Directory Security tab.

4)     ChooseAssign an existing certificate. You?ll be presented with keys from the LocalMachine | Personal store; the localhost certificate should be listed. Selectit.

 

Before you start opening ASP.NET Web sites with SSLenabled, it?s a good idea to test the SSL certificate to verify the trust chain.You can use the IIS Diagnostic Toolkit to do this. Download and install thetoolkit from http://www.microsoft.com/downloads/details.aspx?familyid=9BFA49BC-376B-4A54-95AA-73C9156706E7&displaylang=en.Then, from the Start menu find the program group for SSL Diagnostics and launchthe SSL Diagnostics tool, as shown in Figure 4.

 


Figure 4: Accessing the IISDiagnostic Toolkit.

 

A test certificate will fail this test with the error: ?Acertificate chain processed, but terminated in a root certificate which is nottrusted by the trust provider.? That?s because the certificate was not issuedby a provider installed in the Trusted Root Certification Authorities store. Thisproblem will be solved if you import the localhost.cer file into Local Machine| Trusted Root Certification Authorities.

 

Q. How do I test an ASP.NET Web site with SSL enabled?

 

A. ASP.NET Web site projects can be file-based using thebuilt-in Web server, or be IIS-based. Generally speaking, to test anysecurity-related features of a Web site it is better to use IIS ? and only IISsupports opening Web site projects with SSL enabled. To debug with SSL, you mustadd the Web site project to the solution and check the Use Secure Sockets Layercheckbox, as shown in Figure 5.

 


Figure 5: Opening a Web site projectin Visual Studio with SSL support.

 

Now when you debug, the browser address will use the HTTPSscheme instead of HTTP, by default. You can still browse to the Web site usingHTTP if you want to test the application without SSL.

 

Had you forgotten to install the SSL certificate in theTrusted Root Certification Authorities store, you would have seen a message inIE 7 similar to that shown in Figure 6. Note: Only trusted SSL certificateswill work for CardSpace-enabled sites (even for testing on your local machine).

 


Figure 6: IE 7 performs strictchecking on SSL certificates while you browse.

 

Q. Can you explain the security requirements around run-timeaccess to certificates for secure messaging?

 

A. The location of certificates used for secure messaging(ASMX, WSE, WCF) depends on the configuration of each application ? but thereare some typical usage patterns:

  • Client Certificates.When certificates are used to authenticate a client application, itscertificate with the private key (.pfx) is usually installed in the CurrentUser | Personal store. This key is used to sign messages from the client, whichmust be validated at the service. The service uses the client?s public key tovalidate the authenticity of message signatures, and to identify the client.This public cert is usually installed to the Local Machine | Personal or LocalMachine | Trusted People store (depending on where the service run time willlook for authorized certificates).
  • ServiceCertificates. The service certificate and private key are usually installedin the Local Machine | Personal store. This key is used to authenticate theservice to the client, and to decrypt messages from the client. The client usesthe service?s public key to encrypt messages. When the service attempts todecrypt messages, it requires access to its private key at run time, and thisposes some security constraints.

 

If you are hosting services (ASMX, WSE, WCF) in IIS, theASP.NET account is used to access service certificates at run time. If you arerunning services in a file-based Web site, the logged-in user account is used.In either case, you need to make sure that the appropriate account has accessto the private key at run time.

 

It turns out that Local Machine keys are installed in adirectory similar to:

 

C:\Documents and Settings\All Users\ApplicationData\Microsoft\Crypto\RSA\MachineKeys

 

So, you can browse to that directory in file explorer andgrant the ASP.NET (or appropriate) account access to the path. That would grantthe account access to all private key certificates on the local machine. Tolock this down to a particular certificate, you must know for which certificatefile to modify security. Fortunately, both WSE and the .NET Framework 3.0 SDK(for WCF) provide tools that make it easy to specify security for a particularcertificate.

 

The WSE X.509 Certificate Tool and the CertKeyFileTool(respectively) let you open any logical certificate store and select acertificate. You can view the properties of certificates that have private keys? and modify security, as shown in Figure 7.

 


Figure 7: Both the WSE and WCFcertificate tools can lead you to a properties dialog for a specificcertificate file. This is where you add accounts that need run-time access toprivate keys.

 

Conclusion

Whether you are testing secure ASP.NET Web applicationsand services, using WSE, or using WCF for IIS-hosted service scenarios ... you?lldefinitely encounter the need to create and/or install test certificates. Ihope this digest of information around creating, importing, and controllingaccess to certificates will help you skip past the pain of setting up yourdevelopment environment to work with certificates.

 

If you have additional questions on this or other ASP.NETtopics, drop me a line at mailto:underthehood@aspnetpro.com.Thanks for reading!

 

Michele LerouxBustamante is Chief Architect at IDesign Inc., Microsoft Regional Directorfor San Diego, Microsoft MVP for XML Web services, and a BEA TechnicalDirector. At IDesign Michele provides training, mentoring, and high-endarchitecture consulting services, specializing in scalable and secure .NETarchitecture design, globalization, Web services, and interoperability withJava platforms. She is a board member for the International Association ofSoftware Architects (IASA), a frequent conference presenter, conference chairof SD?s Web Services track, and a frequently published author. She is currentlywriting a book for O?Reilly on the Windows Communication Foundation (http://www.thatindigogirl.com). Reachher at http://www.idesign.net or http://www.dasblonde.net.

 

 

 

 

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS