Apache httpd
Security
Bezpečnost

Lukáš Bařinka

© 2021

REV 2.10

TOC

Obsah

  1. Authentication
  2. Authorization
  3. Lab: Authnz
  4. Transport Layer Security
  5. SSL/TLS configuration
  6. Client side certificates
  1. Autentizace
  2. Autorizace
  3. Lab: Authnz
  4. Bezpečnost přenosu dat
  5. Konfigurace SSL/TLS
  6. Klientské certifikáty

Basic concepts

Základní pojmy

  • Authentication Verification of an user identity – login
  • Authorization Test if the authenticated user is allowed to have access to a resource
  • Access control Additional conditions and restrictions to allow or prevent access to a resource
  • Module types
    • auth_* Authentication type - HTTP Basic or HTTP Digest
    • authn_* Authentication provider
    • authz_* Authorization provider
    • authnz_* Authentication/Authorization provider
  • Autentizace Ověření identity – přihlášení
  • Autorizace Ověření oprávnění klienta na požadovaný zdroj na základě autentizace
  • Kontrola přístupu Ověření, dalších podmínek omezujících použití zdroje
  • Typy modulů
    • auth_* Typ autentizace - HTTP Basic nebo HTTP Digest
    • authn_* Poskytovatel autentizace
    • authz_* Poskytovatel autorizace
    • authnz_* Poskytovatel autentizace i autorizace

Authentication

Autentizace

Directives

Direktivy

  • AuthType selects the type - basic / digest Určuje typ - basic / digest
    
    									AuthType Basic|Digest|Form|None
    								
    Context: directory, .htaccess Kontext: directory, .htaccess
  • AuthName Sets the name of the authorization realm Nastavuje realm
    
    									AuthName auth-domain
    								
    Context: directory, .htaccess Kontext: directory, .htaccess

Basic authentication

Basic autentizace

  1. Client requests resource without login data
    
    									GET /private/index.html HTTP/1.0
    									Host: www.mycorp.net
    								
  2. Server responses with HTTP 401 UNAUTHORIZED message
    
    									HTTP/1.0 401 UNAUTHORIZED
    									Server: Apache
    									WWW-Authenticate: Basic realm="Secured"
    								
  1. Klient požádá o zdroj bez toho, aby uvedl přihlašovací údaje
    
    									GET /private/index.html HTTP/1.0
    									Host: www.mycorp.net
    								
  2. Dostane odpověď HTTP 401 UNAUTHORIZED
    
    									HTTP/1.0 401 UNAUTHORIZED
    									Server: Apache
    									WWW-Authenticate: Basic realm="Secured"
    								
  1. User gets realm displayed and form to login
  2. Client sends login data (username and password) within another request to server
    
    									GET /private/index.html HTTP/1.0
    									Host: www.mycorp.net
    									Authorization: Basic eTM2YXdzOnRham5laGVzbG8=
    								
  3. Server responses according to configuration and login data with
    
    									HTTP 200 OK
    								
    or again with
    
    									HTTP 401 UNAUTHORIZED
    								
  1. Klient zobrazí realm a pole pro vložení přihlašovacích údajů
  2. Po zadání přihlašovacích údajů klient odešle další požadavek
    
    									GET /private/index.html HTTP/1.0
    									Host: www.mycorp.net
    									Authorization: Basic eTM2YXdzOnRham5laGVzbG8=
    								
  3. Podle konfigurace server odpoví
    
    									HTTP 200 OK
    								
    nebo opět
    
    									HTTP 401 UNAUTHORIZED
    								

Basic authentication data transfer method

Přenos dat metodou Basic

  • Authentication data are sent within request headers encoded using base64
  • The encoding serves as data transfer protection and does not represent any security!
  • Informace pro autentizaci jsou odeslány spolu s požadavkem zakódované pomocí base64 v HTTP hlavičce
  • Kódování se používá aby nedošlo k porušení dat protokolu HTTP a neznamená žádnou bezpečnost!

mod_auth_basic module

Modul mod_auth_basic

  • AuthBasicProvider directive Sets the authentication provider(s)
    
    									AuthBasicProvider file
    								
    Context: directory, .htaccess mod_authn_file implements file provider
  • AuthBasicAuthoritative directive Sets whether authorization and authentication are passed to lower level modules
    
    									AuthBasicAuthoritative On|Off
    								
    Context: directory, .htaccess
  • Direktiva AuthBasicProvider Nastavuje způsob uložení dat pro autentizaci
    
    									AuthBasicProvider file
    								
    Kontext: directory, .htaccess Poskytovatel souborového (file) úložište je implementovavý v mod_authn_file
  • Direktiva AuthBasicAuthoritative Nastavuje, jestli autorizace a autentizace se má postoupit do dalšího modulu nižší úrovně
    
    									AuthBasicAuthoritative On|Off
    								
    Kontext: directory, .htaccess
  • AuthBasicFake Fake basic authentication using the given expressions for username and password which is passed as Authorization header to the service behind the webserver
    
    									AuthBasicFake off|username [password]
    								
    Context: directory, .htaccess
  • AuthBasicFake Slouží k nastavení jména a hesla, které se použijí při dotazech na další server uvnitř Authorization hlavičky
    
    									AuthBasicFake off|username [password]
    								
    Kontext: directory, .htaccess

