chiark / gitweb /
Ripped out a lot of crap. Now it compiles and passes the test vectors.
[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 }
106
107 static void key_t_ustr(Tcl_Obj *o) {
108   obj_updatestr_array(o, OBJ_CIPHKEY(o)->value, OBJ_CIPHKEY(o)->valuelen);
109 }
110
111 static int key_t_sfa(Tcl_Interp *ip, Tcl_Obj *o) {
112   int rc, l;
113   CiphKeyValue *val;
114
115   rc= Tcl_ConvertToType(ip,o,&hbytes_type);  if (rc) return rc;
116   val= TALLOC(sizeof(*val));
117   val->valuelen= l= hbytes_len(OBJ_HBYTES(o));
118   val->value= TALLOC(l);
119   val->buffers= 0;
120   val->bufferslen= 0;
121   memcpy(val->value, hbytes_data(OBJ_HBYTES(o)), l);
122   noalg(val);
123
124   objfreeir(o);
125   o->internalRep.otherValuePtr= val;
126   o->typePtr= &blockcipherkey_type;
127
128   return TCL_OK;
129 }
130   
131 Tcl_ObjType blockcipherkey_type = {
132   "blockcipher-key",
133   key_t_free, key_t_dup, key_t_ustr, key_t_sfa
134 };
135
136 static CiphKeyValue *get_key(Tcl_Interp *ip, Tcl_Obj *key_obj,
137                              const void *alg, int want_bufferslen) {
138   CiphKeyValue *key;
139   int rc;
140   
141   rc= Tcl_ConvertToType(ip,key_obj,&blockcipherkey_type);  if (rc) return 0;
142   key= OBJ_CIPHKEY(key_obj);
143
144   if (key->alg != alg) {
145     freealg(key);
146     noalg(key);
147     key->alg= alg;
148   }
149   
150   if (key->bufferslen < want_bufferslen) {
151     TFREE(key->buffers);
152     key->buffers= TALLOC(want_bufferslen);
153     key->bufferslen= want_bufferslen;
154   }
155   return key;
156 }
157
158 int do_hbytes_blockcipher(ClientData cd, Tcl_Interp *ip, int encrypt,
159                           HBytes_Var v, const BlockCipherAlgInfo *alg,
160                           Tcl_Obj *key_obj, const BlockCipherModeInfo *mode,
161                           HBytes_Value iv, HBytes_Value *result) {
162   int rc, want_bufferslen, data_len, iv_want;
163   CiphKeyValue *key;
164   const char *failure;
165   void *sched, **schedp;
166
167   want_bufferslen= alg->blocksize * (mode->buf_blocks + mode->iv_blocks);
168   key= get_key(ip, key_obj, alg, want_bufferslen);  if (!key) return TCL_ERROR;
169
170   schedp= (alg->decrypt.make_schedule==alg->encrypt.make_schedule
171            || encrypt) ? &key->alpha : &key->beta;
172   sched= *schedp;
173   if (!sched) {
174     if (key->valuelen < alg->key_min) return staticerr(ip, "key too short");
175     if (key->valuelen > alg->key_max) return staticerr(ip, "key too long");
176
177     sched= TALLOC(alg->schedule_size);
178     (encrypt ? &alg->encrypt : &alg->decrypt)->make_schedule
179       (sched, key->value, key->valuelen);
180     *schedp= sched;
181   }
182
183   iv_want= alg->blocksize * mode->iv_blocks;
184   if (!iv_want) {
185     if (!hbytes_issentinel(&iv))
186       return staticerr(ip,"iv supplied but mode does not take one");
187   } else if (hbytes_issentinel(&iv)) {
188     if (!encrypt) return staticerr(ip,"must supply iv when decrypting");
189     rc= get_urandom(ip, key->buffers, iv_want);
190     if (rc) return rc;
191   } else {
192     int iv_supplied= hbytes_len(&iv);
193     if (iv_supplied > iv_want)
194       return staticerr(ip, "iv too large for algorithm and mode");
195     memcpy(key->buffers, hbytes_data(&iv), iv_supplied);
196     memset(key->buffers + iv_supplied, 0, iv_want - iv_supplied);
197   }
198
199   data_len= hbytes_len(v.hb);
200   if (data_len % alg->blocksize)
201     return staticerr(ip, "block cipher input not whole number of blocks");
202
203   failure=
204     (encrypt ? mode->encrypt : mode->decrypt)
205     (hbytes_data(v.hb), data_len / alg->blocksize,
206      key->buffers, key->buffers + iv_want,
207      alg, encrypt,
208      alg->blocksize, sched);
209
210   if (failure)
211     return staticerr(ip, failure);
212
213   hbytes_array(result, key->buffers, iv_want);
214
215   return TCL_OK;
216 }
217
218 static void dbuf(const char *m, const Byte *a, int l) {
219   fprintf(stderr,"dbuf %s l=%d ",m,l);
220   while (l-->0) fprintf(stderr,"%02x",*a++);
221   putc('\n',stderr);
222 }
223
224 int do_hbytes_hmac(ClientData cd, Tcl_Interp *ip, const HashAlgInfo *alg,
225                    HBytes_Value message, Tcl_Obj *key_obj,
226                    Tcl_Obj *maclen_obj, HBytes_Value *result) {
227   /* key->alpha = state after H(K XOR ipad <unfinished>
228    * key->beta = state after H(K XOR opad <unfinished>
229    * key->buffers = room for one block, or one state
230    */
231   CiphKeyValue *key;
232   Byte *dest;
233   int i, ml, rc;
234
235   if (maclen_obj) {
236     rc= Tcl_GetIntFromObj(ip, maclen_obj, &ml);  if (rc) return rc;
237     if (ml<0 || ml>alg->hashsize)
238       return staticerr(ip, "requested hmac output size out of range");
239   } else {
240     ml= alg->hashsize;
241   }
242
243   key= get_key(ip, key_obj, alg,
244                alg->blocksize > alg->statesize
245                ? alg->blocksize : alg->statesize);
246
247   if (!key->alpha) {
248     assert(!key->beta);
249     
250     if (key->valuelen > alg->blocksize)
251       return staticerr(ip, "key to hmac longer than hash block size");
252
253 dbuf("start key",key->value,key->valuelen);
254     memcpy(key->buffers, key->value, key->valuelen);
255     memset(key->buffers + key->valuelen, 0, alg->blocksize - key->valuelen);
256     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= 0x36;
257
258     key->alpha= TALLOC(alg->statesize);
259     alg->init(key->alpha);
260 dbuf("inner key",key->buffers,alg->blocksize);
261     alg->update(key->alpha, key->buffers, alg->blocksize);
262     
263     key->beta= TALLOC(alg->statesize);
264     alg->init(key->beta);
265     for (i=0; i<alg->blocksize; i++) key->buffers[i] ^= (0x5c ^ 0x36);
266     alg->update(key->beta, key->buffers, alg->blocksize);
267 dbuf("inner key",key->buffers,alg->blocksize);
268   }
269   assert(key->beta);
270
271   dest= hbytes_arrayspace(result, alg->hashsize);
272
273   memcpy(key->buffers, key->alpha, alg->statesize);
274   alg->update(key->buffers, hbytes_data(&message), hbytes_len(&message));
275   alg->final(key->buffers, dest);
276 dbuf("inner hash",dest,alg->hashsize);
277
278   memcpy(key->buffers, key->beta, alg->statesize);
279   alg->update(key->buffers, dest, alg->hashsize);
280   alg->final(key->buffers, dest);
281 dbuf("outer hash",dest,alg->hashsize);
282
283   hbytes_unappend(result, alg->hashsize - ml);
284
285   return TCL_OK;
286 }