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