free cleanup 12
[openssl.git] / crypto / ocsp / ocsp_ht.c
1 /* ocsp_ht.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
4  * 2006.
5  */
6 /* ====================================================================
7  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <ctype.h>
63 #include <string.h>
64 #include "e_os.h"
65 #include <openssl/asn1.h>
66 #include <openssl/ocsp.h>
67 #include <openssl/err.h>
68 #include <openssl/buffer.h>
69
70 /* Stateful OCSP request code, supporting non-blocking I/O */
71
72 /* Opaque OCSP request status structure */
73
74 struct ocsp_req_ctx_st {
75     int state;                  /* Current I/O state */
76     unsigned char *iobuf;       /* Line buffer */
77     int iobuflen;               /* Line buffer length */
78     BIO *io;                    /* BIO to perform I/O with */
79     BIO *mem;                   /* Memory BIO response is built into */
80     unsigned long asn1_len;     /* ASN1 length of response */
81     unsigned long max_resp_len; /* Maximum length of response */
82 };
83
84 #define OCSP_MAX_RESP_LENGTH    (100 * 1024)
85 #define OCSP_MAX_LINE_LEN       4096;
86
87 /* OCSP states */
88
89 /* If set no reading should be performed */
90 #define OHS_NOREAD              0x1000
91 /* Error condition */
92 #define OHS_ERROR               (0 | OHS_NOREAD)
93 /* First line being read */
94 #define OHS_FIRSTLINE           1
95 /* MIME headers being read */
96 #define OHS_HEADERS             2
97 /* OCSP initial header (tag + length) being read */
98 #define OHS_ASN1_HEADER         3
99 /* OCSP content octets being read */
100 #define OHS_ASN1_CONTENT        4
101 /* First call: ready to start I/O */
102 #define OHS_ASN1_WRITE_INIT     (5 | OHS_NOREAD)
103 /* Request being sent */
104 #define OHS_ASN1_WRITE          (6 | OHS_NOREAD)
105 /* Request being flushed */
106 #define OHS_ASN1_FLUSH          (7 | OHS_NOREAD)
107 /* Completed */
108 #define OHS_DONE                (8 | OHS_NOREAD)
109 /* Headers set, no final \r\n included */
110 #define OHS_HTTP_HEADER         (9 | OHS_NOREAD)
111
112 static int parse_http_line1(char *line);
113
114 OCSP_REQ_CTX *OCSP_REQ_CTX_new(BIO *io, int maxline)
115 {
116     OCSP_REQ_CTX *rctx;
117     rctx = OPENSSL_malloc(sizeof(OCSP_REQ_CTX));
118     if (!rctx)
119         return NULL;
120     rctx->state = OHS_ERROR;
121     rctx->max_resp_len = OCSP_MAX_RESP_LENGTH;
122     rctx->mem = BIO_new(BIO_s_mem());
123     rctx->io = io;
124     rctx->asn1_len = 0;
125     if (maxline > 0)
126         rctx->iobuflen = maxline;
127     else
128         rctx->iobuflen = OCSP_MAX_LINE_LEN;
129     rctx->iobuf = OPENSSL_malloc(rctx->iobuflen);
130     if (!rctx->iobuf || !rctx->mem) {
131         OCSP_REQ_CTX_free(rctx);
132         return NULL;
133     }
134     return rctx;
135 }
136
137 void OCSP_REQ_CTX_free(OCSP_REQ_CTX *rctx)
138 {
139     if (!rctx)
140         return;
141     BIO_free(rctx->mem);
142     if (rctx->iobuf)
143         OPENSSL_free(rctx->iobuf);
144     OPENSSL_free(rctx);
145 }
146
147 BIO *OCSP_REQ_CTX_get0_mem_bio(OCSP_REQ_CTX *rctx)
148 {
149     return rctx->mem;
150 }
151
152 void OCSP_set_max_response_length(OCSP_REQ_CTX *rctx, unsigned long len)
153 {
154     if (len == 0)
155         rctx->max_resp_len = OCSP_MAX_RESP_LENGTH;
156     else
157         rctx->max_resp_len = len;
158 }
159
160 int OCSP_REQ_CTX_i2d(OCSP_REQ_CTX *rctx, const ASN1_ITEM *it, ASN1_VALUE *val)
161 {
162     static const char req_hdr[] =
163         "Content-Type: application/ocsp-request\r\n"
164         "Content-Length: %d\r\n\r\n";
165     int reqlen = ASN1_item_i2d(val, NULL, it);
166     if (BIO_printf(rctx->mem, req_hdr, reqlen) <= 0)
167         return 0;
168     if (ASN1_item_i2d_bio(it, rctx->mem, val) <= 0)
169         return 0;
170     rctx->state = OHS_ASN1_WRITE_INIT;
171     return 1;
172 }
173
174 int OCSP_REQ_CTX_nbio_d2i(OCSP_REQ_CTX *rctx,
175                           ASN1_VALUE **pval, const ASN1_ITEM *it)
176 {
177     int rv, len;
178     const unsigned char *p;
179
180     rv = OCSP_REQ_CTX_nbio(rctx);
181     if (rv != 1)
182         return rv;
183
184     len = BIO_get_mem_data(rctx->mem, &p);
185     *pval = ASN1_item_d2i(NULL, &p, len, it);
186     if (*pval == NULL) {
187         rctx->state = OHS_ERROR;
188         return 0;
189     }
190     return 1;
191 }
192
193 int OCSP_REQ_CTX_http(OCSP_REQ_CTX *rctx, const char *op, const char *path)
194 {
195     static const char http_hdr[] = "%s %s HTTP/1.0\r\n";
196
197     if (!path)
198         path = "/";
199
200     if (BIO_printf(rctx->mem, http_hdr, op, path) <= 0)
201         return 0;
202     rctx->state = OHS_HTTP_HEADER;
203     return 1;
204 }
205
206 int OCSP_REQ_CTX_set1_req(OCSP_REQ_CTX *rctx, OCSP_REQUEST *req)
207 {
208     return OCSP_REQ_CTX_i2d(rctx, ASN1_ITEM_rptr(OCSP_REQUEST),
209                             (ASN1_VALUE *)req);
210 }
211
212 int OCSP_REQ_CTX_add1_header(OCSP_REQ_CTX *rctx,
213                              const char *name, const char *value)
214 {
215     if (!name)
216         return 0;
217     if (BIO_puts(rctx->mem, name) <= 0)
218         return 0;
219     if (value) {
220         if (BIO_write(rctx->mem, ": ", 2) != 2)
221             return 0;
222         if (BIO_puts(rctx->mem, value) <= 0)
223             return 0;
224     }
225     if (BIO_write(rctx->mem, "\r\n", 2) != 2)
226         return 0;
227     rctx->state = OHS_HTTP_HEADER;
228     return 1;
229 }
230
231 OCSP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path, OCSP_REQUEST *req,
232                                int maxline)
233 {
234
235     OCSP_REQ_CTX *rctx = NULL;
236     rctx = OCSP_REQ_CTX_new(io, maxline);
237     if (!rctx)
238         return NULL;
239
240     if (!OCSP_REQ_CTX_http(rctx, "POST", path))
241         goto err;
242
243     if (req && !OCSP_REQ_CTX_set1_req(rctx, req))
244         goto err;
245
246     return rctx;
247
248  err:
249     OCSP_REQ_CTX_free(rctx);
250     return NULL;
251 }
252
253 /*
254  * Parse the HTTP response. This will look like this: "HTTP/1.0 200 OK". We
255  * need to obtain the numeric code and (optional) informational message.
256  */
257
258 static int parse_http_line1(char *line)
259 {
260     int retcode;
261     char *p, *q, *r;
262     /* Skip to first white space (passed protocol info) */
263
264     for (p = line; *p && !isspace((unsigned char)*p); p++)
265         continue;
266     if (!*p) {
267         OCSPerr(OCSP_F_PARSE_HTTP_LINE1, OCSP_R_SERVER_RESPONSE_PARSE_ERROR);
268         return 0;
269     }
270
271     /* Skip past white space to start of response code */
272     while (*p && isspace((unsigned char)*p))
273         p++;
274
275     if (!*p) {
276         OCSPerr(OCSP_F_PARSE_HTTP_LINE1, OCSP_R_SERVER_RESPONSE_PARSE_ERROR);
277         return 0;
278     }
279
280     /* Find end of response code: first whitespace after start of code */
281     for (q = p; *q && !isspace((unsigned char)*q); q++)
282         continue;
283
284     if (!*q) {
285         OCSPerr(OCSP_F_PARSE_HTTP_LINE1, OCSP_R_SERVER_RESPONSE_PARSE_ERROR);
286         return 0;
287     }
288
289     /* Set end of response code and start of message */
290     *q++ = 0;
291
292     /* Attempt to parse numeric code */
293     retcode = strtoul(p, &r, 10);
294
295     if (*r)
296         return 0;
297
298     /* Skip over any leading white space in message */
299     while (*q && isspace((unsigned char)*q))
300         q++;
301
302     if (*q) {
303         /*
304          * Finally zap any trailing white space in message (include CRLF)
305          */
306
307         /* We know q has a non white space character so this is OK */
308         for (r = q + strlen(q) - 1; isspace((unsigned char)*r); r--)
309             *r = 0;
310     }
311     if (retcode != 200) {
312         OCSPerr(OCSP_F_PARSE_HTTP_LINE1, OCSP_R_SERVER_RESPONSE_ERROR);
313         if (!*q)
314             ERR_add_error_data(2, "Code=", p);
315         else
316             ERR_add_error_data(4, "Code=", p, ",Reason=", q);
317         return 0;
318     }
319
320     return 1;
321
322 }
323
324 int OCSP_REQ_CTX_nbio(OCSP_REQ_CTX *rctx)
325 {
326     int i, n;
327     const unsigned char *p;
328  next_io:
329     if (!(rctx->state & OHS_NOREAD)) {
330         n = BIO_read(rctx->io, rctx->iobuf, rctx->iobuflen);
331
332         if (n <= 0) {
333             if (BIO_should_retry(rctx->io))
334                 return -1;
335             return 0;
336         }
337
338         /* Write data to memory BIO */
339
340         if (BIO_write(rctx->mem, rctx->iobuf, n) != n)
341             return 0;
342     }
343
344     switch (rctx->state) {
345     case OHS_HTTP_HEADER:
346         /* Last operation was adding headers: need a final \r\n */
347         if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
348             rctx->state = OHS_ERROR;
349             return 0;
350         }
351         rctx->state = OHS_ASN1_WRITE_INIT;
352
353     case OHS_ASN1_WRITE_INIT:
354         rctx->asn1_len = BIO_get_mem_data(rctx->mem, NULL);
355         rctx->state = OHS_ASN1_WRITE;
356
357     case OHS_ASN1_WRITE:
358         n = BIO_get_mem_data(rctx->mem, &p);
359
360         i = BIO_write(rctx->io, p + (n - rctx->asn1_len), rctx->asn1_len);
361
362         if (i <= 0) {
363             if (BIO_should_retry(rctx->io))
364                 return -1;
365             rctx->state = OHS_ERROR;
366             return 0;
367         }
368
369         rctx->asn1_len -= i;
370
371         if (rctx->asn1_len > 0)
372             goto next_io;
373
374         rctx->state = OHS_ASN1_FLUSH;
375
376         (void)BIO_reset(rctx->mem);
377
378     case OHS_ASN1_FLUSH:
379
380         i = BIO_flush(rctx->io);
381
382         if (i > 0) {
383             rctx->state = OHS_FIRSTLINE;
384             goto next_io;
385         }
386
387         if (BIO_should_retry(rctx->io))
388             return -1;
389
390         rctx->state = OHS_ERROR;
391         return 0;
392
393     case OHS_ERROR:
394         return 0;
395
396     case OHS_FIRSTLINE:
397     case OHS_HEADERS:
398
399         /* Attempt to read a line in */
400
401  next_line:
402         /*
403          * Due to &%^*$" memory BIO behaviour with BIO_gets we have to check
404          * there's a complete line in there before calling BIO_gets or we'll
405          * just get a partial read.
406          */
407         n = BIO_get_mem_data(rctx->mem, &p);
408         if ((n <= 0) || !memchr(p, '\n', n)) {
409             if (n >= rctx->iobuflen) {
410                 rctx->state = OHS_ERROR;
411                 return 0;
412             }
413             goto next_io;
414         }
415         n = BIO_gets(rctx->mem, (char *)rctx->iobuf, rctx->iobuflen);
416
417         if (n <= 0) {
418             if (BIO_should_retry(rctx->mem))
419                 goto next_io;
420             rctx->state = OHS_ERROR;
421             return 0;
422         }
423
424         /* Don't allow excessive lines */
425         if (n == rctx->iobuflen) {
426             rctx->state = OHS_ERROR;
427             return 0;
428         }
429
430         /* First line */
431         if (rctx->state == OHS_FIRSTLINE) {
432             if (parse_http_line1((char *)rctx->iobuf)) {
433                 rctx->state = OHS_HEADERS;
434                 goto next_line;
435             } else {
436                 rctx->state = OHS_ERROR;
437                 return 0;
438             }
439         } else {
440             /* Look for blank line: end of headers */
441             for (p = rctx->iobuf; *p; p++) {
442                 if ((*p != '\r') && (*p != '\n'))
443                     break;
444             }
445             if (*p)
446                 goto next_line;
447
448             rctx->state = OHS_ASN1_HEADER;
449
450         }
451
452         /* Fall thru */
453
454     case OHS_ASN1_HEADER:
455         /*
456          * Now reading ASN1 header: can read at least 2 bytes which is enough
457          * for ASN1 SEQUENCE header and either length field or at least the
458          * length of the length field.
459          */
460         n = BIO_get_mem_data(rctx->mem, &p);
461         if (n < 2)
462             goto next_io;
463
464         /* Check it is an ASN1 SEQUENCE */
465         if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
466             rctx->state = OHS_ERROR;
467             return 0;
468         }
469
470         /* Check out length field */
471         if (*p & 0x80) {
472             /*
473              * If MSB set on initial length octet we can now always read 6
474              * octets: make sure we have them.
475              */
476             if (n < 6)
477                 goto next_io;
478             n = *p & 0x7F;
479             /* Not NDEF or excessive length */
480             if (!n || (n > 4)) {
481                 rctx->state = OHS_ERROR;
482                 return 0;
483             }
484             p++;
485             rctx->asn1_len = 0;
486             for (i = 0; i < n; i++) {
487                 rctx->asn1_len <<= 8;
488                 rctx->asn1_len |= *p++;
489             }
490
491             if (rctx->asn1_len > rctx->max_resp_len) {
492                 rctx->state = OHS_ERROR;
493                 return 0;
494             }
495
496             rctx->asn1_len += n + 2;
497         } else
498             rctx->asn1_len = *p + 2;
499
500         rctx->state = OHS_ASN1_CONTENT;
501
502         /* Fall thru */
503
504     case OHS_ASN1_CONTENT:
505         n = BIO_get_mem_data(rctx->mem, NULL);
506         if (n < (int)rctx->asn1_len)
507             goto next_io;
508
509         rctx->state = OHS_DONE;
510         return 1;
511
512     case OHS_DONE:
513         return 1;
514
515     }
516
517     return 0;
518
519 }
520
521 int OCSP_sendreq_nbio(OCSP_RESPONSE **presp, OCSP_REQ_CTX *rctx)
522 {
523     return OCSP_REQ_CTX_nbio_d2i(rctx,
524                                  (ASN1_VALUE **)presp,
525                                  ASN1_ITEM_rptr(OCSP_RESPONSE));
526 }
527
528 /* Blocking OCSP request handler: now a special case of non-blocking I/O */
529
530 OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req)
531 {
532     OCSP_RESPONSE *resp = NULL;
533     OCSP_REQ_CTX *ctx;
534     int rv;
535
536     ctx = OCSP_sendreq_new(b, path, req, -1);
537
538     if (!ctx)
539         return NULL;
540
541     do {
542         rv = OCSP_sendreq_nbio(&resp, ctx);
543     } while ((rv == -1) && BIO_should_retry(b));
544
545     OCSP_REQ_CTX_free(ctx);
546
547     if (rv)
548         return resp;
549
550     return NULL;
551 }