Digest authentication

Digest autentizace

  • Tries to solves HTTP Basic authentication problems
    • Uses MD5 hash function
    • A nonce number, generates the webserver Nonce = number used once
    • Response value algorithm
      
      											H1 = md5(username:realm:password)
      											H2 = md5(method:digestURI),
      											response = md5(H1:nonce:H2)
      										
  • Unsupported by many web browsers or authentication modules and does not solve man-in-the-middle attack ⇒ HTTP Basic Authentication + SSL/TLS
    is strongly recommended
  • Snaží se překonat nevýhody Basic verze
    • Používá hashovací funkci MD5
    • Číslo nonce, určuje webserver Nonce = number used once
    • Způsob výpočtu
      
      											H1 = md5(username:realm:password)
      											H2 = md5(method:digestURI),
      											response = md5(H1:nonce:H2)
      										
  • Velmi často nepodporované prohlížeči i moduly pro autentizaci stejně tak metoda neřeší např. útok man-in-the-middle ⇒ použití HTTP Basic Authentication a SSL/TLS
  1. Client requests resource without login data
    
    									GET /private-digest/index.html HTTP/1.0
    									Host: www.mycorp.net
    								
  2. Server responses with HTTP 401 UNAUTHORIZED message
    
    									HTTP 401 UNAUTHORIZED
    									Server: Apache
    									WWW-Authenticate: Digest realm="Secured", \
    									  nonce="rCILfGxcBAA=75f715e2f17a607a2d5760692c755c1d142a06a7", \
    									  algorithm=MD5, domain="/private"
    									…
    								
  3. User gets realm displayed and form to login
  1. Klient požádá o zdroj bez toho, aby uvedl přihlašovací údaje.
    
    									GET /private-digest/index.html HTTP/1.0
    									Host: www.mycorp.net
    								
  2. Dostane odpověď
    
    									HTTP 401 UNAUTHORIZED
    									Server: Apache
    									WWW-Authenticate: Digest realm="Secured", \
    									  nonce="rCILfGxcBAA=75f715e2f17a607a2d5760692c755c1d142a06a7", \
    									  algorithm=MD5, domain="/private"
    									…
    								
  3. Klient zobrazí realm a pole pro vložení přihlašovacích údajů
  1. Client sends login data (username and digest) within another request to server
    
    									GET /private-digest/index.html HTTP/1.0
    									Host: www.mycorp.net
    									Authorization: Digest username="alice", realm="Secured", \
    									  nonce="rCILfGxcBAA=75f715e2f17a607a2d5760692c755c1d142a06a7", \
    									  uri="/private-digest/index.html", algorithm=MD5, \
    									  response="cbcb5ab6b72ff3f8a9cff3073fccafd3", \
    									  qop=auth, nc=00000001, cnonce="4c45d62bd34bb841"
    								
  2. Server responses according to configuration and login data (it can compute correct digest) with
    
    									HTTP 200 OK
    								
    or again with
    
    									HTTP 401 UNAUTHORIZED
    								
  1. Po zadání přihlašovacích údajů klient odešle odpověď
    
    									GET /private-digest/index.html HTTP/1.0
    									Host: www.mycorp.net
    									Authorization: Digest username="alice", realm="Secured", \
    									  nonce="rCILfGxcBAA=75f715e2f17a607a2d5760692c755c1d142a06a7", \
    									  uri="/private-digest/index.html", algorithm=MD5, \
    									  response="cbcb5ab6b72ff3f8a9cff3073fccafd3", \
    									  qop=auth, nc=00000001, cnonce="4c45d62bd34bb841"
    								
  2. Server ověří response (dokáže dopředu spočítat výsledek) a odpoví
    
    									HTTP 200 OK
    								
    nebo opět
    
    									HTTP 401 UNAUTHORIZED
    								

Login data storage

Uložení přihlašovacích údajů

  • AuthUserFile Sets pathname to user password file
    
    									AuthUserFile /pathname/to/.htpasswd
    								
    Context: directory, .htaccess
  • AuthGroupFile Sets pathname to group file
    
    									AuthGroupFile /pathname/to/.htgroup
    								
    Context: directory, .htaccess
    
    									GroupName: user1 user2 …
    								
  • AuthUserFile Nastavuje cestu k souboru s uživateli
    
    									AuthUserFile /cesta/k/.htpasswd
    								
    Kontext: directory, .htaccess
  • AuthGroupFile Nastavuje cestu k souboru se skupinami
    
    									AuthGroupFile /cesta/k/.htgroup
    								
    Kontext: directory, .htaccess
    
    									GroupName: user1 user2 …
    								

Password generation and storage

Generování a ukládání hesel

  • htpasswd command
    -cCreate a new file
    -bUse the password from the command line rather than prompting for it
    -DDelete the specified user
    -nDon't update file; display results on stdout
  • Příkaz htpasswd
    -cVytvoří nový soubor
    -bPoužije argument z příkazové řádky jako heslo
    -DSmaže zadaného uživatele
    -nNezmění soubor, jenom zobrazí výsledek na výstup

							htpasswd passwordfile username
							htpasswd -b passwordfile username password

							htpasswd -n username
							htpasswd -nb username password
						

