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