chiark / gitweb /
ulong improved; clock arithmetic hbytes abolished; secnet responder implemented and...
[chiark-tcl.git] / crypto / crypto.c
1 /*
2  */
3
4 #include <endian.h>
5
6 #include "hbytes.h"
7 #include "tables.h"
8 #include "serpent.h"
9
10 void memxor(Byte *dest, const Byte *src, int l) {
11   while (l--) *dest++ ^= *src++;
12 }
13
14 const PadMethod padmethods[]= {
15   { "un", 0, 0 },
16   { "ua", 0, 1 },
17   { "pn", 1, 0 },
18   { "pa", 1, 1 },
19   { 0 }
20 };
21
22 int do_hbytes_pkcs5(ClientData cd, Tcl_Interp *ip,
23                     const PadMethod *meth, HBytes_Var v, Tcl_Obj *block,
24                     int *ok) {
25   int rc, blocksize, padlen, old_len, i;
26   Byte *padding;
27   const Byte *unpad;
28   
29   if (meth->use_algname) {
30     const BlockCipherAlgInfo *alg;
31     alg= enum_lookup_cached(ip,block,blockcipheralginfos,"cipher alg for pad");
32     if (!alg) return TCL_ERROR;
33     blocksize= alg->blocksize;
34   } else {
35     rc= Tcl_GetIntFromObj(ip, block, &blocksize);  if (rc) return rc;
36     if (blocksize < 1 || blocksize > 255)
37       return staticerr(ip, "block size out of pkcs#5 range 1..255");
38   }
39
40   if (meth->pad) {
41     padlen= blocksize - (hbytes_len(v.hb) % blocksize);
42     padding= hbytes_append(v.hb, padlen);
43     memset(padding, padlen, padlen);
44   } else {
45     old_len= hbytes_len(v.hb);  if (old_len % blocksize) goto bad;
46     unpad= hbytes_unappend(v.hb, 1);  if (!unpad) goto bad;
47     padlen= *unpad;
48     if (padlen < 1 || padlen > blocksize) goto bad;
49     unpad= hbytes_unappend(v.hb, padlen-1);  if (!unpad) goto bad;
50     for (i=0; i<padlen-1; i++, unpad++) if (*unpad != padlen) goto bad;
51   }
52
53   *ok= 1;
54   return TCL_OK;
55
56  bad:
57   *ok= 0;
58   return TCL_OK;
59 }
60
61 int do_hbytes_hash(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
62                    HBytes_Value message, HBytes_Value *result) {
63   Byte *dest;
64
65   dest= hbytes_arrayspace(result,alg->hashsize);
66   alg->oneshot(dest, hbytes_data(&message), hbytes_len(&message));
67   return TCL_OK;
68 }
69
70 #define OBJ_CIPHKEY(o) ((CiphKeyValue*)(o)->internalRep.otherValuePtr)
71
72 typedef struct {
73   int valuelen, bufferslen;
74   Byte *value, *buffers;
75   const void *alg;
76   void *alpha, *beta; /* key schedules etc.; each may be 0 */
77 } CiphKeyValue;
78
79 static void freealg(CiphKeyValue *key) {
80   TFREE(key->alpha);
81   TFREE(key->beta);
82 }
83
84 static void key_t_free(Tcl_Obj *obj) {
85   CiphKeyValue *key= OBJ_CIPHKEY(obj);
86   freealg(key);
87   TFREE(key->value);
88   TFREE(key->buffers);
89 }
90
91 static void noalg(CiphKeyValue *key) {
92   key->alg= 0;
93   key->alpha= key->beta= 0;
94 }
95
96 static void key_t_dup(Tcl_Obj *src_obj, Tcl_Obj *dup_obj) {
97   CiphKeyValue *src= OBJ_CIPHKEY(src_obj);
98   CiphKeyValue *dup= TALLOC(sizeof(*dup));
99   dup->valuelen= src->valuelen;
100   dup->value= src->valuelen ? TALLOC(src->valuelen) : 0;
101   dup->buffers= 0; dup->bufferslen= 0;
102   memcpy(dup->value, src->value, src->valuelen);
103   noalg(dup);
104   dup_obj->internalRep.otherValuePtr= dup;
105   dup_obj->typePtr= &blockcipherkey_type;
106 }
107
108 static void key_t_ustr(Tcl_Obj *o) {
109   obj_updatestr_array(o, OBJ_CIPHKEY(o)->value, OBJ_CIPHKEY(o)->valuelen);
110 }
111
112 static int key_t_sfa(Tcl_Interp *ip, Tcl_Obj *o) {
113   int rc, l;
114   CiphKeyValue *val;
115
116   rc= Tcl_ConvertToType(ip,o,&hbytes_type);  if (rc) return rc;
117   val= TALLOC(sizeof(*val));
118   val->valuelen= l= hbytes_len(OBJ_HBYTES(o));
119   val->value= TALLOC(l);
120   val->buffers= 0;
121   val->bufferslen= 0;
122   memcpy(val->value, hbytes_data(OBJ_HBYTES(o)), l);
123   noalg(val);
124
125   objfreeir(o);
126   o->internalRep.otherValuePtr= val;
127   o->typePtr= &blockcipherkey_type;
128
129   return TCL_OK;
130 }
131   
132 Tcl_ObjType blockcipherkey_type = {
133   "blockcipher-key",
134   key_t_free, key_t_dup, key_t_ustr, key_t_sfa
135 };
136
137 static CiphKeyValue *get_key(Tcl_Interp *ip, Tcl_Obj *key_obj,
138                              const void *alg, int want_bufferslen) {
139   CiphKeyValue *key;
140   int rc;
141   
142   rc= Tcl_ConvertToType(ip,key_obj,&blockcipherkey_type);  if (rc) return 0;
143   key= OBJ_CIPHKEY(key_obj);
144
145   if (key->alg != alg) {
146     freealg(key);
147     noalg(key);
148     key->alg= alg;
149   }
150   
151   if (key->bufferslen < want_bufferslen) {
152     TFREE(key->buffers);
153     key->buffers= TALLOC(want_bufferslen);
154     key->bufferslen= want_bufferslen;
155   }
156   return key;
157 }
158
159 int do_hbytes_blockcipher(ClientData cd, Tcl_Interp *ip,
160                           const BlockCipherOp *op,
161                           int objc, Tcl_Obj *const *objv) {
162   return op->func((void*)op,ip,objc,objv);
163 }
164
165 static int blockcipher_prep(Tcl_Interp *ip, Tcl_Obj *key_obj,
166                             const HBytes_Value *iv, int decrypt,
167                             const BlockCipherAlgInfo *alg,
168                             const BlockCipherModeInfo *mode, int data_len,
169                             const CiphKeyValue **key_r, const void **sched_r,
170                             const Byte **iv_r, int *iv_lenbytes_r,
171                             Byte **buffers_r, int *nblocks_r) {
172   void *sched, **schedp;
173   int want_bufferslen, want_iv;
174   int rc;
175   CiphKeyValue *key;
176
177   if (data_len % alg->blocksize)
178     return staticerr(ip, "block cipher input not whole number of blocks");
179
180   want_bufferslen= alg->blocksize * (mode->buf_blocks + mode->iv_blocks);
181   key= get_key(ip, key_obj, alg, want_bufferslen);  if (!key) return TCL_ERROR;
182
183   schedp= (alg->decrypt.make_schedule==alg->encrypt.make_schedule
184            || !decrypt) ? &key->alpha : &key->beta;
185   sched= *schedp;
186   if (!sched) {
187     if (key->valuelen < alg->key_min) return staticerr(ip, "key too short");
188     if (key->valuelen > alg->key_max) return staticerr(ip, "key too long");
189
190     sched= TALLOC(alg->schedule_size);
191     (decrypt ? &alg->decrypt : &alg->encrypt)->make_schedule
192       (sched, key->value, key->valuelen);
193     *schedp= sched;
194   }
195
196   want_iv= alg->blocksize * mode->iv_blocks;
197   if (!want_iv) {
198     if (!hbytes_issentinel(iv))
199       return staticerr(ip,"iv supplied but mode does not take one");
200   } else if (hbytes_issentinel(iv)) {
201     if (decrypt) return staticerr(ip,"must supply iv when decrypting");
202     rc= get_urandom(ip, key->buffers, want_iv);
203     if (rc) return rc;
204   } else {
205     int iv_supplied= hbytes_len(iv);
206     if (iv_supplied > want_iv)
207       return staticerr(ip, "iv too large for algorithm and mode");
208     memcpy(key->buffers, hbytes_data(iv), iv_supplied);
209     memset(key->buffers + iv_supplied, 0, want_iv - iv_supplied);
210   }
211
212   *key_r= key;
213   *sched_r= sched;
214
215   *iv_r= key->buffers;
216   *iv_lenbytes_r= want_iv;
217
218   *buffers_r= key->buffers + want_iv;
219   *nblocks_r= data_len / alg->blocksize;
220   
221   return TCL_OK;
222 }
223
224 int do_blockcipherop_d(ClientData cd, Tcl_Interp *ip,
225                        HBytes_Var v, const BlockCipherAlgInfo *alg,
226                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
227                        HBytes_Value iv, HBytes_Value *result) {
228   return do_blockcipherop_e(cd,ip,v,alg,key_obj,mode,iv,result);
229 }
230
231 int do_blockcipherop_e(ClientData cd, Tcl_Interp *ip,
232                        HBytes_Var v, const BlockCipherAlgInfo *alg,
233                        Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
234                        HBytes_Value iv, HBytes_Value *result) {
235   const BlockCipherOp *op= (const void*)cd;
236   int encrypt= op->encrypt;
237   int rc, iv_lenbytes;
238   const CiphKeyValue *key;
239   const char *failure;
240   const Byte *ivbuf;
241   Byte *buffers;
242   const void *sched;
243   int nblocks;
244
245   if (!mode->encrypt)
246     return staticerr(ip, "mode does not support encrypt/decrypt");
247
248   rc= blockcipher_prep(ip,key_obj,&iv,!encrypt,
249                        alg,mode, hbytes_len(v.hb),
250                        &key,&sched,
251                        &ivbuf,&iv_lenbytes,
252                        &buffers,&nblocks);
253   if (rc) return rc;
254   
255   failure=
256     (encrypt ? mode->encrypt : mode->decrypt)
257     (hbytes_data(v.hb), nblocks, ivbuf, buffers, alg, encrypt, sched);
258
259   if (failure)
260     return staticerr(ip, failure);
261
262   hbytes_array(result, ivbuf, iv_lenbytes);
263
264   return TCL_OK;
265 }
266
267 int do_blockcipherop_mac(ClientData cd, Tcl_Interp *ip,
268                          HBytes_Value msg, const BlockCipherAlgInfo *alg,
269                          Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
270                          HBytes_Value iv, HBytes_Value *result) {
271   const CiphKeyValue *key;
272   const char *failure;
273   const Byte *ivbuf;
274   Byte *buffers;
275   const void *sched;
276   int nblocks, iv_lenbytes;
277   int rc;
278
279   if (!mode->mac)
280     return staticerr(ip, "mode does not support mac generation");
281   
282   rc= blockcipher_prep(ip,key_obj,&iv,0,
283                        alg,mode, hbytes_len(&msg),
284                        &key,&sched,
285                        &ivbuf,&iv_lenbytes,
286                        &buffers,&nblocks);
287   if (rc) return rc;
288
289   failure= mode->mac(hbytes_data(&msg), nblocks, ivbuf, buffers, alg, sched);
290   if (failure)
291     return staticerr(ip,failure);
292
293   hbytes_array(result, buffers, alg->blocksize * mode->mac_blocks);
294
295   return TCL_OK;
296 }
297
298 static void dbuf(const char *m, const Byte *a, int l) {
299   fprintf(stderr,"dbuf %s l=%d ",m,l);
300   while (l-->0) fprintf(stderr,"%02x",*a++);
301   putc('\n',stderr);
302 }
303
304 int do_hbytes_hmac(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
305                    HBytes_Value message, Tcl_Obj *key_obj,
306                    Tcl_Obj *maclen_obj, HBytes_Value *result) {
307   /* key->alpha = state after H(K XOR ipad <unfinished>
308    * key->beta = state after H(K XOR opad <unfinished>
309    * key->buffers = room for one block, or one state
310    */
311   CiphKeyValue *key;
312   Byte *dest;
313   int i, ml, rc;
314
315   if (maclen_obj) {
316     rc= Tcl_GetIntFromObj(ip, maclen_obj, &ml);  if (rc) return rc;
317     if (ml<0 || ml>alg->hashsize)
318       return staticerr(ip, "requested hmac output size out of range");
319   } else {
320     ml= alg->hashsize;
321   }
322
323   key= get_key(ip, key_obj, alg,
324                alg->blocksize > alg->statesize
325                ? alg->blocksize : alg->statesize);
326
327   if (!key->alpha) {
328     assert(!key->beta);
329     
330     if (key->valuelen > alg->blocksize)
331       return staticerr(ip, "key to hmac longer than hash block size");
332
333 dbuf("start key",key->value,key->valuelen);
334     memcpy(key->buffers, key->value, key->valuelen);
335     memset(key->buffers + key->valuelen, 0, alg->blocksize - key->valuelen);
336     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= 0x36;
337
338     key->alpha= TALLOC(alg->statesize);
339     alg->init(key->alpha);
340 dbuf("inner key",key->buffers,alg->blocksize);
341     alg->update(key->alpha, key->buffers, alg->blocksize);
342     
343     key->beta= TALLOC(alg->statesize);
344     alg->init(key->beta);
345     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= (0x5c ^ 0x36);
346     alg->update(key->beta, key->buffers, alg->blocksize);
347 dbuf("inner key",key->buffers,alg->blocksize);
348   }
349   assert(key->beta);
350
351   dest= hbytes_arrayspace(result, alg->hashsize);
352
353   memcpy(key->buffers, key->alpha, alg->statesize);
354   alg->update(key->buffers, hbytes_data(&message), hbytes_len(&message));
355   alg->final(key->buffers, dest);
356 dbuf("inner hash",dest,alg->hashsize);
357
358   memcpy(key->buffers, key->beta, alg->statesize);
359   alg->update(key->buffers, dest, alg->hashsize);
360   alg->final(key->buffers, dest);
361 dbuf("outer hash",dest,alg->hashsize);
362
363   hbytes_unappend(result, alg->hashsize - ml);
364
365   return TCL_OK;
366 }