Authorization

Autorizace

Directives

Direktivy

  • Require (core) Allows request based on condition - user, valid-user, group, …
    
    									Require [not] entity-name
    								
    Context: directory, .htaccess
  • Satisfy (core) legacy Access policy if both Allow and Require used
    → It is replaced by RequireAny / RequireAll containers
    
    									Satisfy Any|All
    								
    Default: Satisfy All, context: directory, .htaccess
  • Require (core) Vyžaduje splnění kritéria - user, valid-user, group, …
    
    									Require [not] entity-name
    								
    Kontext: directory, .htaccess
  • Satisfy (core) legacy Vyžaduje splnění alespoň nějakého/všech kritérií
    (Require nebo Allow from)
    → Je nahrazeno kontejnery RequireAny / RequireAll
    
    									Satisfy Any|All
    								
    Výchozí: Satisfy All, kontext: directory, .htaccess

Access control options

Možnosti kontroly přístupu

  • Require Allows or denies access to requested resource based on many conditions Řídí přístup ke zdroji na základě různých kritérií
    
    									Require all denied|granted
    									Require host address
    									Require ip ip.address
    									Require forward-dns hostname
    									Require local
    									Require env variable
    									Require method http-method
    									Require expr expression
    									Require user username
    									Require group groupname
    									Require valid-user
    									Require not …
    								

Owner-based Authorization

Autorizace vlastníka

  • mod_authz_owner module
  • Authorization based on resource ownership
  • Adds new Require entities
    • file-owner
    • file-group
  • If the resource is not actually present in the filesystem (i.e. a virtual or multiviews resource), it will deny the access
  • AuthzOwnerAuthoritative Sets whether authorization will be passed on to lower level modules deprecated
    
    									AuthzOwnerAuthoritative On|Off
    								
  • Modul mod_authz_owner
  • Provádí autorizaci na základě vlastnictví zdroje
  • Poskytuje možnosti kontroly (Require)
    • file-owner
    • file-group
  • Pokud požadovaný zdroj neexistuje na filesystému (např. virtuální nebo multiview zdroj), přístup bude odepřen
  • AuthzOwnerAuthoritative Povoluje/zakazuje postoupení kontroly dalším modulům deprecated
    
    									AuthzOwnerAuthoritative On|Off
    								

Configuration example

Ukázka konfigurace


							<Directory /var/www/main/private>
							  AuthType basic
							  AuthName "Secured"
							  AuthBasicProvider file
							  AuthBasicAuthoritative On
							  AuthUserFile /var/www/.htpasswd
							  Require valid-user
							</Directory>
						

Configuration merging

Kombinace konfigurací

  • AuthMerging Controls the manner of configuration sections combination
    
    									AuthMerging Off | And | Or
    								
    Default: AuthMerging Off, context: directory, .htaccess
    
    									<Directory "/www/docs">          # alpha only
    									  AuthType Basic
    									  AuthName Documents
    									  AuthBasicProvider file
    									  AuthUserFile "/usr/local/apache/passwd/passwords"
    									  AuthGroupFile "/usr/local/apache/passwd/groups"
    									  Require group alpha
    									</Directory>
    
    									<Directory "/www/docs/ab">       # alpha or beta
    									  AuthMerging Or
    									  Require group beta
    									</Directory>
    
    									<Directory "/www/docs/ab/gamma"> # gama only – the default manner
    									  Require group gamma
    									</Directory>
    								
  • AuthMerging Ovládá způsob kombinace konfiguračních sekcí (kontejnerů)
    
    									AuthMerging Off | And | Or
    								
    Výchozí: AuthMerging Off, kontext: directory, .htaccess
    
    									<Directory "/www/docs">          # jenoma alpha
    									  AuthType Basic
    									  AuthName Documents
    									  AuthBasicProvider file
    									  AuthUserFile "/usr/local/apache/passwd/passwords"
    									  AuthGroupFile "/usr/local/apache/passwd/groups"
    									  Require group alpha
    									</Directory>
    
    									<Directory "/www/docs/ab">       # alpha nebo beta
    									  AuthMerging Or
    									  Require group beta
    									</Directory>
    
    									<Directory "/www/docs/ab/gamma"> # jenom gama – výchozí způsob kombinace
    									  Require group gamma
    									</Directory>
    								

LAB: Authnz

Authentication/Authorization

Autentizace/Autorizace

The goal is to configure authentication required to access resources. Usernames and passwords have to be created for that purpose inside webserver (they do not need to match operating system users). In another case, those users need to correspond to system users to use ownership condition.

Cílem je nakonfigurovat použití autentizace pro umožnění přístupu ke zdrojům. K tomu je potřeba definovat uživatele (a jejich hesla) v rámci webového serveru. Aby bylo možné vyzkoušet navázat autorizaci na vlastnictví souborů, je potřeba také vytvořit odpovídající uživatele v operačním systému.

  • Create operating system users
  • Create testing directory with files
  • Create webserver users
  • Define various conditions required to access resources
  • Vytvořit nové uživatele v operačním systému
  • Vytvořit testovací adresář se soubory
  • Vytvořit uživatele pro webserver
  • Nadefinovat různé podmínky pro přístup k souborům pro webové uživatele

