User Tools

Site Tools


informatica:linux:apache2

This is an old revision of the document!


Apache httpd

apache apache2 httpd web http

Iniciar automaticamente en tiempo de arranque

1. Editar /etc/default/apache2, y como indica el propio fichero, dejar la linea tal que así:

'NO_START=0'

2. Reiniciar la máquina

3. Verificar que el servidor web se arrancó él solito

Seguridad

Por usuario y contraseña

Modificamos el virtualhost de: /etc/apache2/sites-enabled/

<Directory /home/web/datos>
AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile /etc/apache2/contrasenyas
#si hay mas de un usuario lo separamos por espacios
Require user usuario_acceso
</Directory>

Para crear el fichero con usuarios al fichero contrasenyas:

# htpasswd -c /etc/apache2/contrasenyas usuario_acceso

Una vez creado el fichero, MUY IMPORTANTE no poner la opcion -c, para añadir los siguientes usuarios:

  # htpasswd /etc/apache2/contrasenyas usuario_segundo

Acceso por IP

Añadir la directiva:

Order deny,allow
Deny from all
Allow from dev.example.com
Allow from 10.0.0.0/8

Mezclar las dos directivas

Con la opción Satisfy se mezclan las dos opciones.

All: se tiene que cumplir usuario e ip
Any: se tiene que cumplir una de las dos
      <Directory />
              Options Indexes FollowSymLinks Multiviews
              AllowOverride None
              AuthType Basic
              AuthName "Usuari i contrasenya"
              AuthUserFile /etc/apache2/contrasenyes
              Require user hacklab
              Deny from All
              Allow from 10.0.0.0/8
              Satisfy Any
      </Directory>

Hacer peticiones a un servidor apache con Telnet

http://www.apacheweek.com/features/http11

# telnet google.com 80
Trying 173.194.34.209...
Connected to google.com.
Escape character is '^]'.
GET / HTTP/1.0 
HTTP/1.0 302 Found
Location: http://www.google.es/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=b417d3365d4d7c94:FF=0:TM=1328183646:LM=1328183646:S=Zm54DaCFzY3Q2kxB; expires=Sat, 01-Feb-2014 11:54:06 GMT; path=/; domain=.google.com
Date: Thu, 02 Feb 2012 11:54:06 GMT
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.es/">here</A>.
</BODY></HTML>
Connection closed by foreign host.

Proxy inverso

Habilitar módulos

Hay que habilitar los módulos creando los enlaces simbólicos:

/etc/apache2/mods-enabled
proxy_http.load -> ../mods-available/proxy_http.load
proxy.load -> ../mods-available/proxy.load
rewrite.load -> ../mods-available/rewrite.load

Creando el virtual Host

Redirigimos todas las peticiones de mldonkey.lobo99.com a http://localhost:4080/, así podemos acceder a ese puerto desde el 80, por si en estamos detrás de nu proxy que está capado.

<VirtualHost *:80>
      ServerName mldonkey.lobo99.com

      ProxyPass         / http://localhost:4080/
      ProxyPassReverse  / http://localhost:4080/
</VirtualHost>

Permisos

Si nos da un error 403 Forbidden, pTenemos que dar permisos en el fichero:

/etc/apache2/mods-enabled/proxy.conf
   ProxyRequest off
<Proxy *>
    AddDefaultCharset off
    Order deny,allow
    #Deny from all
    Allow from all
</Proxy>

Conexión SSL

Si queremos redirigir a una web https tenemos que habilitar los siguientes módulos:

/etc/apache2/mods-enabled
proxy_connect.load -> ../mods-available/proxy_connect.load
ssl.load -> ../mods-available/ssl.load
ssl.conf -> ../mods-available/ssl.conf

En la configuración del VirtualHost tenemos que poner:

<VirtualHost *:80>
      ServerName admin.lobo99.com

      ProxyRequests off
      SSLProxyEngine on
      ProxyPass         / https://localhost:10000/
      ProxyPassReverse  / https://localhost:10000/
</VirtualHost>

SSL

Habilitar los módulos de ssl en apache

Crear enlace simbólico a ssl.conf y ssl.load en mods-enabled:

#cd /etc/apache2/mods-enabled
#ln -s ../mods-available/ssl.conf ssl.conf
#ln -s ../mods-available/ssl.load ssl.load

o con:

#a2enmod ssl

Generamos certificado:

# openssl req $@ -newkey rsa:4096 -new -x509 -days 3650 -nodes -out /etc/apache2/apache.pem -keyout /etc/apache2/apache.key

Otra forma:

