Apache/SSL, MySQL und PHP

aus openSUSE, der freien Wissensdatenbank

Apache mit OpenSSL, MySQL, PHP auf OpenSuSE 11.0

Zweck dieser Anleitungung ist es, ein Minimalsystem unter OpenSuse 11.0 aufzusetzen und eine Übersicht über die enthaltenen Tools zu geben. Dies kann als Einstieg für zahllose Webanwendungen dienen, die auf der Basis von Apache MySQL und PHP (xAMP) laufen. Teilweise läßt sich der Text auch als Anleitung verwenden, um die einzelnen Dienste zu installieren oder zu konfigurieren.

Der Text bietet lediglich eine grobe Übersicht. Führen sie die Befehle nicht unhinterfragt aus, wenn Sie sie nicht verstehen. Beachten Sie auch, daß Sie mit diesem Minimalsystem bei weitem noch nicht fertig sind. Wesentliche Schritte, die anschließend noch folgen müssen, sind z.B. die Absicherung Ihrers Systems und diverse Feineinstellungen.

Am besten ist es, wenn Sie die folgenden Schritte als root auf der Konsole ausführen. Alternativ dazu wäre es möglich, daß Sie sich für die einzelnen Befehle über sudo administrative Rechte geben oder Werkzeuge der grafische Oberfläche nutzen. Im folgenden wird die Default-Shell von Open SUSE verwendet, i.d.R. ist das die bash (Bourne Again Shell).


Inhaltsverzeichnis

Ausgangspunkt und Vorgehensweise

Vorausgesetzt wird

  • eine funktionierende OpenSUSE 11.0 Installation
  • Grundkenntnisse von Unix and Unix-ähnlichen Systemen
  • Grundkenntnisse von Computernetzwerken

Im Verlauf der Installation werden

  • einige SUSE-spezifische Tools verwendet, z.B. YaST
  • ein behelfsmäßiges SSL-Zertifikat erstellt

Noch kurz zur Darstellung: In den Kästen werden jeweiligen die Befehle mit dem Prompt angegeben, so wie Sie sie auch in der Konsole sehen, also <Hostname>:<Arbeitsverzeichnis> # <Befehl>. I.d.R. folgt danach ein zweiter Kasten, der die Ausgabe enthält, die der Befehl erzeugt, z.B.:

   orion:/ # uname -a
Linux orion 2.6.25.20-0.5-default #1 SMP 2009-08-14 01:48:11 +0200 i686 athlon i386 GNU/Linux

MySQL

Installieren Sie den MySQL:

   orion:~ # yast2 -i mysql

Konfigurieren Sie den MySQL-Server so, daß er automatisch beim Booten startet:

   orion:~ # chkconfig --add mysql
mysql                     0:off  1:off  2:on   3:on   4:off  5:on   6:off

Der Ausgabe sollte zu entnehmen sein, daß die Runlevel 3 und 5 aktiv sind. Starten Sie nun den MySQL-Server:

   orion:~ # rcmysql start
 Creating MySQL privilege database... 
 Installing MySQL system tables...
 OK
 Filling help tables...
 OK
 PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
 To do so, start the server, then issue the following commands:
 /usr/bin/mysqladmin -u root password 'new-password'
 /usr/bin/mysqladmin -u root -h orion password 'new-password'

 Alternatively you can run:
 /usr/bin/mysql_secure_installation

 which will also give you the option of removing the test
 databases and anonymous user created by default.  This is
 strongly recommended for production servers.

 See the manual for more instructions.

 You can start the MySQL daemon with:
 cd /usr ; /usr/bin/mysqld_safe &

 You can test the MySQL daemon with mysql-test-run.pl
 cd mysql-test ; perl mysql-test-run.pl

 Please report any problems with the /usr/bin/mysqlbug script!

 The latest information about MySQL is available on the web at
 http://www.mysql.com
 Support MySQL by buying support/licenses at http://shop.mysql.com
 Updating MySQL privilege database... 
 Looking for 'mysql' in: /usr/bin/mysql
 Looking for 'mysqlcheck' in: /usr/bin/mysqlcheck
 Running 'mysqlcheck'...
 mysql.columns_priv                                 OK
 mysql.db                                           OK
 mysql.func                                         OK
 mysql.help_category                                OK
 mysql.help_keyword                                 OK
 mysql.help_relation                                OK
 mysql.help_topic                                   OK
 mysql.host                                         OK
 mysql.proc                                         OK
 mysql.procs_priv                                   OK
 mysql.tables_priv                                  OK
 mysql.time_zone                                    OK
 mysql.time_zone_leap_second                        OK
 mysql.time_zone_name                               OK
 mysql.time_zone_transition                         OK
 mysql.time_zone_transition_type                    OK
 mysql.user                                         OK
 Running 'mysql_fix_privilege_tables'...
 OK
 Starting service MySQL                                                done