Tips

Tipy

If authenticated user is required but there is no authentication configured, server status is 500.

Pokud je požadován přihlášený uživatel, ale autentizace není nakonfigurovaná, server vrací stavový kód 500.


							useradd alice    # already present
							useradd bob      # already present
							useradd cecil    # new system user
						

							echo -n user:pass | base64  # ↓
							curl -H 'Authorization: Basic …' URL
						
  1. Create /var/www/main/private directory and its files alice.txt and bob.txt with corresponding owners
  2. Restrict access to that directory from localhost only
  3. Configure web users alice, bob, and cecil to access to that directory
  4. Allow access for alice only to that directory
  1. Vytvořte adresář /var/www/main/private a v něm soubory alice.txt a bob.txt, které budou vlastnit příslušní uživatelé
  2. Přístup do adresáře povolte pouze z localhostu
  3. Pro tento adresář vytvořte uživatelská konta uživatelům alice, bob a cecil
  4. Přístup do adresáře povolte pouze alice
  1. Allow access to that directory for any authenticated user
  2. Allow access to that directory
    • for all from localhost, or
    • for authenticated users from anywhere
  1. Přístup do adresáře povolte libovolnému přihlášenému uživateli
  2. Přístup do adresáře povolte
    • pro všechny z localhostu nebo
    • pro přihlášené uživatele odkudkoli
  1. Load authz_owner module
  2. Allow access only for its file owners
  3. Allow access only for its file owners or user cecil
  4. Allow access only for its file owners or user cecil but from localhost only
  1. Načtěte modul authz_owner
  2. Přístup k souborům v adresáři povolte pouze vlastníkům souborů
  3. Přístup k souborům v adresáři povolte pouze vlastníkům souborů nebo uživateli cecil
  4. Přístup k souborům v adresáři povolte pouze vlastníkům souborů nebo uživateli cecil a to pouze z localhostu

Discussion

Diskuze


							LoadModule authz_owner_module \
							           modules/mod_authz_owner.so

							<Directory /var/www/main/private>
							        AuthType basic
							        AuthName "Secured"
							        AuthBasicProvider file
							        AuthBasicAuthoritative On
							        AuthUserFile /var/www/.htpasswd

							        <RequireAll>
							            <RequireAny>
							                 Require file-owner
							                 Require user cecil
							            </RequireAny>
							             Require local
							        </RequireAll>

							</Directory>
						

Transport Layer Security

Bezpečnost přenosu dat

PKI concepts

PKI pojmy

Private Key Infrastructure
  • Asymmetric cryptography – A pair of keys:
    • Private key Decoding (decryption), digital signature
    • Public key Encoding (encryption), digital signature verification
  • Certificate = Public key + Real identity information of subject and issuer ⇒ Authenticity and legitimacy is guaranteed by CA signature
    • Subject Person, server, or entity
    • Issuer Certificate Authority (CA)
    • Period of validity Not before/after date
    • Administrative information Version, serial number
    • A distinguished name (DN) is used to provide an identity
  • Asymetrická kryptografie – 2 různé klíče:
    • Privátní klíč Dekódování, digitální podpis
    • Veřejný klíč Zakódování, ověření digitálního podpisu
  • Certifikát = Veřejný klíč + Informace identifikující majitele a vydavatele ⇒ Lze ověřit, že certifikát je pravý (digitálně podepsaný CA)
    • Subjekt komu byl vydán
    • Vydavatel certifikační autorita (CA)
    • Doba platnosti Ne před/po datu
    • Administrativní informace verze, sériové číslo
    • Informace o vlastníkovi ve formě Distinguished Name (DN)

Distinguished Name

DN field
Example
Abbrev.Description
Common Name
CN=fit.cvut.cz
CNName being certified
Organization
O=CTU in Prague
OName is associated with this organization
Organizational Unit
OU=ICT
OUName is associated with this organization unit (department)
City/Locality
L=Prague 6 - Dejvice
LName is located in this City
State/Province
ST=Prague
STName is located in this State/Province
Country
C=CZ
CName is located in this Country (ISO code)
DN pole
Příklad
ZkratkaPopis
Common Name
CN=fit.cvut.cz
CNcertifikované jméno
Organization
O=ČVUT v Praze
Ojméno organizace
Organizational Unit
OU=ICT
OUjméno organizační jednotky
City/Locality
L=Praha 6 - Dejvice
Ljméno města
State/Province
ST=Hlavní město Praha
STjméno kraje
Country
C=CZ
Cjméno země (ISO code)

PKI formats

Formát uložení

Binary format of a certificate – variants:

