Add axTLS sourcecode
[project/luci.git] / libs / nixio / axTLS / ssl / gen_cert.c
1 /*
2  * Copyright (c) 2007, Cameron Rich
3  * 
4  * All rights reserved.
5  * 
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * * Redistributions of source code must retain the above copyright notice, 
10  *   this list of conditions and the following disclaimer.
11  * * Redistributions in binary form must reproduce the above copyright notice, 
12  *   this list of conditions and the following disclaimer in the documentation 
13  *   and/or other materials provided with the distribution.
14  * * Neither the name of the axTLS project nor the names of its contributors 
15  *   may be used to endorse or promote products derived from this software 
16  *   without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #ifdef CONFIG_SSL_GENERATE_X509_CERT
34 #include <string.h>
35 #include <stdlib.h>
36 #include "ssl.h"
37
38 /**
39  * Generate a basic X.509 certificate
40  */
41
42 static uint8_t set_gen_length(int len, uint8_t *buf, int *offset)
43 {
44     if (len < 0x80) /* short form */
45     {
46         buf[(*offset)++] = len;
47         return 1;
48     }
49     else /* long form */
50     {
51         int i, length_bytes = 0;
52
53         if (len & 0x00FF0000)
54             length_bytes = 3;
55         else if (len & 0x0000FF00)
56             length_bytes = 2;
57         else if (len & 0x000000FF)
58             length_bytes = 1;
59             
60         buf[(*offset)++] = 0x80 + length_bytes;
61
62         for (i = length_bytes-1; i >= 0; i--)
63         {
64             buf[*offset+i] = len & 0xFF;
65             len >>= 8;
66         }
67
68         *offset += length_bytes;
69         return length_bytes+1;
70     }
71 }
72
73 static int pre_adjust_with_size(uint8_t type,
74         int *seq_offset, uint8_t *buf, int *offset)
75 {
76     buf[(*offset)++] = type;
77     *seq_offset = *offset;
78     *offset += 4;   /* fill in later */
79     return *offset;
80 }
81
82 static void adjust_with_size(int seq_size, int seq_start, 
83                 uint8_t *buf, int *offset)
84 {
85     uint8_t seq_byte_size; 
86     int orig_seq_size = seq_size;
87     int orig_seq_start = seq_start;
88
89     seq_size = *offset-seq_size;
90     seq_byte_size = set_gen_length(seq_size, buf, &seq_start);
91
92     if (seq_byte_size != 4)
93     {
94         memmove(&buf[orig_seq_start+seq_byte_size], 
95                 &buf[orig_seq_size], seq_size);
96         *offset -= 4-seq_byte_size;
97     }
98 }
99
100 static void gen_serial_number(uint8_t *buf, int *offset)
101 {
102     static const uint8_t ser_oid[] = { ASN1_INTEGER, 1, 0x7F };
103     memcpy(&buf[*offset], ser_oid , sizeof(ser_oid));
104     *offset += sizeof(ser_oid);
105 }
106
107 static void gen_signature_alg(uint8_t *buf, int *offset)
108 {
109     /* OBJECT IDENTIFIER sha1withRSAEncryption (1 2 840 113549 1 1 5) */
110     static const uint8_t sig_oid[] = 
111     {
112         ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, 
113         0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05,
114         ASN1_NULL, 0x00
115     };
116
117     memcpy(&buf[*offset], sig_oid, sizeof(sig_oid));
118     *offset += sizeof(sig_oid);
119 }
120
121 static int gen_dn(const char *name, uint8_t dn_type, 
122                         uint8_t *buf, int *offset)
123 {
124     int ret = X509_OK;
125     int name_size = strlen(name);
126
127     if (name_size > 0x70)    /* just too big */
128     {
129         ret = X509_NOT_OK;
130         goto error;
131     }
132
133     buf[(*offset)++] = ASN1_SET;
134     set_gen_length(9+name_size, buf, offset);
135     buf[(*offset)++] = ASN1_SEQUENCE;
136     set_gen_length(7+name_size, buf, offset);
137     buf[(*offset)++] = ASN1_OID;
138     buf[(*offset)++] = 3;
139     buf[(*offset)++] = 0x55;
140     buf[(*offset)++] = 0x04;
141     buf[(*offset)++] = dn_type;
142     buf[(*offset)++] = ASN1_PRINTABLE_STR;
143     buf[(*offset)++] = name_size;
144     strcpy(&buf[*offset], name);
145     *offset += name_size;
146
147 error:
148     return ret;
149 }
150
151 static int gen_issuer(const char * dn[], uint8_t *buf, int *offset)
152 {
153     int ret = X509_OK;
154     int seq_offset;
155     int seq_size = pre_adjust_with_size(
156                             ASN1_SEQUENCE, &seq_offset, buf, offset);
157     char fqdn[128]; 
158
159     /* we need the common name, so if not configured, work out the fully
160      * qualified domain name */
161     if (dn[X509_COMMON_NAME] == NULL || strlen(dn[X509_COMMON_NAME]) == 0)
162     {
163         int fqdn_len;
164         gethostname(fqdn, sizeof(fqdn));
165         fqdn_len = strlen(fqdn);
166         fqdn[fqdn_len++] = '.';
167         getdomainname(&fqdn[fqdn_len], sizeof(fqdn)-fqdn_len);
168         fqdn_len = strlen(fqdn);
169
170         if (fqdn[fqdn_len-1] == '.')    /* ensure '.' is not last char */
171             fqdn[fqdn_len-1] = 0;
172
173         dn[X509_COMMON_NAME] = fqdn;
174     }
175
176     if ((ret = gen_dn(dn[X509_COMMON_NAME], 3, buf, offset)))
177         goto error;
178
179     if (dn[X509_ORGANIZATION] != NULL && strlen(dn[X509_ORGANIZATION]) > 0)
180     {
181         if ((ret = gen_dn(dn[X509_ORGANIZATION], 10, buf, offset)))
182             goto error;
183     }
184
185     if (dn[X509_ORGANIZATIONAL_UNIT] != NULL &&
186                                 strlen(dn[X509_ORGANIZATIONAL_UNIT]) > 0)
187     {
188         if ((ret = gen_dn(dn[X509_ORGANIZATIONAL_UNIT], 11, buf, offset)))
189             goto error;
190     }
191
192     adjust_with_size(seq_size, seq_offset, buf, offset);
193
194 error:
195     return ret;
196 }
197
198 static void gen_utc_time(uint8_t *buf, int *offset)
199 {
200     static const uint8_t time_seq[] = 
201     {
202         ASN1_SEQUENCE, 30, 
203         ASN1_UTC_TIME, 13, 
204         '0', '7', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z', 
205         ASN1_UTC_TIME, 13,  /* make it good for 30 or so years */
206         '3', '8', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z'
207     };
208
209     /* fixed time */
210     memcpy(&buf[*offset], time_seq, sizeof(time_seq));
211     *offset += sizeof(time_seq);
212 }
213
214 static void gen_pub_key2(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset)
215 {
216     static const uint8_t pub_key_seq[] = 
217     {
218         ASN1_INTEGER, 0x03, 0x01, 0x00, 0x01 /* INTEGER 65537 */
219     };
220
221     int seq_offset;
222     int pub_key_size = rsa_ctx->num_octets;
223     uint8_t *block = (uint8_t *)alloca(pub_key_size);
224     int seq_size = pre_adjust_with_size(
225                             ASN1_SEQUENCE, &seq_offset, buf, offset);
226     buf[(*offset)++] = ASN1_INTEGER;
227     bi_export(rsa_ctx->bi_ctx, rsa_ctx->m, block, pub_key_size);
228
229     if (*block & 0x80)  /* make integer positive */
230     {
231         set_gen_length(pub_key_size+1, buf, offset);
232         buf[(*offset)++] = 0;
233     }
234     else
235         set_gen_length(pub_key_size, buf, offset);
236
237     memcpy(&buf[*offset], block, pub_key_size);
238     *offset += pub_key_size;
239     memcpy(&buf[*offset], pub_key_seq, sizeof(pub_key_seq));
240     *offset += sizeof(pub_key_seq);
241     adjust_with_size(seq_size, seq_offset, buf, offset);
242 }
243
244 static void gen_pub_key1(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset)
245 {
246     int seq_offset;
247     int seq_size = pre_adjust_with_size(
248                             ASN1_BIT_STRING, &seq_offset, buf, offset);
249     buf[(*offset)++] = 0;   /* bit string is multiple of 8 */
250     gen_pub_key2(rsa_ctx, buf, offset);
251     adjust_with_size(seq_size, seq_offset, buf, offset);
252 }
253
254 static void gen_pub_key(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset)
255 {
256     /*  OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) */
257     static const uint8_t rsa_enc_oid[] =
258     {
259         ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09,
260         0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,
261         ASN1_NULL, 0x00
262     };
263
264     int seq_offset;
265     int seq_size = pre_adjust_with_size(
266                             ASN1_SEQUENCE, &seq_offset, buf, offset);
267
268     memcpy(&buf[*offset], rsa_enc_oid, sizeof(rsa_enc_oid));
269     *offset += sizeof(rsa_enc_oid);
270     gen_pub_key1(rsa_ctx, buf, offset);
271     adjust_with_size(seq_size, seq_offset, buf, offset);
272 }
273
274 static void gen_signature(const RSA_CTX *rsa_ctx, const uint8_t *sha_dgst, 
275                         uint8_t *buf, int *offset)
276 {
277     static const uint8_t asn1_sig[] = 
278     {
279         ASN1_SEQUENCE,  0x21, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 
280         0x2b, 0x0e, 0x03, 0x02, 0x1a, /* sha1 (1 3 14 3 2 26) */
281         ASN1_NULL, 0x00, ASN1_OCTET_STRING, 0x14 
282     };
283
284     uint8_t *enc_block = (uint8_t *)alloca(rsa_ctx->num_octets);
285     uint8_t *block = (uint8_t *)alloca(sizeof(asn1_sig) + SHA1_SIZE);
286     int sig_size;
287
288     /* add the digest as an embedded asn.1 sequence */
289     memcpy(block, asn1_sig, sizeof(asn1_sig));
290     memcpy(&block[sizeof(asn1_sig)], sha_dgst, SHA1_SIZE);
291
292     sig_size = RSA_encrypt(rsa_ctx, block, 
293                             sizeof(asn1_sig) + SHA1_SIZE, enc_block, 1);
294
295     buf[(*offset)++] = ASN1_BIT_STRING;
296     set_gen_length(sig_size+1, buf, offset);
297     buf[(*offset)++] = 0;   /* bit string is multiple of 8 */
298     memcpy(&buf[*offset], enc_block, sig_size);
299     *offset += sig_size;
300 }
301
302 static int gen_tbs_cert(const char * dn[],
303                     const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset,
304                     uint8_t *sha_dgst)
305 {
306     int ret = X509_OK;
307     SHA1_CTX sha_ctx;
308     int seq_offset;
309     int begin_tbs = *offset;
310     int seq_size = pre_adjust_with_size(
311                         ASN1_SEQUENCE, &seq_offset, buf, offset);
312
313     gen_serial_number(buf, offset);
314     gen_signature_alg(buf, offset);
315
316     /* CA certicate issuer */
317     if ((ret = gen_issuer(dn, buf, offset)))
318         goto error;
319
320     gen_utc_time(buf, offset);
321
322     /* certificate issuer */
323     if ((ret = gen_issuer(dn, buf, offset)))
324         goto error;
325
326     gen_pub_key(rsa_ctx, buf, offset);
327     adjust_with_size(seq_size, seq_offset, buf, offset);
328
329     SHA1_Init(&sha_ctx);
330     SHA1_Update(&sha_ctx, &buf[begin_tbs], *offset-begin_tbs);
331     SHA1_Final(sha_dgst, &sha_ctx);
332
333 error:
334     return ret;
335 }
336
337 /**
338  * Create a new certificate.
339  */
340 EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data)
341 {
342     int ret = X509_OK, offset = 0, seq_offset;
343     /* allocate enough space to load a new certificate */
344     uint8_t *buf = (uint8_t *)alloca(ssl_ctx->rsa_ctx->num_octets*2 + 512);
345     uint8_t sha_dgst[SHA1_SIZE];
346     int seq_size = pre_adjust_with_size(ASN1_SEQUENCE, 
347                                     &seq_offset, buf, &offset);
348
349     if ((ret = gen_tbs_cert(dn, ssl_ctx->rsa_ctx, buf, &offset, sha_dgst)) < 0)
350         goto error;
351
352     gen_signature_alg(buf, &offset);
353     gen_signature(ssl_ctx->rsa_ctx, sha_dgst, buf, &offset);
354     adjust_with_size(seq_size, seq_offset, buf, &offset);
355     *cert_data = (uint8_t *)malloc(offset); /* create the exact memory for it */
356     memcpy(*cert_data, buf, offset);
357
358 error:
359     return ret < 0 ? ret : offset;
360 }
361
362 #endif
363