Windows下Apache+SSL+Tomcat測試環境搭建

如果在Httpd.conf中沒有設置ServerName,在啓動Apache時會報Could not determine the server's fully qualified domain name, using ${yourIP} for ServerName
錯。只要在Httpd.conf中增加 ServerName wangqs就可以了。

在windows中,可以在HKEY_LOCAL_MACHINE/SOFTWARE/Apache Group/Apache中找到Apache的配置信息,如果作爲了Windows服務,可以在HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet、Services/中找到相應的定義
配置Apache的SSL通道
需要軟件:Apache2.0.59、
          Apache SSL Module注意對Apache版本的一致、
   OpenSSL(以上資源可從我的資源中下載,需要點數,呵呵)

   就是Apache增加模塊的一些基本。關鍵點如下:
   在Httpd.conf中增加 include conf/ssl.conf(ssl.conf中對SSL Module進行了配置)
   配置SSL也就是在Apache中配置了一個虛擬主機
   對SSL的配置需要主要該虛擬主機名也即ServerName的配置,必須和服務器證書的Custom Name一致,否則報錯
   在ssl.conf中指定服務器證書的位置以及私鑰所在的位置。如果要求建立雙向鏈接還需要執行CA證書的位置。如果對於通過SSL進來的請求需要發送到其他服務器,如需要經過JK發送到Tomcat,在virtualHost中增加相應的轉發。
   Listen wangqs:443
   <VirtualHost wangqs:443>
       DocumentRoot "d:/data/apache/www"
              ServerName wangqs:443
              SSLEngine On
       #server cert
              SSLCertificateFile conf/server.crt
       #server private key
              SSLCertificateKeyFile conf/server.key
              ErrorLog logs/SSL.log
              LogLevel debug
              JKMount /*.srv ajp13
              JKMount /*.jsp ajp13
   </VirtualHost>


   也可以不要ssl.conf這個配置文件,直接將上面的這段虛擬主機配置信息增加到Httpd.conf文件下面
   參考 1、http://blog.ericsk.org/archives/215
        2、http://tud.at/programm/apache-ssl-win32-howto.php3
        3、http://www.choucou.com/article.asp?id=118
        4、http://www.openssl.org/docs/apps/x509.html
        5、http://dev2dev.bea.com.cn/bbsdoc/2007/03/java-soa-pass-ssl-certif.html
        6、http://www.cnblogs.com/bjrmt/archive/2006/08/01/464634.html
   如果要求客戶訪問時出示證書,沒有證書不允許訪問時,修改ssl.conf中的如下配置:
   #證書目錄
   SSLCACertificatePath conf/certs
   #ca證書位置
          SSLCACertificateFile conf/certs/ca.crt
          SSLCertificateChainFile conf/certs/ca.crt
          #要求用戶出示證書,參數可以取值{none, optional, require and optional_no_ca} depth根據證書籤署的實際情況設置
   SSLVerifyClient require
          SSLVerifyDepth  1
   證書的生成使用openssl,簡要指令如下:
   OpenSSL
產生CA自簽名證書:
# genrsa [產生密鑰命令] -out[密鑰文件輸出路徑] 1024 [密鑰位數]
openssl genrsa -out ca/ca-key.pem 1024

# req[產生證書命令] -new[新生成] -out[證書文件輸出路徑] -key[私鑰文件路徑]

openssl req -new -out ca/ca-req.csr -key ca/ca-key.pem -subj $CA_DN

# x509[簽發x509證書命令] -req[輸入待簽發證書] -in[輸入待簽發證書文件路徑] -out[產生x509證書文件輸出路徑]
# -signkey[自簽發密鑰文件路徑] -days[證書有效期]
openssl x509 -req -in ca/ca-req.csr -out ca/ca-cert.pem -signkey ca/ca-key.pem -days 365

# 生成CA證書: ca/ca-cert.pfx, 注意一定要記住導出密碼:默認爲 ssl
# pkcs12[生成PKCS12格式證書命令] -export[導出文件] -clerts[僅導出client證書] -password[導出密碼]
# -in[輸入的client證書文件路徑] -inkey[client證書密鑰文件路徑] -out[導出PKS12格式文件路徑]

openssl pkcs12 -export -clcerts -in ca/ca-cert.pem -inkey ca/ca-key.pem -out ca/ca-cert.pfx

#私鑰
openssl genrsa -des3 -out ssl/ca.key 1024
#請求證書
openssl req -config openssl.cnf -new -key ssl/ca.key -out ssl/ca.csr
#自簽名
openssl x509 -days 3650 -req -signkey ssl/ca.key -in ssl/ca.csr -out ssl/ca.crt

openssl genrsa -out ssl/server.key 1024
openssl req -config openssl.cnf -new -key ssl/server.key -out ssl/server.csr
#使用CA的私鑰給服務器端證書籤名
openssl ca -config openssl.cnf -days 3650 -cert ssl/ca.crt -keyfile ssl/ca.key -in ssl/server.csr -out ssl/server.crt

openssl genrsa -out ssl/client.key 1024
openssl req -config openssl.cnf -new -key ssl/client.key -out ssl/client.csr
openssl ca -config openssl.cnf -days 3650 -cert ssl/ca.crt -keyfile ssl/ca.key -in ssl/client.csr -out ssl/client.crt
openssl pkcs12 -export -clcerts -in ssl/client.csr -inkey ssl/client.key -out ssl/client.pfx

在客戶端只有一條這樣的證書時,不會彈出證書選擇框要求用戶進行證書選擇,在多於一張該CA簽發的證書時就會彈出證書選擇框要求用戶進行證書選擇
如果需要在Tomcat中提取用戶用來登錄的證書信息,需要配置Tomcat的SSL通道,在Apache和Tomcat之間建立起單向SSL連接。Tomcat的SSL配置網上有很多相關資料,不再羅嗦,我的server.xml中配置  
<Connector port="8443"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" debug="0" scheme="https" secure="true"
               clientAuth="false" keystoreFile="D:/developEnv/server/Tomcat528/conf/server.keystore" keystorePass="111111"
        truststoreFile="D:/developEnv/server/Tomcat528/conf/server.truststore" turststorePass="111111" sslProtocol="TLS"/>
<Connector port="8009" enableLookups="false" redirectPort="8443" debug="0" protocol="AJP/1.3"/>
JK的worker.properties無需修改,由於需要Apache將客戶登錄的證書信息轉發給Tomcat,需要修改SSL.conf,將 SSLOptions +ExportCertData 註釋去掉,ExportCertData:This exports two additional environment variables: SSL_CLIENT_CERT and SSL_SERVER_CERT. These contain the PEM-encoded certificates of the server (always existing) and the client (only existing when client authentication is used). This can be used to import the certificates into CGI scripts).
這樣在Servlet進行證書信息的提取:import java.security.Principal;
 import java.security.cert.X509Certificate;
 X509Certificate[] certChain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
            if (certChain == null) {
                out.println("no javax.servlet.request.X509Certificate instance");
            } else {
                int len = certChain.length;
               if (len > 0) {
                    X509Certificate cert = (X509Certificate) certChain[0];
                    Principal pSubject = cert.getSubjectDN();
                    certSubject = pSubject.getName();
                }
Apache很強大的。

以下爲參考2的內容:
        The Apache + SSL on Win32 HOWTO
Version 1.6.6 (changelog: view source)

A newer and hopefully more often updated version of this HOWTO which also covers Apache 2 is available from http://raibledesigns.com/tomcat/ssl-howto.html. Also check out this tutorial covering Apache 2 on Windows Server 2003 if you use that.

Spanish translation maintained by Sergio Artigas

French translation maintained by Jean-Francois Moreau

Danish translation maintained by Morten Fischer-Nielsen

Overview
This page describes the installation of the Win32 version of Apache with the mod_ssl extension. The newest version should always be available from http://tud.at/programm/apache-ssl-win32-howto.php3.
This process worked for many people on Windows NT, 98, ME, 2000 and XP; please mail me your suggestions and bug reports.
You can even install Apache with SSL in addition to the Microsoft Internet Information Server if you need to.

Note: sometimes, there are changes between the precompiled apache distributions so that this HOWTO is not correct anymore. In this case, if the current version does not work for you, download an older version - one that was published before the modification date of this HOWTO.
Or, if you like adventures, try to make it run, and mail me if you needed to change anything.

Please note that Apache 1.3.x on Win32 is considered beta quality as it doesn't reach the stability and performance of Apache on Un*x platforms. The 2.x versions are perhaps better but this HOWTO doesn't cover 2.x yet.

1.: Installing Apache
Get the Win32 version of the Apache web server from one of the mirrors. It is called something like apache_x_y_z_win32.exe. This is a self-extracting archive that contains the Apache base system and sample configuration files.

Don't mix Apache versions 1.3 and 2! It won't work. If you find 1.3.x on modssl.org, you cannot expect it to work with 2.0.x.

Install Apache as described in http://www.apache.org/docs/windows.html.

Note: You can skip this step and get a full Apache+SSL distribution from modssl.org, as described below. There will be no fancy installation program but you won't need to overwrite the stock Apache files. This is the better way if you are experienced and don't fear editing configuration files (which you will need to do anyway).

Change at least the following parameters in Apache-dir/conf/httpd.conf:
[Replace all occurences of www.my-server.dom with the real domain name!]

Port 80 to # Port 80 (Comment it out; Port is not necessary, Listen overrides it later.)
(if not in addition to IIS) Listen 80
Listen 443 (So your server listens on the standard SSL port)
ServerName www.my-server.dom
(if in addition to IIS) DocumentRoot and the corresponding <Directory some-dir> to your Inetpub/wwwroot
Install the Apache service (NT/2000 only) and start the server. Verify that everything works before proceeding to the SSL installation because this limits the possible errors.

Try http://www.my-server.dom:443/. It won't be encrypted yet but if this works then the port configuration (port 443) is right.

2.: Getting OpenSSL and mod_ssl
Go to http://www.modssl.org/contrib/ or http://hunter.campbus.com/ and find a file called like Apache_X-mod_ssl_Y-openssl_Z-WIN32[-i386].zip. Download and unzip it to a new directory.
If you need the newest version, you will have to compile it yourself if it is not there. Don't ask me about it; I don't have it, I don't compile the versions on modssl.org, and I don't have access to development tools on Win32.

Copy the files ssleay32.dll and libeay32.dll from the Apache/modssl distribution directory to WINNT/System32. This is important! About 70 % of the e-mails I receive is because people forget to do this. If you don't find those files or openssl.exe in the apache zip, get a file called like openssl-version-win32.zip from one of the download sites.

You'll need a config file for OpenSSL.exe. Here is one (right-click on it and "Save as..."). (There is an openssl.cnf in the distribution with different wording of some questions, but it should do it, too.) Copy it to the directory openssl.exe is in.
(This is a normal text file. It is really called so; however, some Windows versions insist on hiding the extension from you. You can edit it with Windows notepad or a good editor, but it shouldn't be necessary.)

3.: Creating a test certificate
The following instructions are from http://www.apache-ssl.org/#FAQ.

openssl req -config openssl.cnf -new -out my-server.csr
This creates a certificate signing request and a private key. When asked for "Common Name (eg, your websites domain name)", give the exact domain name of your web server (e.g. www.my-server.dom). The certificate belongs to this server name and browsers complain if the name doesn't match.

openssl rsa -in privkey.pem -out my-server.key
This removes the passphrase from the private key. You MUST understand what this means; my-server.key should be only readable by the apache server and the administrator.
You should delete the .rnd file because it contains the entropy information for creating the key and could be used for cryptographic attacks against your private key.

openssl x509 -in my-server.csr -out my-server.cert -req -signkey my-server.key -days 365
This creates a self-signed certificate that you can use until you get a "real" one from a certificate authority. (Which is optional; if you know your users, you can tell them to install the certificate into their browsers.) Note that this certificate expires after one year, you can increase -days 365 if you don't want this.

If you have users with MS Internet Explorer 4.x and want them to be able to install the certificate into their certificate storage (by downloading and opening it), you need to create a DER-encoded version of the certificate:
openssl x509 -in my-server.cert -out my-server.der.crt -outform DER

Create an Apache/conf/ssl directory and move my-server.key and my-server.cert into it.

4.: Configuring Apache and mod_ssl
Copy the executable files (*.exe, *.dll, *.so) from the downloaded apache-mod_ssl distribution over your original Apache installation directory (remember to stop Apache first and DO NOT overwrite your edited config files etc.!).

Find the LoadModule directives in your httpd.conf file and add this after the existing ones, according to the file you have found in the distribution:

LoadModule ssl_module modules/ApacheModuleSSL.dll
or
LoadModule ssl_module modules/ApacheModuleSSL.so
or
LoadModule ssl_module modules/mod_ssl.so
in newer versions.

In newer versions of the distribution, it could also be necessary to add
AddModule mod_ssl.c
after the AddModule lines that are already in the config file.

Add the following to the end of httpd.conf:

# see http://www.modssl.org/docs/2.8/ssl_reference.html for more info
SSLMutex sem
SSLRandomSeed startup builtin
SSLSessionCache none

SSLLog logs/SSL.log
SSLLogLevel info
# You can later change "info" to "warn" if everything is OK

<VirtualHost www.my-server.dom:443>
SSLEngine On
SSLCertificateFile conf/ssl/my-server.cert
SSLCertificateKeyFile conf/ssl/my-server.key
</VirtualHost>


Don't forget to call apache with -D SSL if the IfDefine directive is active in the config file!

You might need to use regedit to change the key HKEY_LOCAL_MACHINE/SOFTWARE/Apache Group/Apache/X.Y.Z to the correct number if the apache.exe from modssl.org/contrib is not the same version as the previously installed one. (This seems not to be necessary with recent versions.)

Also, if you use IfDefine directives and start apache as a service, you need to edit the apache command line in the registry (HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Apache2) (I haven't tried this).

Start the server, this time from the command prompt (not as a service) in order to see the error messages that prevent Apache from starting. If everything is OK, (optionally) press CTRL+C to stop the server and start it as a service if you prefer.
If it doesn't work, Apache should write meaningful messages to the screen and/or into the error.log and SSL.log files in the Apache/logs directory.
If something doesn't work, set all LogLevels to the maximum and look into the logfiles. They are very helpful.

DON'T e-mail me or the other contributors without having plain Apache installed (Step 1). We will ignore your request; we are not the Free Apache Helpdesk and there is enough good documentation on configuring Apache; if that is not enough for you, you shouldn't run a secure server anyway. Also, DON'T e-mail without having looked into the error.log and SSL.log with LogLevel set to Debug.

Debugging connect problems
Problems connecting to the server with a browser can have many reasons, many of them on the client (proxy, DNS, general IE dumbness).

So, if you encounter problems connecting with SSL, try another browser and/or look into the settings. If even this doesn't work, you can use OpenSSL to debug the problem.

bb@www$ openssl s_client -connect no-such-machine:443
gethostbyname failure  # Error resolving this DNS name. Connect with the IP address.
connect:errno=2

bb@www$ openssl s_client -connect www1.tud.at:443
connect: Connection refused  
connect:errno=111
# No SSL server on this port. Double-check the Listen and Port directives.

bb@www$ openssl s_client -connect apcenter.apcinteractive.net:443
# everything OK. OpenSSL shows the information it obtained from the server.
CONNECTED(00000003)
depth=0 /C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
verify error:num=18:self signed certificate
verify return:1
depth=0 /C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
verify return:1
---
Certificate chain
 0 s:/C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
   i:/C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIC0TCCAjoCAQAwDQYJKoZIhvcNAQEEBQAwgbAxCzAJBgNVBAYTAmF0MQ0wCwYDV
[...]
9ucXUnk=
-----END CERTIFICATE-----
subject=/C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
issuer=/C=at/ST=Wien/L=Wien/O=APC interactive/OU=Lifecycle Management/CN=apcenter.apcinteractive.net/[email protected]
---
No client certificate CA names sent
---
SSL handshake has read 1281 bytes and written 320 bytes
---
New, TLSv1/SSLv3, Cipher is EDH-RSA-DES-CBC3-SHA
Server public key is 1024 bit
SSL-Session:
    Protocol  : TLSv1
    Cipher    : EDH-RSA-DES-CBC3-SHA
    Session-ID: 49ACE1CF484A67D2C476B923D52110A6FCA1A7CE53D76DF7F233DEBF2333D4FB
    Session-ID-ctx:
    Master-Key: 00E9FA964253752294ECD69C18ADBA527B7170C112E2B3BCB25EA8F4FD847EC46E1FF0194EF8E16985B5E38BF6F12131
    Key-Arg   : None
    Start Time: 980696025
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
[Enter:
GET / HTTP/1.0
and press RETURN twice]
HTTP/1.1 200 OK
Date: Sun, 28 Jan 2001 15:34:58 GMT
Server: Apache/1.3.9 (Win32) mod_ssl/2.4.9 OpenSSL/0.9.4
Cache-Control: no-cache, no-store, must-revalidate, private
Expires: 0
Pragma: no-cache
X-Powered-By: PHP/4.0.4
Last-Modified: Sun, 28 Jan 2001 15:35:00 GMT
Connection: close
Content-Type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
# the server shows its main document

Common problems
Q: I see the following when starting Apache:

Syntax error on line [some number] of ...httpd.conf
Cannot load apache/modules/mod_ssl.so into server
(126) The module could not be found:


A: Did you copy the openssl DLLs to WINNT/SYSTEM32 (or WINDOWS/SYSTEM on Win9x/ME)?
You can verify this by copying openssl.exe into a directory of its own and executing it. If it complains about not being able to find some DLLs, then you haven't copied them into the correct directory.
One user told me that he had this problem even when he did everything right. He then found the problem: corrupt openssl DLLs. So if you get this error despite having done everything correctly, try the openssl DLLs from another version from modssl.org/contrib.

Q: I see the following when starting Apache:

Syntax error on line [some number] of apache/conf/httpd.conf:
Cannot load apache/modules/apachemodulessl.dll into server:
(127) The specified procedure could not be found:
or:
Syntax error on line [some number] of apache/conf/httpd.conf:
Invalid command 'SSLMutex', perhaps mis-spelled or defined by a module not
included in the server configuration

A: You didn't add the AddModule line (or not where it belongs, it belongs below the other AddModule lines).

Q: SSL doesn't work in the browser and I see the following in some logfile:

[Fri Nov 16 15:46:30 2001] [error] OpenSSL: error:1407609C:SSL
routines:SSL23_GET_CLIENT_HELLO:http request [Hint: speaking HTTP to
HTTPS port!?]

A: How much clearer can an error message get? Your VirtualHost or Listen configuration is wrong.

Questions about Java servlets, OpenSSL compilation etc.
Don't ask us about installing servlet extensions, recompiling mod_ssl or Apache with EAPI, recompiled versions etc. We have no idea and won't be able help you. We are just users and not programmers.
If your needs are so special, you are better off with a Debian GNU/Linux or OpenBSD server. It will save you lots of trouble. Really.

Links
Apache Web Server: http://www.apache.org
mod_ssl: http://www.modssl.org
mod_ssl configuration: http://www.modssl.org/docs/2.8/ssl_reference.html
OpenSSL: http://www.openssl.org
PHP Hypertext preprocessor: http://www.php.net

Author of this document: Balázs Bárány (http://tud.at)
(mail me your questions, but only after having looked into the error logs with LogLevel debug. You can mail me in English, German and Hungarian.
If I am constantly ignoring your e-mail, read all the hints in the HOWTO about how to e-mail me.)

Contributor: Horst Bräuner (OpenSSL configuration on NT)
Contributor: Christoph Zich (Windows 98)
Contributor: Torsten Stanienda (Test with 1.3.12, IfDefine directive)
Contributor: Peter Holm (Listen and Port directives)

Last change: 2007-08-25

This document can be redistributed under the GNU Free Documentation License. © Balázs Bárány 1999-2007

 

引用3部分內容如下:

5、這時就有了三張證書和三個私鑰,一個是demoCA下的根證書,ssl.crt下的服務器證書和客戶證書。及demoCA/private下的根key,ssl.crt下的服務器key和客戶key,在conf下的ssl.conf下指定證書的位置和服務器key的位置.

我是在conf下建立一個ssl.crt目錄,並將所有的key和證書放到這裏

#cp demoCA/cacert.pem cacert.pem

同時複製一份證書,更名爲ca.crt

#cp cacert.pem ca.crt

步驟三、編輯ssl.conf

#cd /usr/local/apache/conf

編輯ssl.conf

指定服務器證書位置

SSLCertificateFile /usr/local/apache/conf/ssl.crt/server.crt

指定服務器證書key位置

SSLCertificateKeyFile /usr/local/apache/conf/ssl.crt/server.key

證書目錄

SSLCACertificatePath /usr/local/apache/conf/ssl.crt

根證書位置

SSLCACertificateFile /usr/local/apache/conf/ssl.crt/cacert.pem

開啓客戶端SSL請求

SSLVerifyClient require

SSLVerifyDepth 1

啓動ssl

/usr/local/apache/bin/apachectl startssl

會要求輸入server.key的密碼
啓動,這樣一個默認的SSL服務器及http服務器就啓動了,

步驟四、安裝和使用證書
把剛纔生成的證書:根證書ca.crt和客戶證書client.pfx下到客戶端,並安裝,
ca.crt安裝到信任的機構,client.pfx直接在windows安裝或安裝到個人證書位置,然後用IP訪問HTTP和https服務器。

當OpenSSL 提示您“CommonName”時,確保你輸入了服務器的FQDN("Fully Qualified Domain Name" ,即,當您爲一個以後用https://www.foo.dom/訪問的網站生成一個CSR時,這裏輸入"www.foo.dom"。

否則會發生證書驗證的時候(跳出來一個對話框) 有一個感嘆號

第三項:該安全證書上的名稱無效,或與站點名稱不匹配 (黃色歎號)

當OpenSSL 提示您“CommonName”時,確保你輸入了服務器的FQDN("Fully Qualified Domain Name" ,即,當您爲一個以後用https://www.foo.dom/訪問的網站生成一個CSR時,這裏輸入"www.foo.dom"。

否則會發生證書驗證..........

https://DomainName要和證書裏的CommonName項對應吧!表示是爲
DomainName發的證書?對

總結:
解決問題花費時間:4個小時
主要時間花費在證書體系的生成,對OpenSSL不熟悉

發佈了28 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章