Je nach dem aktuellen Zustand Ihres Systems kann die Ausgabe mehr oder weniger abweichen, insbesondere, wenn Sie MySQL schon einmal installiert hatten. Mit netstat können Sie testen, ob der MySQL-Server läuft:

   orion:/ # netstat -lpt | grep "mysql"
tcp        0      0 *:mysql                 *:*                     LISTEN      15826/mysqld        

Als nächstes sollten Sie zumindest ein Paßwort für den root-Account setzen. Sie können hierzu, wie in der o.g. Ausgabe vorgeschlagen, das Script mysql_secure_installation ausführen:

   orion:~ # /usr/bin/mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!


In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):

Wenn Sie MySQL gerade erst installiert haben, drücken Sie Enter. Ansonsten geben Sie das bestehende root-Paßwort ein. Gemeint ist der Datenbankuser root, nicht der gleichnamige Linuxuser.

OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] 

Geben Sie hier ein starkes Paßwort für den root-Account ein. Es sollte mindesten zehn Zeichen lang sein. Verwenden Sie Zahlen, Buchstaben und Sonderzeichen. Verwenden Sie nicht das Paßwort des Linuxusers root.

New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] 
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] 
 ... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] 
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] 
 ... Success!

Cleaning up...



All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Wenn Sie die Default-Einstellungen übernommen haben, ist MySQL jetzt so konfiguriert, daß der root-Account nicht übers Netzwerk, sondern nur lokal zugänglich ist. Testen Sie, ob die Installation erfolgreich war, indem Sie sich einloggen:

   orion:~ # mysql -u root -p <Paßwort>
 Welcome to the MySQL monitor.  Commands end with ; or \g.
 Your MySQL connection id is 9
 Server version: 5.0.51a SUSE MySQL RPM

 Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 mysql> 

Wenn Sie das MySQL-Prompt sehen, wissen Sie, daß der Server läuft und ansprechbar ist. Sie können jetzt SQL-Befehle eingeben, z.B.:

   mysql> SELECT NOW();
+---------------------+
| now()               |
+---------------------+
| 2009-08-20 21:47:24 | 
+---------------------+
1 row in set (0.00 sec) 

Mit exit quit oder /q verlassen Sie den MySQL-Monitor und kehrenzur Shell zurück:

   mysql> exit
Bye

Wechseln Sie für einen letzten Test mit su in Ihren normalen Useraccount und geben Sie nochmals mysql -u root -p ein. Wenn alles geklappt hat, können Sie sich auch als normaler User in den MySQL-Monitor einloggen.

PHP

PHP ist schnell installiert:

   orion:~ # yast2 -i php5

Installieren Sie auch das MySQL-Modul:

   orion:~ # yast2 -i php5-mysql

Weiter unten finden sie noch Hinweise zu weiteren Modulen.

Apache

Als nächstes installieren Sie den Apache 2.2 Server MPM Prefork ...

   orion:/ # yast2 -i apache2

... und das dazugehörende PHP-Modul:

   orion:/ # yast2 -i apache2-mod_php5

Wie bei den meisten Linux-Distributionen gibt es unterschiedliche Paketzusammenstellungen. Schauen Sie deshalb in der Konfigurationsdatei nach, ob unter APACHE_MODULES php5 eingetragen ist:

   orion:/ # less /etc/sysconfig/apache2

