9bfb0cbd82f0908f9325377f533f2e12aeb1b414
[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 (http://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 (http://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 (http://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 key password",
105   " -out arg         - output file (response)- default stdout",
106   " -in arg          - input file (request)- default stdin",
107   " -connect arg     - URL of the server for the connection ex: www.openevidence.org",
108   " -mimetype arg    - MIME type for data in ex : application/timestamp-query or application/dvcs -default application/timestamp-query",
109   " -acceptmime arg  - MIME type acceptable for the response ex : application/timestamp-response or application/dvcs -default none",
110   " -accesstype arg  - an Object identifier in an AIA/SIA method, e.g. AD_DVCS or ad_timestamping",
111   NULL
112 };
113
114 /*
115
116 ./curlx -p12 psy.p12 -envpass XX -in request -verbose -accesstype AD_DVCS
117 -mimetype application/dvcs -acceptmime application/dvcs -out response
118
119 */
120
121 /*
122  * We use this ZERO_NULL to avoid picky compiler warnings,
123  * when assigning a NULL pointer to a function pointer var.
124  */
125
126 #define ZERO_NULL 0
127
128 /* This is a context that we pass to all callbacks */
129
130 typedef struct sslctxparm_st {
131   unsigned char * p12file ;
132   const char * pst ;
133   PKCS12 * p12 ;
134   EVP_PKEY * pkey ;
135   X509 * usercert ;
136   STACK_OF(X509) * ca ;
137   CURL * curl;
138   BIO * errorbio;
139   int accesstype ;
140   int verbose;
141
142 } sslctxparm;
143
144 /* some helper function. */
145
146 static char *i2s_ASN1_IA5STRING( ASN1_IA5STRING *ia5)
147 {
148   char *tmp;
149   if(!ia5 || !ia5->length)
150     return NULL;
151   tmp = OPENSSL_malloc(ia5->length + 1);
152   memcpy(tmp, ia5->data, ia5->length);
153   tmp[ia5->length] = 0;
154   return tmp;
155 }
156
157 /* A conveniance routine to get an access URI. */
158
159 static unsigned char *my_get_ext(X509 * cert, const int type, int extensiontype) {
160
161   int i;
162   STACK_OF(ACCESS_DESCRIPTION) * accessinfo ;
163   accessinfo =  X509_get_ext_d2i(cert, extensiontype, NULL, NULL) ;
164
165   if (!sk_ACCESS_DESCRIPTION_num(accessinfo))
166     return NULL;
167   for (i = 0; i < sk_ACCESS_DESCRIPTION_num(accessinfo); i++) {
168     ACCESS_DESCRIPTION * ad = sk_ACCESS_DESCRIPTION_value(accessinfo, i);
169     if (OBJ_obj2nid(ad->method) == type) {
170       if (ad->location->type == GEN_URI) {
171         return i2s_ASN1_IA5STRING(ad->location->d.ia5);
172       }
173       return NULL;
174     }
175   }
176   return NULL;
177 }
178
179 /* This is an application verification call back, it does not
180    perform any addition verification but tries to find a URL
181    in the presented certificat. If found, this will become
182    the URL to be used in the POST.
183 */
184
185 static int ssl_app_verify_callback(X509_STORE_CTX *ctx, void *arg)
186 {
187   sslctxparm * p = (sslctxparm *) arg;
188   int ok;
189
190   if (p->verbose > 2)
191     BIO_printf(p->errorbio,"entering ssl_app_verify_callback\n");
192
193   if ((ok= X509_verify_cert(ctx)) && ctx->cert) {
194     unsigned char * accessinfo ;
195     if (p->verbose > 1)
196       X509_print_ex(p->errorbio,ctx->cert,0,0);
197
198     if (accessinfo = my_get_ext(ctx->cert,p->accesstype ,NID_sinfo_access)) {
199       if (p->verbose)
200         BIO_printf(p->errorbio,"Setting URL from SIA to: %s\n", accessinfo);
201
202       curl_easy_setopt(p->curl, CURLOPT_URL,accessinfo);
203     }
204     else if (accessinfo = my_get_ext(ctx->cert,p->accesstype,
205                                      NID_info_access)) {
206       if (p->verbose)
207         BIO_printf(p->errorbio,"Setting URL from AIA to: %s\n", accessinfo);
208
209       curl_easy_setopt(p->curl, CURLOPT_URL,accessinfo);
210     }
211   }
212   if (p->verbose > 2)
213     BIO_printf(p->errorbio,"leaving ssl_app_verify_callback with %d\n", ok);
214   return(ok);
215 }
216
217
218 /* This is an example of an curl SSL initialisation call back. The callback sets:
219    - a private key and certificate
220    - a trusted ca certificate
221    - a preferred cipherlist
222    - an application verification callback (the function above)
223 */
224
225 static CURLcode sslctxfun(CURL * curl, void * sslctx, void * parm) {
226
227   sslctxparm * p = (sslctxparm *) parm;
228   SSL_CTX * ctx = (SSL_CTX *) sslctx ;
229
230   if (!SSL_CTX_use_certificate(ctx,p->usercert)) {
231     BIO_printf(p->errorbio, "SSL_CTX_use_certificate problem\n"); goto err;
232   }
233   if (!SSL_CTX_use_PrivateKey(ctx,p->pkey)) {
234     BIO_printf(p->errorbio, "SSL_CTX_use_PrivateKey\n"); goto err;
235   }
236
237   if (!SSL_CTX_check_private_key(ctx)) {
238     BIO_printf(p->errorbio, "SSL_CTX_check_private_key\n"); goto err;
239   }
240
241   SSL_CTX_set_quiet_shutdown(ctx,1);
242   SSL_CTX_set_cipher_list(ctx,"RC4-MD5");
243   SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
244
245   X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), sk_X509_value(p->ca, sk_X509_num(p->ca)-1));
246
247   SSL_CTX_set_verify_depth(ctx,2);
248
249   SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,ZERO_NULL);
250
251   SSL_CTX_set_cert_verify_callback(ctx, ssl_app_verify_callback, parm);
252
253
254   return CURLE_OK ;
255   err:
256   ERR_print_errors(p->errorbio);
257   return CURLE_SSL_CERTPROBLEM;
258
259 }
260
261 int main(int argc, char **argv) {
262
263   BIO* in=NULL;
264   BIO* out=NULL;
265
266   char * outfile = NULL;
267   char * infile = NULL ;
268
269   int tabLength=100;
270   char *binaryptr;
271   char* mimetype;
272   char* mimetypeaccept=NULL;
273   char* contenttype;
274   const char** pp;
275   unsigned char* hostporturl = NULL;
276   BIO * p12bio ;
277   char **args = argv + 1;
278   unsigned char * serverurl;
279   sslctxparm p;
280   char *response;
281
282   CURLcode res;
283   struct curl_slist * headers=NULL;
284   int badarg=0;
285
286   binaryptr = malloc(tabLength);
287
288   p.verbose = 0;
289   p.errorbio = BIO_new_fp (stderr, BIO_NOCLOSE);
290
291   curl_global_init(CURL_GLOBAL_DEFAULT);
292
293   /* we need some more for the P12 decoding */
294
295   OpenSSL_add_all_ciphers();
296   OpenSSL_add_all_digests();
297   ERR_load_crypto_strings();
298
299
300
301   while (*args && *args[0] == '-') {
302     if (!strcmp (*args, "-in")) {
303       if (args[1]) {
304         infile=*(++args);
305       } else badarg=1;
306     } else if (!strcmp (*args, "-out")) {
307       if (args[1]) {
308         outfile=*(++args);
309       } else badarg=1;
310     } else if (!strcmp (*args, "-p12")) {
311       if (args[1]) {
312         p.p12file = *(++args);
313       } else badarg=1;
314     } else if (strcmp(*args,"-envpass") == 0) {
315       if (args[1]) {
316         p.pst = getenv(*(++args));
317       } else badarg=1;
318     } else if (strcmp(*args,"-connect") == 0) {
319       if (args[1]) {
320         hostporturl = *(++args);
321       } else badarg=1;
322     } else if (strcmp(*args,"-mimetype") == 0) {
323       if (args[1]) {
324         mimetype = *(++args);
325       } else badarg=1;
326     } else if (strcmp(*args,"-acceptmime") == 0) {
327       if (args[1]) {
328         mimetypeaccept = *(++args);
329       } else badarg=1;
330     } else if (strcmp(*args,"-accesstype") == 0) {
331       if (args[1]) {
332         if ((p.accesstype = OBJ_obj2nid(OBJ_txt2obj(*++args,0))) == 0) badarg=1;
333       } else badarg=1;
334     } else if (strcmp(*args,"-verbose") == 0) {
335       p.verbose++;
336     } else badarg=1;
337     args++;
338   }
339
340   if (mimetype==NULL || mimetypeaccept == NULL) badarg = 1;
341
342   if (badarg) {
343     for (pp=curlx_usage; (*pp != NULL); pp++)
344       BIO_printf(p.errorbio,"%s\n",*pp);
345     BIO_printf(p.errorbio,"\n");
346     goto err;
347   }
348
349
350
351   /* set input */
352
353   if ((in=BIO_new(BIO_s_file())) == NULL) {
354     BIO_printf(p.errorbio, "Error setting input bio\n");
355     goto err;
356   } else if (infile == NULL)
357     BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT);
358   else if (BIO_read_filename(in,infile) <= 0) {
359     BIO_printf(p.errorbio, "Error opening input file %s\n", infile);
360     BIO_free(in);
361     goto err;
362   }
363
364   /* set output  */
365
366   if ((out=BIO_new(BIO_s_file())) == NULL) {
367     BIO_printf(p.errorbio, "Error setting output bio.\n");
368     goto err;
369   } else if (outfile == NULL)
370     BIO_set_fp(out,stdout,BIO_NOCLOSE|BIO_FP_TEXT);
371   else if (BIO_write_filename(out,outfile) <= 0) {
372     BIO_printf(p.errorbio, "Error opening output file %s\n", outfile);
373     BIO_free(out);
374     goto err;
375   }
376
377
378   p.errorbio = BIO_new_fp (stderr, BIO_NOCLOSE);
379
380   if (!(p.curl = curl_easy_init())) {
381     BIO_printf(p.errorbio, "Cannot init curl lib\n");
382     goto err;
383   }
384
385
386
387   if (!(p12bio = BIO_new_file(p.p12file , "rb"))) {
388     BIO_printf(p.errorbio, "Error opening P12 file %s\n", p.p12file); goto err;
389   }
390   if (!(p.p12 = d2i_PKCS12_bio (p12bio, NULL))) {
391     BIO_printf(p.errorbio, "Cannot decode P12 structure %s\n", p.p12file); goto err;
392   }
393
394   p.ca= NULL;
395   if (!(PKCS12_parse (p.p12, p.pst, &(p.pkey), &(p.usercert), &(p.ca) ) )) {
396     BIO_printf(p.errorbio,"Invalid P12 structure in %s\n", p.p12file); goto err;
397   }
398
399   if (sk_X509_num(p.ca) <= 0) {
400     BIO_printf(p.errorbio,"No trustworthy CA given.%s\n", p.p12file); goto err;
401   }
402
403   if (p.verbose > 1)
404     X509_print_ex(p.errorbio,p.usercert,0,0);
405
406   /* determine URL to go */
407
408   if (hostporturl) {
409     serverurl = malloc(9+strlen(hostporturl));
410     sprintf(serverurl,"https://%s",hostporturl);
411   }
412   else if (p.accesstype != 0) { /* see whether we can find an AIA or SIA for a given access type */
413     if (!(serverurl = my_get_ext(p.usercert,p.accesstype,NID_info_access))) {
414       int j=0;
415       BIO_printf(p.errorbio,"no service URL in user cert "
416                  "cherching in others certificats\n");
417       for (j=0;j<sk_X509_num(p.ca);j++) {
418         if ((serverurl = my_get_ext(sk_X509_value(p.ca,j),p.accesstype,
419                                     NID_info_access)))
420           break;
421         if ((serverurl = my_get_ext(sk_X509_value(p.ca,j),p.accesstype,
422                                     NID_sinfo_access)))
423           break;
424       }
425     }
426   }
427
428   if (!serverurl) {
429     BIO_printf(p.errorbio, "no service URL in certificats,"
430                " check '-accesstype (AD_DVCS | ad_timestamping)'"
431                " or use '-connect'\n");
432     goto err;
433   }
434
435   if (p.verbose)
436     BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl);
437
438   curl_easy_setopt(p.curl, CURLOPT_URL, serverurl);
439
440   /* Now specify the POST binary data */
441
442   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr);
443   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE,(long)tabLength);
444
445   /* pass our list of custom made headers */
446
447   contenttype = malloc(15+strlen(mimetype));
448   sprintf(contenttype,"Content-type: %s",mimetype);
449   headers = curl_slist_append(headers,contenttype);
450   curl_easy_setopt(p.curl, CURLOPT_HTTPHEADER, headers);
451
452   if (p.verbose)
453     BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl);
454
455   {
456     FILE *outfp;
457     BIO_get_fp(out,&outfp);
458     curl_easy_setopt(p.curl, CURLOPT_WRITEDATA, outfp);
459   }
460
461   res = curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun)  ;
462
463   if (res != CURLE_OK)
464     BIO_printf(p.errorbio,"%d %s=%d %d\n", __LINE__, "CURLOPT_SSL_CTX_FUNCTION",CURLOPT_SSL_CTX_FUNCTION,res);
465
466   curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_DATA, &p);
467
468   {
469     int lu; int i=0;
470     while ((lu = BIO_read (in,&binaryptr[i],tabLength-i)) >0 ) {
471       i+=lu;
472       if (i== tabLength) {
473         tabLength+=100;
474         binaryptr=realloc(binaryptr,tabLength); /* should be more careful */
475       }
476     }
477     tabLength = i;
478   }
479   /* Now specify the POST binary data */
480
481   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr);
482   curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE,(long)tabLength);
483
484
485   /* Perform the request, res will get the return code */
486
487   BIO_printf(p.errorbio,"%d %s %d\n", __LINE__, "curl_easy_perform",
488              res = curl_easy_perform(p.curl));
489   {
490     int result =curl_easy_getinfo(p.curl,CURLINFO_CONTENT_TYPE,&response);
491     if( mimetypeaccept && p.verbose)
492       if(!strcmp(mimetypeaccept,response))
493         BIO_printf(p.errorbio,"the response has a correct mimetype : %s\n",
494                    response);
495       else
496         BIO_printf(p.errorbio,"the response doesn\'t have an acceptable "
497                    "mime type, it is %s instead of %s\n",
498                    response,mimetypeaccept);
499   }
500
501   /*** code d'erreur si accept mime ***, egalement code return HTTP != 200 ***/
502
503 /* free the header list*/
504
505   curl_slist_free_all(headers);
506
507   /* always cleanup */
508   curl_easy_cleanup(p.curl);
509
510   BIO_free(in);
511   BIO_free(out);
512   return (EXIT_SUCCESS);
513
514   err: BIO_printf(p.errorbio,"error");
515   exit(1);
516 }