Network Access and Client Privacy Protection

only for RuBoard - do not distribute or recompile

Web applications, based as they are on networking, are subject to dangers from wiretapping or snooping. It s bad enough when wiretapping actually involves wires, but with wireless networking on the rise, it may be possible for an attacker to join your network just by wandering into your vicinity with a suitable receiver and transmitter. (Two things you can do to reduce the risk are to require a password before access to the network is allowed and to turn on encryption of wireless traffic.)

Information sent over the network may be intercepted by a third party, inspected, and used for various forms of mischief such as masquerading as someone else or mounting replay attacks. Stolen names and passwords can be used later to forge an identity. Captured data can be replayed by sending it to the Web server for processing again. (You didn t really intend to submit 317 individual orders for a dozen self-sealing stem bolts? Maybe you ordered once and someone else replayed your order 316 times.)

In a Web environment, the most obvious source of network traffic is the information that travels between your Web server and remote clients. Your basic tool for protecting these connections is encryption. This can be done by enabling support for SSL (the Secure Sockets Layer protocol) in your Web server, at least for clients that also support SSL.[3] Connections between the Web server and MySQL may also provide a network-based point of exposure. To protect information that passes between Apache and MySQL, you have a couple of options. If you run Apache and MySQL on the same host, you can keep information between the two from traveling over the network by having your Web scripts specify the hostname localhost when connecting to MySQL server. Then the connections will not use TCP/IP connections that are subject to eavesdropping. They will use UNIX domain sockets or the loopback interface, for which traffic is not routed onto the Internet. If you run Apache and MySQL on separate hosts, you can use SSH port-forwarding to create a secure tunnel. (MySQL includes direct support for establishing SSL connections from version 3.23.9 and on, but this capability is not yet available from within DBI scripts.)

[3] For example, versions of the lynx browser prior to 2.8.3 do not support secure connections, and even for recent versions, SSL support is optional.

For some applications, another network information channel may be involved. For example, an e-commerce application might set up a connection between Apache and a vendor with whom you have a merchant account for handling credit card transactions. This kind of channel normally will be encrypted for security.

Information on how SSL works, how to use it for setting up secure connections for your Web clients, and how to create secure connections to the MySQL server are covered in the following sections of this chapter. The topic of connecting to merchant account vendors is covered in Chapter 10, E-Commerce Applications.

Dangers of Password Fields

One type of input field you can use in forms is the password field. (With CGI.pm, these are produced using the password_field() call.) Password fields pose a kind of security risk, but not because of anything the client does. The danger occurs from Web developers being lulled into thinking that password fields are secure in any way. They aren t. The browser shows bullets or asterisks rather than the characters the user actually enters into the field, but that provides only an illusion of security. Other people may not be able to look over the user s shoulder to see the characters in the browser window, but the password is sent over the network to the Web server as unencrypted plain text. If the connection is wiretapped, the password will be just as visible as any other information in the form. If you really need to protect the password from snooping, use a secure connection.

Do You Have a Privacy Policy?