Binární formát certifikátu – způsoby uložení:

  • DER – Raw binary data Distinguished Encoding Rules
    • MS Outlook
  • PEM – Base64 encoded (ASCII) Privacy Enhanced Mail
    • Transport protocols – SMTP, HTTP
    • Default formate in OpenSSL As well as Apache httpd and other server software
  • DER – přímo binární data Distinguished Encoding Rules
    • MS Outlook
  • PEM – Base64 encoded (ASCII) Privacy Enhanced Mail
    • Přenos – SMTP, HTTP
    • OpenSSL implicitně používá formát PEM Stejně jako Apache httpd a další serverový software

							openssl x509 -in cert.pem -out cert.der -outform DER
						

Certificate Authorities

Certifikační autority

  • Issues certificates for subjects by verifying the information in a certificate request before granting the certificate
  • Important in Public Key Infrastructure Guarantees authenticity
    • Certificate Chain A Certificate Authority may also issue a certificate for another Certificate Authority
    • Root-level CA The certificate is "self-signed" – There is no one to sign it! The wide publication of a public key by the root authority reduces the risk in trusting this key!
  • Vydává certifikáty ostatním účastníkům komunikace, které před vydáním ověří (obsažené informace)
  • Zásadní pro Public Key Infrastructure Zajišťuje pravost
    • Certificate Chain Řetězec certifikátů CA v hierarchii – lze použít pro ověřování
    • Root-level CA Kořenová CA má self-signed certifikát – není nikdo, kdo by jej ověřil! Publikace otisku na více místech, kontrola!

Self-signed certificate generation

Generování self-signed certifikátu

  • Key (RSA) and certificate (X.509) generation (interactive) Vygenerování klíče (RSA) a certifikátu (X.509) (interaktivně)
    
    									openssl req -new -x509 -nodes -out server.crt -keyout server.key -days 365
    								
    
    									Generating a 1024 bit RSA private key
    									…
    									Country Name (2 letter code) [AU]:CZ
    									State or Province Name (full name) [Some-State]:Prague
    									Locality Name (eg, city) []:Prague
    									Organization Name (eg, company) [Internet Widgits Pty Ltd]:MyCorporation
    									Organizational Unit Name (eg, section) []:Web
    									Common Name (eg, YOUR name) []:www.mycorp.net
    									Email Address []:admin@mycorp.net
    								
  • Batch generation (parameters) Vygenerování v dávkovém režimu
    
    									openssl req -new -x509 -nodes -out server.crt -keyout server.key -days 365 \
    									-subj "/C=CZ/ST=Prague/L=Prague/O=MyCorporation/OU=Web/"\
    									"CN=www.mycorp.net/emailAddress=admin@mycorp.net/"
    								
  • Display certificate information Zobrazení informací v certifikátu
    
    									openssl x509 -noout -text -in server.crt
    								

SSL/TLS protocol

Protokol SSL/TLS

  • Protocol layer: TCP/IP – HTTP Between reliable connection-oriented network layer protocol (TCP/IP) and
    application protocol layer (HTTP)
    • Transfer security and authentication (usually server)
    • Versions SSLv2(1995-2011), SSLv3(1996-2015), TLSv1.0(1999-2020), TLSv1.1(2006-2020),
      TLSv1.2(2008-), TLSv1.3(2018-)
  • Communication
    1. Handshake (establishing a session)
    2. Data transfer
  • Handshake
    • Negotiate the Cipher Suite to be used during data transfer
    • Establish and share a session key
    • [Optionally] Authenticate the server to the client
    • [Optionally] Authenticate the client to the server
  • Mezivrstva TCP/IP – aplikace
    • Zabezpečení a autentizace (typicky serveru)
    • Verze SSLv2(1995-2011), SSLv3(1996-2015), TLSv1.0(1999-2020), TLSv1.1(2006-2020),
      TLSv1.2(2008-), TLSv1.3(2018-)
  • Komunikace
    1. Handshake
    2. Přenos dat
  • Handshake
    • Dohoda o šifrách, které se budou používat v průběhu přenosu
    • Vytvoření session mezi komunikujícími stranami
    • [volitelně] Autentizace serveru
    • [volitelně] Autentizace klienta

Security

Bezpečnost

  • Client uses CA public key to verify digital signature of server certificate
  • Client checks whether CA issued the certificate is trusted (browser list)
  • Client checks period of validity of the certificate
  • Client compare current DNS server name with certificate name to prevent Man-in-the-Middle attack
  • Attack protection against known vectors Including Man-in-the-Middle, attempt to use less secure versions, or obsolete cipher algorithms
  • Klient používá veřejný klíč certifikační autority (CA) k ověření jejího digitálního podpisu v serverovém certifikátu
  • Klient ověřuje, zda je vydávající certifikační autorita na seznamu důvěryhodných CA
  • Klient kontroluje dobu životnosti serverového certifikátu
  • K ochraně před útoky typu Man-in-the-Middle porovnává klient aktuální DNS jméno serveru se jménem z certifikátu
  • Ochrana před několika známými útoky Včetně Man-in-the-Middle, snaha o použití nižší (méně bezpečné) verze protokolu nebo slabšího šifrovacího algoritmu
  • To ensure data integrity, all application records have order numbers used as part of MAC Message Authentication Codes
  • HMAC (hashed MAC) involves a cryptographic hash function and a secret cryptographic key, so only key holder can verify integrity and the authenticity of a message
    • Defined by RFC 2104
    • TLS only
  • Message closing communication (Finished) contains hash of all transferred messages during initialization
  • Pseudorandom function splits input data into two parts that are processed separately using different hash algorithm (MD5/SHA) and XOR the results To prevent functions vulnerabilities
  • Opatření všech aplikačních záznamů pořadovými čísly a používání těchto čísel v MAC Message Authentication Codes
  • Používání ověřovacího kódu zprávy rozšířeného o klíč (HMAC), takže jen vlastník klíče dokáže MAC ověřit
    • Definováno v RFC 2104
    • Jen v TLS
  • Zpráva ukončující inicializaci (Finished) obsahuje hash všech zpráv vyměněných v rámci inicializace oběma stranami
  • Pseudonáhodná funkce rozděluje vstupní data na poloviny a zpracovává každou z nich jiným hashovacím algoritmem (MD5/SHA) a výsledek XORuje Ochrana proti prolomení jedné funkce

