example_httpsrv_tls_cert_auth.c 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * –– cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (c) 2016-2018 Silvio Clecio <[email protected]>
  11. *
  12. * This file is part of Sagui library.
  13. *
  14. * Sagui library is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Lesser General Public License as published by
  16. * the Free Software Foundation, either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * Sagui library is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Lesser General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Lesser General Public License
  25. * along with Sagui library. If not, see <http://www.gnu.org/licenses/>.
  26. */
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include <gnutls/gnutls.h>
  31. #include <gnutls/x509.h>
  32. #include <sagui.h>
  33. /* NOTE: Error checking has been omitted to make it clear. */
  34. /*
  35. * Simple example using TLS client authentication.
  36. *
  37. * Client example using cURL:
  38. *
  39. * curl -k --cert certs/client.p12 --pass abc123 --cert-type p12 https://localhost:<PORT>
  40. *
  41. * Certificate generation:
  42. *
  43. * ## CA
  44. * certtool --generate-privkey --outfile ca.key
  45. * echo 'cn = GnuTLS test CA' > ca.tmpl
  46. * echo 'ca' >> ca.tmpl
  47. * echo 'cert_signing_key' >> ca.tmpl
  48. * echo 'expiration_days = 3650' >> ca.tmpl
  49. * certtool --generate-self-signed --load-privkey ca.key --template ca.tmpl --outfile ca.pem
  50. *
  51. * ## Server
  52. * certtool --generate-privkey --outfile server.key
  53. * echo 'organization = GnuTLS test server' > server.tmpl
  54. * echo 'cn = test.gnutls.org' >> server.tmpl
  55. * echo 'tls_www_server' >> server.tmpl
  56. * echo 'expiration_days = 3650' >> server.tmpl
  57. * certtool --generate-certificate --load-ca-privkey ca.key --load-ca-certificate ca.pem --load-privkey server.key --template server.tmpl --outfile server.pem
  58. *
  59. * ## Client
  60. * certtool --generate-privkey --outfile client.key
  61. * echo 'cn = GnuTLS test client' > client.tmpl
  62. * echo 'tls_www_client' >> client.tmpl
  63. * echo 'expiration_days = 3650' >> client.tmpl
  64. * certtool --generate-certificate --load-ca-certificate ca.pem --load-ca-privkey ca.key --load-privkey client.key --template client.tmpl --outfile client.pem
  65. * certtool --to-p12 --p12-name=MyKey --password=abc123 --load-ca-certificate ca.pem --load-privkey client.key --load-certificate client.pem --outder --outfile client.p12
  66. */
  67. #define KEY_FILE SG_EXAMPLES_CERTS_DIR "/server.key"
  68. #define CERT_FILE SG_EXAMPLES_CERTS_DIR "/server.pem"
  69. #define CA_FILE SG_EXAMPLES_CERTS_DIR "/ca.pem"
  70. #define ERR_SIZE 256
  71. #define PAGE_FMT "<html><head><title>Hello world</title></head><body><font color=\"%s\">%s</font></font></body></html>"
  72. #define SECRET_MSG "Secret"
  73. static void concat(char *s1, ...) {
  74. va_list ap;
  75. const char *s;
  76. va_start(ap, s1);
  77. while ((s = va_arg(ap, const char *)))
  78. strcat(s1, s);
  79. va_end(ap);
  80. }
  81. static bool sess_verify_cert(gnutls_session_t tls_session, const char *line_break, char *err) {
  82. gnutls_x509_crt_t cert = NULL;
  83. const gnutls_datum_t *certs;
  84. size_t len;
  85. unsigned int status, certs_size;
  86. int ret;
  87. if (!tls_session || !line_break || !err) {
  88. sg_strerror(EINVAL, err, ERR_SIZE);
  89. return false;
  90. }
  91. if ((ret = gnutls_certificate_verify_peers2(tls_session, &status)) != GNUTLS_E_SUCCESS) {
  92. concat(err, "Error verifying peers: ", gnutls_strerror(ret), line_break, NULL);
  93. goto fail;
  94. }
  95. if (status & GNUTLS_CERT_INVALID)
  96. concat(err, "The certificate is not trusted", line_break, NULL);
  97. if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  98. concat(err, "The certificate has not got a known issuer", line_break, NULL);
  99. if (status & GNUTLS_CERT_REVOKED)
  100. concat(err, "The certificate has been revoked", line_break, NULL);
  101. if (gnutls_certificate_type_get(tls_session) != GNUTLS_CRT_X509) {
  102. concat(err, "The certificate type is not X.509", line_break, NULL);
  103. goto fail;
  104. }
  105. if ((ret = gnutls_x509_crt_init(&cert)) != GNUTLS_E_SUCCESS) {
  106. concat(err, "Error in the certificate initialization: ", gnutls_strerror(ret), line_break, NULL);
  107. goto fail;
  108. }
  109. if (!(certs = gnutls_certificate_get_peers(tls_session, &certs_size))) {
  110. concat(err, "No certificate was found", line_break, NULL);
  111. goto fail;
  112. }
  113. if ((ret = gnutls_x509_crt_import(cert, &certs[0], GNUTLS_X509_FMT_DER)) != GNUTLS_E_SUCCESS) {
  114. concat(err, "Error parsing certificate: ", gnutls_strerror(ret), line_break, NULL);
  115. goto fail;
  116. }
  117. if (gnutls_x509_crt_get_expiration_time(cert) < time(NULL)) {
  118. concat(err, "The certificate has expired", line_break, NULL);
  119. goto fail;
  120. }
  121. if (gnutls_x509_crt_get_activation_time(cert) > time(NULL)) {
  122. concat(err, "The certificate has not been activated yet", line_break, NULL);
  123. goto fail;
  124. }
  125. fail:
  126. len = strlen(err);
  127. err[len - strlen("<br>")] = '\0';
  128. gnutls_x509_crt_deinit(cert);
  129. return len == 0;
  130. }
  131. static void req_cb(__SG_UNUSED void *cls, __SG_UNUSED struct sg_httpreq *req, struct sg_httpres *res) {
  132. char msg[ERR_SIZE];
  133. char *color, *page;
  134. size_t page_size;
  135. unsigned int status;
  136. if (sess_verify_cert(sg_httpreq_tls_session(req), "<br>", msg)) {
  137. strcpy(msg, SECRET_MSG);
  138. color = "green";
  139. status = 200;
  140. } else {
  141. color = "red";
  142. status = 500;
  143. }
  144. page_size = (size_t) snprintf(NULL, 0, PAGE_FMT, color, msg);
  145. page = sg_alloc(page_size);
  146. snprintf(page, page_size, PAGE_FMT, color, msg);
  147. sg_httpres_send(res, page, "text/html; charset=utf-8", status);
  148. sg_free(page);
  149. }
  150. int main(void) {
  151. struct sg_httpsrv *srv = sg_httpsrv_new(req_cb, NULL);
  152. gnutls_datum_t key_file, cert_file, ca_file;
  153. int ret, status = EXIT_FAILURE;
  154. memset(&key_file, 0, sizeof(gnutls_datum_t));
  155. memset(&cert_file, 0, sizeof(gnutls_datum_t));
  156. memset(&ca_file, 0, sizeof(gnutls_datum_t));
  157. if ((ret = gnutls_load_file(KEY_FILE, &key_file)) != GNUTLS_E_SUCCESS) {
  158. fprintf(stderr, "Error loading the private key \"%s\": %s\n", KEY_FILE, gnutls_strerror(ret));
  159. fflush(stdout);
  160. goto fail;
  161. }
  162. if ((ret = gnutls_load_file(CERT_FILE, &cert_file)) != GNUTLS_E_SUCCESS) {
  163. fprintf(stderr, "Error loading the certificate \"%s\": %s\n", CERT_FILE, gnutls_strerror(ret));
  164. fflush(stdout);
  165. goto fail;
  166. }
  167. if ((ret = gnutls_load_file(CA_FILE, &ca_file)) != GNUTLS_E_SUCCESS) {
  168. fprintf(stderr, "Error loading the CA \"%s\": %s\n", CA_FILE, gnutls_strerror(ret));
  169. fflush(stdout);
  170. goto fail;
  171. }
  172. if (sg_httpsrv_tls_listen2(srv, (const char *) key_file.data, NULL, (const char *) cert_file.data,
  173. (const char *) ca_file.data, NULL, 0 /* 0 = port chosen randomly */, false)) {
  174. status = EXIT_SUCCESS;
  175. fprintf(stdout, "Server running at https://localhost:%d\n", sg_httpsrv_port(srv));
  176. fflush(stdout);
  177. getchar();
  178. }
  179. fail:
  180. sg_httpsrv_free(srv);
  181. if (key_file.size > 0)
  182. gnutls_free(key_file.data);
  183. if (cert_file.size > 0)
  184. gnutls_free(cert_file.data);
  185. if (ca_file.size > 0)
  186. gnutls_free(ca_file.data);
  187. return status;
  188. }