Wenn Sie ein wenig scrollen, sollten Sie eine Zeile finden, die etwa so aussieht:

APACHE_MODULES="actions alias auth_basic authn_file authz_host authz_groupfile authz_default authz_user 
authn_dbm autoindex cgi dir env expires include log_config mime negotiation setenvif ssl suexec userdir php5"

Um den Viewer zu beenden drücken Sie "q". Konfigurieren Sie Apache so, daß er beim Booten automatisch startet:

   orion:/ # chkconfig --add apache2
apache2                   0:off  1:off  2:off  3:on   4:off  5:on   6:off

Die Runlevels 3 und 5 sollten aktiv sein. Starten Sie nun Apache:

orion:/ # rcapache2 start
Starting httpd2 (prefork)                                             done

Lassen Sie sich einige Infos zur Version sowie wichtigen Dateien und Verzeichnissen anzeigen:

   orion:/ # httpd2 -V
Server version: Apache/2.2.8 (Linux/SUSE)
Server built:   Jun  6 2008 23:42:07
Server's Module Magic Number: 20051115:11
Server loaded:  APR 1.2.12, APR-Util 1.2.12
Compiled using: APR 1.2.12, APR-Util 1.2.12
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/srv/www"
 -D SUEXEC_BIN="/usr/sbin/suexec2"
 -D DEFAULT_PIDLOG="/var/run/httpd2.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/var/run/accept.lock"
 -D DEFAULT_ERRORLOG="/var/log/apache2/error_log"
 -D AP_TYPES_CONFIG_FILE="/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/etc/apache2/httpd.conf"

Aktivieren Sie SSL. Das geht am einfachsten mit dem Skript a2enflag:

   orion:/ # a2enflag SSL

In Ihrer Konfigurationsdatei /etc/sysconfig/apache2 sollte jetzt das Flag SSL gesetzt sein:

APACHE_SERVER_FLAGS="SSL"

Sie können natürlich auch einen beliegigen Editor nehmen und die APACHE_SERVER_FLAGS von Hand anpassen. Starten Sie Apache danach neu:

   orion:/ # rcapache2 restart
Syntax OK
Shutting down httpd2 (waiting for all children to terminate)          done
Starting httpd2 (prefork)                                             done

Schauen Sie nach, ob der Server auf http- und https-Anfragen wartet:

   orion:/ # netstat -lpt | grep "http"
tcp        0      0 *:www-http              *:*                     LISTEN      13450/httpd2-prefor 
tcp        0      0 *:https                 *:*                     LISTEN      13450/httpd2-prefor


Fehlende Übersetzung

Dieser Artikel ist noch nicht (vollständig) übersetzt. Sie finden den zu übersetzenden Artikel im englischen Wiki unter Apache ssl php mysql.
Wenn Sie ihn übersetzen möchten, dann freuen wir uns über ihre Hilfe. Lesen Sie dazu bitte auch den openSUSE-Stilleitfaden.
Wenn Sie den Artikel vollständig übersetzt haben, dann entfernen Sie bitte diesen Hinweis.

Wenn Sie ein wenig Beschäftigung suchen, schauen Sie sich doch einfach mal die anderen Übersetzungskandidaten an.

Die Firewall konfigurieren (Netfilter)

Zur Konfiguration der Firewall wird oft iptables verwendet. Anstatt die Filterregeln mit einem Skript zu laden können Sie auch Yast nutzen.

   orion:~ # yast2

Es sollte das blaue YaST-Kontrollzentrum erscheinen. Wenn Sie stattdessen die graphische Variante erhalten, geben Sie zusätzlich die Option --ncurses ein. Scrollen Sie mit den Pfeiltasten auf "Sicherheit und Benutzer":

Bild:Bjryast fw1ac.png

Wechseln Sie mit der Tab-Taste in den rechten Teil, markieren Sie den Punkt "Firewall" und drücken Sie Enter. Wenn Sie möchten, daß Apache für andere Rechner erreichbar ist, fügen Sie Apache 2 zu der Liste "Erlaubte Dienste hinzu". Tun Sie dies jedoch nur, wenn Sie wirklich sicher sind, daß Sie das auch wollen. Zum ersten Experimentieren reicht es völlig, wenn Apache erstmal nur auf dem localhost erreichbar ist.