HTTPS

  • URI scheme — secure HTTP communication
    → combination of HTTP and SSL or TLS
  • Provides secure communication between client and server (eavesdropping)
  • Does not prevent man-in-the-middle attacks
    ⇒ Server authentication required
  • URI schéma — zabezpečená komunikace protokolem HTTP
    → kombinace HTTP a SSL nebo TLS
  • Zajišťuje postačující bezpečnost proti odposlechnutí
  • Není bezpečná proti útoku man-in-the-middle
    ⇒ Nutnost autentizace serveru

Cipher algorithms

Šifrovací algoritmy

Security is dependent on cryptographic algorithms supported by web server and web browser Bezpečnost je značně závislá na kryptografických algoritmech podporovaných web serverem a prohlížečem https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslciphersuite

  • Key Exchange Algorithm: RSA, Diffie-Hellman, Elliptic Curve Diffie-Hellman, Secure Remote Password
  • Authentication Algorithm: RSA, Diffie-Hellman, DSS, ECDSA, or none.
  • Cipher/Encryption Algorithm: AES, DES, Triple-DES, RC4, RC2, IDEA, etc.
  • MAC Digest Algorithm: MD5, SHA or SHA1, SHA256, SHA384.

SSL/TLS virtualhosting

  • SSL/TLS does not have information from higher levels! Host:
    → 1 certificate for 1 IP address and port
  • Server Name Indication (SNI) Server identification on TLS layer (RFC 3546)
  • SSL/TLS nemá znalost o protokolech vyšších vrstev! Host:!
    → 1 certifikát pro 1 IP adresu a port
  • Server Name Indication (SNI) Identifikace serveru na úrovni TLS (RFC 3546)

SSL/TLS configuration

Konfigurace SSL/TLS

SSL module

Modul SSL

  • Based on OpenSSL
    • Implements [SSLv2], SSLv3, TLSv1.x
    • Provides used cryptographic algorithms
  • Postaven na OpenSSL
    • Implementuje [SSLv2], SSLv3, TLSv1.x
    • Potřebné kryptografické algoritmy

							<IfDefine SSL>
							  LoadModule ssl_module modules/mod_ssl.so
							</IfDefine>
						

							openssl version
							OpenSSL 1.1.1k  25 Mar 2021
						

SSL/TLS directives

