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