Bild:Bjryast fw2ac.png

Press tab (7 times) until you reach Advanced then press enter.

Press tab (2 times) until you you reach the TCP Ports and type 80 443.

Bild:Bjryast fw3ac.png

Press tab (4 times) until you reach OK and press enter.

Press tab (3 times) until you reach Next.

A configuration summary indicating your changes to your system. Kindly check if:

+ TCP Ports: 443, 80 is shown on Open Services, Ports and Protocol

Bild:Bjryast fw4ac.png

Press enter or F10 to confirm changes and go back to the main menu of Yast2 Control Center.

Press tab twice again and press enter to quit (F9).

To verify if your system allows http (80) and https (443) traffic to pass through your box:

    linux-iifk:~ # iptables -L | less

Check for lines similar to this:

 ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:https
 ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:http

SSL aktivieren

Erzeugen Sie eine behelfsmäßiges SSL-Zertifikat für Ihren Rechner, in dem Sie das Skript gensslcert ausführen. Hierdurch wird u.a. die Datei CA.crt ins Verzeichnis /srv/www/htdocs geschrieben.

   orion:~ # gensslcert
comment         mod_ssl server certificate
name
C               XY
ST              unknown
L               unknown
U               web server
O               SuSE Linux Web Server
CN              orion.h11.berlin
email           webmaster@orion.h11.berlin
srvdays         730
CAdays          2190

creating CA key ...
859033 semi-random bytes loaded
Generating RSA private key, 2048 bit long modulus
...................................................................................+++
.................................+++
e is 65537 (0x10001)

creating CA request/certificate ...
„/etc/apache2/ssl.crt/ca.crt“ -> „/srv/www/htdocs/CA.crt“

creating server key ...
859033 semi-random bytes loaded
Generating RSA private key, 1024 bit long modulus
........++++++
.....++++++
e is 65537 (0x10001)

creating server request ...
creating server certificate ...
Signature ok
subject=/C=XY/ST=unknown/L=unknown/O=SuSE Linux Web Server/OU=web server/CN=orion.h11.berlin/emailAddress=webmaster@orion.h11.berlin
Getting CA Private Key

Verify: matching certificate & key modulus

Verify: matching certificate signature
/etc/apache2/ssl.crt/server.crt: OK

Wechseln Sie dann ins virtual-hosts-Verzeichnis von Apache ...

   orion:~ # cd /etc/apache2/vhosts.d

... und kopieren Sie die Datei vhost-ssl.template in eine conf-Datei, die den Namen Ihres Rechners hat (in diesem Fall orion):

   orion:/etc/apache2/vhosts.d # cp vhost-ssl.template orion.conf

Starten Sie dann Apache neu:

   orion:~ # rcapache2 restart
Syntax OK
Shutting down httpd2 (waiting for all children to terminate)      done
Starting httpd2 (prefork)                                         done


Den http-Server testen

Erzeugen Sie ein php-Skript, das Ihnen die aktuelle Konfiguration Ihres Systems ausgibt:

   orion:~ # echo "<?php phpinfo(); ?>" >> /srv/www/htdocs/test.php

Rufen Sie die Seite mit Ihren Browser auf:

   http://<ihre.Domain>/test.php

Sie sollten eine Seite angezeigt bekommen, die so ähnlich aussieht, wie diese:

Bild:Bjryast fw5ac.png

Scrollen Sie zum MySQL-Abschnitt:

PHP Version 5.3.0

System 	Linux orion 2.6.25.20-0.5-default #1 SMP 2009-08-14 01:48:11 +0200 i686
Build Date 	Aug 19 2009 23:08:38 

[...]

mysql
MySQL Support	enabled
Active Persistent Links 	0
Active Links 	0
Client API version 	5.0.51a
MYSQL_MODULE_TYPE 	external
MYSQL_SOCKET 	/var/lib/mysql/mysql.sock
MYSQL_INCLUDE 	-I/usr/include/mysql
MYSQL_LIBS 	-L/usr/lib -lmysqlclient