Direktivy SSL/TLS

  • SSLEngine directive Enable/disable SSL, usually per virtualhost
    
    									SSLEngine On|Off|optional
    								
    Context: server, virtualhost
  • SSLOptions directive Configure various SSL engine run-time options
    
    									SSLOptions [+|-] option …
    								
    Context: server, virtualhost, directory, .htaccess
    • StdEnvVars SSL related CGI/SSI environment variables are created
    • ExportCertData additional CGI/SSI environment variables are created
  • SSLEngine Zapne/vypne SSL, typicky virtualhost
    
    									SSLEngine On|Off|optional
    								
    Kontext: server, virtualhost
  • SSLOptions Nastavuje různé možnosti SSL
    
    									SSLOptions [+|-] option …
    								
    Kontext: server, virtualhost, directory, .htaccess
    • StdEnvVars exportuje standardní proměnné prostředí spojené se SSL
    • ExportCertData do proměnných prostředí uloží certifikáty klienta a serveru
  • SSLProtocol directive Configure usable SSL/TLS protocol versions SSLv3, TLSv1, TLSv1.1, TLSv1.2, TLSv1.3, All
    
    									SSLProtocol [+|-]protocol
    								
    Default: SSLProtocol All, context: server, virtualhost
    
    									SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    								
  • SSLProtocol Určuje verzi protokolu SSLv3, TLSv1, TLSv1.1, TLSv1.2, TLSv1.3, All
    
    									SSLProtocol [+|-]protocol
    								
    Výchozí: SSLProtocol All, kontext: server, virtualhost
    
    									SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    								
  • SSLCipherSuite directive Cipher Suite available for negotiation in SSL handshake Určuje šifry, které se mohou použít při dojednání s klientem
    
    									SSLCipherSuite cipher-spec
    								
    Default: SSLCipherSuite DEFAULT (depends on OpenSSL version), context: server, virtualhost, directory, .htaccess Výchozí: SSLCipherSuite DEFAULT (závisí na verzi OpenSSL), kontext: server, virtualhost, directory, .htaccess

    Since TLSv1.3 does not offer renegotiations, specifying ciphers for it in a directory context is not allowed.

    Od TLSv1.3 není podporováno nové vyjednávání (renegotiations), proto není možná konfigurace per adresář.

    
    									# Be liberal in general
    									SSLCipherSuite ALL:!aNULL:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP:+eNULL
    									<Location "/strong/area">
    										  # But here and below requires strong ciphers
    										  SSLCipherSuite HIGH:!aNULL:!MD5
    									</Location>
    								
    noneAdd cipher to list
    +Move matching ciphers to the current location in list
    -Remove cipher from list (can be added later again)
    !Kill cipher from list completely (can not be added later again)
    nonePřidá šifru do seznamu
    +Přesune šifru na aktuální pozici v seznamu
    -Odebere šifru ze seznamu (lze přidat později)
    !Odebere úplně šifru ze seznamu (nelze přidat později)
  • SSLCertificateFile directive Server PEM-encoded X.509 certificate data file/token identifier
    
    									SSLCertificateFile /pathname/to/certificate.crt
    								
    Context: server, virtualhost
  • SSLCertificateKeyFile directive Server PEM-encoded private key file
    
    									SSLCertificateKeyFile /pathname/to/certificate.key
    								
    Context: server, virtualhost
  • SSLCertificateChainFile directive File of PEM-encoded Server CA Certificates
    
    									SSLCertificateChainFile /pathname/to/ca.crt
    								
    Context: server, virtualhost
  • SSLCertificateFile Souboru s certifikátem serveru v PEM formátu
    
    									SSLCertificateFile /cesta/k/certifikatu.crt
    								
    Kontext: server, virtualhost
  • SSLCertificateKeyFile Souboru s privátním klíčem serveru v PEM formátu
    
    									SSLCertificateKeyFile /cesta/k/certifikatu.key
    								
    Kontext: server, virtualhost
  • SSLCertificateChainFile Souboru s řetězcem certifikátů CA – vydaly certifikát serveru
    
    									SSLCertificateChainFile /cesta/k/ca.crt
    								
    Kontext: server, virtualhost
  • SSLRequireSSL directive Deny access when SSL is not used for the HTTP request
    
    									SSLRequireSSL
    								
    Context: directory, .htaccess
  • SSLRequire directive - deprecated ⇒ Use Require expr instead Allow access only when an arbitrarily complex boolean expression is true, it's possible to use environment variables
    
    									SSLRequire true | false | expr && expr ...
    								
    Context: directory, .htaccess
    
    									SSLRequire %{SSL_CIPHER_USEKEYSIZE} >= 128
    								
  • SSLRequireSSL Direktiva vynucuje SSL pro přístup ke zdroji
    
    									SSLRequireSSL
    								
    Kontext: directory, .htaccess
  • SSLRequire - deprecated ⇒ Místo ní použijte Require expr Udává požadavky, které musí být splněny při komunikaci - boolovská podmínka - lze používat proměnné prostředí
    
    									SSLRequire true | false | expr && expr ...
    								
    Kontext: directory, .htaccess
    
    									SSLRequire %{SSL_CIPHER_USEKEYSIZE} >= 128
    								

Configuration example

Ukázka konfigurace


							Listen …:443

							LoadModule ssl_module modules/mod_ssl.so

							<VirtualHost …:443>
								  ServerName www.mycorp.net

								  # enable SSL
								  SSLEngine on
								  # TLSv1.2, TLSv1.3
								  SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
								  # SSL Cipher Suite:
								  SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:…
								  # Server Certificate (RSA)
								  SSLCertificateFile conf/ssl/mycorp.crt
								  # Server Private Key (RSA)
								  SSLCertificateKeyFile conf/ssl/mycorp.key

								  CustomLog /var/log/apache2/ssl.log "%h %t \"%r\" %{SSL_PROTO}x %{SSL_CIPHER}x"
							</VirtualHost>
						
https://ssl-config.mozilla.org/#server=apache

Secure communication testing

Testování šifrované komunikace

  • Communication with HTTP server testing
    
    									telnet localhost 80
    									GET / HTTP/1.0
    								
  • Communication with HTTPS server testing
    
    									openssl s_client -connect localhost:443 -state -debug
    									GET / HTTP/1.0^V↵↵^V↵↵
    								
    Lines end with CR+LF (\r\n): Use ^V↵↵ to insert CR+LF
  • Test komunikace s HTTP serverem
    
    									telnet localhost 80
    									GET / HTTP/1.0
    								
  • Test komunikace s HTTPS serverem
    
    									openssl s_client -connect localhost:443 -state -debug
    									GET / HTTP/1.0^V↵↵^V↵↵
    								
    Jako konec řádku je potřeba odeslat \r\n: ^V↵↵

LAB: SSL/TLS

SSL/TLS

The goal is to configure secure connection. A pair of keys (private and public) and a certificate are needed for that. It is possible to have different certificates for different virtualhosts.