#openssl req -new -x509 -days 365 -sha1 -newkey rsa:1024 -nodes -keyout server.key -out server.crt 
# -x509 identifies that a certificate is required, rather than just a certificate request (see below).
# -days 365 sets the certificate to expire in a year. You may want to extend this period. Make a note of the expiry date so that you can renew it when necessary!
# -sha1 specifies that SHA1 encryption should be used.
# rsa:1024 sets the key as 1024 bit RSA.
# -nodes specifies no passphrase.
# -keyout and -out specify where to store the certificate and key. The key should be root-readable only; the certificate can be world-readable, and must be readable by the user that Apache runs as.

Rellenamos los datos

Country Name (2 letter code) [AU]:ES
State or Province Name (full name) [Some-State]:Barcelona
Locality Name (eg, city) []:Mataro
Organization Name (eg, company) [Internet Widgits Pty Ltd]:prueba
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:
Email Address []:
#chmod 600 /etc/apache2/apache.pem
<VirtualHost *:443>
      ServerAdmin admin@midominio.com
      DocumentRoot /var/www/
      SSLEngine on
                SSLCertificateFile /etc/apache2/apache.pem
                SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown

              Options FollowSymLinks

              Options Indexes FollowSymLinks MultiViews
              # This directive allows us to have apache2's default start page
              # in /apache2-default/, but still have / go to the right place
              # RedirectMatch ^/$ /mail/

     ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

      ErrorLog /var/log/apache2/error.log

      # Possible values include: debug, info, notice, warn, error, crit,
      # alert, emerg.
      LogLevel warn

      CustomLog /var/log/apache2/access.log combined
      ServerSignature On

  Alias /doc/ "/usr/share/doc/"

</VirtualHost>

Pedir un certificado

Para pedir un certificado tenemos que poner lo siguiente:

<Location /cert>
        SSLVerifyClient optional
        SSLVerifyDepth 4
        SSLOptions +ExportCertData +StdEnvVars +StrictRequire
        SSLRequire ****condiciones de validación*****
</Location>

Una de las condiciones de validación puede ser:

        SSLRequire %{SSL_CLIENT_S_DN_OU} in {"CEPSA"}

Sacar información de un certificado:

# openssl x509 -in cacert.pem  -noout -text
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 0 (0x0)
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=ES, ST=ES, O=ES, OU=ES, CN=ES
        Validity
            Not Before: Dec 23 17:10:23 2010 GMT
            Not After : Dec 22 17:10:23 2013 GMT
        Subject: C=ES, ST=ES, O=ES, OU=ES, CN=ES
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (1024 bit)
                Modulus (1024 bit):
                    00:e2:d2:9d:1f:30:d2:bf:85:ba:ac:5b:c1:20:18:
                    20:18:ef:8a:bd:11:fc:3b:24:e0:d1:b2:3f:cb:23:
                    3b:95:20:7f:07:3b:92:95:55:e1:90:7c:61:7d:47:
                    43:75:d3:a7:cd:19:fa:32:31:eb:d6:80:38:84:ed:
                    70:21:39:3b:c7:d3:f5:cc:4c:75:85:81:9c:43:91:
                    47:b1:12:3a:76:22:e0:33:6f:ee:10:a1:37:5d:b6:
                    d8:15:7e:d6:23:27:f5:a2:f6:b2:fe:ec:d6:7e:6d:
                    b8:d8:0b:cb:9f:4a:4f:a4:e7:cd:da:69:10:02:fe:
                    31:0f:1b:9f:75:2c:cf:f8:89
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                E5:29:4E:27:24:7C:9A:5E:AA:9A:5D:E3:2B:62:F4:D6:59:AB:3D:59
            X509v3 Authority Key Identifier: 
                keyid:E5:29:4E:27:24:7C:9A:5E:AA:9A:5D:E3:2B:62:F4:D6:59:AB:3D:59
                DirName:/C=ES/ST=ES/O=ES/OU=ES/CN=ES
                serial:00

            X509v3 Basic Constraints: 
                CA:TRUE
    Signature Algorithm: sha1WithRSAEncryption
        3f:27:f3:4f:8b:2e:57:68:8c:59:53:2f:54:c6:f9:e6:5d:59:
        fd:42:4f:c6:1d:8e:d7:15:f4:92:45:23:fb:ee:c9:38:c3:b1:
        7d:74:94:da:70:ee:3b:56:12:db:8a:35:70:d3:f8:8f:4e:ea:
        db:d1:17:35:b0:2e:15:d0:32:97:82:0e:ae:9c:17:0e:82:49:
        06:84:55:a9:be:e2:7b:09:ca:13:82:f3:2e:a8:dc:6f:fb:de:
        55:40:9f:70:bd:61:f0:f4:3c:2f:ad:91:d4:ff:e9:cf:12:a4:
        76:8f:7c:4d:f8:e0:12:d2:8e:5f:b7:d6:7c:f5:88:b6:db:c4:
        c1:44

