Accessor update; fix API, document one.
[openssl.git] / crypto / ocsp / ocsp_cl.c
1 /* ocsp_cl.c */
2 /*
3  * Written by Tom Titchener <Tom_Titchener@groove.net> for the OpenSSL
4  * project.
5  */
6
7 /*
8  * History: This file was transfered to Richard Levitte from CertCo by Kathy
9  * Weinhold in mid-spring 2000 to be included in OpenSSL or released as a
10  * patch kit.
11  */
12
13 /* ====================================================================
14  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  *
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  *
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in
25  *    the documentation and/or other materials provided with the
26  *    distribution.
27  *
28  * 3. All advertising materials mentioning features or use of this
29  *    software must display the following acknowledgment:
30  *    "This product includes software developed by the OpenSSL Project
31  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
32  *
33  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
34  *    endorse or promote products derived from this software without
35  *    prior written permission. For written permission, please contact
36  *    openssl-core@openssl.org.
37  *
38  * 5. Products derived from this software may not be called "OpenSSL"
39  *    nor may "OpenSSL" appear in their names without prior written
40  *    permission of the OpenSSL Project.
41  *
42  * 6. Redistributions of any form whatsoever must retain the following
43  *    acknowledgment:
44  *    "This product includes software developed by the OpenSSL Project
45  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
48  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
50  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
51  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
52  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
53  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
54  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
56  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
57  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
58  * OF THE POSSIBILITY OF SUCH DAMAGE.
59  * ====================================================================
60  *
61  * This product includes cryptographic software written by Eric Young
62  * (eay@cryptsoft.com).  This product includes software written by Tim
63  * Hudson (tjh@cryptsoft.com).
64  *
65  */
66
67 #include <stdio.h>
68 #include <time.h>
69 #include "internal/cryptlib.h"
70 #include <openssl/objects.h>
71 #include <openssl/rand.h>
72 #include <openssl/x509.h>
73 #include <openssl/pem.h>
74 #include <openssl/x509v3.h>
75 #include <openssl/ocsp.h>
76 #include "ocsp_lcl.h"
77
78 /*
79  * Utility functions related to sending OCSP requests and extracting relevant
80  * information from the response.
81  */
82
83 /*
84  * Add an OCSP_CERTID to an OCSP request. Return new OCSP_ONEREQ pointer:
85  * useful if we want to add extensions.
86  */
87
88 OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid)
89 {
90     OCSP_ONEREQ *one = NULL;
91
92     if ((one = OCSP_ONEREQ_new()) == NULL)
93         goto err;
94     OCSP_CERTID_free(one->reqCert);
95     one->reqCert = cid;
96     if (req && !sk_OCSP_ONEREQ_push(req->tbsRequest.requestList, one))
97         goto err;
98     return one;
99  err:
100     OCSP_ONEREQ_free(one);
101     return NULL;
102 }
103
104 /* Set requestorName from an X509_NAME structure */
105
106 int OCSP_request_set1_name(OCSP_REQUEST *req, X509_NAME *nm)
107 {
108     GENERAL_NAME *gen;
109
110     gen = GENERAL_NAME_new();
111     if (gen == NULL)
112         return 0;
113     if (!X509_NAME_set(&gen->d.directoryName, nm)) {
114         GENERAL_NAME_free(gen);
115         return 0;
116     }
117     gen->type = GEN_DIRNAME;
118     GENERAL_NAME_free(req->tbsRequest.requestorName);
119     req->tbsRequest.requestorName = gen;
120     return 1;
121 }
122
123 /* Add a certificate to an OCSP request */
124
125 int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert)
126 {
127     OCSP_SIGNATURE *sig;
128     if (req->optionalSignature == NULL)
129         req->optionalSignature = OCSP_SIGNATURE_new();
130     sig = req->optionalSignature;
131     if (sig == NULL)
132         return 0;
133     if (cert == NULL)
134         return 1;
135     if (sig->certs == NULL
136         && (sig->certs = sk_X509_new_null()) == NULL)
137         return 0;
138
139     if (!sk_X509_push(sig->certs, cert))
140         return 0;
141     X509_up_ref(cert);
142     return 1;
143 }
144
145 /*
146  * Sign an OCSP request set the requestorName to the subjec name of an
147  * optional signers certificate and include one or more optional certificates
148  * in the request. Behaves like PKCS7_sign().
149  */
150
151 int OCSP_request_sign(OCSP_REQUEST *req,
152                       X509 *signer,
153                       EVP_PKEY *key,
154                       const EVP_MD *dgst,
155                       STACK_OF(X509) *certs, unsigned long flags)
156 {
157     int i;
158     X509 *x;
159
160     if (!OCSP_request_set1_name(req, X509_get_subject_name(signer)))
161         goto err;
162
163     if ((req->optionalSignature = OCSP_SIGNATURE_new()) == NULL)
164         goto err;
165     if (key) {
166         if (!X509_check_private_key(signer, key)) {
167             OCSPerr(OCSP_F_OCSP_REQUEST_SIGN,
168                     OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
169             goto err;
170         }
171         if (!OCSP_REQUEST_sign(req, key, dgst))
172             goto err;
173     }
174
175     if (!(flags & OCSP_NOCERTS)) {
176         if (!OCSP_request_add1_cert(req, signer))
177             goto err;
178         for (i = 0; i < sk_X509_num(certs); i++) {
179             x = sk_X509_value(certs, i);
180             if (!OCSP_request_add1_cert(req, x))
181                 goto err;
182         }
183     }
184
185     return 1;
186  err:
187     OCSP_SIGNATURE_free(req->optionalSignature);
188     req->optionalSignature = NULL;
189     return 0;
190 }
191
192 /* Get response status */
193
194 int OCSP_response_status(OCSP_RESPONSE *resp)
195 {
196     return ASN1_ENUMERATED_get(resp->responseStatus);
197 }
198
199 /*
200  * Extract basic response from OCSP_RESPONSE or NULL if no basic response
201  * present.
202  */
203
204 OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp)
205 {
206     OCSP_RESPBYTES *rb;
207     rb = resp->responseBytes;
208     if (!rb) {
209         OCSPerr(OCSP_F_OCSP_RESPONSE_GET1_BASIC, OCSP_R_NO_RESPONSE_DATA);
210         return NULL;
211     }
212     if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) {
213         OCSPerr(OCSP_F_OCSP_RESPONSE_GET1_BASIC, OCSP_R_NOT_BASIC_RESPONSE);
214         return NULL;
215     }
216
217     return ASN1_item_unpack(rb->response, ASN1_ITEM_rptr(OCSP_BASICRESP));
218 }
219
220 ASN1_OCTET_STRING *OCSP_resp_get0_signature(OCSP_BASICRESP *bs)
221 {
222     return bs->signature;
223 }
224
225 /*
226  * Return number of OCSP_SINGLERESP reponses present in a basic response.
227  */
228
229 int OCSP_resp_count(OCSP_BASICRESP *bs)
230 {
231     if (!bs)
232         return -1;
233     return sk_OCSP_SINGLERESP_num(bs->tbsResponseData.responses);
234 }
235
236 /* Extract an OCSP_SINGLERESP response with a given index */
237
238 OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx)
239 {
240     if (!bs)
241         return NULL;
242     return sk_OCSP_SINGLERESP_value(bs->tbsResponseData.responses, idx);
243 }
244
245 ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(OCSP_BASICRESP* bs)
246 {
247     if (!bs)
248         return NULL;
249     return bs->tbsResponseData.producedAt;
250 }
251
252 /* Look single response matching a given certificate ID */
253
254 int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last)
255 {
256     int i;
257     STACK_OF(OCSP_SINGLERESP) *sresp;
258     OCSP_SINGLERESP *single;
259     if (!bs)
260         return -1;
261     if (last < 0)
262         last = 0;
263     else
264         last++;
265     sresp = bs->tbsResponseData.responses;
266     for (i = last; i < sk_OCSP_SINGLERESP_num(sresp); i++) {
267         single = sk_OCSP_SINGLERESP_value(sresp, i);
268         if (!OCSP_id_cmp(id, single->certId))
269             return i;
270     }
271     return -1;
272 }
273
274 /*
275  * Extract status information from an OCSP_SINGLERESP structure. Note: the
276  * revtime and reason values are only set if the certificate status is
277  * revoked. Returns numerical value of status.
278  */
279
280 int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason,
281                             ASN1_GENERALIZEDTIME **revtime,
282                             ASN1_GENERALIZEDTIME **thisupd,
283                             ASN1_GENERALIZEDTIME **nextupd)
284 {
285     int ret;
286     OCSP_CERTSTATUS *cst;
287     if (!single)
288         return -1;
289     cst = single->certStatus;
290     ret = cst->type;
291     if (ret == V_OCSP_CERTSTATUS_REVOKED) {
292         OCSP_REVOKEDINFO *rev = cst->value.revoked;
293         if (revtime)
294             *revtime = rev->revocationTime;
295         if (reason) {
296             if (rev->revocationReason)
297                 *reason = ASN1_ENUMERATED_get(rev->revocationReason);
298             else
299                 *reason = -1;
300         }
301     }
302     if (thisupd)
303         *thisupd = single->thisUpdate;
304     if (nextupd)
305         *nextupd = single->nextUpdate;
306     return ret;
307 }
308
309 /*
310  * This function combines the previous ones: look up a certificate ID and if
311  * found extract status information. Return 0 is successful.
312  */
313
314 int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status,
315                           int *reason,
316                           ASN1_GENERALIZEDTIME **revtime,
317                           ASN1_GENERALIZEDTIME **thisupd,
318                           ASN1_GENERALIZEDTIME **nextupd)
319 {
320     int i;
321     OCSP_SINGLERESP *single;
322     i = OCSP_resp_find(bs, id, -1);
323     /* Maybe check for multiple responses and give an error? */
324     if (i < 0)
325         return 0;
326     single = OCSP_resp_get0(bs, i);
327     i = OCSP_single_get0_status(single, reason, revtime, thisupd, nextupd);
328     if (status)
329         *status = i;
330     return 1;
331 }
332
333 /*
334  * Check validity of thisUpdate and nextUpdate fields. It is possible that
335  * the request will take a few seconds to process and/or the time wont be
336  * totally accurate. Therefore to avoid rejecting otherwise valid time we
337  * allow the times to be within 'nsec' of the current time. Also to avoid
338  * accepting very old responses without a nextUpdate field an optional maxage
339  * parameter specifies the maximum age the thisUpdate field can be.
340  */
341
342 int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd,
343                         ASN1_GENERALIZEDTIME *nextupd, long nsec, long maxsec)
344 {
345     int ret = 1;
346     time_t t_now, t_tmp;
347     time(&t_now);
348     /* Check thisUpdate is valid and not more than nsec in the future */
349     if (!ASN1_GENERALIZEDTIME_check(thisupd)) {
350         OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_ERROR_IN_THISUPDATE_FIELD);
351         ret = 0;
352     } else {
353         t_tmp = t_now + nsec;
354         if (X509_cmp_time(thisupd, &t_tmp) > 0) {
355             OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_NOT_YET_VALID);
356             ret = 0;
357         }
358
359         /*
360          * If maxsec specified check thisUpdate is not more than maxsec in
361          * the past
362          */
363         if (maxsec >= 0) {
364             t_tmp = t_now - maxsec;
365             if (X509_cmp_time(thisupd, &t_tmp) < 0) {
366                 OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_TOO_OLD);
367                 ret = 0;
368             }
369         }
370     }
371
372     if (!nextupd)
373         return ret;
374
375     /* Check nextUpdate is valid and not more than nsec in the past */
376     if (!ASN1_GENERALIZEDTIME_check(nextupd)) {
377         OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD);
378         ret = 0;
379     } else {
380         t_tmp = t_now - nsec;
381         if (X509_cmp_time(nextupd, &t_tmp) < 0) {
382             OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_EXPIRED);
383             ret = 0;
384         }
385     }
386
387     /* Also don't allow nextUpdate to precede thisUpdate */
388     if (ASN1_STRING_cmp(nextupd, thisupd) < 0) {
389         OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY,
390                 OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE);
391         ret = 0;
392     }
393
394     return ret;
395 }
396
397 OCSP_CERTID *OCSP_SINGLERESP_get0_id(OCSP_SINGLERESP *single)
398 {
399     return single->certId;
400 }