Den https-Server testen

   https://<ihre.Domain>/test.php

Da Sie Ihr Zertifikat nicht von einer offiziellen Zertifizierungstelle signiert wurde, zeigt der Browser eine Warnung an:

Bild:Bnjr lamp ssl 1.png

Es folgen einige Beispiele für solche Sicherheitswarnungen und die

a) Firefox: Dieser Verbindung wird nicht vertraut [...] Dem Zertifikat wird nicht vertraut, weil das Aussteller-Zertifikat unbekannt ist. Es wurden keine Server-Namen gefunden, für die dieses Zertifikat gültig ist. (Fehlercode: sec_error_unknown_issuer)

-- Klicken Sie "Ausnahmen hinzufügen", "Zertifikat ansehen", "Ausnahmeregel bestätigen"

b) Opera: The server’s certificate chain is incomplete and the signer(s) are not registered. Accept?

-- Click “Approve”

c) Lynx: SSL error: unable to get local issuer certificate - Continue ? (y)

-- Just press enter until you get the same output as http connection

The output should be the same as the one you saw using http connection.

Bild:Bnjr lamp ssl 2.png

Worth noting is the inclusion of the hardened php project :)

This server is protected with the Suhosin Patch 0.9.6.2 http://www.hardened-php.net/

Additional notes

  • Remove test.php on the www directory after you have tested the system.
  • Always restart Apache if you have loaded/removed modules by issuing:
    linux-iifk:~ # rcapache2 restart
  • This is also true for changes in PHP
  • Should you need other modules for PHP like gd just replace php5-mysql in the install command. The command should be:
    linux-iifk:~ # yast2 -i php5-gd
  • The config file for PHP is /etc/php5/apache2/php.ini
  • Log files for Apache are located at /var/log/apache2
  • Default data directory for Apache is located at /srv/www/htdocs

You can check which shared modules are present by displaying all the Apache 2 modules by:

    linux-iifk:~ # httpd2 -M
Loaded Modules:
core_module (static)
mpm_prefork_module (static)
http_module (static)
so_module (static)
actions_module (shared)
alias_module (shared)
auth_basic_module (shared)
authn_file_module (shared)
authz_host_module (shared)
authz_groupfile_module (shared)
authz_default_module (shared)
authz_user_module (shared)
authn_dbm_module (shared)
autoindex_module (shared)
cgi_module (shared)
dir_module (shared)
env_module (shared)
expires_module (shared)
include_module (shared)
log_config_module (shared)
mime_module (shared)
negotiation_module (shared)
setenvif_module (shared)
ssl_module (shared)
suexec_module (shared)
userdir_module (shared)
php5_module (shared)
Syntax OK
  • The config file for MySQL is in /etc/my.cnf
  • Log and data files are stored for mysql are stored at /var/lib/mysql
  • Acessing the MySQL server remotely should have tcp port 3306 open on your firewall
  • The command “zypper install” can be used instead of "yast2 -i"
  • Please do not forget to lock down your system.
  • Many,many,many thanks to OpenSuSE, Apache, PHP, Hardened PHP, MySQL, OpenSSL, Opera, Mozilla, Lynx, Vi, KDE, GNU and all Linux folks.

Further reading

For Yast 2 in text mode: http://www.novell.com/documentation/sled10/sled_deployment_sp1/index.html?page=/documentation/sled10/sled_deployment_sp1/data/cha_yast2.html

For tips/guide using zypper: http://en.opensuse.org/Zypper/Usage

For guides on how to configure/use Apache Version 2.2: http://httpd.apache.org/docs/2.2/

For guides on how to configure MySQL: http://dev.mysql.com/doc/refman/5.0/en/

For info about PHP: http://www.php.net/manual/en/

For info about packet filtering on GNU/Linux: http://www.netfilter.org/

For info about OpenSSL: http://httpd.apache.org/docs/2.2/ssl/ http://www.openssl.org/