chiark / gitweb /
wiringpi: much implementation, move pwmc/pwmr
[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   if (data_len % alg->blocksize)
256     return cht_staticerr(ip, "block cipher input not whole number of blocks",
257                      "HBYTES BLOCKCIPHER LENGTH");
258
259   want_bufferslen= alg->blocksize * (mode->buf_blocks + mode->iv_blocks);
260   key= get_key(ip, key_obj, alg, want_bufferslen);  if (!key) return TCL_ERROR;
261
262   schedp= (alg->decrypt.make_schedule==alg->encrypt.make_schedule
263            || !decrypt) ? &key->alpha : &key->beta;
264   sched= *schedp;
265   if (!sched) {
266     if (key->valuelen < alg->key_min)
267       return cht_staticerr(ip, "key too short", "HBYTES BLOCKCIPHER PARAMS");
268     if (key->valuelen > alg->key_max)
269       return cht_staticerr(ip, "key too long", "HBYTES BLOCKCIPHER PARAMS");
270
271     sched= TALLOC(alg->schedule_size);
272     (decrypt ? &alg->decrypt : &alg->encrypt)->make_schedule
273       (sched, key->value, key->valuelen);
274     *schedp= sched;
275   }
276
277   want_iv= alg->blocksize * mode->iv_blocks;
278   if (!want_iv) {
279     if (!cht_hb_issentinel(iv))
280       return cht_staticerr(ip,"iv supplied but mode does not take one", 0);
281   } else if (cht_hb_issentinel(iv)) {
282     if (decrypt) return cht_staticerr(ip,"must supply iv when decrypting", 0);
283     rc= cht_get_urandom(ip, key->buffers, want_iv);
284     if (rc) return rc;
285   } else {
286     int iv_supplied= cht_hb_len(iv);
287     if (iv_supplied > want_iv)
288       return cht_staticerr(ip, "iv too large for algorithm and mode",
289                        "HBYTES BLOCKCIPHER PARAMS");
290     memcpy(key->buffers, cht_hb_data(iv), iv_supplied);
291     memset(key->buffers + iv_supplied, 0, want_iv - iv_supplied);
292   }
293
294   *key_r= key;
295   *sched_r= sched;
296
297   *iv_r= key->buffers;
298   *iv_lenbytes_r= want_iv;
299
300   *buffers_r= key->buffers + want_iv;
301   *nblocks_r= data_len / alg->blocksize;
302   
303   return TCL_OK;
304 }
305
306 int cht_do_blockcipherop_d(ClientData cd, Tcl_Interp *ip,
307                        HBytes_Var v, const BlockCipherAlgInfo *alg,
308                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
309                        HBytes_Value iv, HBytes_Value *result) {
310   return cht_do_blockcipherop_e(cd,ip,v,alg,key_obj,mode,iv,result);
311 }
312
313 int cht_do_blockcipherop_e(ClientData cd, Tcl_Interp *ip,
314                        HBytes_Var v, const BlockCipherAlgInfo *alg,
315                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
316                        HBytes_Value iv, HBytes_Value *result) {
317   const BlockCipherOp *op= (const void*)cd;
318   int encrypt= op->encrypt;
319   int rc, iv_lenbytes;
320   const CiphKeyValue *key;
321   const char *failure;
322   const Byte *ivbuf;
323   Byte *buffers;
324   const void *sched;
325   int nblocks;
326
327   if (!mode->encrypt)
328     return cht_staticerr(ip, "mode does not support encrypt/decrypt", 0);
329
330   rc= blockcipher_prep(ip,key_obj,&iv,!encrypt,
331                        alg,mode, cht_hb_len(v.hb),
332                        &key,&sched,
333                        &ivbuf,&iv_lenbytes,
334                        &buffers,&nblocks);
335   if (rc) return rc;
336   
337   failure=
338     (encrypt ? mode->encrypt : mode->decrypt)
339     (cht_hb_data(v.hb), nblocks, ivbuf, buffers, alg, encrypt, sched);
340
341   if (failure)
342     return cht_staticerr(ip, failure, "HBYTES BLOCKCIPHER CRYPTFAIL CRYPT");
343
344   cht_hb_array(result, ivbuf, iv_lenbytes);
345
346   return TCL_OK;
347 }
348
349 int cht_do_blockcipherop_mac(ClientData cd, Tcl_Interp *ip,
350                          HBytes_Value msg, const BlockCipherAlgInfo *alg,
351                          Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
352                          HBytes_Value iv, HBytes_Value *result) {
353   const CiphKeyValue *key;
354   const char *failure;
355   const Byte *ivbuf;
356   Byte *buffers;
357   const void *sched;
358   int nblocks, iv_lenbytes;
359   int rc;
360
361   if (!mode->mac)
362     return cht_staticerr(ip, "mode does not support mac generation", 0);
363   
364   rc= blockcipher_prep(ip,key_obj,&iv,0,
365                        alg,mode, cht_hb_len(&msg),
366                        &key,&sched,
367                        &ivbuf,&iv_lenbytes,
368                        &buffers,&nblocks);
369   if (rc) return rc;
370
371   failure= mode->mac(cht_hb_data(&msg), nblocks, ivbuf, buffers, alg, sched);
372   if (failure)
373     return cht_staticerr(ip,failure, "HBYTES BLOCKCIPHER CRYPTFAIL MAC");
374
375   cht_hb_array(result, buffers, alg->blocksize * mode->mac_blocks);
376
377   return TCL_OK;
378 }
379
380 int cht_do_hbcrypto_hmac(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
381                    HBytes_Value message, Tcl_Obj *key_obj,
382                    Tcl_Obj *maclen_obj, HBytes_Value *result) {
383   /* key->alpha = state after H(K XOR ipad <unfinished>
384    * key->beta = state after H(K XOR opad <unfinished>
385    * key->buffers = room for one block, or one state
386    */
387   CiphKeyValue *key;
388   Byte *dest;
389   int i, ml, rc;
390
391   if (maclen_obj) {
392     rc= Tcl_GetIntFromObj(ip, maclen_obj, &ml);  if (rc) return rc;
393     if (ml<0 || ml>alg->hashsize)
394       return cht_staticerr(ip, "requested hmac output size out of range",
395                        "HBYTES HMAC PARAMS");
396   } else {
397     ml= alg->hashsize;
398   }
399
400   key= get_key(ip, key_obj, alg,
401                alg->blocksize > alg->statesize
402                ? alg->blocksize : alg->statesize);
403
404   if (!key->alpha) {
405     assert(!key->beta);
406     
407     if (key->valuelen > alg->blocksize)
408       return cht_staticerr(ip, "key to hmac longer than hash block size",
409                        "HBYTES HMAC PARAMS");
410
411     memcpy(key->buffers, key->value, key->valuelen);
412     memset(key->buffers + key->valuelen, 0, alg->blocksize - key->valuelen);
413     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= 0x36;
414
415     key->alpha= TALLOC(alg->statesize);
416     alg->init(key->alpha);
417     alg->update(key->alpha, key->buffers, alg->blocksize);
418     
419     key->beta= TALLOC(alg->statesize);
420     alg->init(key->beta);
421     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= (0x5c ^ 0x36);
422     alg->update(key->beta, key->buffers, alg->blocksize);
423   }
424   assert(key->beta);
425
426   dest= cht_hb_arrayspace(result, alg->hashsize);
427
428   memcpy(key->buffers, key->alpha, alg->statesize);
429   alg->update(key->buffers, cht_hb_data(&message), cht_hb_len(&message));
430   alg->final(key->buffers, dest);
431
432   memcpy(key->buffers, key->beta, alg->statesize);
433   alg->update(key->buffers, dest, alg->hashsize);
434   alg->final(key->buffers, dest);
435
436   cht_hb_unappend(result, alg->hashsize - ml);
437
438   return TCL_OK;
439 }
440
441 int cht_do_blockcipherop_prop(ClientData cd, Tcl_Interp *ip,
442                           const BlockCipherPropInfo *prop,
443                           const BlockCipherAlgInfo *alg, int *result) {
444   *result= *(const int*)((const char*)alg + prop->int_offset);
445   return TCL_OK;
446 }
447
448 int cht_do_hbcrypto_hash_prop(ClientData cd, Tcl_Interp *ip,
449                         const HashAlgPropInfo *prop,
450                         const HashAlgInfo *alg, int *result) {
451   *result= *(const int*)((const char*)alg + prop->int_offset);
452   return TCL_OK;
453 }