Cílem je nakonfigurovat použití šifrovaného spojení se serverem. K tomu je zapotřebí vytvořit dvojici klíčů (veřejný a soukromý) a certifikáty. Pro různé virtualhosty je možné použít různé certifikáty.

  • Create a pair of keys and self-signed certificate
  • Configure server to use SSL/TLS on TCP port 443
  • Configure keys and certificate pathnames for virtualhosts
  • Vytvořit klíče a self-signed certifikát
  • Nakonfigurovat použití portu 443 a SSL/TLS
  • Nakonfigurovat použití klíčů a certifikátů pro virtualhosty

Tips

Tipy

  • Header files of SSL library are needed to compile mod_ssl module E.g. They are part of libssl-dev package in Debian
    
    									apt install -y libssl-dev
    								
  • Pro kompilaci mod_ssl jsou zapotřebí hlavičkové soubory knihovny SSL Např. v Debianu jsou součástí balíku libssl-dev
    
    									apt install -y libssl-dev
    								
  1. Create private server key and self-signed certificate for www.mycorp.net domain
  2. Configure server to use that key and certificate
  3. Enable server to use secure connection on TCP port 443
  4. Create keys (or use existing ones) and certificates for www.othercorp1.net and www.othercorp2.net domains
  5. Configure name-based virtual hosts to use appropriate keys and certificates
  1. Vytvořte privátní klíč serveru a self-signed certifikát pro doménu www.mycorp.net
  2. Umístěte vygenerované data do konfigurace serveru
  3. Nakonfigurujte použití šifrovaného spojení pro port 443
  4. Vytvořte klíče (lze použít existující) a certifikáty pro domény www.othercorp1.net a www.othercorp2.net
  5. Nakonfigurujte name-based virtuální hostitele pro použití příslušných certifikátů

Client side certificates

Klientské certifikáty

Client side principle

Fungování klientských certifikátů

  • To authenticate a client
  • To use with SSL/TLS
  • Pro autentizaci uživatele
  • Při použití SSL/TLS
  1. [ Create CA ]
  2. Create client-side certificate Key→Request→Sign
  3. Configure server to accept CA
  4. Configure access control to resources Based on certificate information
  1. [ Vytvoření CA ]
  2. Vytvoření klientského certifikátu Klíč→Žádost→Podpis
  3. Nastavení serveru pro použití CA
  4. Nastavení omezení přístupu ke zdrojům Na základě údajů z certifikátu

How-to create and use

Vytvoření a použití

  1. Create CA (optional) Vytvoření CA (volitené)
    
    									openssl genrsa -out CA.key 2048
    									openssl req -x509 -new -nodes -days 7300 -key CA.key -days 7300 -out CA.pem
    								
  2. Create client-side certificate Key→Request→Sign Vytvoření klientského certifikátu Klíč→Žádost→Podpis
    
    									openssl genrsa -out alice.key 2048
    									openssl req -new -key alice.key -out alice.csr
    									openssl x509 -sha256 -req -in alice.csr -out alice.crt \
    									             -CA CA.pem -CAkey CA.key -CAcreateserial -days 1095
    								

    .csr = Certificate Signing Request

  1. Server configuration Nastavení serveru
    
    									<VirtualHost ....:443>
    									  ServerName www.mycorp.net
    									  ServerAlias www.aliascorp.net
    									  DocumentRoot /var/www/vhosts/mycorp
    
    									  SSLEngine on
    									  SSLCertificateFile server.crt
    									  SSLCertificateKeyFile server.key
    
    									  SSLCACertificateFile CA.pem
    
    									  <Location />
    									    SSLOptions +StdEnvVars
    									    SSLVerifyClient require
    									    SSLRequire ( %{SSL_CLIENT_S_DN_CN} == 'Alice' )
    									  </Location>
    
    									</VirtualHost>
    								
  2. Test access to resource Test přístupu
    
    									curl -i -k -E alice.crt --key alice.key https://www.mycorp.net/
    								

Access control based on client certificates

Řízení přístupu pomocí klientských certifikátů

  • SSLVerifyClient directive Type of client certificate verification
    
    									SSLVerifyClient none
    								
    Context: server, virtualhost, directory, .htaccess
    noneno client certificate is required at all
    optionalthe client may present a valid certificate
    requirethe client has to present a valid certificate
    optional_no_cathe client may present a valid certificate but it need not to be verifiable Not for authentication
  • SSLVerifyClient Určuje způsob ověření klientského certifikátu
    
    									SSLVerifyClient none
    								
    Kontext: server, virtualhost, directory, .htaccess
    nonenení vyžadován/zpracováván certifikát
    optionalklient může poskytnou certifikát
    requireje vyžadován certifikát
    optional_no_caklient může poskytnout certifikát, který není ověřitelný Not for authentication
  • SSLUserName directive Variable name to determine user name
    
    									SSLUserName varname
    								
    Context: server, directory, .htaccess Kontext: server, directory, .htaccess
    
    									SSLUserName SSL_CLIENT_S_DN_CN
    
    									<Location />
    									  SSLOptions +StdEnvVars
    									  SSLVerifyClient optional
    									</Location>
    
    									<Directory /var/www/main/private>
    									  Require user Alice
    									</Directory>