################################ Revisar ##############################

aptitude update && aptitude install ssl-cert

make-ssl-cert generate-default-snakeoil –force-overwrite

/etc/cups/ssl/server.crt /etc/ssl/certs/ca-certificates.crt

/etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/private/ssl-cert-snakeoil.key

a2enmod ssl

apache2ctl restart

netstat -tpan | grep 443 tcp6 0 0 :::443 :::* LISTEN 1625/apache2

Extraer certificados de firefox

Miramos cual es nuestro kesytore en firefox:

# ls -1d $HOME/.mozilla/firefox/*default
/home/jose/.mozilla/firefox/az0qqip1.default

Ahora sacamos los nombres de los certificados:

# certutil -L -h 'Builtin Object Token' -d /home/jose/.mozilla/firefox/az0qqip1.default
Certificate Nickname                                         Trust Attributes
                                                             SSL,S/MIME,JAR/XPI
Builtin Object Token:GTE CyberTrust Root CA                  ,,   
Builtin Object Token:GTE CyberTrust Global Root              C,C,C
Builtin Object Token:Thawte Personal Freemail CA             ,C,  
Builtin Object Token:Thawte Server CA                        C,,C 
Builtin Object Token:Thawte Premium Server CA                C,,C 

Y ahora sacamos un certificado. Cuidadin con los espacios:

eval certutil -d /home/jose/.mozilla/firefox/az0qqip1.default -L -n "Builtin\ Object\ Token:GTE\ CyberTrust\ Root\ CA" -a
[opensc-pkcs11] ctx.c:367:load_dynamic_driver: dynamic library '/usr/lib64/libopensc-dnie.so': invalid module version
[opensc-pkcs11] ctx.c:467:load_card_drivers: Unable to load 'dnie'.
[opensc-pkcs11] reader-pcsc.c:906:pcsc_detect_readers: SCardEstablishContext failed: 0x8010001d
[opensc-pkcs11] reader-pcsc.c:1015:pcsc_detect_readers: returning with: No readers found
[opensc-pkcs11] reader-pcsc.c:906:pcsc_detect_readers: SCardEstablishContext failed: 0x8010001d
[opensc-pkcs11] reader-pcsc.c:1015:pcsc_detect_readers: returning with: No readers found
-----BEGIN CERTIFICATE-----
MIIB+jCCAWMCAgGjMA0GCSqGSIb3DQEBBAUAMEUxCzAJBgNVBAYTAlVTMRgwFgYD
VQQKEw9HVEUgQ29ycG9yYXRpb24xHDAaBgNVBAMTE0dURSBDeWJlclRydXN0IFJv
b3QwHhcNOTYwMjIzMjMwMTAwWhcNMDYwMjIzMjM1OTAwWjBFMQswCQYDVQQGEwJV
UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMRwwGgYDVQQDExNHVEUgQ3liZXJU
cnVzdCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC45k+625h8cXyv
RLfTD0bZZOWTwUKOx7pJjTUteueLveUFMVnGsS8KDPufpz+iCWaEVh43KRuH6X4M
ypqfpX/1FZSj1aJGgthoTNE3FQZor734sLPwKfWVWgkWYXcKIiXUT0Wqx73llt/5
1KiOQswkwB6RJ0q1bQaAYznEol44AwIDAQABMA0GCSqGSIb3DQEBBAUAA4GBABKz
dcZfHeFhVYAA1IFLezEPI2PnPfMD+fQ2qLvZ46WXTeorKeDWanOB5sCJo9Px4KWl
IjeaY8JIILTbcuPI9tl8vrGvU9oUtCG41tWW4/5ODFlitppK+ULdjG+BqXH/9Apy
bW1EDp3zdHSo1TRJ6V6e6bR64eVaH4QwnNOfpSXY
-----END CERTIFICATE-----

Comprobar una web por https

Lo podemos hacer con openssl client simply. Nos podemos encontrar dos tipos de errores:

Certificado autofirmado

Error por wget:

