summaryrefslogtreecommitdiff
path: root/doc/tex/ex-rfc2818.tex
blob: 6d3a36f22911e33415bc14096f7d04aa80458a3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
\index{Verifying certificate paths}
\label{ex:rfc2818}

\begin{verbatim}

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

/* This function will try to verify the peer's certificate, and
 * also check if the hostname matches, and the activation, expiration dates.
 */
void verify_certificate( gnutls_session session, const char* hostname)
{
   int status;
   const gnutls_datum* cert_list;
   int cert_list_size;
   gnutls_x509_crt cert;

   /* This function only works with X.509 certificates.
    */
   if ( gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
      return;

   /* This verification function uses the trusted CAs in the credentials
    * structure. So you must have installed one or more CA certificates.
    */
   status = gnutls_certificate_verify_peers(session);

   if (status == GNUTLS_E_NO_CERTIFICATE_FOUND) {
      printf("No certificate was sent\n");
      return;
   }

   if (status & GNUTLS_CERT_INVALID)
      printf("The certificate is not trusted.\n");

   if (status & GNUTLS_CERT_ISSUER_NOT_FOUND)
      printf("The certificate hasn't got a known issuer.\n");

   if (status & GNUTLS_CERT_REVOKED)
     printf("The certificate has been revoked.\n");


   if ( gnutls_x509_crt_init( &cert) < 0) {
      printf("error in initialization\n");
      return;
   }

   cert_list = gnutls_certificate_get_peers( session, &cert_list_size);
   if ( cert_list == NULL) {
      printf("No certificate was found!\n");
      return;
   }

   /* This is not a real world example, since we only check the first 
    * certificate in the given chain.
    */
   if ( gnutls_x509_crt_import( cert, &cert_list[0], GNUTLS_X509_FMT_DER) < 0) {
      printf("error parsing certificate\n");
      return;
   }

   /* Beware here we do not check for errors.
    */
   if ( gnutls_x509_crt_get_expiration( cert) < time(0)) {
      printf("The certificate has expired\n");
      return;
   }

   if ( gnutls_x509_crt_get_activation_time( cert) > time(0)) {
      printf("The certificate is not yet activated\n");
      return;
   }

   if ( !gnutls_x509_crt_check_hostname( cert, hostname)) {
      printf("The certificate does not match hostname\n");
      return;
   }

   gnutls_x509_crt_deinit( cert);

   return;
}

\end{verbatim}