Imported Upstream version 7.53.1
[platform/upstream/curl.git] / docs / examples / curlx.c
1 /*
2   curlx.c  Authors: Peter Sylvester, Jean-Paul Merlin
3
4   This is a little program to demonstrate the usage of
5
6   - an ssl initialisation callback setting a user key and trustbases
7   coming from a pkcs12 file
8   - using an ssl application callback to find a URI in the
9   certificate presented during ssl session establishment.
10
11 */
12 /* <DESC>
13  * demonstrates use of SSL context callback, requires OpenSSL
14  * </DESC>
15  */
16
17 /*
18  * Copyright (c) 2003 The OpenEvidence Project.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions, the following disclaimer,
26  *    and the original OpenSSL and SSLeay Licences below.
27  *
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions, the following disclaimer
30  *    and the original OpenSSL and SSLeay Licences below in
31  *    the documentation and/or other materials provided with the
32  *    distribution.
33  *
34  * 3. All advertising materials mentioning features or use of this
35  *    software must display the following acknowledgments:
36  *    "This product includes software developed by the Openevidence Project
37  *    for use in the OpenEvidence Toolkit. (http://www.openevidence.org/)"
38  *    This product includes software developed by the OpenSSL Project
39  *    for use in the OpenSSL Toolkit (https://www.openssl.org/)"
40  *    This product includes cryptographic software written by Eric Young
41  *    (eay@cryptsoft.com).  This product includes software written by Tim
42  *    Hudson (tjh@cryptsoft.com)."
43  *
44  * 4. The names "OpenEvidence Toolkit" and "OpenEvidence Project" must not be
45  *    used to endorse or promote products derived from this software without
46  *    prior written permission. For written permission, please contact
47  *    openevidence-core@openevidence.org.
48  *
49  * 5. Products derived from this software may not be called "OpenEvidence"
50  *    nor may "OpenEvidence" appear in their names without prior written
51  *    permission of the OpenEvidence Project.
52  *
53  * 6. Redistributions of any form whatsoever must retain the following
54  *    acknowledgments:
55  *    "This product includes software developed by the OpenEvidence Project
56  *    for use in the OpenEvidence Toolkit (http://www.openevidence.org/)
57  *    This product includes software developed by the OpenSSL Project
58  *    for use in the OpenSSL Toolkit (https://www.openssl.org/)"
59  *    This product includes cryptographic software written by Eric Young
60  *    (eay@cryptsoft.com).  This product includes software written by Tim
61  *    Hudson (tjh@cryptsoft.com)."
62  *
63  * THIS SOFTWARE IS PROVIDED BY THE OpenEvidence PROJECT ``AS IS'' AND ANY
64  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
66  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenEvidence PROJECT OR
67  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
68  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
69  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
70  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
71  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
72  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
73  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
74  * OF THE POSSIBILITY OF SUCH DAMAGE.
75  * ====================================================================
76  *
77  * This product includes software developed by the OpenSSL Project
78  * for use in the OpenSSL Toolkit (https://www.openssl.org/)
79  * This product includes cryptographic software written by Eric Young
80  * (eay@cryptsoft.com).  This product includes software written by Tim
81  * Hudson (tjh@cryptsoft.com).
82  *
83  */
84
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <curl/curl.h>
89 #include <openssl/x509v3.h>
90 #include <openssl/x509_vfy.h>
91 #include <openssl/crypto.h>
92 #include <openssl/lhash.h>
93 #include <openssl/objects.h>
94 #include <openssl/err.h>
95 #include <openssl/evp.h>
96 #include <openssl/x509.h>
97 #include <openssl/pkcs12.h>
98 #include <openssl/bio.h>
99 #include <openssl/ssl.h>
100
101 static const char *curlx_usage[]={
102   "usage: curlx args\n",
103   " -p12 arg         - tia  file ",
104   " -envpass arg     - environement variable which content the tia private"
105   " key password",
106   " -out arg         - output file (response)- default stdout",
107   " -in arg          - input file (request)- default stdin",
108   " -connect arg     - URL of the server for the connection ex:"
109   " www.openevidence.org",
110   " -mimetype arg    - MIME type for data in ex : application/timestamp-query"
111   " or application/dvcs -default application/timestamp-query",
112   " -acceptmime arg  - MIME type acceptable for the response ex : "
113   "application/timestamp-response or application/dvcs -default none",
114   " -accesstype arg  - an Object identifier in an AIA/SIA method, e.g."
115   " AD_DVCS or ad_timestamping",
116   NULL
117 };
118
119 /*
120
121 ./curlx -p12 psy.p12 -envpass XX -in request -verbose -accesstype AD_DVCS
122 -mimetype application/dvcs -acceptmime application/dvcs -out response
123
124 */
125
126 /*
127  * We use this ZERO_NULL to avoid picky compiler warnings,
128  * when assigning a NULL pointer to a function pointer var.
129  */
130
131 #define ZERO_NULL 0
132
133 /* This is a context that we pass to all callbacks */
134
135 typedef struct sslctxparm_st {
136   unsigned char *p12file;
137   const char *pst;
138   PKCS12 *p12;
139   EVP_PKEY *pkey;
140   X509 *usercert;
141   STACK_OF(X509) * ca;
142   CURL *curl;
143   BIO *errorbio;
144   int accesstype;
145   int verbose;
146
147 } sslctxparm;
148
149 /* some helper function. */
150
151 static char *ia5string(ASN1_IA5STRING *ia5)
152 {
153   char *tmp;
154   if(!ia5 || !ia5->length)
155     return NULL;
156   tmp = OPENSSL_malloc(ia5->length + 1);
157   memcpy(tmp, ia5->data, ia5->length);
158   tmp[ia5->length] = 0;
159   return tmp;
160 }
161
162 /* A conveniance routine to get an access URI. */
163 static unsigned char *my_get_ext(X509 *cert, const int type,
164                                  int extensiontype)
165 {
166   int i;
167   STACK_OF(ACCESS_DESCRIPTION) * accessinfo;
168   accessinfo =  X509_get_ext_d2i(cert, extensiontype, NULL, NULL);
169
170   if(!sk_ACCESS_DESCRIPTION_num(accessinfo))
171     return NULL;
172   for(i = 0; i < sk_ACCESS_DESCRIPTION_num(accessinfo); i++) {
173     ACCESS_DESCRIPTION * ad = sk_ACCESS_DESCRIPTION_value(accessinfo, i);
174     if(OBJ_obj2nid(ad->method) == type) {
175       if(ad->location->type == GEN_URI) {
176         return ia5string(ad->location->d.ia5);
177       }
178       return NULL;
179     }
180   }
181   return NULL;
182 }
183
184 /* This is an application verification call back, it does not
185    perform any addition verification but tries to find a URL
186    in the presented certificat. If found, this will become
187    the URL to be used in the POST.
188 */
189
190 static int ssl_app_verify_callback(X509_STORE_CTX *ctx, void *arg)
191 {
192   sslctxparm * p = (sslctxparm *) arg;
193   int ok;
194
195   if(p->verbose > 2)
196     BIO_printf(p->errorbio, "entering ssl_app_verify_callback\n");
197
198   if((ok= X509_verify_cert(ctx)) && ctx->cert) {
199     unsigned char *accessinfo;
200     if(p->verbose > 1)
201       X509_print_ex(p->errorbio, ctx->cert, 0, 0);
202
203     accessinfo = my_get_ext(ctx->cert, p->accesstype, NID_sinfo_access);
204     if(accessinfo) {
205       if(p->verbose)
206         BIO_printf(p->errorbio, "Setting URL from SIA to: %s\n", accessinfo);
207
208       curl_easy_setopt(p->curl, CURLOPT_URL, accessinfo);
209     }
210     else if(accessinfo = my_get_ext(ctx->cert, p->accesstype,
211                                     NID_info_access)) {
212       if(p->verbose)
213         BIO_printf(p->errorbio, "Setting URL from AIA to: %s\n", accessinfo);
214
215       curl_easy_setopt(p->curl, CURLOPT_URL, accessinfo);
216     }
217   }
218   if(p->verbose > 2)
219     BIO_printf(p->errorbio, "leaving ssl_app_verify_callback with %d\n", ok);
220
221   return ok;
222 }
223
224
225 /* The SSL initialisation callback. The callback sets:
226    - a private key and certificate
227    - a trusted ca certificate
228    - a preferred cipherlist
229    - an application verification callback (the function above)
230 */
231
232 static CURLcode sslctxfun(CURL *curl, void *sslctx, void *parm)
233 {
234   sslctxparm *p = (sslctxparm *) parm;
235   SSL_CTX *ctx = (SSL_CTX *) sslctx;
236
237   if(!SSL_CTX_use_certificate(ctx, p->usercert)) {
238     BIO_printf(p->errorbio, "SSL_CTX_use_certificate problem\n");
239     goto err;
240   }
241   if(!SSL_CTX_use_PrivateKey(ctx, p->pkey)) {
242     BIO_printf(p->errorbio, "SSL_CTX_use_PrivateKey\n");
243     goto err;
244   }
245
246   if(!SSL_CTX_check_private_key(ctx)) {
247     BIO_printf(p->errorbio, "SSL_CTX_check_private_key\n");
248     goto err;
249   }
250
251   SSL_CTX_set_quiet_shutdown(ctx, 1);
252   SSL_CTX_set_cipher_list(ctx, "RC4-MD5");
253   SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
254
255   X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx),
256                       sk_X509_value(p->ca, sk_X509_num(p->ca)-1));
257
258   SSL_CTX_set_verify_depth(ctx, 2);
259   SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, ZERO_NULL);
260   SSL_CTX_set_cert_verify_callback(ctx, ssl_app_verify_callback, parm);
261
262   return CURLE_OK;
263   err:
264   ERR_print_errors(p->errorbio);
265   return CURLE_SSL_CERTPROBLEM;
266
267 }
268
269 int main(int argc, char **argv)
270 {
271   BIO* in=NULL;
272   BIO* out=NULL;
273
274   char *outfile = NULL;
275   char *infile = NULL;
276
277   int tabLength=100;
278   char *binaryptr;
279   char *mimetype;
280   char *mimetypeaccept=NULL;
281   char *contenttype;
282   const char **pp;
283   unsigned char *hostporturl = NULL;
284   BIO *p12bio;
285   char **args = argv + 1;
286   unsigned char *serverurl;
287   sslctxparm p;
288   char *response;
289
290   CURLcode res;
291   struct curl_slist *headers=NULL;
292   int badarg=0;
293
294   binaryptr = malloc(tabLength);
295
296   p.verbose = 0;
297   p.errorbio = BIO_new_fp(stderr, BIO_NOCLOSE);
298
299   curl_global_init(CURL_GLOBAL_DEFAULT);
300
301   /* we need some more for the P12 decoding */
302
303   OpenSSL_add_all_ciphers();
304   OpenSSL_add_all_digests();
305   ERR_load_crypto_strings();
306
307   while(*args && *args[0] == '-') {
308     if(!strcmp (*args, "-in")) {
309       if(args[1]) {
310         infile=*(++args);
311       }
312       else
313         badarg=1;
314     }
315     else if(!strcmp (*args, "-out")) {
316       if(args[1]) {
317         outfile=*(++args);
318       }
319       else
320         badarg=1;
321     }
322     else if(!strcmp (*args, "-p12")) {
323       if(args[1]) {
324         p.p12file = *(++args);
325       }
326       else
327         badarg=1;
328     }
329     else if(strcmp(*args, "-envpass") == 0) {
330       if(args[1]) {
331         p.pst = getenv(*(++args));
332       }
333       else
334         badarg=1;
335     }
336     else if(strcmp(*args, "-connect") == 0) {
337       if(args[1]) {
338         hostporturl = *(++args);
339       }
340       else
341         badarg=1;
342     }
343     else if(strcmp(*args, "-mimetype") == 0) {
344       if(args[1]) {
345         mimetype = *(++args);
346       }
347       else
348         badarg=1;
349     }
350     else if(strcmp(*args, "-acceptmime") == 0) {
351       if(args[1]) {
352         mimetypeaccept = *(++args);
353       }
354       else
355         badarg=1;
356     }
357     else if(strcmp(*args, "-accesstype") == 0) {
358       if(args[1]) {
359         p.accesstype = OBJ_obj2nid(OBJ_txt2obj(*++args, 0));
360         if(p.accesstype == 0)
361           badarg=1;
362       }
363       else
364         badarg=1;
365     }
366     else if(strcmp(*args, "-verbose") == 0) {
367       p.verbose++;
368     }
369     else
370       badarg=1;
371     args++;
372   }
373
374   if(mimetype==NULL || mimetypeaccept == NULL)
375     badarg = 1;
376
377   if(badarg) {
378     for(pp=curlx_usage; (*pp != NULL); pp++)
379       BIO_printf(p.errorbio, "%s\n", *pp);
380     BIO_printf(p.errorbio, "\n");
381     goto err;
382   }
383
384   /* set input */
385
386   if((in=BIO_new(BIO_s_file())) == NULL) {
387     BIO_printf(p.errorbio, "Error setting input bio\n");
388     goto err;
389   }
390   else if(infile == NULL)
391     BIO_set_fp(in, stdin, BIO_NOCLOSE|BIO_FP_TEXT);
392   else if(BIO_read_filename(in, infile) <= 0) {
393     BIO_printf(p.errorbio, "Error opening input file %s\n", infile);
394     BIO_free(in);
395     goto err;
396   }
397
398   /* set output  */
399
400   if((out=BIO_new(BIO_s_file())) == NULL) {
401     BIO_printf(p.errorbio, "Error setting output bio.\n");
402     goto err;
403   }
404   else if(outfile == NULL)
405     BIO_set_fp(out, stdout, BIO_NOCLOSE|BIO_FP_TEXT);
406   else if(BIO_write_filename(out, outfile) <= 0) {
407     BIO_printf(p.errorbio, "Error opening output file %s\n", outfile);
408     BIO_free(out);
409     goto err;
410   }
411
412
413   p.errorbio = BIO_new_fp(stderr, BIO_NOCLOSE);
414
415   p.curl = curl_easy_init();
416   if(!p.curl) {
417     BIO_printf(p.errorbio, "Cannot init curl lib\n");
418     goto err;
419   }
420
421   p12bio = BIO_new_file(p.p12file, "rb");
422   if(!p12bio) {
423     BIO_printf(p.errorbio, "Error opening P12 file %s\n", p.p12file);
424     goto err;
425   }
426   p.p12 = d2i_PKCS12_bio(p12bio, NULL);
427   if(!p.p12) {
428     BIO_printf(p.errorbio, "Cannot decode P12 structure %s\n", p.p12file);
429     goto err;
430   }
431
432   p.ca= NULL;
433   if(!(PKCS12_parse (p.p12, p.pst, &(p.pkey), &(p.usercert), &(p.ca) ) )) {
434     BIO_printf(p.errorbio, "Invalid P12 structure in %s\n", p.p12file);
435     goto err;
436   }
437
438   if(sk_X509_num(p.ca) <= 0) {
439     BIO_printf(p.errorbio, "No trustworthy CA given.%s\n", p.p12file);
440     goto err;
441   }
442
443   if(p.verbose > 1)
444     X509_print_ex(p.errorbio, p.usercert, 0, 0);
445
446   /* determine URL to go */
447
448   if(hostporturl) {
449     size_t len = strlen(hostporturl) + 9;
450     serverurl = malloc(len);
451     snprintf(serverurl, len, "https://%s", hostporturl);
452   }
453   else if(p.accesstype != 0) { /* see whether we can find an AIA or SIA for a
454                                   given access type */
455     serverurl = my_get_ext(p.usercert, p.accesstype, NID_info_access);
456     if(!serverurl) {
457       int j=0;
458       BIO_printf(p.errorbio, "no service URL in user cert "
459                  "cherching in others certificats\n");
460       for(j=0; j<sk_X509_num(p.ca); j++) {
461         serverurl = my_get_ext(sk_X509_value(p.ca, j), p.accesstype,
462                                NID_info_access);
463         if(serverurl)
464           break;
465         serverurl = my_get_ext(sk_X509_value(p.ca, j), p.accesstype,
466                                NID_sinfo_access);
467         if(serverurl)
468           break;
469       }
470     }
471   }
472
473   if(!serverurl) {
474     BIO_printf(p.errorbio, "no service URL in certificats,"
475                " check '-accesstype (AD_DVCS | ad_timestamping)'"
476                " or use '-connect'\n");
477     goto err;
478   }
479
480   if(p.verbose)
481     BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl);
482
483   curl_easy_setopt(p.curl, CURLOPT_URL, serverurl);
484
485   /* Now specify the POST binary data */
486
487   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr);
488   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE, (long)tabLength);
489
490   /* pass our list of custom made headers */
491
492   contenttype = malloc(15+strlen(mimetype));
493   snprintf(contenttype, 15+strlen(mimetype), "Content-type: %s", mimetype);
494   headers = curl_slist_append(headers, contenttype);
495   curl_easy_setopt(p.curl, CURLOPT_HTTPHEADER, headers);
496
497   if(p.verbose)
498     BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl);
499
500   {
501     FILE *outfp;
502     BIO_get_fp(out, &outfp);
503     curl_easy_setopt(p.curl, CURLOPT_WRITEDATA, outfp);
504   }
505
506   res = curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun);
507
508   if(res != CURLE_OK)
509     BIO_printf(p.errorbio, "%d %s=%d %d\n", __LINE__,
510                "CURLOPT_SSL_CTX_FUNCTION", CURLOPT_SSL_CTX_FUNCTION, res);
511
512   curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_DATA, &p);
513
514   {
515     int lu; int i=0;
516     while((lu = BIO_read(in, &binaryptr[i], tabLength-i)) >0) {
517       i+=lu;
518       if(i== tabLength) {
519         tabLength+=100;
520         binaryptr=realloc(binaryptr, tabLength); /* should be more careful */
521       }
522     }
523     tabLength = i;
524   }
525   /* Now specify the POST binary data */
526
527   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr);
528   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE, (long)tabLength);
529
530
531   /* Perform the request, res will get the return code */
532
533   BIO_printf(p.errorbio, "%d %s %d\n", __LINE__, "curl_easy_perform",
534              res = curl_easy_perform(p.curl));
535   {
536     int result =curl_easy_getinfo(p.curl, CURLINFO_CONTENT_TYPE, &response);
537     if(mimetypeaccept && p.verbose)
538       if(!strcmp(mimetypeaccept, response))
539         BIO_printf(p.errorbio, "the response has a correct mimetype : %s\n",
540                    response);
541       else
542         BIO_printf(p.errorbio, "the response doesn\'t have an acceptable "
543                    "mime type, it is %s instead of %s\n",
544                    response, mimetypeaccept);
545   }
546
547   /*** code d'erreur si accept mime ***, egalement code return HTTP != 200 ***/
548
549 /* free the header list*/
550
551   curl_slist_free_all(headers);
552
553   /* always cleanup */
554   curl_easy_cleanup(p.curl);
555
556   BIO_free(in);
557   BIO_free(out);
558   return (EXIT_SUCCESS);
559
560   err: BIO_printf(p.errorbio, "error");
561   exit(1);
562 }