chiark / gitweb /
hbcrypto hash-{init,update,final} for incremental hashing
[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 #define OBJ_CIPHKEY(o) ((CiphKeyValue*)(o)->internalRep.otherValuePtr)
151
152 typedef struct {
153   int valuelen, bufferslen;
154   Byte *value, *buffers;
155   const void *alg;
156   void *alpha, *beta; /* key schedules etc.; each may be 0 */
157 } CiphKeyValue;
158
159 static void freealg(CiphKeyValue *key) {
160   TFREE(key->alpha);
161   TFREE(key->beta);
162 }
163
164 static void key_t_free(Tcl_Obj *obj) {
165   CiphKeyValue *key= OBJ_CIPHKEY(obj);
166   freealg(key);
167   TFREE(key->value);
168   TFREE(key->buffers);
169 }
170
171 static void noalg(CiphKeyValue *key) {
172   key->alg= 0;
173   key->alpha= key->beta= 0;
174 }
175
176 static void key_t_dup(Tcl_Obj *src_obj, Tcl_Obj *dup_obj) {
177   CiphKeyValue *src= OBJ_CIPHKEY(src_obj);
178   CiphKeyValue *dup= TALLOC(sizeof(*dup));
179   dup->valuelen= src->valuelen;
180   dup->value= src->valuelen ? TALLOC(src->valuelen) : 0;
181   dup->buffers= 0; dup->bufferslen= 0;
182   memcpy(dup->value, src->value, src->valuelen);
183   noalg(dup);
184   dup_obj->internalRep.otherValuePtr= dup;
185   dup_obj->typePtr= &cht_blockcipherkey_type;
186 }
187
188 static void key_t_ustr(Tcl_Obj *o) {
189   cht_obj_updatestr_array(o, OBJ_CIPHKEY(o)->value, OBJ_CIPHKEY(o)->valuelen);
190 }
191
192 static int key_t_sfa(Tcl_Interp *ip, Tcl_Obj *o) {
193   int rc, l;
194   CiphKeyValue *val;
195
196   rc= Tcl_ConvertToType(ip,o,&cht_hbytes_type);  if (rc) return rc;
197   val= TALLOC(sizeof(*val));
198   val->valuelen= l= cht_hb_len(OBJ_HBYTES(o));
199   val->value= TALLOC(l);
200   val->buffers= 0;
201   val->bufferslen= 0;
202   memcpy(val->value, cht_hb_data(OBJ_HBYTES(o)), l);
203   noalg(val);
204
205   cht_objfreeir(o);
206   o->internalRep.otherValuePtr= val;
207   o->typePtr= &cht_blockcipherkey_type;
208
209   return TCL_OK;
210 }
211   
212 Tcl_ObjType cht_blockcipherkey_type = {
213   "blockcipher-key",
214   key_t_free, key_t_dup, key_t_ustr, key_t_sfa
215 };
216
217 static CiphKeyValue *get_key(Tcl_Interp *ip, Tcl_Obj *key_obj,
218                              const void *alg, int want_bufferslen) {
219   CiphKeyValue *key;
220   int rc;
221   
222   rc= Tcl_ConvertToType(ip,key_obj,&cht_blockcipherkey_type);  if (rc) return 0;
223   key= OBJ_CIPHKEY(key_obj);
224
225   if (key->alg != alg) {
226     freealg(key);
227     noalg(key);
228     key->alg= alg;
229   }
230   
231   if (key->bufferslen < want_bufferslen) {
232     TFREE(key->buffers);
233     key->buffers= TALLOC(want_bufferslen);
234     key->bufferslen= want_bufferslen;
235   }
236   return key;
237 }
238
239 int cht_do_hbcrypto_blockcipher(ClientData cd, Tcl_Interp *ip,
240                           const BlockCipherOp *op,
241                           int objc, Tcl_Obj *const *objv) {
242   return op->func((void*)op,ip,objc,objv);
243 }
244
245 static int blockcipher_prep(Tcl_Interp *ip, Tcl_Obj *key_obj,
246                             const HBytes_Value *iv, int decrypt,
247                             const BlockCipherAlgInfo *alg,
248                             const BlockCipherModeInfo *mode, int data_len,
249                             const CiphKeyValue **key_r, const void **sched_r,
250                             const Byte **iv_r, int *iv_lenbytes_r,
251                             Byte **buffers_r, int *nblocks_r) {
252   void *sched, **schedp;
253   int want_bufferslen, want_iv;
254   int rc;
255   CiphKeyValue *key;
256
257   if (data_len % alg->blocksize)
258     return cht_staticerr(ip, "block cipher input not whole number of blocks",
259                      "HBYTES BLOCKCIPHER LENGTH");
260
261   want_bufferslen= alg->blocksize * (mode->buf_blocks + mode->iv_blocks);
262   key= get_key(ip, key_obj, alg, want_bufferslen);  if (!key) return TCL_ERROR;
263
264   schedp= (alg->decrypt.make_schedule==alg->encrypt.make_schedule
265            || !decrypt) ? &key->alpha : &key->beta;
266   sched= *schedp;
267   if (!sched) {
268     if (key->valuelen < alg->key_min)
269       return cht_staticerr(ip, "key too short", "HBYTES BLOCKCIPHER PARAMS");
270     if (key->valuelen > alg->key_max)
271       return cht_staticerr(ip, "key too long", "HBYTES BLOCKCIPHER PARAMS");
272
273     sched= TALLOC(alg->schedule_size);
274     (decrypt ? &alg->decrypt : &alg->encrypt)->make_schedule
275       (sched, key->value, key->valuelen);
276     *schedp= sched;
277   }
278
279   want_iv= alg->blocksize * mode->iv_blocks;
280   if (!want_iv) {
281     if (!cht_hb_issentinel(iv))
282       return cht_staticerr(ip,"iv supplied but mode does not take one", 0);
283   } else if (cht_hb_issentinel(iv)) {
284     if (decrypt) return cht_staticerr(ip,"must supply iv when decrypting", 0);
285     rc= cht_get_urandom(ip, key->buffers, want_iv);
286     if (rc) return rc;
287   } else {
288     int iv_supplied= cht_hb_len(iv);
289     if (iv_supplied > want_iv)
290       return cht_staticerr(ip, "iv too large for algorithm and mode",
291                        "HBYTES BLOCKCIPHER PARAMS");
292     memcpy(key->buffers, cht_hb_data(iv), iv_supplied);
293     memset(key->buffers + iv_supplied, 0, want_iv - iv_supplied);
294   }
295
296   *key_r= key;
297   *sched_r= sched;
298
299   *iv_r= key->buffers;
300   *iv_lenbytes_r= want_iv;
301
302   *buffers_r= key->buffers + want_iv;
303   *nblocks_r= data_len / alg->blocksize;
304   
305   return TCL_OK;
306 }
307
308 int cht_do_blockcipherop_d(ClientData cd, Tcl_Interp *ip,
309                        HBytes_Var v, const BlockCipherAlgInfo *alg,
310                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
311                        HBytes_Value iv, HBytes_Value *result) {
312   return cht_do_blockcipherop_e(cd,ip,v,alg,key_obj,mode,iv,result);
313 }
314
315 int cht_do_blockcipherop_e(ClientData cd, Tcl_Interp *ip,
316                        HBytes_Var v, const BlockCipherAlgInfo *alg,
317                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
318                        HBytes_Value iv, HBytes_Value *result) {
319   const BlockCipherOp *op= (const void*)cd;
320   int encrypt= op->encrypt;
321   int rc, iv_lenbytes;
322   const CiphKeyValue *key;
323   const char *failure;
324   const Byte *ivbuf;
325   Byte *buffers;
326   const void *sched;
327   int nblocks;
328
329   if (!mode->encrypt)
330     return cht_staticerr(ip, "mode does not support encrypt/decrypt", 0);
331
332   rc= blockcipher_prep(ip,key_obj,&iv,!encrypt,
333                        alg,mode, cht_hb_len(v.hb),
334                        &key,&sched,
335                        &ivbuf,&iv_lenbytes,
336                        &buffers,&nblocks);
337   if (rc) return rc;
338   
339   failure=
340     (encrypt ? mode->encrypt : mode->decrypt)
341     (cht_hb_data(v.hb), nblocks, ivbuf, buffers, alg, encrypt, sched);
342
343   if (failure)
344     return cht_staticerr(ip, failure, "HBYTES BLOCKCIPHER CRYPTFAIL CRYPT");
345
346   cht_hb_array(result, ivbuf, iv_lenbytes);
347
348   return TCL_OK;
349 }
350
351 int cht_do_blockcipherop_mac(ClientData cd, Tcl_Interp *ip,
352                          HBytes_Value msg, const BlockCipherAlgInfo *alg,
353                          Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
354                          HBytes_Value iv, HBytes_Value *result) {
355   const CiphKeyValue *key;
356   const char *failure;
357   const Byte *ivbuf;
358   Byte *buffers;
359   const void *sched;
360   int nblocks, iv_lenbytes;
361   int rc;
362
363   if (!mode->mac)
364     return cht_staticerr(ip, "mode does not support mac generation", 0);
365   
366   rc= blockcipher_prep(ip,key_obj,&iv,0,
367                        alg,mode, cht_hb_len(&msg),
368                        &key,&sched,
369                        &ivbuf,&iv_lenbytes,
370                        &buffers,&nblocks);
371   if (rc) return rc;
372
373   failure= mode->mac(cht_hb_data(&msg), nblocks, ivbuf, buffers, alg, sched);
374   if (failure)
375     return cht_staticerr(ip,failure, "HBYTES BLOCKCIPHER CRYPTFAIL MAC");
376
377   cht_hb_array(result, buffers, alg->blocksize * mode->mac_blocks);
378
379   return TCL_OK;
380 }
381
382 int cht_do_hbcrypto_hmac(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
383                    HBytes_Value message, Tcl_Obj *key_obj,
384                    Tcl_Obj *maclen_obj, HBytes_Value *result) {
385   /* key->alpha = state after H(K XOR ipad <unfinished>
386    * key->beta = state after H(K XOR opad <unfinished>
387    * key->buffers = room for one block, or one state
388    */
389   CiphKeyValue *key;
390   Byte *dest;
391   int i, ml, rc;
392
393   if (maclen_obj) {
394     rc= Tcl_GetIntFromObj(ip, maclen_obj, &ml);  if (rc) return rc;
395     if (ml<0 || ml>alg->hashsize)
396       return cht_staticerr(ip, "requested hmac output size out of range",
397                        "HBYTES HMAC PARAMS");
398   } else {
399     ml= alg->hashsize;
400   }
401
402   key= get_key(ip, key_obj, alg,
403                alg->blocksize > alg->statesize
404                ? alg->blocksize : alg->statesize);
405
406   if (!key->alpha) {
407     assert(!key->beta);
408     
409     if (key->valuelen > alg->blocksize)
410       return cht_staticerr(ip, "key to hmac longer than hash block size",
411                        "HBYTES HMAC PARAMS");
412
413     memcpy(key->buffers, key->value, key->valuelen);
414     memset(key->buffers + key->valuelen, 0, alg->blocksize - key->valuelen);
415     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= 0x36;
416
417     key->alpha= TALLOC(alg->statesize);
418     alg->init(key->alpha);
419     alg->update(key->alpha, key->buffers, alg->blocksize);
420     
421     key->beta= TALLOC(alg->statesize);
422     alg->init(key->beta);
423     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= (0x5c ^ 0x36);
424     alg->update(key->beta, key->buffers, alg->blocksize);
425   }
426   assert(key->beta);
427
428   dest= cht_hb_arrayspace(result, alg->hashsize);
429
430   memcpy(key->buffers, key->alpha, alg->statesize);
431   alg->update(key->buffers, cht_hb_data(&message), cht_hb_len(&message));
432   alg->final(key->buffers, dest);
433
434   memcpy(key->buffers, key->beta, alg->statesize);
435   alg->update(key->buffers, dest, alg->hashsize);
436   alg->final(key->buffers, dest);
437
438   cht_hb_unappend(result, alg->hashsize - ml);
439
440   return TCL_OK;
441 }
442
443 int cht_do_blockcipherop_prop(ClientData cd, Tcl_Interp *ip,
444                           const BlockCipherPropInfo *prop,
445                           const BlockCipherAlgInfo *alg, int *result) {
446   *result= *(const int*)((const char*)alg + prop->int_offset);
447   return TCL_OK;
448 }
449
450 int cht_do_hbcrypto_hash_prop(ClientData cd, Tcl_Interp *ip,
451                         const HashAlgPropInfo *prop,
452                         const HashAlgInfo *alg, int *result) {
453   *result= *(const int*)((const char*)alg + prop->int_offset);
454   return TCL_OK;
455 }