# wget https://aca-web.gencat.cat/eines/gestio
  --2011-02-02 17:02:26--  https://aca-web.gencat.cat/eines/gestio
  Resolving aca-web.gencat.cat... 83.247.130.118
  Connecting to aca-web.gencat.cat|83.247.130.118|:443... connected.
  ERROR: cannot verify aca-web.gencat.cat's certificate, issued by "/C=ES/O=Agencia Catalana de Certificacio (NIF Q-0801176-I)/L=Passatge de la Concepcio 11 08008 Barcelona/OU=Serveis Publics de Certificacio ECV-2/OU=Vegeu https://www.catcert.net/verCIC-2   (c)03/OU=Secretaria d'Administracio i Funcio Publica/CN=EC-SAFP":
  Self-signed certificate encountered.
  To connect to aca-web.gencat.cat insecurely, use '--no-check-certificate'.

Error por openssl:

# openssl s_client -connect aca-web.gencat.cat:443 -debug
Verify return code: 19 (self signed certificate in certificate chain)

Solución:

Exportamos la cadena de certificados desde firefox por ejemplo y lo grabamos como aca-web.gencat.cat_cadena.pem
Ahora hacemos:

# wget --ca-certificate=aca-web.gencat.cat_cadena.pem  https://aca-web.gencat.cat/eines/gestio
# openssl s_client -connect aca-web.gencat.cat:443 -debug -CAfile aca-web.gencat.cat_cadena.pem

Certificado emitido a otro nombre

# wget https://www.indymedia.org
--2011-02-03 10:19:35--  https://www.indymedia.org/
Resolviendo www.indymedia.org... 72.232.204.178
Conectando a www.indymedia.org|72.232.204.178|:443... conectado.
ERROR: certificate common name «chavez.indymedia.org» doesn't match requested host name «www.indymedia.org».
Para conectar con www.indymedia.org de forma no segura, use «--no-check-certificate».

WebDAV

1. Enlaces simbólicos:

cd /etc/apache2/mods-enabled

ln -s ../mods-available/dav_fs.conf dav_fs.conf

ln -s ../mods-available/dav_fs.load dav_fs.load

ln -s ../mods-available/dav.load dav.load

ln -s ../mods-available/dav_lock.load dav_lock.load

2. Ruta a la bd. Añadir a apache2.conf esto:

DavLockDB /var/log/apache2/dav_lock_db

3. Crear esa ruta.

cd /var/log touch dav_lock_db

4. Habilitar soporte dav. Añadir al directorio x en apache2.conf:

Dav on

5. Reiniciar apache

apachectl restart

6. Descargar el cliente unix con soporte dav cadaver:

http://packages.debian.org/unstable/web/cadaver

6. Instalarlo:

dpkg -i cadaver_xxx

7. Intentar la conexión:

cadaver –proxy=proxyvip:8080 http://87.223.245.32

De momento no sale

Virtualhosts

Antecedentes:

-Tenemos un servidor apache 2.x corriendo

-Tenemos ip dinámica, que en este caso resuelve dyndns.com

-Queremos tener más de un dominio a la vez (p.ej):

.dominio_1.mine.nu

.dominio_2.mine.nu

Cada uno de estos dominios apunta a un directorio distinto del servidor donde corre apache

1. cd /etc/apache2/sites-available

2. touch dominio_1

3. vim dominio_1

4. Pegar lo siguiente:

NameVirtualHost *

<VirtualHost *>
	
ServerName dominio_1.mine.nu
	
ServerAdmin webmaster@localhost

DocumentRoot /ruta/dominio_1/

<Directory />

Options FollowSymLinks

AllowOverride None

</Directory>

<Directory /ruta/dominio_1/>

Options Indexes FollowSymLinks MultiViews

AllowOverride None

Order allow,deny

allow from all

</Directory>

</VirtualHost>

6. wq (grabar el fichero y salir)

7. touch dominio_2

8. vim dominio_2

9. Pegar lo siguiente:

NameVirtualHost *

<VirtualHost *>
	
ServerName dominio_2.mine.nu
	
ServerAdmin webmaster@localhost

DocumentRoot /ruta/dominio_2/

<Directory />

Options FollowSymLinks

AllowOverride None

</Directory>

<Directory /ruta/dominio_2/>

Options Indexes FollowSymLinks MultiViews

AllowOverride None

Order allow,deny

allow from all

</Directory>

</VirtualHost>

10. wq (grabar el fichero y salir)

11. Habilitamos dominio_1

ln -s dominio_1 ../sites-enabled/dominio_1

12. Habilitamos dominio_2

ln -s dominio_2 ../sites-enabled/dominio_2

13. Creo que con eso ya está, pero por si acaso recargamos apache2

apache2ctl restart
informatica/linux/apache2.1352366503.txt.gz · Last modified: 2015/04/13 20:19 (external edit)