tlsauthentication.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. We left the basic authentication chapter with the unsatisfactory conclusion that
  2. any traffic, including the credentials, could be intercepted by anyone between
  3. the browser client and the server. Protecting the data while it is sent over
  4. unsecured lines will be the goal of this chapter.
  5. Since version 0.4, the @emph{MHD} library includes support for encrypting the
  6. traffic by employing SSL/TSL. If @emph{GNU libmicrohttpd} has been configured to
  7. support these, encryption and decryption can be applied transparently on the
  8. data being sent, with only minimal changes to the actual source code of the example.
  9. @heading Preparation
  10. First, a private key for the server will be generated. With this key, the server
  11. will later be able to authenticate itself to the client---preventing anyone else
  12. from stealing the password by faking its identity. The @emph{OpenSSL} suite, which
  13. is available on many operating systems, can generate such a key. For the scope of
  14. this tutorial, we will be content with a 1024 bit key:
  15. @verbatim
  16. > openssl genrsa -out server.key 1024
  17. @end verbatim
  18. @noindent
  19. In addition to the key, a certificate describing the server in human readable tokens
  20. is also needed. This certificate will be attested with our aforementioned key. In this way,
  21. we obtain a self-signed certificate, valid for one year.
  22. @verbatim
  23. > openssl req -days 365 -out server.pem -new -x509 -key server.key
  24. @end verbatim
  25. @noindent
  26. To avoid unnecessary error messages in the browser, the certificate needs to
  27. have a name that matches the @emph{URI}, for example, "localhost" or the domain.
  28. If you plan to have a publicly reachable server, you will need to ask a trusted third party,
  29. called @emph{Certificate Authority}, or @emph{CA}, to attest the certificate for you. This way,
  30. any visitor can make sure the server's identity is real.
  31. Whether the server's certificate is signed by us or a third party, once it has been accepted
  32. by the client, both sides will be communicating over encrypted channels. From this point on,
  33. it is the client's turn to authenticate itself. But this has already been implemented in the basic
  34. authentication scheme.
  35. @heading Changing the source code
  36. We merely have to extend the server program so that it loads the two files into memory,
  37. @verbatim
  38. int
  39. main ()
  40. {
  41. struct MHD_Daemon *daemon;
  42. char *key_pem;
  43. char *cert_pem;
  44. key_pem = load_file (SERVERKEYFILE);
  45. cert_pem = load_file (SERVERCERTFILE);
  46. if ((key_pem == NULL) || (cert_pem == NULL))
  47. {
  48. printf ("The key/certificate files could not be read.\n");
  49. return 1;
  50. }
  51. @end verbatim
  52. @noindent
  53. and then we point the @emph{MHD} daemon to it upon initialization.
  54. @verbatim
  55. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
  56. PORT, NULL, NULL,
  57. &answer_to_connection, NULL,
  58. MHD_OPTION_HTTPS_MEM_KEY, key_pem,
  59. MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
  60. MHD_OPTION_END);
  61. if (NULL == daemon)
  62. {
  63. printf ("%s\n", cert_pem);
  64. free (key_pem);
  65. free (cert_pem);
  66. return 1;
  67. }
  68. @end verbatim
  69. @noindent
  70. The rest consists of little new besides some additional memory cleanups.
  71. @verbatim
  72. getchar ();
  73. MHD_stop_daemon (daemon);
  74. free (key_pem);
  75. free (cert_pem);
  76. return 0;
  77. }
  78. @end verbatim
  79. @noindent
  80. The rather unexciting file loader can be found in the complete example @code{tlsauthentication.c}.
  81. @heading Remarks
  82. @itemize @bullet
  83. @item
  84. While the standard @emph{HTTP} port is 80, it is 443 for @emph{HTTPS}. The common internet browsers assume
  85. standard @emph{HTTP} if they are asked to access other ports than these. Therefore, you will have to type
  86. @code{https://localhost:8888} explicitly when you test the example, or the browser will not know how to
  87. handle the answer properly.
  88. @item
  89. The remaining weak point is the question how the server will be trusted initially. Either a @emph{CA} signs the
  90. certificate or the client obtains the key over secure means. Anyway, the clients have to be aware (or configured)
  91. that they should not accept certificates of unknown origin.
  92. @item
  93. The introduced method of certificates makes it mandatory to set an expiration date---making it less feasible to
  94. hardcode certificates in embedded devices.
  95. @item
  96. The cryptographic facilities consume memory space and computing time. For this reason, websites usually consists
  97. both of uncritically @emph{HTTP} parts and secured @emph{HTTPS}.
  98. @end itemize
  99. @heading Client authentication
  100. You can also use MHD to authenticate the client via SSL/TLS certificates
  101. (as an alternative to using the password-based Basic or Digest authentication).
  102. To do this, you will need to link your application against @emph{gnutls}.
  103. Next, when you start the MHD daemon, you must specify the root CA that you're
  104. willing to trust:
  105. @verbatim
  106. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
  107. PORT, NULL, NULL,
  108. &answer_to_connection, NULL,
  109. MHD_OPTION_HTTPS_MEM_KEY, key_pem,
  110. MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
  111. MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem,
  112. MHD_OPTION_END);
  113. @end verbatim
  114. With this, you can then obtain client certificates for each session.
  115. In order to obtain the identity of the client, you first need to
  116. obtain the raw GnuTLS session handle from @emph{MHD} using
  117. @code{MHD_get_connection_info}.
  118. @verbatim
  119. #include <gnutls/gnutls.h>
  120. #include <gnutls/x509.h>
  121. gnutls_session_t tls_session;
  122. union MHD_ConnectionInfo *ci;
  123. ci = MHD_get_connection_info (connection,
  124. MHD_CONNECTION_INFO_GNUTLS_SESSION);
  125. tls_session = (gnutls_session_t) ci->tls_session;
  126. @end verbatim
  127. You can then extract the client certificate:
  128. @verbatim
  129. /**
  130. * Get the client's certificate
  131. *
  132. * @param tls_session the TLS session
  133. * @return NULL if no valid client certificate could be found, a pointer
  134. * to the certificate if found
  135. */
  136. static gnutls_x509_crt_t
  137. get_client_certificate (gnutls_session_t tls_session)
  138. {
  139. unsigned int listsize;
  140. const gnutls_datum_t * pcert;
  141. gnutls_certificate_status_t client_cert_status;
  142. gnutls_x509_crt_t client_cert;
  143. if (tls_session == NULL)
  144. return NULL;
  145. if (gnutls_certificate_verify_peers2(tls_session,
  146. &client_cert_status))
  147. return NULL;
  148. if (0 != client_cert_status)
  149. {
  150. fprintf (stderr,
  151. "Failed client certificate invalid: %d\n",
  152. client_cert_status);
  153. return NULL;
  154. }
  155. pcert = gnutls_certificate_get_peers(tls_session,
  156. &listsize);
  157. if ( (pcert == NULL) ||
  158. (listsize == 0))
  159. {
  160. fprintf (stderr,
  161. "Failed to retrieve client certificate chain\n");
  162. return NULL;
  163. }
  164. if (gnutls_x509_crt_init(&client_cert))
  165. {
  166. fprintf (stderr,
  167. "Failed to initialize client certificate\n");
  168. return NULL;
  169. }
  170. /* Note that by passing values between 0 and listsize here, you
  171. can get access to the CA's certs */
  172. if (gnutls_x509_crt_import(client_cert,
  173. &pcert[0],
  174. GNUTLS_X509_FMT_DER))
  175. {
  176. fprintf (stderr,
  177. "Failed to import client certificate\n");
  178. gnutls_x509_crt_deinit(client_cert);
  179. return NULL;
  180. }
  181. return client_cert;
  182. }
  183. @end verbatim
  184. Using the client certificate, you can then get the client's distinguished name
  185. and alternative names:
  186. @verbatim
  187. /**
  188. * Get the distinguished name from the client's certificate
  189. *
  190. * @param client_cert the client certificate
  191. * @return NULL if no dn or certificate could be found, a pointer
  192. * to the dn if found
  193. */
  194. char *
  195. cert_auth_get_dn(gnutls_x509_crt_t client_cert)
  196. {
  197. char* buf;
  198. size_t lbuf;
  199. lbuf = 0;
  200. gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf);
  201. buf = malloc(lbuf);
  202. if (buf == NULL)
  203. {
  204. fprintf (stderr,
  205. "Failed to allocate memory for certificate dn\n");
  206. return NULL;
  207. }
  208. gnutls_x509_crt_get_dn(client_cert, buf, &lbuf);
  209. return buf;
  210. }
  211. /**
  212. * Get the alternative name of specified type from the client's certificate
  213. *
  214. * @param client_cert the client certificate
  215. * @param nametype The requested name type
  216. * @param index The position of the alternative name if multiple names are
  217. * matching the requested type, 0 for the first matching name
  218. * @return NULL if no matching alternative name could be found, a pointer
  219. * to the alternative name if found
  220. */
  221. char *
  222. MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert,
  223. int nametype,
  224. unsigned int index)
  225. {
  226. char* buf;
  227. size_t lbuf;
  228. unsigned int seq;
  229. unsigned int subseq;
  230. unsigned int type;
  231. int result;
  232. subseq = 0;
  233. for (seq=0;;seq++)
  234. {
  235. lbuf = 0;
  236. result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf,
  237. &type, NULL);
  238. if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
  239. return NULL;
  240. if (nametype != (int) type)
  241. continue;
  242. if (subseq == index)
  243. break;
  244. subseq++;
  245. }
  246. buf = malloc(lbuf);
  247. if (buf == NULL)
  248. {
  249. fprintf (stderr,
  250. "Failed to allocate memory for certificate alt name\n");
  251. return NULL;
  252. }
  253. result = gnutls_x509_crt_get_subject_alt_name2(client_cert,
  254. seq,
  255. buf,
  256. &lbuf,
  257. NULL, NULL);
  258. if (result != nametype)
  259. {
  260. fprintf (stderr,
  261. "Unexpected return value from gnutls: %d\n",
  262. result);
  263. free (buf);
  264. return NULL;
  265. }
  266. return buf;
  267. }
  268. @end verbatim
  269. Finally, you should release the memory associated with the client
  270. certificate:
  271. @verbatim
  272. gnutls_x509_crt_deinit (client_cert);
  273. @end verbatim
  274. @heading Using TLS Server Name Indication (SNI)
  275. SNI enables hosting multiple domains under one IP address with TLS. So
  276. SNI is the TLS-equivalent of virtual hosting. To use SNI with MHD, you
  277. need at least GnuTLS 3.0. The main change compared to the simple hosting
  278. of one domain is that you need to provide a callback instead of the key
  279. and certificate. For example, when you start the MHD daemon, you could
  280. do this:
  281. @verbatim
  282. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
  283. PORT, NULL, NULL,
  284. &answer_to_connection, NULL,
  285. MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback,
  286. MHD_OPTION_END);
  287. @end verbatim
  288. Here, @code{sni_callback} is the name of a function that you will have to
  289. implement to retrieve the X.509 certificate for an incoming connection.
  290. The callback has type @code{gnutls_certificate_retrieve_function2} and
  291. is documented in the GnuTLS API for the @code{gnutls_certificate_set_retrieve_function2}
  292. as follows:
  293. @deftypefn {Function Pointer} int {*gnutls_certificate_retrieve_function2} (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey)
  294. @table @var
  295. @item req_ca_cert
  296. is only used in X.509 certificates. Contains a list with the CA names that the server considers trusted. Normally we should send a certificate that is signed by one of these CAs. These names are DER encoded. To get a more meaningful value use the function @code{gnutls_x509_rdn_get()}.
  297. @item pk_algos
  298. contains a list with server’s acceptable signature algorithms. The certificate returned should support the server’s given algorithms.
  299. @item pcert
  300. should contain a single certificate and public or a list of them.
  301. @item pcert_length
  302. is the size of the previous list.
  303. @item pkey
  304. is the private key.
  305. @end table
  306. @end deftypefn
  307. A possible implementation of this callback would look like this:
  308. @verbatim
  309. struct Hosts
  310. {
  311. struct Hosts *next;
  312. const char *hostname;
  313. gnutls_pcert_st pcrt;
  314. gnutls_privkey_t key;
  315. };
  316. static struct Hosts *hosts;
  317. int
  318. sni_callback (gnutls_session_t session,
  319. const gnutls_datum_t* req_ca_dn,
  320. int nreqs,
  321. const gnutls_pk_algorithm_t* pk_algos,
  322. int pk_algos_length,
  323. gnutls_pcert_st** pcert,
  324. unsigned int *pcert_length,
  325. gnutls_privkey_t * pkey)
  326. {
  327. char name[256];
  328. size_t name_len;
  329. struct Hosts *host;
  330. unsigned int type;
  331. name_len = sizeof (name);
  332. if (GNUTLS_E_SUCCESS !=
  333. gnutls_server_name_get (session,
  334. name,
  335. &name_len,
  336. &type,
  337. 0 /* index */))
  338. return -1;
  339. for (host = hosts; NULL != host; host = host->next)
  340. if (0 == strncmp (name, host->hostname, name_len))
  341. break;
  342. if (NULL == host)
  343. {
  344. fprintf (stderr,
  345. "Need certificate for %.*s\n",
  346. (int) name_len,
  347. name);
  348. return -1;
  349. }
  350. fprintf (stderr,
  351. "Returning certificate for %.*s\n",
  352. (int) name_len,
  353. name);
  354. *pkey = host->key;
  355. *pcert_length = 1;
  356. *pcert = &host->pcrt;
  357. return 0;
  358. }
  359. @end verbatim
  360. Note that MHD cannot offer passing a closure or any other additional information
  361. to this callback, as the GnuTLS API unfortunately does not permit this at this
  362. point.
  363. The @code{hosts} list can be initialized by loading the private keys and X.509
  364. certificates from disk as follows:
  365. @verbatim
  366. static void
  367. load_keys(const char *hostname,
  368. const char *CERT_FILE,
  369. const char *KEY_FILE)
  370. {
  371. int ret;
  372. gnutls_datum_t data;
  373. struct Hosts *host;
  374. host = malloc (sizeof (struct Hosts));
  375. host->hostname = hostname;
  376. host->next = hosts;
  377. hosts = host;
  378. ret = gnutls_load_file (CERT_FILE, &data);
  379. if (ret < 0)
  380. {
  381. fprintf (stderr,
  382. "*** Error loading certificate file %s.\n",
  383. CERT_FILE);
  384. exit(1);
  385. }
  386. ret =
  387. gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM,
  388. 0);
  389. if (ret < 0)
  390. {
  391. fprintf(stderr,
  392. "*** Error loading certificate file: %s\n",
  393. gnutls_strerror (ret));
  394. exit(1);
  395. }
  396. gnutls_free (data.data);
  397. ret = gnutls_load_file (KEY_FILE, &data);
  398. if (ret < 0)
  399. {
  400. fprintf (stderr,
  401. "*** Error loading key file %s.\n",
  402. KEY_FILE);
  403. exit(1);
  404. }
  405. gnutls_privkey_init (&host->key);
  406. ret =
  407. gnutls_privkey_import_x509_raw (host->key,
  408. &data, GNUTLS_X509_FMT_PEM,
  409. NULL, 0);
  410. if (ret < 0)
  411. {
  412. fprintf (stderr,
  413. "*** Error loading key file: %s\n",
  414. gnutls_strerror (ret));
  415. exit(1);
  416. }
  417. gnutls_free (data.data);
  418. }
  419. @end verbatim
  420. The code above was largely lifted from GnuTLS. You can find other
  421. methods for initializing certificates and keys in the GnuTLS manual
  422. and source code.