Imported Upstream version 7.59.0
[platform/upstream/curl.git] / docs / examples / cacertinmem.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 /* <DESC>
23  * CA cert in memory with OpenSSL to get a HTTPS page.
24  * </DESC>
25  */
26
27 #include <openssl/err.h>
28 #include <openssl/ssl.h>
29 #include <curl/curl.h>
30 #include <stdio.h>
31
32 size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream)
33 {
34   fwrite(ptr, size, nmemb, (FILE *)stream);
35   return (nmemb*size);
36 }
37
38 static CURLcode sslctx_function(CURL *curl, void *sslctx, void *parm)
39 {
40   CURLcode rv = CURLE_ABORTED_BY_CALLBACK;
41   X509_STORE *store = NULL;
42   X509 *cert = NULL;
43   BIO *bio = NULL;
44   char *mypem =
45     /* CA for example.com. CN = DigiCert High Assurance EV Root CA */
46     "-----BEGIN CERTIFICATE-----\n"
47     "MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\n"
48     "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
49     "d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n"
50     "ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\n"
51     "MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n"
52     "LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n"
53     "RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n"
54     "+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\n"
55     "PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\n"
56     "xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\n"
57     "Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\n"
58     "hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\n"
59     "EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\n"
60     "MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\n"
61     "FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n"
62     "nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n"
63     "eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n"
64     "hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n"
65     "Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n"
66     "vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n"
67     "+OkuE6N36B9K\n"
68     "-----END CERTIFICATE-----\n";
69
70   /* clear the current thread's OpenSSL error queue */
71   ERR_clear_error();
72
73   /* get a BIO */
74   bio = BIO_new_mem_buf(mypem, -1);
75   if(!bio)
76     goto err;
77
78   /* use it to read the PEM formatted certificate from memory into an X509
79    * structure that SSL can use
80    */
81   if(!PEM_read_bio_X509(bio, &cert, 0, NULL))
82     goto err;
83
84   /* get a pointer to the X509 certificate store (which may be empty!) */
85   store = SSL_CTX_get_cert_store((SSL_CTX *)sslctx);
86   if(!store)
87     goto err;
88
89   /* add our certificate to this store */
90   if(!X509_STORE_add_cert(store, cert)) {
91     unsigned long error = ERR_peek_last_error();
92
93     /* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
94      * certificate is already in the store. That could happen if
95      * libcurl already loaded the certificate from a ca cert bundle
96      * set at libcurl build-time or runtime.
97      */
98     if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
99        ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE)
100       goto err;
101
102     ERR_clear_error();
103   }
104
105   rv = CURLE_OK;
106
107 err:
108   if(rv != CURLE_OK) {
109     char errbuf[256];
110     unsigned long error = ERR_peek_last_error();
111
112     fprintf(stderr, "error adding certificate\n");
113     if(error) {
114       ERR_error_string_n(error, errbuf, sizeof errbuf);
115       fprintf(stderr, "%s\n", errbuf);
116     }
117   }
118
119   X509_free(cert);
120   BIO_free(bio);
121   ERR_clear_error();
122
123   return rv;
124 }
125
126 int main(void)
127 {
128   CURL *ch;
129   CURLcode rv;
130
131   rv = curl_global_init(CURL_GLOBAL_ALL);
132   ch = curl_easy_init();
133   rv = curl_easy_setopt(ch, CURLOPT_VERBOSE, 0L);
134   rv = curl_easy_setopt(ch, CURLOPT_HEADER, 0L);
135   rv = curl_easy_setopt(ch, CURLOPT_NOPROGRESS, 1L);
136   rv = curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1L);
137   rv = curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, *writefunction);
138   rv = curl_easy_setopt(ch, CURLOPT_WRITEDATA, stdout);
139   rv = curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, *writefunction);
140   rv = curl_easy_setopt(ch, CURLOPT_HEADERDATA, stderr);
141   rv = curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM");
142   rv = curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 1L);
143   rv = curl_easy_setopt(ch, CURLOPT_URL, "https://www.example.com/");
144
145   /* turn off the default CA locations (optional)
146    * otherwise libcurl will load CA certificates from the locations that
147    * were detected/specified at build-time
148    */
149   rv = curl_easy_setopt(ch, CURLOPT_CAINFO, NULL);
150   rv = curl_easy_setopt(ch, CURLOPT_CAPATH, NULL);
151
152   /* first try: retrieve page without ca certificates -> should fail
153    * unless libcurl was built --with-ca-fallback enabled at build-time
154    */
155   rv = curl_easy_perform(ch);
156   if(rv == CURLE_OK)
157     printf("*** transfer succeeded ***\n");
158   else
159     printf("*** transfer failed ***\n");
160
161   /* use a fresh connection (optional)
162    * this option seriously impacts performance of multiple transfers but
163    * it is necessary order to demonstrate this example. recall that the
164    * ssl ctx callback is only called _before_ an SSL connection is
165    * established, therefore it will not affect existing verified SSL
166    * connections already in the connection cache associated with this
167    * handle. normally you would set the ssl ctx function before making
168    * any transfers, and not use this option.
169    */
170   rv = curl_easy_setopt(ch, CURLOPT_FRESH_CONNECT, 1L);
171
172   /* second try: retrieve page using cacerts' certificate -> will succeed
173    * load the certificate by installing a function doing the necessary
174    * "modifications" to the SSL CONTEXT just before link init
175    */
176   rv = curl_easy_setopt(ch, CURLOPT_SSL_CTX_FUNCTION, *sslctx_function);
177   rv = curl_easy_perform(ch);
178   if(rv == CURLE_OK)
179     printf("*** transfer succeeded ***\n");
180   else
181     printf("*** transfer failed ***\n");
182
183   curl_easy_cleanup(ch);
184   curl_global_cleanup();
185   return rv;
186 }