chiark / gitweb /
6da6cc0f3f8a33e3f592ca716c53835e50c0f456
[tripe] / server / keyset.c
1 /* -*-c-*-
2  *
3  * Handling of symmetric keysets
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "tripe.h"
30
31 /*----- Handy macros ------------------------------------------------------*/
32
33 #define KEYOK(ks, now) ((ks)->sz_exp > 0 && (ks)->t_exp > now)
34
35 /*----- Low-level packet encryption and decryption ------------------------*/
36
37 /* --- Encrypted data format --- *
38  *
39  * Let %$p_i$% be the %$i$%-th plaintext message, with type %$t$%.  We first
40  * compute
41  *
42  *   %$c_i = \mathcal{E}\textrm{-CBC}_{K_{\text{E}}}(p_i)$%
43  *
44  * as the CBC-ciphertext of %$p_i$%, and then
45  *
46  *   %$\sigma_i = \mathcal{T}_{K_{\text{M}}}(t, i, c_i)$%
47  *
48  * as a MAC on the %%\emph{ciphertext}%%.  The message sent is then the pair
49  * %$(\sigma_i, c_i)$%.  This construction is provably secure in the NM-CCA
50  * sense (assuming that the cipher is IND-CPA, and the MAC is SUF-CMA)
51  * [Bellare and Namprempre].
52  *
53  * This also ensures that, assuming the key is good, we have a secure channel
54  * [Krawczyk].  Actually, [Krawczyk] shows that, if the cipher is either a
55  * simple stream cipher or a block cipher in CBC mode, we can use the MAC-
56  * then-encrypt scheme and still have a secure channel.  However, I like the
57  * NM-CCA guarantee from [Bellare and Namprempre].  I'm less worried about
58  * the Horton Principle [Wagner and Schneier].
59  */
60
61 /* --- @doencrypt@ --- *
62  *
63  * Arguments:   @keyset *ks@ = pointer to keyset to use
64  *              @unsigned ty@ = type of message this is
65  *              @buf *b@ = pointer to an input buffer
66  *              @buf *bb@ = pointer to an output buffer
67  *
68  * Returns:     Zero if OK; @KSERR_REGEN@ if it's time to generate new keys.
69  *              Also returns zero if there was insufficient buffer space, but
70  *              the buffer is broken in this case.
71  *
72  * Use:         Encrypts a message with the given key.  We assume that the
73  *              keyset is OK to use.
74  */
75
76 static int doencrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
77 {
78   int rc;
79   size_t sz = BLEFT(b);
80   size_t osz, nsz;
81
82   /* --- Initial tracing --- */
83
84   IF_TRACING(T_KEYSET, {
85     trace(T_KEYSET,
86           "keyset: encrypting packet %lu (type %u) using keyset %u",
87           (unsigned long)ks->oseq, ty, ks->seq);
88     trace_block(T_CRYPTO, "crypto: plaintext packet", BCUR(b), sz);
89   })
90
91   /* --- Apply the bulk-crypto transformation --- */
92
93   rc = ks->bulk->encrypt(ks, ty, b, bb);
94   if (rc || !BOK(bb)) return (rc);
95
96   /* --- Do the necessary accounting for data volume --- */
97
98   osz = ks->sz_exp;
99   nsz = osz > sz ? osz - sz : 0;
100   if (osz >= ks->sz_regen && ks->sz_regen > nsz) {
101     T( trace(T_KEYSET, "keyset: keyset %u data regen limit exceeded -- "
102              "forcing exchange", ks->seq); )
103     rc = KSERR_REGEN;
104   }
105   ks->sz_exp = nsz;
106
107   /* --- We're done --- */
108
109   return (rc);
110 }
111
112 /* --- @dodecrypt@ --- *
113  *
114  * Arguments:   @keyset *ks@ = pointer to keyset to use
115  *              @unsigned ty@ = expected type code
116  *              @buf *b@ = pointer to an input buffer
117  *              @buf *bb@ = pointer to an output buffer
118  *              @uint32 *seq@ = where to store the sequence number
119  *
120  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.
121  *
122  * Use:         Attempts to decrypt a message with the given key.  No other
123  *              checking (e.g., sequence number checks) is performed.  We
124  *              assume that the keyset is OK to use, and that there is
125  *              sufficient output buffer space reserved.  If the decryption
126  *              is successful, the buffer pointer is moved past the decrypted
127  *              packet, and the packet's sequence number is stored in @*seq@.
128  */
129
130 static int dodecrypt(keyset *ks, unsigned ty, buf *b, buf *bb, uint32 *seq)
131 {
132   const octet *q = BCUR(bb);
133   int rc;
134
135   IF_TRACING(T_KEYSET, {
136     trace(T_KEYSET,
137           "keyset: try decrypting packet (type %u) using keyset %u",
138           ty, ks->seq);
139     trace_block(T_CRYPTO, "crypto: ciphertext packet", BCUR(b), BLEFT(b));
140   })
141
142   rc = ks->bulk->decrypt(ks, ty, b, bb, seq);
143   if (rc) return (rc);
144
145   IF_TRACING(T_KEYSET, {
146     trace(T_KEYSET, "keyset: decrypted OK (sequence = %lu)",
147           (unsigned long)*seq);
148     trace_block(T_CRYPTO, "crypto: decrypted packet", q, BCUR(bb) - q);
149   })
150   return (0);
151 }
152
153 /*----- Operations on a single keyset -------------------------------------*/
154
155 /* --- @ks_drop@ --- *
156  *
157  * Arguments:   @keyset *ks@ = pointer to a keyset
158  *
159  * Returns:     ---
160  *
161  * Use:         Decrements a keyset's reference counter.  If the counter hits
162  *              zero, the keyset is freed.
163  */
164
165 void ks_drop(keyset *ks)
166 {
167   if (--ks->ref)
168     return;
169
170 #define DROP(dir, a, drop) do { if (ks->dir.a) drop(ks->dir.a); } while (0)
171 #define DROP_DIR(dir) do {                                              \
172   DROP(dir, c, GC_DESTROY);                                             \
173   DROP(dir, m, GM_DESTROY);                                             \
174 } while (0)
175
176   DROP_DIR(in);
177   DROP_DIR(out);
178
179 #undef DROP
180 #undef DROP_DIR
181
182   DESTROY(ks);
183 }
184
185 /* --- @ks_gen@ --- *
186  *
187  * Arguments:   @const void *k@ = pointer to key material
188  *              @size_t x, y, z@ = offsets into key material (see below)
189  *              @peer *p@ = pointer to peer information
190  *
191  * Returns:     A pointer to the new keyset.
192  *
193  * Use:         Derives a new keyset from the given key material.  The
194  *              offsets @x@, @y@ and @z@ separate the key material into three
195  *              parts.  Between the @k@ and @k + x@ is `my' contribution to
196  *              the key material; between @k + x@ and @k + y@ is `your'
197  *              contribution; and between @k + y@ and @k + z@ is a shared
198  *              value we made together.  These are used to construct two
199  *              pairs of symmetric keys.  Each pair consists of an encryption
200  *              key and a message authentication key.  One pair is used for
201  *              outgoing messages, the other for incoming messages.
202  *
203  *              The new key is marked so that it won't be selected for output
204  *              by @ksl_encrypt@.  You can still encrypt data with it by
205  *              calling @ks_encrypt@ directly.
206  */
207
208 static void gen_dir(const algswitch *algs, struct ksdir *ksd,
209                     const char *whichdir,
210                     const octet *from, size_t fromsz,
211                     const octet *to, size_t tosz,
212                     const octet *both, size_t bothsz)
213 {
214 #define SETKEY(what, a, init) do {                                      \
215   ghash *_h;                                                            \
216   octet *_hh;                                                           \
217                                                                         \
218   if (!algs->a)                                                         \
219     ksd->a = 0;                                                         \
220   else {                                                                \
221     _h = GH_INIT(algs->h);                                              \
222     HASH_STRING(_h, "tripe-" what);                                     \
223     GH_HASH(_h, from, fromsz);                                          \
224     GH_HASH(_h, to, tosz);                                              \
225     GH_HASH(_h, both, bothsz);                                          \
226     _hh = GH_DONE(_h, 0);                                               \
227     IF_TRACING(T_KEYSET, { IF_TRACING(T_CRYPTO, {                       \
228       char _buf[32];                                                    \
229       sprintf(_buf, "crypto: %s key " what, whichdir);                  \
230       trace_block(T_CRYPTO, _buf, _hh, algs->a##ksz);                   \
231     }) })                                                               \
232     ksd->a = init(algs->a, _hh, algs->a##ksz);                          \
233     GH_DESTROY(_h);                                                     \
234   }                                                                     \
235 } while (0)
236
237   SETKEY("encryption", c, GC_INIT);
238   SETKEY("integrity", m, GM_KEY);
239
240 #undef SETKEY
241 }
242
243 keyset *ks_gen(const void *k, size_t x, size_t y, size_t z, peer *p)
244 {
245   keyset *ks = CREATE(keyset);
246   time_t now = time(0);
247   const octet *pp = k;
248   const algswitch *algs = &p->kx.kpriv->algs;
249   T( static unsigned seq = 0; )
250
251   T( trace(T_KEYSET, "keyset: adding new keyset %u", seq); )
252
253   gen_dir(algs, &ks->in, "incoming", pp, x, pp + x, y - x, pp + y, z - y);
254   gen_dir(algs, &ks->out, "outgoing", pp + x, y - x, pp, x, pp + y, z - y);
255
256   T( ks->seq = seq++; )
257   ks->bulk = algs->bulk;
258   ks->ref = 1;
259   ks->t_exp = now + T_EXP;
260   ks->sz_exp = algs->expsz;
261   ks->sz_regen = algs->expsz/2;
262   ks->oseq = 0;
263   seq_reset(&ks->iseq);
264   ks->next = 0;
265   ks->p = p;
266   ks->f = KSF_LISTEN;
267   ks->tagsz = algs->tagsz;
268   return (ks);
269 }
270
271 /* --- @ks_activate@ --- *
272  *
273  * Arguments:   @keyset *ks@ = pointer to a keyset
274  *
275  * Returns:     ---
276  *
277  * Use:         Activates a keyset, so that it can be used for encrypting
278  *              outgoing messages.
279  */
280
281 void ks_activate(keyset *ks)
282 {
283   if (ks->f & KSF_LISTEN) {
284     T( trace(T_KEYSET, "keyset: activating keyset %u", ks->seq); )
285     ks->f &= ~KSF_LISTEN;
286   }
287 }
288
289 /* --- @ks_encrypt@ --- *
290  *
291  * Arguments:   @keyset *ks@ = pointer to a keyset
292  *              @unsigned ty@ = message type
293  *              @buf *b@ = pointer to input buffer
294  *              @buf *bb@ = pointer to output buffer
295  *
296  * Returns:     Zero if successful; @KSERR_REGEN@ if we should negotiate a
297  *              new key; @KSERR_NOKEYS@ if the key is not usable.  Also
298  *              returns zero if there was insufficient buffer (but the output
299  *              buffer is broken in this case).
300  *
301  * Use:         Encrypts a block of data using the key.  Note that the `key
302  *              ought to be replaced' notification is only ever given once
303  *              for each key.  Also note that this call forces a keyset to be
304  *              used even if it's marked as not for data output.
305  *
306  *              The encryption transform is permitted to corrupt @buf_u@ for
307  *              its own purposes.  Neither the source nor destination should
308  *              be within @buf_u@; and callers mustn't expect anything stored
309  *              in @buf_u@ to still
310  */
311
312 int ks_encrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
313 {
314   time_t now = time(0);
315
316   if (!KEYOK(ks, now)) {
317     buf_break(bb);
318     return (KSERR_NOKEYS);
319   }
320   return (doencrypt(ks, ty, b, bb));
321 }
322
323 /* --- @ks_decrypt@ --- *
324  *
325  * Arguments:   @keyset *ks@ = pointer to a keyset
326  *              @unsigned ty@ = expected type code
327  *              @buf *b@ = pointer to an input buffer
328  *              @buf *bb@ = pointer to an output buffer
329  *
330  * Returns:     Zero on success; @KSERR_...@ on failure.  Also returns
331  *              zero if there was insufficient buffer (but the output buffer
332  *              is broken in this case).
333  *
334  * Use:         Attempts to decrypt a message using a given key.  Note that
335  *              requesting decryption with a key directly won't clear a
336  *              marking that it's not for encryption.
337  *
338  *              The decryption transform is permitted to corrupt @buf_u@ for
339  *              its own purposes.  Neither the source nor destination should
340  *              be within @buf_u@; and callers mustn't expect anything stored
341  *              in @buf_u@ to still
342  */
343
344 int ks_decrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
345 {
346   time_t now = time(0);
347   uint32 seq;
348   int err;
349
350   if (!KEYOK(ks, now)) return (KSERR_DECRYPT);
351   if (buf_ensure(bb, BLEN(b))) return (0);
352   if ((err = dodecrypt(ks, ty, b, bb, &seq)) != 0) return (err);
353   if (seq_check(&ks->iseq, seq, "SYMM")) return (KSERR_SEQ);
354   return (0);
355 }
356
357 /*----- Keyset list handling ----------------------------------------------*/
358
359 /* --- @ksl_free@ --- *
360  *
361  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
362  *
363  * Returns:     ---
364  *
365  * Use:         Frees (releases references to) all of the keys in a keyset.
366  */
367
368 void ksl_free(keyset **ksroot)
369 {
370   keyset *ks, *ksn;
371   for (ks = *ksroot; ks; ks = ksn) {
372     ksn = ks->next;
373     ks->f &= ~KSF_LINK;
374     ks_drop(ks);
375   }
376 }
377
378 /* --- @ksl_link@ --- *
379  *
380  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
381  *              @keyset *ks@ = pointer to a keyset
382  *
383  * Returns:     ---
384  *
385  * Use:         Links a keyset into a list.  A keyset can only be on one list
386  *              at a time.  Bad things happen otherwise.
387  */
388
389 void ksl_link(keyset **ksroot, keyset *ks)
390 {
391   assert(!(ks->f & KSF_LINK));
392   ks->next = *ksroot;
393   *ksroot = ks;
394   ks->f |= KSF_LINK;
395   ks->ref++;
396 }
397
398 /* --- @ksl_prune@ --- *
399  *
400  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
401  *
402  * Returns:     ---
403  *
404  * Use:         Prunes the keyset list by removing keys which mustn't be used
405  *              any more.
406  */
407
408 void ksl_prune(keyset **ksroot)
409 {
410   time_t now = time(0);
411
412   while (*ksroot) {
413     keyset *ks = *ksroot;
414
415     if (ks->t_exp <= now) {
416       T( trace(T_KEYSET, "keyset: expiring keyset %u (time limit reached)",
417                ks->seq); )
418       goto kill;
419     } else if (ks->sz_exp == 0) {
420       T( trace(T_KEYSET, "keyset: expiring keyset %u (data limit reached)",
421                ks->seq); )
422       goto kill;
423     } else {
424       ksroot = &ks->next;
425       continue;
426     }
427
428   kill:
429     *ksroot = ks->next;
430     ks->f &= ~KSF_LINK;
431     ks_drop(ks);
432   }
433 }
434
435 /* --- @ksl_encrypt@ --- *
436  *
437  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
438  *              @unsigned ty@ = message type
439  *              @buf *b@ = pointer to input buffer
440  *              @buf *bb@ = pointer to output buffer
441  *
442  * Returns:     Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
443  *              new key; @KSERR_NOKEYS@ if there are no suitable keys
444  *              available.  Also returns zero if there was insufficient
445  *              buffer space (but the output buffer is broken in this case).
446  *
447  * Use:         Encrypts a packet.
448  */
449
450 int ksl_encrypt(keyset **ksroot, unsigned ty, buf *b, buf *bb)
451 {
452   time_t now = time(0);
453   keyset *ks = *ksroot;
454
455   for (;;) {
456     if (!ks) {
457       T( trace(T_KEYSET, "keyset: no suitable keysets found"); )
458       buf_break(bb);
459       return (KSERR_NOKEYS);
460     }
461     if (KEYOK(ks, now) && !(ks->f & KSF_LISTEN))
462       break;
463     ks = ks->next;
464   }
465
466   return (doencrypt(ks, ty, b, bb));
467 }
468
469 /* --- @ksl_decrypt@ --- *
470  *
471  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
472  *              @unsigned ty@ = expected type code
473  *              @buf *b@ = pointer to input buffer
474  *              @buf *bb@ = pointer to output buffer
475  *
476  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
477  *              zero if there was insufficient buffer (but the output buffer
478  *              is broken in this case).
479  *
480  * Use:         Decrypts a packet.
481  */
482
483 int ksl_decrypt(keyset **ksroot, unsigned ty, buf *b, buf *bb)
484 {
485   time_t now = time(0);
486   keyset *ks;
487   uint32 seq;
488   int err;
489
490   if (buf_ensure(bb, BLEN(b)))
491     return (0);
492
493   for (ks = *ksroot; ks; ks = ks->next) {
494     if (!KEYOK(ks, now))
495       continue;
496     if ((err = dodecrypt(ks, ty, b, bb, &seq)) == 0) {
497       if (ks->f & KSF_LISTEN) {
498         T( trace(T_KEYSET, "keyset: implicitly activating keyset %u",
499                  ks->seq); )
500         ks->f &= ~KSF_LISTEN;
501       }
502       if (seq_check(&ks->iseq, seq, "SYMM"))
503         return (KSERR_SEQ);
504       else
505         return (0);
506     }
507     if (err != KSERR_DECRYPT) return (err);
508   }
509   T( trace(T_KEYSET, "keyset: no matching keys, or incorrect MAC"); )
510   return (KSERR_DECRYPT);
511 }
512
513 /*----- That's all, folks -------------------------------------------------*/