chiark / gitweb /
working on making xargs work
[chiark-tcl.git] / crypto / crypto.c
1 /*
2  */
3
4 #include <endian.h>
5
6 #include "hbytes.h"
7 #include "tables.h"
8
9 void memxor(Byte *dest, const Byte *src, int l) {
10   while (l--) *dest++ ^= *src++;
11 }
12
13 const PadOp padops[]= {
14   { "un", 0, 0 },
15   { "ua", 0, 1 },
16   { "pn", 1, 0 },
17   { "pa", 1, 1 },
18   { 0 }
19 };
20
21 typedef struct {
22   HBytes_Value *hb;
23   int pad, blocksize; /* 0 or 1 */
24 } PadMethodClientData;
25
26 int do_hbytes_pad(ClientData cd, Tcl_Interp *ip, const PadOp *op,
27                   HBytes_Var v, Tcl_Obj *blocksz, const PadMethodInfo *meth,
28                   int methargsc, Tcl_Obj *const *methargsv) {
29   PadMethodClientData pmcd;
30   int rc;
31   
32   if (op->use_algname) {
33     const BlockCipherAlgInfo *alg;
34     alg= enum_lookup_cached(ip,blocksz,blockcipheralginfos,
35                             "blockcipher alg for pad");
36     if (!alg) return TCL_ERROR;
37     pmcd.blocksize= alg->blocksize;
38   } else {
39     rc= Tcl_GetIntFromObj(ip, blocksz, &pmcd.blocksize);  if (rc) return rc;
40     if (pmcd.blocksize < 1) staticerr(ip, "block size must be at least 1", 0);
41   }
42
43   pmcd.hb= v.hb;
44   pmcd.pad= op->pad;
45
46   return meth->func(&pmcd,ip,methargsc,methargsv);
47 }
48   
49 int do_padmethodinfo_rfc2406(ClientData cd, Tcl_Interp *ip,
50                              Tcl_Obj *nxthdr_arg, int *ok) {
51   const PadMethodClientData *pmcd= (const void*)cd;
52   int i, rc, padlen, old_len;
53   
54   if (pmcd->blocksize > 256)
55     return staticerr(ip, "block size too large for RFC2406 padding", 0);
56
57   if (pmcd->pad) {
58     Byte *padding;
59     HBytes_Value nxthdr;
60
61     rc= pat_hb(ip,nxthdr_arg,&nxthdr);
62     if (rc) return rc;
63
64     if (hbytes_len(&nxthdr) != 1) return
65       staticerr(ip, "RFC2406 next header field must be exactly 1 byte", 0);
66     padlen= pmcd->blocksize-1 - ((hbytes_len(pmcd->hb)+1) % pmcd->blocksize);
67     padding= hbytes_append(pmcd->hb, padlen+2);
68     for (i=1; i<=padlen; i++)
69       *padding++ = i;
70     *padding++ = padlen;
71     *padding++ = hbytes_data(&nxthdr)[0];
72     *ok= 1;
73     
74   } else {
75     const Byte *padding, *trailer;
76     HBytes_Value nxthdr;
77     Tcl_Obj *nxthdr_valobj, *ro;
78     
79     *ok= 0;
80     old_len= hbytes_len(pmcd->hb);  if (old_len % pmcd->blocksize) goto quit;
81     trailer= hbytes_unappend(pmcd->hb, 2); if (!trailer) goto quit;
82
83     padlen= trailer[0];
84     hbytes_array(&nxthdr,trailer+1,1);
85     nxthdr_valobj= ret_hb(ip,nxthdr);
86     ro= Tcl_ObjSetVar2(ip,nxthdr_arg,0,nxthdr_valobj,TCL_LEAVE_ERR_MSG);
87     if (!ro) { Tcl_DecrRefCount(nxthdr_valobj); return TCL_ERROR; }
88
89     padding= hbytes_unappend(pmcd->hb, padlen);
90     for (i=1; i<=padlen; i++)
91       if (*padding++ != i) goto quit;
92
93     *ok= 1;
94
95   quit:;
96
97   }
98
99   return TCL_OK;
100 }
101
102 int do_padmethodinfo_pkcs5(ClientData cd, Tcl_Interp *ip, int *ok) {
103   const PadMethodClientData *pmcd= (const void*)cd;
104   int padlen, old_len, i;
105   
106   if (pmcd->blocksize > 255)
107     return staticerr(ip, "block size too large for pkcs#5", 0);
108
109   if (pmcd->pad) {
110
111     Byte *padding;
112
113     padlen= pmcd->blocksize - (hbytes_len(pmcd->hb) % pmcd->blocksize);
114     padding= hbytes_append(pmcd->hb, padlen);
115     memset(padding, padlen, padlen);
116
117   } else {
118
119     const Byte *padding;
120
121     old_len= hbytes_len(pmcd->hb);  if (old_len % pmcd->blocksize) goto bad;
122     padding= hbytes_unappend(pmcd->hb, 1);  if (!padding) goto bad;
123     padlen= *padding;
124     if (padlen < 1 || padlen > pmcd->blocksize) goto bad;
125     padding= hbytes_unappend(pmcd->hb, padlen-1);  if (!padding) goto bad;
126
127     for (i=0; i<padlen-1; i++, padding++) if (*padding != padlen) goto bad;
128
129   }
130
131   *ok= 1;
132   return TCL_OK;
133
134  bad:
135   *ok= 0;
136   return TCL_OK;
137 }
138
139 int do_hbytes_hash(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
140                    HBytes_Value message, HBytes_Value *result) {
141   Byte *dest;
142
143   dest= hbytes_arrayspace(result,alg->hashsize);
144   alg->oneshot(dest, hbytes_data(&message), hbytes_len(&message));
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= &blockcipherkey_type;
184 }
185
186 static void key_t_ustr(Tcl_Obj *o) {
187   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,&hbytes_type);  if (rc) return rc;
195   val= TALLOC(sizeof(*val));
196   val->valuelen= l= hbytes_len(OBJ_HBYTES(o));
197   val->value= TALLOC(l);
198   val->buffers= 0;
199   val->bufferslen= 0;
200   memcpy(val->value, hbytes_data(OBJ_HBYTES(o)), l);
201   noalg(val);
202
203   objfreeir(o);
204   o->internalRep.otherValuePtr= val;
205   o->typePtr= &blockcipherkey_type;
206
207   return TCL_OK;
208 }
209   
210 Tcl_ObjType 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,&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 do_hbytes_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 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 staticerr(ip, "key too short", "HBYTES BLOCKCIPHER PARAMS");
268     if (key->valuelen > alg->key_max)
269       return 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 (!hbytes_issentinel(iv))
280       return staticerr(ip,"iv supplied but mode does not take one", 0);
281   } else if (hbytes_issentinel(iv)) {
282     if (decrypt) return staticerr(ip,"must supply iv when decrypting", 0);
283     rc= get_urandom(ip, key->buffers, want_iv);
284     if (rc) return rc;
285   } else {
286     int iv_supplied= hbytes_len(iv);
287     if (iv_supplied > want_iv)
288       return staticerr(ip, "iv too large for algorithm and mode",
289                        "HBYTES BLOCKCIPHER PARAMS");
290     memcpy(key->buffers, hbytes_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 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 do_blockcipherop_e(cd,ip,v,alg,key_obj,mode,iv,result);
311 }
312
313 int 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 staticerr(ip, "mode does not support encrypt/decrypt", 0);
329
330   rc= blockcipher_prep(ip,key_obj,&iv,!encrypt,
331                        alg,mode, hbytes_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     (hbytes_data(v.hb), nblocks, ivbuf, buffers, alg, encrypt, sched);
340
341   if (failure)
342     return staticerr(ip, failure, "HBYTES BLOCKCIPHER CRYPTFAIL CRYPT");
343
344   hbytes_array(result, ivbuf, iv_lenbytes);
345
346   return TCL_OK;
347 }
348
349 int 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 staticerr(ip, "mode does not support mac generation", 0);
363   
364   rc= blockcipher_prep(ip,key_obj,&iv,0,
365                        alg,mode, hbytes_len(&msg),
366                        &key,&sched,
367                        &ivbuf,&iv_lenbytes,
368                        &buffers,&nblocks);
369   if (rc) return rc;
370
371   failure= mode->mac(hbytes_data(&msg), nblocks, ivbuf, buffers, alg, sched);
372   if (failure)
373     return staticerr(ip,failure, "HBYTES BLOCKCIPHER CRYPTFAIL MAC");
374
375   hbytes_array(result, buffers, alg->blocksize * mode->mac_blocks);
376
377   return TCL_OK;
378 }
379
380 int do_hbytes_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 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 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= hbytes_arrayspace(result, alg->hashsize);
427
428   memcpy(key->buffers, key->alpha, alg->statesize);
429   alg->update(key->buffers, hbytes_data(&message), hbytes_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   hbytes_unappend(result, alg->hashsize - ml);
437
438   return TCL_OK;
439 }
440
441 int 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 do_hbytes_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 }