It s important not only to take steps to ensure your clients privacy, but also to make sure they know you take their privacy seriously. You may put a lot of effort into addressing security issues, but if visitors can t tell that you re doing so, they may have a nagging sense of unease about using your site or divulging personal or confidential information to you. A simple measure you can take to make your users aware of your efforts is a prominent link to a privacy statement in which you set out for your visitors the efforts you re taking to protect their information. If you use cookies to associate users with session information, you can explain why the cookies you use are not dangerous to them. You can point out that you use secure connections where necessary to ensure confidentiality of sensitive or private information. You can also explain to customers that you re not going to engage in practices such as selling their names to other people (assuming you re not going to). The TRUSTe Web site (http://www.truste.com/) is a good place to visit for helpful information about privacy guidelines.

The Basis for Secure Web Connections

A client requests a secure connection to the Web server in a very simple way, by using a URL that begins with https rather than with http. The first example below illustrates how to request a normal connection and the second how to request a secure connection:

 http://www.snake.net/  https://www.snake.net/ 

When the server receives a secure-connection request, the server and client engage in some negotiation, the result of which is an encrypted channel over which to exchange information in a safe way. A typical visible sign of this on the client end is the appearance in the browser window of an icon showing a padlock in locked state.

Secure Web connections are implemented using SSL (https means HTTP over SSL , the Secure Sockets Layer protocol). This protocol uses public key encryption to establish a connection in which only the parties involved know the key required to decrypt traffic that flows over the connection. This keeps out untrusted third parties. SSL connections also enable the client to verify the server s authenticity based on the server s digital certificate. This protects the client by preventing site spoofing one site posing as another to fool the client into submitting private information.

Public key cryptography is based on key pairs. The keys are related in such a way that data encrypted using one key can be decrypted only with the other key. The key owner keeps one key secret (the private key), but makes the other available to anyone that wants it (the public key). For example, if you want to send me a private message, I send you my public key. You use the key to encrypt the message and send me the result. If your message is intercepted by an eavesdropper, it doesn t matter, because the message can be decrypted only by my private key, which only I know. (Obviously, it s extremely important to protect the private key so that no one else can access it. Anyone who comes into possession of a private key can use it to decrypt traffic obtained by wiretapping.)

One problem with the preceding scenario is that you don t necessarily know that I m me. Someone else might be posing as me, trying to trick you into sending some interesting bit of information. This imposter would send you a public key and claim it s mine, when in reality it may be just the complement of the imposter s secret key. In a Web context, this scam takes the form of a fake Web site setting itself up to appear to be some other site. This is where digital certificates come in. If I m running a Web server, my certificate verifies my identity so that you can trust me when I say who I am. Possession of a digital certificate (also known as the server ID) indicates that the organization running the Web server has satisfied the authorization procedure for a certificate authority, which is a trusted third party (generally a company such as VeriSign or Thawte). The server s digital certificate contains the information such as the following:

  • The Web server host name

  • The server owner s name and identification information

  • The server s public key

  • The certificate authority s digital certificate

  • The time period over which the certificate is valid

With the preceding background in mind, we re in a position to discuss what actually happens behind the scenes when a client requests a secure connection to the Web server:

  1. The client issues a request that begins with https.

  2. The server responds by sending the client its digital certificate to assure the client that the server is in fact who it says it is, rather than an imposter setting itself up as someone else.

  3. The client checks the credentials in the certificate to verify the server s authenticity. Browsers such as those from Netscape and Microsoft ship with a list of certificate authorities that they trust, so the browser checks the server certificate against this list to see whether it was issued by a recognized authority. If not, the browser engages the user in a dialog that allows the user to examine the contents of the certificate and to decline or accept the certificate.

  4. If the certificate is accepted, the browser generates a secret key to use for encrypting connection traffic. This secret is known as the session key, and it has two important properties: It is very difficult to guess, and it will be known only to the client and the server.

  5. The client must transmit the session key to the server, but protect it so that no one else can intercept the key and figure it out. To do this, the client extracts the server s public key from the server s certificate and uses it to encrypt the session key before sending it to the server.

  6. The server receives the encrypted session key and decrypts it using its own private key. Only the server knows this key, so at this point, only the client and server know the session key. All further traffic between the two is encrypted using this key for the duration of the session. The session key ensures that any information sent between the client and server is encrypted with some unique value that cannot be guessed by attackers. An attacker might wiretap the connection, but the content will appear to be gibberish due to the encryption, and cannot be interpreted without the session key.

You can set up your own digital server certificate to use for testing. When you re ready to obtain a real certificate, there are many certificate authority companies to choose from. (The Apache-SSL home page at http://www.apache-ssl.org/ lists several.) You should visit the Web sites of a few of these vendors; they re good sources for a great deal of helpful information. Of course, the content of those sites also includes a certain amount of promotional hype. Here s an interesting claim from one of these vendors, extolling how easy it is to enable secure communications: Because SSL is built into all major browsers and Web servers, simply installing a digital certificate, or Server ID, enables SSL capabilities. That statement glosses over the fact that although Apache is the major Web server, the default Apache configuration includes no SSL support, so installing a certificate will do nothing. You can recompile the server to take advantage of SSL, but the procedure isn t necessarily so trivial as the claim makes it sound. You ll need to check your installation to see whether SSL capabilities are already present. (For example, OpenBSD ships an SSL-enabled version of Apache, and SSL can be turned on by starting httpd with the -DSSL command-line option or by using apachectl startssl.) If not, you ll need to do a little work. The next section provides some guidelines for doing this.

Should Secure Connections Be the Default?

If secure connections keep information private, why not just use them all the time? For one thing, secure connections have greater computational requirements. They put a lot more load on your server, so you don t want to use them indiscriminately. Another factor to consider is that applications have differing security requirements, and not all applications need an encrypted connection. A script that displays public information probably won t need much in the way of special security treatment. On the other hand, if the application involves money or sensitive personal information such as a credit card number, that s a clue that you should give more than average attention to security.

Clients Can Provide Credentials, Too

When a client issues a request for a secure connection, the server provides a certificate as proof of its identity. Servers can also ask clients to authenticate themselves. This is based on the use of client digital certificates (see, for example, http://www.verisign.com/clientauth/). VeriSign says that more than a million people have digital IDs. That sounds like a lot, but it s actually just a small fraction of the Web-browsing population. Still, expect to see the popularity of client certificates increase in the future, because digital certificates enable you to dispense with your passwords and hold promise for unifying the authentication process across multiple sites. They can also be useful in situations such as when a company issues certificates to employees for the purpose of accessing its internal servers.

Using Secure Connections

To provide secure Web connections for visitors to your site, you must have a Web server that has SSL support built in. If your version of Apache is currently enabled for SSL, you just need to make sure your server certificate and key files are set up and that the file httpd.conf is configured the way you want it; see Configuring Apache for SSL Support. Otherwise, you can recompile Apache to allow secure connections, or use a related version such as Apache-SSL. Another possibility is to use one of the commercial servers with SSL such as Raven (Covalent) or Stonghold. The latter approach might be preferable if you want someone else to do the work of building the server. The Web sites for these server vendors are

http://www.covalent.net/

http://www.c2net.com/

There are other commercial vendors, too; you may want to do further research for comparison.

If you elect to configure Apache yourself, you ll need source distributions for Apache and for mod_ssl, the Apache module that provides support for SSL connections. You will also need to install OpenSSL if you don t already have it, because mod_ssl actually uses OpenSSL to do much of its work. If you don t have OpenSSL, check to see whether you have SSLeay. If you do, you can use it rather than OpenSSL. SSLeay is the original name of what is now OpenSSL, although some of its commands are named and invoked differently.

If you want to use Apache-SSL rather than Apache, you won t need mod_ssl, but you ll still need OpenSSL. The Web sites for the various components just mentioned can be visited at the following locations:

http://www.apache.org/

http://www.apache-ssl.org/

http://www.modssl.org/

http://www.openssl.org/

A Sample mod_ssl Installation Procedure

I don t want to turn this chapter into an installation manual, but installation of mod_ssl is not always completely obvious, so you may find it helpful to see an example. The following sequence of commands are those I used on a system running Red Hat Linux 7.0. (These particular commands will almost certainly be different for your machine, so be sure to read carefully the installation instructions included with each component you plan to install.) The example assumes that you ve already obtained the source distributions for any components you need and that they re all located under a common parent directory. If you use a different layout, some of the pathnames shown in the commands will need adjustment. The make install commands may need to be run as root.

If you do not already have OpenSSL installed on your system, configure, build, and install it from the main OpenSSL source directory. The following commands install it under the /usr/local/ssl directory:

 %./config --prefix=/usr/local/ssl  % make  % make test  % make install 

Then move into the mod_ssl source tree and configure it:

 %./configure \      --with-apache=../apache_1.3.19 \      --with-ssl=/usr/local/ssl \      --enable-shared=ssl \      --disable-rule=SSL_COMPAT \      --with-crt=$PWD/pkg.sslcfg/server.crt \      --with-key=$PWD/pkg.sslcfg/server.key 

The configure command installs the mod_ssl files into the Apache source tree. That means you don t need to run make in the mod_ssl directory; when you compile Apache, mod_ssl will be built automatically. The --with-ssl option indicates the base directory of the installed OpenSSL; the option shown in the preceding command indicates that OpenSSL is installed under /usr/local/ssl. If you want to point mod_ssl at the OpenSSL source tree, you can do that instead; the following command has a --with-ssl option that points to the OpenSSL tree located at ../openssl-0.9.6 :

 %./configure \      --with-apache=../apache_1.3.19 \      --with-ssl=../openssl-0.9.6 \      --enable-shared=ssl \      --disable-rule=SSL_COMPAT \      --with-crt=$PWD/pkg.sslcfg/server.crt \      --with-key=$PWD/pkg.sslcfg/server.key 

If you do use an OpenSSL source distribution when configuring mod_ssl, the configure command still expects to find the OpenSSL binaries under the directory indicated by the --with-ssl option. Therefore, before running configure in the mod_ssl directory, you should configure and build OpenSSL in ../openssl-0.9.6, but do not run make clean there.

mod_ssl patches the source for Apache to extend its programming interface. The implication of this is that you ll not only need to rebuild Apache, but also any additional modules you use that aren t part of the Apache source tree. If you build DSO versions of the mod_perl and mod_php modules, for example, they ll need to be recompiled as well. We ll get to this shortly.

After running the configure command in the mod_ssl source directory, change into the Apache source directory and run make to recompile Apache. As this operation completes, it should display some information about building a server digital certificate and key files:

 Before you install the package you now should prepare the SSL  certificate system by running the 'make certificate' command..  For different situations the following variants are provided:  % make certificate TYPE=dummy    (dummy self-signed Snake Oil cert)  % make certificate TYPE=test     (test cert signed by Snake Oil CA)  % make certificate TYPE=custom   (custom cert signed by own CA)  % make certificate TYPE=existing (existing cert)         CRT=/path/to/your.crt [KEY=/path/to/your.key] 

To build a new certificate, use one of the first three make certificate commands shown here (the first is the simplest). The certificate won t be genuine in the sense of having been issued by a trusted certificate authority, but it s good enough for testing purposes. After creating the certificate, install Apache:

 % make install 

If this is not your initial Apache installation, you may find that make install doesn t modify your already-installed httpd.conf file or module files. It might also fail to replace some of the programs already installed in the Apache bin directory. In this case, you can move the originals to a different location and run the installation command again. Then you can compare the new configuration files with the originals and merge in any local changes that you want to retain.

As noted earlier, the configuration command for mod_ssl modifies the Apache source code to use an extended API (EAPI). This changes the Apache programming interface not just for mod_ssl, but for other Apache modules. You ll need to recompile any such modules you use that are built outside the Apache source tree, such as external DSO modules. If you use DSO versions of mod_perl and mod_php, for example, you ll have to rebuild them. Ideally, this should be just a matter of reconfiguring the modules using the same configuration commands you used originally. DSO modules are built with the help of the apxs utility that is part of the Apache distribution. The new version of apxs that you ve just installed should report the correct compiler flags to let the configuration commands for your DSO modules know about the presence of mod_ssl and the need to compile with the -DEAPI flag that is needed for the extended API. For example, I configure mod_perl using this command:

 % perl Makefile.PL \       USE_APXS=1 \       WITH_APXS=/usr/local/apache/bin/apxs \       EVERYTHING=1 

For mod_php (PHP 4), I use this command:

 %./configure \      --with-mysql=/usr/local/mysql \      --with-apxs=/usr/local/apache/bin/apxs \      --enable-track-vars 

In both cases, the configuration command runs the new version of apxs, which reports the proper flags indicating that mod_ssl is available and that the extended API is to be used. After configuring each module, rebuild and reinstall it.

Configuring Apache for SSL Support

At this point, you should have an Apache server that has mod_ssl support built in, as well as certificate and key files that the server can use to set up secure connections with clients. Now you must modify httpd.conf to reflect how you want mod_ssl to operate. You may find that the make install command for Apache put several SSL-related directives in your configuration file already; if so, it probably won t be necessary to do much here other than look through the file and check that all the settings seem reasonable.

This section describes some of the configuration directives you ll need to use. What I hope to do here is provide enough information that you can set up a working system, and make it easier for you to assimilate the more complete documentation about configuration directives that you ll find in the reference chapter of the mod_ssl manual. The discussion here shows representative examples only; the mod_ssl manual contains more extensive information and additional examples. (If you re using Apache-SSL rather than Apache and mod_ssl, you should consult the Apache-SSL documentation, because the SSL directives for that server differ somewhat from those for mod_ssl.)

First, tell Apache about the mod_ssl module by listing it in the configuration file with LoadModule. For UNIX, the directive might look like this:

 LoadModule ssl_module modules/libssl.so 

For Windows, the module name is different:

 LoadModule ssl_module modules/ApacheModuleSSL.dll 

The actual pathname to your module files under the server root directory may be somewhat different; adjust the LoadModule directive to match. (For example, it s common under UNIX for module files to be installed in a directory named libexec rather than modules.) You may also need an AddModule directive:

 AddModule mod_ssl.c 

The server needs to listen on an additional port because SSL connections are not handled on the default port. Normally the HTTP and HTTPS ports are 80 and 443; to tell the server to pay attention to these ports, use Listen directives (if you use different port numbers, make the appropriate substitutions):

 Listen 80  Listen 443 

You ll also need to modify your network routing configuration to allow inbound traffic on port 443 if you re behind a firewall or a router that currently blocks that port. Otherwise, you ll test your SSL configuration on your internal network and it will work fine, but connections to the server from outside your network will fail.

Enable the SSL engine:

 SSLEngine on 

The argument must be on or off. You will probably want to use this directive inside <VirtualHost> blocks. Otherwise, it applies globally and the server will expect all connections to be secure; that is, the server no longer will understand normal non-SSL URLs! At a minimum, enable SSL within a generic virtual host block like this one:

 <VirtualHost _default_:443>  SSLEngine on  </VirtualHost> 

If you use a more complex virtual hosting setup, associate SSL directives with each virtual host for which you want to enable SSL capabilities. For example, you can place SSLEngine directives within <VirtualHost> blocks to selectively enable or disable SSL processing for individual hosts. Other directives described in the rest of this section that are commonly used on a host-specific basis include the locations of key files, allowable cipher types, or log file locations.

Tell the server where its private key and digital certificate files are:

 SSLCertificateKeyFile conf/ssl.key/server.key  SSLCertificateFile conf/ssl.crt/server.crt 

These pathnames are typical defaults; make sure they match your setup. SSLCertificateFile can be used twice if you have both RSA-based and DSA-based certificates.

List the cipher types that the client can negotiate. I usually find that the Apache make install step installs a directive such as this in my httpd.conf file (see the mod_ssl manual for a list of all the cipher types and how to construct the list):

 SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL 

mod_ssl can use a connection cache so that successive secure requests from the same client need not all engage in the entire authentication and key generation process. On the first request, the server assigns the SSL session a unique identifier that the client can present on subsequent requests to minimize overhead. The server remembers these IDs in a cache, which is controlled by several directives. OpenSSL itself caches session information for a single server process, so in an environment such as Windows where there is only one child httpd process, you need not enable the mod_ssl cache at all:

 SSLSessionCache none 

In an environment such as UNIX in which several child httpd processes may be running, successive requests from a single client may be served by different children. In this case, the mod_ssl cache allows the child processes to communicate with each other to determine whether a given client has already set up a secure session. The SSLSessionCache directive specifies the type of cache mechanism to use and SSLSessionCacheTimeout controls how long session information is maintained in the cache. For example, to use a DBM hash file to hold cache entries and maintain them for 5 minutes (300 seconds), use these directives:

 SSLSessionCache dbm:logs/ssl_cache  SSLSessionCacheTimeout 300 

The SSLMutex directive determines how Apache creates a lock for operations that child httpd processes must perform in a mutually exclusive way. Under Windows, you must use a semaphore mutex mechanism:

 SSLMutex sem 

That may also work under UNIX if your platform supports it. A more portable alternative is to use a file:

 SSLMutex file:logs/ssl_mutex 

OpenSSL generates random numbers at server startup time and when a new SSL connection is established. SSLRandomSeed controls how the generator is seeded. The builtin seeding source is always available and can be used in both contexts:

 SSLRandomSeed startup builtin  SSLRandomSeed connect builtin 

However, builtin is not necessarily a very good source of seeding information at server startup time, so you may want to use another source in the startup context. Another common seeding source is the /dev/random device:

 SSLRandomSeed startup file:/dev/random  SSLRandomSeed connect file:/dev/random 

On some systems, /dev/urandom is a better choice than /dev/random. But before you decide to use either one, you should read the mod_ssl manual s discussion of the SSLRandomSeed directive, because there can be significant problems with either device if used improperly. The manual gives other choices for such cases. You can specify multiple seeding sources by listing multiple SSLRandomSeed directives for either context in the configuration file.

If you want to log SSL connections, name the log file using SSLLog and the amount of information you want using SSLLogLevel. The levels are (in increasing order of verbosity) none, error, warn, info, trace, and debug. Here s an example:

 SSLLog logs/ssl.log  SSLLogLevel info 

mod_ssl logs errors to the general Apache error log as well, so there s no need for a special SSL log if you re interested only in error information.

You may find it necessary to compensate for broken browsers. A common problem is that some versions of Internet Explorer cannot connect to secure pages properly unless you include the following directive to modify how mod_ssl communicates with them:

 SetEnvIf User-Agent ".*MSIE.*" \      nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 

A couple of options related to access control that may interest you are SSLRequireSSL and SSLRequire. SSLRequireSSL is used to deny access to particular directories or virtual hosts unless the client accesses their contents using https URLs. SSLRequire is similar but provides more general condition-based testing. You can use it to grant or deny access based on factors such as URLs, time of day, browser type, or CGI variables. If you want to use SSLRequire to check CGI variables that contain SSL information, you ll need to use the SSLOptions directive that configures miscellaneous mod_ssl options. One of the options it provides is StdEnvVars, which causes extra SSL-related variables to be added to the CGI environment in which scripts run. You can see the effect of the StdEnvVars option using the perltest.pl script that was discussed in Chapter 3, Improving Performance with mod_perl. If you have that script installed in your cgi-perl directory, turn on StdEnvVars for that directory like this:

 <Directory /usr/local/apache/cgi-perl/>      SSLOptions +StdEnvVars  </Directory> 

Then invoke the script using insecure and secure connections to see the difference between the output; in the latter case, you ll see a lot of variables that have names beginning with SSL_ :

http://www.snake.net/cgi-perl/perltest.pl

https://www.snake.net/cgi-perl/perltest.pl

Check the mod_ssl manual for more complete information about SSLRequireSSL, SSLRequire, and SSLOptions.

If you want to, you can set up the server so that it can be run either with or without SSL support. To do this, enclose SSL directives in conditional blocks that look like this:

 <IfDefine SSL>  # SSL directives here  </IfDefine> 

For example:

 <IfDefine SSL>      Listen 80      Listen 443  </IfDefine> 

By using conditional blocks, you can enable SSL support by defining the SSL symbol on the httpd command line when you start up Apache. The next section describes how to do this.

Starting Apache with SSL Support Enabled

After you ve modified httpd.conf, check your changes for errors, bring Apache down if no errors are reported, and then bring it back up with SSL support enabled. The commands you use to do this depend on whether you placed SSL-related directives within conditional blocks (<IfDefine SSL>). If you didn t use conditional blocks, use these commands, which are no different from those you d normally use:

 # apachectl configtest  # apachectl stop  # apachectl start 

If you did use conditional blocks to enable SSL support, you ll need to pass the -DSSL command-line option to httpd to test the configuration:

 # httpd -t -DSSL 

apachectl configtest doesn t work for this because it doesn t pass -DSSL to httpd. To restart the server after stopping it, either of the following commands should work:

 # apachectl startssl  # httpd -DSSL 

If you use conditional blocks and you want Apache to start up by default with SSL enabled at system boot time, you ll also need to modify your startup procedure. (For example, if you have an httpd script in an /etc/rc.d/init.d or init.d directory that invokes apache, you ll need to change it to add the -DSSL flag.) If you enabled SSL support in the configuration file unconditionally, no changes to the startup procedure are required.

After your server is running and listening to port 443, try to establish a connection to your server s home page using https in the URL:

 https://www.snake.net/ 

If you re using your own self-signed server certificate, your browser probably will present a series of dialog boxes complaining about the certificate. Just go ahead and accept the certificate anyway. Then you should see your site s home page, as well as a lock icon at the bottom of the browser window displayed in its locked state. The complaints occur because the certificate does not originate from a recognized certificate authority and browsers warn their users when they connect to a server that doesn t provide a certificate from a known source. The connection will still work, but clients who don t understand why this happens will be suspicious, which is completely antithetical to the assurance you re trying to provide by using secure connections! You can get a commercial certificate so that your visitors can connect without warnings. Some of the vendors provide free trial versions that you can use for testing and evaluation purposes before investing in a for-pay certificate. Visit their Web sites for information about the trial versions and for the procedure to follow to obtain an official certificate.

It s likely that when you start Apache with SSL support enabled, you ll be prompted to supply the passphrase for the server s private key file. This happens because the server s private key is encrypted and protected with a password for additional security, but it s not very convenient if you normally plan to start Apache at system startup time automatically. (If your server reboots while you re not around, the startup process will stop at the point where it launches Apache until you enter the private key password.) You can remove the encryption from the key file so that you don t have to supply the password each time Apache starts but be aware that if you do so, and someone gains access to the key file, your security will be compromised.

To create an unencrypted version of the key file, first back up the encrypted version, then create a new version without the password and make sure no one but root can access it. You can do this using the following commands, assuming the file is named server.key and is located in the ssl.key directory under /usr/local/apache/conf. When prompted for the PEM passphrase, enter your server key password.

 # cd /usr/local/apache/conf/ssl.key  # cp server.key server.key.orig  # openssl rsa -in server.key.orig -out server.key  read RSA key  Enter PEM pass phrase:  writing RSA key  # chmod 400 server.key server.key.orig 

Setting Up Secure MySQL Connections

If your Apache and MySQL servers are running on the same host, you can have your scripts connect to MySQL using the host name localhost rather than the host s domain name. Then, traffic over the connection will be routed through the software loopback interface rather than onto any physical network. On the other hand, if the servers run on different hosts, traffic between your Web scripts and MySQL has to go over a network and may be subject to eavesdropping. To protect against this, you can use SSH (secure shell) to forward MySQL traffic from your programs over an encrypted channel to the MySQL server.

Normally, a client such as the mysql program or a DBI script connects to the MySQL server and talks to it directly. When you use SSH to forward the connection, the client program connects instead to a local SSH process running on the same machine. The local SSH process then sends traffic over an encrypted connection to a remote SSH process running on the database host. The remote SSH process contacts the MySQL server on your behalf. Traffic from the server back to the client program gets routed in the other direction over this same encrypted connection. What this means is that instead of unencrypted traffic flowing between MySQL and its clients over the network where anyone with a sniffer can intercept it, that traffic is encrypted and protected from eavesdropping.

This section describes how to implement secure MySQL connections by setting up SSH forwarding. To get this to work, you must have SSH installed on both the Web and database hosts. You must also configure your scripts to connect to the local SSH forwarder running on the Web host, rather than directly to the MySQL server on the database host. (If your scripts open a connection to MySQL by calling a library routine, this is easy just change that routine.) The instructions here assume you have OpenSSH installed on each host and that you have a version recent enough to support SSH protocol version 2. You can use other SSH implementations, but the commands may be somewhat different than those shown here.[4]

[4] An alternative to SSH is Stunnel, which sets up encrypted tunnels between hosts using OpenSSL. See http://stunnel.mirt.net/ and http://www.stunnel.org/.

For this discussion, assume that the Web and database hosts are named www.snake.net and db.snake.net, and that there is an account for a user named paul on each host. You should substitute your own login name and host names, of course. I ll show the sequence of steps needed to set up a forwarding connection, but if you re already using SSH (for example, as an alternative to Telnet), you may already have performed some of the earlier parts of the sequence.

First, you ll need to generate your encryption keys if you don t already have them. To generate private and public key files, run this command on the Web server host www.snake.net:

 % ssh-keygen -t dsa  Generating public/private dsa key pair.  Enter file in which to save the key (/u/paul/.ssh/id_dsa):  Created directory '/u/paul/.ssh'.  Enter passphrase (empty for no passphrase): SomePassPhrase  Enter same passphrase again: SomePassPhrase  Your identification has been saved in /u/paul/.ssh/id_dsa.  Your public key has been saved in /u/paul/.ssh/id_dsa.pub.  The key fingerprint is:  cb:9e:ac:3d:80:32:bc:bf:cf:87:59:5e:60:33:c6:25 paul@www.snake.net 

This creates a directory named .ssh in your home directory and writes files there named id_dsa and id_dsa.pub to hold your private and public keys. The command uses -t dsa to specify DSA-type encryption. You can use -t rsa to specify RSA encryption instead, in which case the files will be named id_rsa and id_rsa.pub. (If your version of ssh-keygen doesn t support the -t option, try ssh-keygen -d.) Then log in on the database server host db.snake.net and run the ssh-keygen command there, too. This will ensure that the .ssh directory is set up and has the proper permissions on both hosts.

Next, copy your public key file id_dsa.pub (or id_rsa.pub) from www.snake.net and append it to the authorized_keys2 file in the .ssh directory on db.snake.net. (If authorized_keys2 doesn t exist, create it.) Make sure that authorized_keys2 is owned by you and has mode 600. If it doesn t belong to you or it doesn t have a restrictive access mode, SSH will probably assume that it s been compromised by an outside user and refuse to use it.

After you ve installed your public key on db.snake.net, try using the ssh program to log in from www.snake.net to db.snake.net:

 % ssh -2 db.snake.net  Enter passphrase for key '/u/paul/.ssh/id_dsa': 

Enter your passphrase to log in, and then log out again. (The first time you run this command, ssh may present you with a dialog about establishing the authenticity of the remote host. Once you add that host to the list of known hosts, the dialog won t be presented again.)

If you want to be able to use ssh in the other direction (that is, to log in from db.snake.net to www.snake.net), copy your public key on db.snake.net to the authorized_keys2 file on www.snake.net. (It s a good idea to do this, because it starts you moving toward SSH and away from Telnet, which is a notoriously insecure protocol.)

Now you should be able to set up a forwarding process. Try running the following command on www.snake.net:

 % ssh -2 -N -f -L 3307:localhost:3306 db.snake.net  Enter passphrase for key '/u/paul/.ssh/id_dsa': 

The final argument of this command, db.snake.net, specifies the host to which the connection should be forwarded. The -L option specifies a local forwarder; the command sets up a local SSH process to listen on port 3307, and a counterpart remote SSH process that forwards to its own local port 3306 (which is the port that MySQL listens to). Note that localhost:3306 in the -L option is interpreted by the remote SSH process; therefore, it refers to port 3306 on db.snake.net. The other arguments have meanings as follows:

  • -2 specifies SSH protocol version 2; this is needed because the command also uses -N, which isn t supported by version 1.

  • -N says that we just want to forward traffic. Without this argument, ssh expects you to specify a command to be executed on the remote host.

  • -f causes ssh to run in the background.

Test the forwarder by trying to connect through it to the MySQL server. You can do this using the mysql program. Suppose you normally connect to MySQL from www.snake.net by running this command:

 % mysql -h db.snake.net -p -u webdev webdb  Enter password: webdevpass 

To use the forwarder instead, connect to local port 3307 like this:

 % mysql -h 127.0.0.1 -P 3307 -p -u webdev webdb  Enter password: webdevpass 

What s happening here is that the ssh command has set up a local process on www.snake.net that is waiting for connections to port 3307. When you run mysql with the -h 127.0.0.1 and -P 3307 arguments, it connects to that process, which sends traffic over a secure connection to the counterpart remote SSH process running on db.snake.net. The remote SSH sends the traffic to port 3306 on its own host, where the MySQL server is listening. This completes the connection between the mysql program on www.snake.net and the MySQL server on db.snake.net.

When connecting through the forwarder, it s important to use 127.0.0.1 rather than the host name localhost, even though in most contexts the two are synonymous. MySQL programs interpret localhost as having a special meaning of connect to the local server using a UNIX domain socket if possible. Using the IP number explicitly requests a TCP/IP connection.

The SSH forwarder can be used by your DBI scripts, too. Suppose you currently connect to MySQL like this:

 $dbh = DBI->connect ("DBI:mysql:host=db.snake.net;database=webdb",                      "webdev", "webdevpass", {PrintError => 0, RaiseError => 1}); 

Change that to connect to port 3307 on the local host (here, too, it s important to use 127.0.0.1 rather than localhost for the host value):

 $dbh = DBI->connect ("DBI:mysql:host=127.0.0.1;port=3307;database=webdb",                      "webdev", "webdevpass", {PrintError => 0, RaiseError => 1}); 

You can also set up a forwarder by starting it from db.snake.net. This is called a remote forwarder. ( Remote is relative to the host on which the clients run.) To ini-tiate a forwarding process from db.snake.net, make sure you ve installed your public key from that host into authorized_keys2 on www.snake.net. Then kill the SSH lis-tener on www.snake.net if it s still running and run this command on db.snake.net:

 % ssh -2 -N -f -R 3307:localhost:3306 www.snake.net  Enter passphrase for key '/u/paul/.ssh/id_dsa': 

This command involves the same two hosts as the previous ssh command, but uses -R rather than -L to specify that the direction of the forwarding is reversed, relative to the host from which you run the command. After starting this forwarder on db.snake.net, you should be able to connect to the MySQL server from www.snake.net using the same command as when you re running a local forwarder:

 % mysql -h 127.0.0.1 -P 3307 -p -u webdev webdb  Enter password: webdevpass 

The preceding procedure shows how to start an SSH forwarder manually. If you want to set up a forwarding connection automatically at system boot time, there are some additional issues to consider:

  • You need to add a step for invoking the forwarding process during the system startup sequence.

  • You don t want ssh to issue any password prompts. You may not be around to answer them, and you don t want the startup sequence to hang because of that. This can be done by using a private key that doesn t have any passphrase. That means you should run the forwarder from a restricted account that doesn t allow logins.

The general procedure for setting up a special forwarding account is as follows:

  • Pick an account name to use and create accounts with that name on both the Apache and MySQL server hosts.

  • Log in to each host under the new account name and run ssh-keygen to generate the private and public key files. However, when you re prompted for the passphrase, just press Return. This will allow ssh to be run without having to specify a password. Then install the public key file from each host into the .ssh/authorized_keys2 file on the other.

  • Try logging in using ssh from one host to the other under the new account name to make sure there s no password prompt.

  • Change the account shell on both hosts to /bin/false. This will disallow logins, but still allow forwarding.

  • Modify the system startup process of one of the hosts to create an SSH forwarder. You can use su or sudo to run the command under the user ID for your forwarding account.

only for RuBoard - do not distribute or recompile


MySQL and Perl for the Web
MySQL and Perl for the Web
ISBN: 0735710546
EAN: 2147483647
Year: 2005
Pages: 77
Authors: Paul DuBois

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net