chiark / gitweb /
988d1bceb01e643afc7a14ef7b7cc57734990960
[chiark-tcl.git] / crypto / crypto.c
1 /*
2  * crypto - Tcl bindings for parts of the `nettle' crypto library
3  * Copyright 2006 Ian Jackson
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18  * 02110-1301, USA.
19  */
20
21
22 #include "chiark_tcl_crypto.h"
23
24 const PadOp cht_padop_entries[]= {
25   { "un", 0, 0 },
26   { "ua", 0, 1 },
27   { "pn", 1, 0 },
28   { "pa", 1, 1 },
29   { 0 }
30 };
31
32 typedef struct {
33   HBytes_Value *hb;
34   int pad, blocksize; /* 0 or 1 */
35 } PadMethodClientData;
36
37 int cht_do_hbcrypto_pad(ClientData cd, Tcl_Interp *ip, const PadOp *op,
38                   HBytes_Var v, Tcl_Obj *blocksz, const PadMethodInfo *meth,
39                   int methargsc, Tcl_Obj *const *methargsv) {
40   PadMethodClientData pmcd;
41   int rc;
42   
43   if (op->use_algname) {
44     const BlockCipherAlgInfo *alg;
45     alg= enum_lookup_cached(ip,blocksz, cht_blockcipheralginfo_entries,
46                             "blockcipher alg for pad");
47     if (!alg) return TCL_ERROR;
48     pmcd.blocksize= alg->blocksize;
49   } else {
50     rc= Tcl_GetIntFromObj(ip, blocksz, &pmcd.blocksize);  if (rc) return rc;
51     if (pmcd.blocksize < 1) cht_staticerr(ip, "block size must be at least 1", 0);
52   }
53
54   pmcd.hb= v.hb;
55   pmcd.pad= op->pad;
56
57   return meth->func(&pmcd,ip,methargsc,methargsv);
58 }
59   
60 int cht_do_padmethodinfo_rfc2406(ClientData cd, Tcl_Interp *ip,
61                              Tcl_Obj *nxthdr_arg, int *ok) {
62   const PadMethodClientData *pmcd= (const void*)cd;
63   int i, rc, padlen, old_len;
64   
65   if (pmcd->blocksize > 256)
66     return cht_staticerr(ip, "block size too large for RFC2406 padding", 0);
67
68   if (pmcd->pad) {
69     Byte *padding;
70     HBytes_Value nxthdr;
71
72     rc= cht_pat_hb(ip,nxthdr_arg,&nxthdr);
73     if (rc) return rc;
74
75     if (cht_hb_len(&nxthdr) != 1) return
76       cht_staticerr(ip, "RFC2406 next header field must be exactly 1 byte", 0);
77     padlen= pmcd->blocksize-1 - ((cht_hb_len(pmcd->hb)+1) % pmcd->blocksize);
78     padding= cht_hb_append(pmcd->hb, padlen+2);
79     for (i=1; i<=padlen; i++)
80       *padding++ = i;
81     *padding++ = padlen;
82     *padding++ = cht_hb_data(&nxthdr)[0];
83     *ok= 1;
84     
85   } else {
86     const Byte *padding, *trailer;
87     HBytes_Value nxthdr;
88     Tcl_Obj *nxthdr_valobj, *ro;
89     
90     *ok= 0;
91     old_len= cht_hb_len(pmcd->hb);  if (old_len % pmcd->blocksize) goto quit;
92     trailer= cht_hb_unappend(pmcd->hb, 2); if (!trailer) goto quit;
93
94     padlen= trailer[0];
95     cht_hb_array(&nxthdr,trailer+1,1);
96     nxthdr_valobj= cht_ret_hb(ip,nxthdr);
97     ro= Tcl_ObjSetVar2(ip,nxthdr_arg,0,nxthdr_valobj,TCL_LEAVE_ERR_MSG);
98     if (!ro) { Tcl_DecrRefCount(nxthdr_valobj); return TCL_ERROR; }
99
100     padding= cht_hb_unappend(pmcd->hb, padlen);
101     for (i=1; i<=padlen; i++)
102       if (*padding++ != i) goto quit;
103
104     *ok= 1;
105
106   quit:;
107
108   }
109
110   return TCL_OK;
111 }
112
113 int cht_do_padmethodinfo_pkcs5(ClientData cd, Tcl_Interp *ip, int *ok) {
114   const PadMethodClientData *pmcd= (const void*)cd;
115   int padlen, old_len, i;
116   
117   if (pmcd->blocksize > 255)
118     return cht_staticerr(ip, "block size too large for pkcs#5", 0);
119
120   if (pmcd->pad) {
121
122     Byte *padding;
123
124     padlen= pmcd->blocksize - (cht_hb_len(pmcd->hb) % pmcd->blocksize);
125     padding= cht_hb_append(pmcd->hb, padlen);
126     memset(padding, padlen, padlen);
127
128   } else {
129
130     const Byte *padding;
131
132     old_len= cht_hb_len(pmcd->hb);  if (old_len % pmcd->blocksize) goto bad;
133     padding= cht_hb_unappend(pmcd->hb, 1);  if (!padding) goto bad;
134     padlen= *padding;
135     if (padlen < 1 || padlen > pmcd->blocksize) goto bad;
136     padding= cht_hb_unappend(pmcd->hb, padlen-1);  if (!padding) goto bad;
137
138     for (i=0; i<padlen-1; i++, padding++) if (*padding != padlen) goto bad;
139
140   }
141
142   *ok= 1;
143   return TCL_OK;
144
145  bad:
146   *ok= 0;
147   return TCL_OK;
148 }
149
150 int cht_do_hbcrypto_hash(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
151                    HBytes_Value message, HBytes_Value *result) {
152   Byte *dest;
153
154   dest= cht_hb_arrayspace(result,alg->hashsize);
155   alg->oneshot(dest, cht_hb_data(&message), cht_hb_len(&message));
156   return TCL_OK;
157 }
158
159 #define OBJ_CIPHKEY(o) ((CiphKeyValue*)(o)->internalRep.otherValuePtr)
160
161 typedef struct {
162   int valuelen, bufferslen;
163   Byte *value, *buffers;
164   const void *alg;
165   void *alpha, *beta; /* key schedules etc.; each may be 0 */
166 } CiphKeyValue;
167
168 static void freealg(CiphKeyValue *key) {
169   TFREE(key->alpha);
170   TFREE(key->beta);
171 }
172
173 static void key_t_free(Tcl_Obj *obj) {
174   CiphKeyValue *key= OBJ_CIPHKEY(obj);
175   freealg(key);
176   TFREE(key->value);
177   TFREE(key->buffers);
178 }
179
180 static void noalg(CiphKeyValue *key) {
181   key->alg= 0;
182   key->alpha= key->beta= 0;
183 }
184
185 static void key_t_dup(Tcl_Obj *src_obj, Tcl_Obj *dup_obj) {
186   CiphKeyValue *src= OBJ_CIPHKEY(src_obj);
187   CiphKeyValue *dup= TALLOC(sizeof(*dup));
188   dup->valuelen= src->valuelen;
189   dup->value= src->valuelen ? TALLOC(src->valuelen) : 0;
190   dup->buffers= 0; dup->bufferslen= 0;
191   memcpy(dup->value, src->value, src->valuelen);
192   noalg(dup);
193   dup_obj->internalRep.otherValuePtr= dup;
194   dup_obj->typePtr= &cht_blockcipherkey_type;
195 }
196
197 static void key_t_ustr(Tcl_Obj *o) {
198   obj_updatestr_array(o, OBJ_CIPHKEY(o)->value, OBJ_CIPHKEY(o)->valuelen);
199 }
200
201 static int key_t_sfa(Tcl_Interp *ip, Tcl_Obj *o) {
202   int rc, l;
203   CiphKeyValue *val;
204
205   rc= Tcl_ConvertToType(ip,o,&cht_hbytes_type);  if (rc) return rc;
206   val= TALLOC(sizeof(*val));
207   val->valuelen= l= cht_hb_len(OBJ_HBYTES(o));
208   val->value= TALLOC(l);
209   val->buffers= 0;
210   val->bufferslen= 0;
211   memcpy(val->value, cht_hb_data(OBJ_HBYTES(o)), l);
212   noalg(val);
213
214   cht_objfreeir(o);
215   o->internalRep.otherValuePtr= val;
216   o->typePtr= &cht_blockcipherkey_type;
217
218   return TCL_OK;
219 }
220   
221 Tcl_ObjType cht_blockcipherkey_type = {
222   "blockcipher-key",
223   key_t_free, key_t_dup, key_t_ustr, key_t_sfa
224 };
225
226 static CiphKeyValue *get_key(Tcl_Interp *ip, Tcl_Obj *key_obj,
227                              const void *alg, int want_bufferslen) {
228   CiphKeyValue *key;
229   int rc;
230   
231   rc= Tcl_ConvertToType(ip,key_obj,&cht_blockcipherkey_type);  if (rc) return 0;
232   key= OBJ_CIPHKEY(key_obj);
233
234   if (key->alg != alg) {
235     freealg(key);
236     noalg(key);
237     key->alg= alg;
238   }
239   
240   if (key->bufferslen < want_bufferslen) {
241     TFREE(key->buffers);
242     key->buffers= TALLOC(want_bufferslen);
243     key->bufferslen= want_bufferslen;
244   }
245   return key;
246 }
247
248 int cht_do_hbcrypto_blockcipher(ClientData cd, Tcl_Interp *ip,
249                           const BlockCipherOp *op,
250                           int objc, Tcl_Obj *const *objv) {
251   return op->func((void*)op,ip,objc,objv);
252 }
253
254 static int blockcipher_prep(Tcl_Interp *ip, Tcl_Obj *key_obj,
255                             const HBytes_Value *iv, int decrypt,
256                             const BlockCipherAlgInfo *alg,
257                             const BlockCipherModeInfo *mode, int data_len,
258                             const CiphKeyValue **key_r, const void **sched_r,
259                             const Byte **iv_r, int *iv_lenbytes_r,
260                             Byte **buffers_r, int *nblocks_r) {
261   void *sched, **schedp;
262   int want_bufferslen, want_iv;
263   int rc;
264   CiphKeyValue *key;
265
266   if (data_len % alg->blocksize)
267     return cht_staticerr(ip, "block cipher input not whole number of blocks",
268                      "HBYTES BLOCKCIPHER LENGTH");
269
270   want_bufferslen= alg->blocksize * (mode->buf_blocks + mode->iv_blocks);
271   key= get_key(ip, key_obj, alg, want_bufferslen);  if (!key) return TCL_ERROR;
272
273   schedp= (alg->decrypt.make_schedule==alg->encrypt.make_schedule
274            || !decrypt) ? &key->alpha : &key->beta;
275   sched= *schedp;
276   if (!sched) {
277     if (key->valuelen < alg->key_min)
278       return cht_staticerr(ip, "key too short", "HBYTES BLOCKCIPHER PARAMS");
279     if (key->valuelen > alg->key_max)
280       return cht_staticerr(ip, "key too long", "HBYTES BLOCKCIPHER PARAMS");
281
282     sched= TALLOC(alg->schedule_size);
283     (decrypt ? &alg->decrypt : &alg->encrypt)->make_schedule
284       (sched, key->value, key->valuelen);
285     *schedp= sched;
286   }
287
288   want_iv= alg->blocksize * mode->iv_blocks;
289   if (!want_iv) {
290     if (!cht_hb_issentinel(iv))
291       return cht_staticerr(ip,"iv supplied but mode does not take one", 0);
292   } else if (cht_hb_issentinel(iv)) {
293     if (decrypt) return cht_staticerr(ip,"must supply iv when decrypting", 0);
294     rc= cht_get_urandom(ip, key->buffers, want_iv);
295     if (rc) return rc;
296   } else {
297     int iv_supplied= cht_hb_len(iv);
298     if (iv_supplied > want_iv)
299       return cht_staticerr(ip, "iv too large for algorithm and mode",
300                        "HBYTES BLOCKCIPHER PARAMS");
301     memcpy(key->buffers, cht_hb_data(iv), iv_supplied);
302     memset(key->buffers + iv_supplied, 0, want_iv - iv_supplied);
303   }
304
305   *key_r= key;
306   *sched_r= sched;
307
308   *iv_r= key->buffers;
309   *iv_lenbytes_r= want_iv;
310
311   *buffers_r= key->buffers + want_iv;
312   *nblocks_r= data_len / alg->blocksize;
313   
314   return TCL_OK;
315 }
316
317 int cht_do_blockcipherop_d(ClientData cd, Tcl_Interp *ip,
318                        HBytes_Var v, const BlockCipherAlgInfo *alg,
319                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
320                        HBytes_Value iv, HBytes_Value *result) {
321   return cht_do_blockcipherop_e(cd,ip,v,alg,key_obj,mode,iv,result);
322 }
323
324 int cht_do_blockcipherop_e(ClientData cd, Tcl_Interp *ip,
325                        HBytes_Var v, const BlockCipherAlgInfo *alg,
326                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
327                        HBytes_Value iv, HBytes_Value *result) {
328   const BlockCipherOp *op= (const void*)cd;
329   int encrypt= op->encrypt;
330   int rc, iv_lenbytes;
331   const CiphKeyValue *key;
332   const char *failure;
333   const Byte *ivbuf;
334   Byte *buffers;
335   const void *sched;
336   int nblocks;
337
338   if (!mode->encrypt)
339     return cht_staticerr(ip, "mode does not support encrypt/decrypt", 0);
340
341   rc= blockcipher_prep(ip,key_obj,&iv,!encrypt,
342                        alg,mode, cht_hb_len(v.hb),
343                        &key,&sched,
344                        &ivbuf,&iv_lenbytes,
345                        &buffers,&nblocks);
346   if (rc) return rc;
347   
348   failure=
349     (encrypt ? mode->encrypt : mode->decrypt)
350     (cht_hb_data(v.hb), nblocks, ivbuf, buffers, alg, encrypt, sched);
351
352   if (failure)
353     return cht_staticerr(ip, failure, "HBYTES BLOCKCIPHER CRYPTFAIL CRYPT");
354
355   cht_hb_array(result, ivbuf, iv_lenbytes);
356
357   return TCL_OK;
358 }
359
360 int cht_do_blockcipherop_mac(ClientData cd, Tcl_Interp *ip,
361                          HBytes_Value msg, const BlockCipherAlgInfo *alg,
362                          Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
363                          HBytes_Value iv, HBytes_Value *result) {
364   const CiphKeyValue *key;
365   const char *failure;
366   const Byte *ivbuf;
367   Byte *buffers;
368   const void *sched;
369   int nblocks, iv_lenbytes;
370   int rc;
371
372   if (!mode->mac)
373     return cht_staticerr(ip, "mode does not support mac generation", 0);
374   
375   rc= blockcipher_prep(ip,key_obj,&iv,0,
376                        alg,mode, cht_hb_len(&msg),
377                        &key,&sched,
378                        &ivbuf,&iv_lenbytes,
379                        &buffers,&nblocks);
380   if (rc) return rc;
381
382   failure= mode->mac(cht_hb_data(&msg), nblocks, ivbuf, buffers, alg, sched);
383   if (failure)
384     return cht_staticerr(ip,failure, "HBYTES BLOCKCIPHER CRYPTFAIL MAC");
385
386   cht_hb_array(result, buffers, alg->blocksize * mode->mac_blocks);
387
388   return TCL_OK;
389 }
390
391 int cht_do_hbcrypto_hmac(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
392                    HBytes_Value message, Tcl_Obj *key_obj,
393                    Tcl_Obj *maclen_obj, HBytes_Value *result) {
394   /* key->alpha = state after H(K XOR ipad <unfinished>
395    * key->beta = state after H(K XOR opad <unfinished>
396    * key->buffers = room for one block, or one state
397    */
398   CiphKeyValue *key;
399   Byte *dest;
400   int i, ml, rc;
401
402   if (maclen_obj) {
403     rc= Tcl_GetIntFromObj(ip, maclen_obj, &ml);  if (rc) return rc;
404     if (ml<0 || ml>alg->hashsize)
405       return cht_staticerr(ip, "requested hmac output size out of range",
406                        "HBYTES HMAC PARAMS");
407   } else {
408     ml= alg->hashsize;
409   }
410
411   key= get_key(ip, key_obj, alg,
412                alg->blocksize > alg->statesize
413                ? alg->blocksize : alg->statesize);
414
415   if (!key->alpha) {
416     assert(!key->beta);
417     
418     if (key->valuelen > alg->blocksize)
419       return cht_staticerr(ip, "key to hmac longer than hash block size",
420                        "HBYTES HMAC PARAMS");
421
422     memcpy(key->buffers, key->value, key->valuelen);
423     memset(key->buffers + key->valuelen, 0, alg->blocksize - key->valuelen);
424     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= 0x36;
425
426     key->alpha= TALLOC(alg->statesize);
427     alg->init(key->alpha);
428     alg->update(key->alpha, key->buffers, alg->blocksize);
429     
430     key->beta= TALLOC(alg->statesize);
431     alg->init(key->beta);
432     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= (0x5c ^ 0x36);
433     alg->update(key->beta, key->buffers, alg->blocksize);
434   }
435   assert(key->beta);
436
437   dest= cht_hb_arrayspace(result, alg->hashsize);
438
439   memcpy(key->buffers, key->alpha, alg->statesize);
440   alg->update(key->buffers, cht_hb_data(&message), cht_hb_len(&message));
441   alg->final(key->buffers, dest);
442
443   memcpy(key->buffers, key->beta, alg->statesize);
444   alg->update(key->buffers, dest, alg->hashsize);
445   alg->final(key->buffers, dest);
446
447   cht_hb_unappend(result, alg->hashsize - ml);
448
449   return TCL_OK;
450 }
451
452 int cht_do_blockcipherop_prop(ClientData cd, Tcl_Interp *ip,
453                           const BlockCipherPropInfo *prop,
454                           const BlockCipherAlgInfo *alg, int *result) {
455   *result= *(const int*)((const char*)alg + prop->int_offset);
456   return TCL_OK;
457 }
458
459 int cht_do_hbcrypto_hash_prop(ClientData cd, Tcl_Interp *ip,
460                         const HashAlgPropInfo *prop,
461                         const HashAlgInfo *alg, int *result) {
462   *result= *(const int*)((const char*)alg + prop->int_offset);
463   return TCL_OK;
464 }