Skip to content

Commit 6140136

Browse files
authored
Merge pull request #364 from etr/feature/client-cert-auth
Add client certificate authentication and SNI callback support
2 parents 42e769c + 436bc41 commit 6140136

18 files changed

+1318
-80
lines changed

README.md

Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,7 @@ You can also check this example on [github](https://github.com/etr/libhttpserver
389389
* _.https_mem_trust(**const std::string&** filename):_ String representing the path to a file containing the CA certificate to be used by the HTTPS daemon to authenticate and trust clients certificates. The presence of this option activates the request of certificate to the client. The request to the client is marked optional, and it is the responsibility of the server to check the presence of the certificate if needed. Note that most browsers will only present a client certificate only if they have one matching the specified CA, not sending any certificate otherwise.
390390
* _.https_priorities(**const std::string&** priority_string):_ SSL/TLS protocol version and ciphers. Must be followed by a string specifying the SSL/TLS protocol versions and ciphers that are acceptable for the application. The string is passed unchanged to gnutls_priority_init. If this option is not specified, `"NORMAL"` is used.
391391
* _.psk_cred_handler(**psk_cred_handler_callback** handler):_ Sets a callback function for TLS-PSK (Pre-Shared Key) authentication. The callback receives a username and should return the corresponding hex-encoded PSK, or an empty string if the user is unknown. This option requires `use_ssl()`, `cred_type(http::http_utils::PSK)`, and an appropriate `https_priorities()` string that enables PSK cipher suites. PSK authentication allows TLS without certificates by using a shared secret key.
392+
* _.sni_callback(**sni_callback_t** callback):_ Sets a callback function for SNI (Server Name Indication) support. The callback receives the server name requested by the client and should return a `std::pair<std::string, std::string>` containing the PEM-encoded certificate and key for that server name. Return empty strings to use the default certificate. Requires libmicrohttpd 0.9.71+ with GnuTLS.
392393

393394
#### Minimal example using HTTPS
394395
```cpp
@@ -712,8 +713,16 @@ The `http_request` class has a set of methods you will have access to when imple
712713
* _**const std::string** get_pass() **const**:_ Returns the `password` as self-identified through basic authentication. The content of the password header will be parsed only if basic authentication is enabled on the server (enabled by default).
713714
* _**const std::string** get_digested_user() **const**:_ Returns the `digested user` as self-identified through digest authentication. The content of the user header will be parsed only if digest authentication is enabled on the server (enabled by default).
714715
* _**bool** check_digest_auth(**const std::string&** realm, **const std::string&** password, **int** nonce_timeout, **bool*** reload_nonce) **const**:_ Allows to check the validity of the authentication token sent through digest authentication (if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716). Takes in input the `realm` of validity of the authentication, the `password` as known to the server to compare against, the `nonce_timeout` to indicate how long the nonce is valid and `reload_nonce` a boolean that will be set by the method to indicate a nonce being reloaded. The method returns `true` if the authentication is valid, `false` otherwise.
715-
* _**bool** has_tls_session() **const**:_ Tests if there is am underlying TLS state of the current request.
716+
* _**bool** has_tls_session() **const**:_ Tests if there is an underlying TLS state of the current request.
716717
* _**gnutls_session_t** get_tls_session() **const**:_ Returns the underlying TLS state of the current request for inspection. (It is an error to call this if the state does not exist.)
718+
* _**bool** has_client_certificate() **const**:_ Returns `true` if the client presented a certificate during the TLS handshake. Requires GnuTLS support.
719+
* _**std::string** get_client_cert_dn() **const**:_ Returns the Distinguished Name (DN) from the client certificate's subject field (e.g., "CN=John Doe,O=Example Corp"). Returns empty string if no client certificate.
720+
* _**std::string** get_client_cert_issuer_dn() **const**:_ Returns the Distinguished Name of the certificate issuer. Returns empty string if no client certificate.
721+
* _**std::string** get_client_cert_cn() **const**:_ Returns the Common Name (CN) from the client certificate's subject. Returns empty string if no client certificate or no CN field.
722+
* _**bool** is_client_cert_verified() **const**:_ Returns `true` if the client certificate was verified against the trust store configured via `https_mem_trust()`. Returns `false` if verification failed or no TLS session.
723+
* _**std::string** get_client_cert_fingerprint_sha256() **const**:_ Returns the SHA-256 fingerprint of the client certificate as a lowercase hex string (64 characters). Returns empty string if no client certificate.
724+
* _**time_t** get_client_cert_not_before() **const**:_ Returns the start of the certificate validity period. Returns -1 if no client certificate.
725+
* _**time_t** get_client_cert_not_after() **const**:_ Returns the end of the certificate validity period. Returns -1 if no client certificate.
717726

718727
Details on the `http::file_info` structure.
719728

@@ -1065,6 +1074,124 @@ To test the above example:
10651074
10661075
You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/centralized_authentication.cpp).
10671076
1077+
### Using Client Certificate Authentication (mTLS)
1078+
Client certificate authentication (also known as mutual TLS or mTLS) provides strong authentication by requiring clients to present X.509 certificates during the TLS handshake. This is the most secure authentication method as it verifies client identity cryptographically.
1079+
1080+
To enable client certificate authentication, configure your webserver with:
1081+
1. `use_ssl()` - Enable TLS
1082+
2. `https_mem_key()` and `https_mem_cert()` - Server certificate
1083+
3. `https_mem_trust()` - CA certificate(s) to verify client certificates
1084+
1085+
```cpp
1086+
#include <httpserver.hpp>
1087+
1088+
using namespace httpserver;
1089+
1090+
class secure_resource : public http_resource {
1091+
public:
1092+
std::shared_ptr<http_response> render_GET(const http_request& req) {
1093+
// Check if client provided a certificate
1094+
if (!req.has_client_certificate()) {
1095+
return std::make_shared<string_response>(
1096+
"Client certificate required", 401, "text/plain");
1097+
}
1098+
1099+
// Check if certificate is verified by our CA
1100+
if (!req.is_client_cert_verified()) {
1101+
return std::make_shared<string_response>(
1102+
"Certificate not verified", 403, "text/plain");
1103+
}
1104+
1105+
// Extract certificate information
1106+
std::string cn = req.get_client_cert_cn(); // Common Name
1107+
std::string dn = req.get_client_cert_dn(); // Subject DN
1108+
std::string issuer = req.get_client_cert_issuer_dn(); // Issuer DN
1109+
std::string fingerprint = req.get_client_cert_fingerprint_sha256();
1110+
time_t not_before = req.get_client_cert_not_before();
1111+
time_t not_after = req.get_client_cert_not_after();
1112+
1113+
return std::make_shared<string_response>(
1114+
"Welcome, " + cn + "!", 200, "text/plain");
1115+
}
1116+
};
1117+
1118+
int main() {
1119+
webserver ws = create_webserver(8443)
1120+
.use_ssl()
1121+
.https_mem_key("server_key.pem")
1122+
.https_mem_cert("server_cert.pem")
1123+
.https_mem_trust("ca_cert.pem"); // CA for client certs
1124+
1125+
secure_resource sr;
1126+
ws.register_resource("/secure", &sr);
1127+
ws.start(true);
1128+
1129+
return 0;
1130+
}
1131+
```
1132+
1133+
Available client certificate methods (require GnuTLS support):
1134+
- `has_client_certificate()` - Check if client presented a certificate
1135+
- `get_client_cert_dn()` - Get the subject Distinguished Name
1136+
- `get_client_cert_issuer_dn()` - Get the issuer Distinguished Name
1137+
- `get_client_cert_cn()` - Get the Common Name from the subject
1138+
- `is_client_cert_verified()` - Check if the certificate chain is verified
1139+
- `get_client_cert_fingerprint_sha256()` - Get hex-encoded SHA-256 fingerprint
1140+
- `get_client_cert_not_before()` - Get certificate validity start time
1141+
- `get_client_cert_not_after()` - Get certificate validity end time
1142+
1143+
To test with curl:
1144+
1145+
# With client certificate
1146+
curl -k --cert client_cert.pem --key client_key.pem https://localhost:8443/secure
1147+
1148+
# Without client certificate (will be rejected)
1149+
curl -k https://localhost:8443/secure
1150+
1151+
You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/client_cert_auth.cpp).
1152+
1153+
### Server Name Indication (SNI) Callback
1154+
SNI allows a server to host multiple TLS certificates on a single IP address. The client indicates which hostname it's connecting to during the TLS handshake, and the server can select the appropriate certificate.
1155+
1156+
To use SNI with libhttpserver, configure an SNI callback that returns the certificate/key pair for each server name:
1157+
1158+
```cpp
1159+
#include <httpserver.hpp>
1160+
#include <map>
1161+
1162+
using namespace httpserver;
1163+
1164+
// Map of server names to cert/key pairs
1165+
std::map<std::string, std::pair<std::string, std::string>> certs;
1166+
1167+
// SNI callback - returns (cert_pem, key_pem) for the requested server name
1168+
std::pair<std::string, std::string> sni_callback(const std::string& server_name) {
1169+
auto it = certs.find(server_name);
1170+
if (it != certs.end()) {
1171+
return it->second;
1172+
}
1173+
return {"", ""}; // Use default certificate
1174+
}
1175+
1176+
int main() {
1177+
// Load certificates for different hostnames
1178+
certs["www.example.com"] = {load_file("www_cert.pem"), load_file("www_key.pem")};
1179+
certs["api.example.com"] = {load_file("api_cert.pem"), load_file("api_key.pem")};
1180+
1181+
webserver ws = create_webserver(443)
1182+
.use_ssl()
1183+
.https_mem_key("default_key.pem") // Default certificate
1184+
.https_mem_cert("default_cert.pem")
1185+
.sni_callback(sni_callback); // SNI callback
1186+
1187+
// ... register resources and start
1188+
ws.start(true);
1189+
return 0;
1190+
}
1191+
```
1192+
1193+
Note: SNI support requires libmicrohttpd 0.9.71 or later compiled with GnuTLS.
1194+
10681195
[Back to TOC](#table-of-contents)
10691196
10701197
## HTTP Utils

configure.ac

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,12 @@ AC_CONFIG_FILES([test/test_content_large:test/test_content_large])
300300
AC_CONFIG_FILES([test/cert.pem:test/cert.pem])
301301
AC_CONFIG_FILES([test/key.pem:test/key.pem])
302302
AC_CONFIG_FILES([test/test_root_ca.pem:test/test_root_ca.pem])
303+
AC_CONFIG_FILES([test/client_cert.pem:test/client_cert.pem])
304+
AC_CONFIG_FILES([test/client_key.pem:test/client_key.pem])
305+
AC_CONFIG_FILES([test/client_cert_no_cn.pem:test/client_cert_no_cn.pem])
306+
AC_CONFIG_FILES([test/client_key_no_cn.pem:test/client_key_no_cn.pem])
307+
AC_CONFIG_FILES([test/client_cert_untrusted.pem:test/client_cert_untrusted.pem])
308+
AC_CONFIG_FILES([test/client_key_untrusted.pem:test/client_key_untrusted.pem])
303309
AC_CONFIG_FILES([test/libhttpserver.supp:test/libhttpserver.supp])
304310
AC_CONFIG_FILES([examples/cert.pem:examples/cert.pem])
305311
AC_CONFIG_FILES([examples/key.pem:examples/key.pem])

examples/client_cert_auth.cpp

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/*
2+
This file is part of libhttpserver
3+
Copyright (C) 2011-2019 Sebastiano Merlino
4+
5+
This library is free software; you can redistribute it and/or
6+
modify it under the terms of the GNU Lesser General Public
7+
License as published by the Free Software Foundation; either
8+
version 2.1 of the License, or (at your option) any later version.
9+
10+
This library is distributed in the hope that it will be useful,
11+
but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13+
Lesser General Public License for more details.
14+
15+
You should have received a copy of the GNU Lesser General Public
16+
License along with this library; if not, write to the Free Software
17+
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
18+
USA
19+
*/
20+
21+
/**
22+
* Example demonstrating client certificate (mTLS) authentication.
23+
*
24+
* This example shows how to:
25+
* 1. Configure the server to request client certificates
26+
* 2. Extract client certificate information in request handlers
27+
* 3. Implement certificate-based access control
28+
*
29+
* To test this example:
30+
*
31+
* 1. Generate server certificate and key:
32+
* openssl req -x509 -newkey rsa:2048 -keyout server_key.pem -out server_cert.pem \
33+
* -days 365 -nodes -subj "/CN=localhost"
34+
*
35+
* 2. Generate a CA certificate for client certs:
36+
* openssl req -x509 -newkey rsa:2048 -keyout ca_key.pem -out ca_cert.pem \
37+
* -days 365 -nodes -subj "/CN=Test CA"
38+
*
39+
* 3. Generate client certificate signed by the CA:
40+
* openssl req -newkey rsa:2048 -keyout client_key.pem -out client_csr.pem \
41+
* -nodes -subj "/CN=Alice/O=Engineering"
42+
* openssl x509 -req -in client_csr.pem -CA ca_cert.pem -CAkey ca_key.pem \
43+
* -CAcreateserial -out client_cert.pem -days 365
44+
*
45+
* 4. Run the server:
46+
* ./client_cert_auth
47+
*
48+
* 5. Test with curl using client certificate:
49+
* curl -k --cert client_cert.pem --key client_key.pem https://localhost:8443/secure
50+
*
51+
* Or without a certificate (will be denied):
52+
* curl -k https://localhost:8443/secure
53+
*/
54+
55+
#include <iostream>
56+
#include <memory>
57+
#include <set>
58+
#include <string>
59+
60+
#include <httpserver.hpp>
61+
62+
// Set of allowed certificate fingerprints (SHA-256, hex-encoded)
63+
// In a real application, this would be loaded from a database or config file
64+
std::set<std::string> allowed_fingerprints;
65+
66+
// Resource that requires client certificate authentication
67+
class secure_resource : public httpserver::http_resource {
68+
public:
69+
std::shared_ptr<httpserver::http_response> render_GET(const httpserver::http_request& req) {
70+
// Check if client provided a certificate
71+
if (!req.has_client_certificate()) {
72+
return std::make_shared<httpserver::string_response>(
73+
"Client certificate required",
74+
httpserver::http::http_utils::http_unauthorized, "text/plain");
75+
}
76+
77+
// Get certificate information
78+
std::string cn = req.get_client_cert_cn();
79+
std::string dn = req.get_client_cert_dn();
80+
std::string issuer = req.get_client_cert_issuer_dn();
81+
std::string fingerprint = req.get_client_cert_fingerprint_sha256();
82+
bool verified = req.is_client_cert_verified();
83+
84+
// Check if certificate is verified by our CA
85+
if (!verified) {
86+
return std::make_shared<httpserver::string_response>(
87+
"Certificate not verified by trusted CA",
88+
httpserver::http::http_utils::http_forbidden, "text/plain");
89+
}
90+
91+
// Optional: Check fingerprint against allowlist
92+
if (!allowed_fingerprints.empty() &&
93+
allowed_fingerprints.find(fingerprint) == allowed_fingerprints.end()) {
94+
return std::make_shared<httpserver::string_response>(
95+
"Certificate not in allowlist",
96+
httpserver::http::http_utils::http_forbidden, "text/plain");
97+
}
98+
99+
// Check certificate validity times
100+
time_t now = time(nullptr);
101+
time_t not_before = req.get_client_cert_not_before();
102+
time_t not_after = req.get_client_cert_not_after();
103+
104+
if (now < not_before) {
105+
return std::make_shared<httpserver::string_response>(
106+
"Certificate not yet valid",
107+
httpserver::http::http_utils::http_forbidden, "text/plain");
108+
}
109+
110+
if (now > not_after) {
111+
return std::make_shared<httpserver::string_response>(
112+
"Certificate has expired",
113+
httpserver::http::http_utils::http_forbidden, "text/plain");
114+
}
115+
116+
// Build response with certificate info
117+
std::string response = "Welcome, " + cn + "!\n\n";
118+
response += "Certificate Details:\n";
119+
response += " Subject DN: " + dn + "\n";
120+
response += " Issuer DN: " + issuer + "\n";
121+
response += " Fingerprint (SHA-256): " + fingerprint + "\n";
122+
response += " Verified: " + std::string(verified ? "Yes" : "No") + "\n";
123+
124+
return std::make_shared<httpserver::string_response>(response, 200, "text/plain");
125+
}
126+
};
127+
128+
// Public resource that shows certificate info but doesn't require it
129+
class info_resource : public httpserver::http_resource {
130+
public:
131+
std::shared_ptr<httpserver::http_response> render_GET(const httpserver::http_request& req) {
132+
std::string response;
133+
134+
if (req.has_client_certificate()) {
135+
response = "Client certificate detected:\n";
136+
response += " Common Name: " + req.get_client_cert_cn() + "\n";
137+
response += " Verified: " + std::string(req.is_client_cert_verified() ? "Yes" : "No") + "\n";
138+
} else {
139+
response = "No client certificate provided.\n";
140+
response += "Use --cert and --key with curl to provide one.\n";
141+
}
142+
143+
return std::make_shared<httpserver::string_response>(response, 200, "text/plain");
144+
}
145+
};
146+
147+
int main() {
148+
std::cout << "Starting HTTPS server with client certificate authentication on port 8443...\n";
149+
std::cout << "\nEndpoints:\n";
150+
std::cout << " /info - Shows certificate info (optional cert)\n";
151+
std::cout << " /secure - Requires valid client certificate\n\n";
152+
153+
// Create webserver with SSL and client certificate trust store
154+
httpserver::webserver ws = httpserver::create_webserver(8443)
155+
.use_ssl()
156+
.https_mem_key("server_key.pem") // Server private key
157+
.https_mem_cert("server_cert.pem") // Server certificate
158+
.https_mem_trust("ca_cert.pem"); // CA certificate for verifying client certs
159+
160+
secure_resource secure;
161+
info_resource info;
162+
163+
ws.register_resource("/secure", &secure);
164+
ws.register_resource("/info", &info);
165+
166+
std::cout << "Server started. Press Ctrl+C to stop.\n\n";
167+
std::cout << "Test commands:\n";
168+
std::cout << " curl -k https://localhost:8443/info\n";
169+
std::cout << " curl -k --cert client_cert.pem --key client_key.pem https://localhost:8443/info\n";
170+
std::cout << " curl -k --cert client_cert.pem --key client_key.pem https://localhost:8443/secure\n";
171+
172+
ws.start(true);
173+
174+
return 0;
175+
}

0 commit comments

Comments
 (0)