~ubuntu-branches/ubuntu/hardy/openvpn/hardy-proposed

« back to all changes in this revision

Viewing changes to crypto.c

  • Committer: Bazaar Package Importer
  • Author(s): Alberto Gonzalez Iniesta
  • Date: 2004-06-10 15:59:39 UTC
  • Revision ID: james.westby@ubuntu.com-20040610155939-dcmtiuvcoqnwek62
Tags: upstream-1.6.0
ImportĀ upstreamĀ versionĀ 1.6.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 *  OpenVPN -- An application to securely tunnel IP networks
 
3
 *             over a single TCP/UDP port, with support for SSL/TLS-based
 
4
 *             session authentication and key exchange,
 
5
 *             packet encryption, packet authentication, and
 
6
 *             packet compression.
 
7
 *
 
8
 *  Copyright (C) 2002-2004 James Yonan <jim@yonan.net>
 
9
 *
 
10
 *  This program is free software; you can redistribute it and/or modify
 
11
 *  it under the terms of the GNU General Public License as published by
 
12
 *  the Free Software Foundation; either version 2 of the License, or
 
13
 *  (at your option) any later version.
 
14
 *
 
15
 *  This program is distributed in the hope that it will be useful,
 
16
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
17
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
18
 *  GNU General Public License for more details.
 
19
 *
 
20
 *  You should have received a copy of the GNU General Public License
 
21
 *  along with this program (see the file COPYING included with this
 
22
 *  distribution); if not, write to the Free Software Foundation, Inc.,
 
23
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
24
 */
 
25
 
 
26
#ifdef WIN32
 
27
#include "config-win32.h"
 
28
#else
 
29
#include "config.h"
 
30
#endif
 
31
 
 
32
#ifdef USE_CRYPTO
 
33
 
 
34
#include "syshead.h"
 
35
 
 
36
#include "crypto.h"
 
37
#include "error.h"
 
38
#include "misc.h"
 
39
#include "thread.h"
 
40
 
 
41
#include "memdbg.h"
 
42
 
 
43
/*
 
44
 * Check for key size creepage.
 
45
 */
 
46
 
 
47
#if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
 
48
#warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
 
49
#endif
 
50
 
 
51
#if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
 
52
#warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
 
53
#endif
 
54
 
 
55
/*
 
56
 * Encryption and Compression Routines.
 
57
 *
 
58
 * On entry, buf contains the input data and length.
 
59
 * On exit, it should be set to the output data and length.
 
60
 *
 
61
 * If buf->len is <= 0 we should return
 
62
 * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
 
63
 *
 
64
 * work is a workspace buffer we are given of size BUF_SIZE.
 
65
 * work may be used to return output data, or the input buffer
 
66
 * may be modified and returned as output.  If output data is
 
67
 * returned in work, the data should start after FRAME_HEADROOM bytes
 
68
 * of padding to leave room for downstream routines to prepend.
 
69
 *
 
70
 * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
 
71
 * by all routines (encryption, decryption, compression, and decompression).
 
72
 *
 
73
 * Note that the buf_prepend return will assert if we try to
 
74
 * make a header bigger than FRAME_HEADROOM.  This should not
 
75
 * happen unless the frame parameters are wrong.
 
76
 */
 
77
 
 
78
#define CRYPT_ERROR(format) \
 
79
  do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
 
80
 
 
81
void
 
82
openvpn_encrypt (struct buffer *buf, struct buffer work,
 
83
                 const struct crypto_options *opt,
 
84
                 const struct frame* frame,
 
85
                 const time_t current)
 
86
{
 
87
  if (buf->len > 0 && opt->key_ctx_bi)
 
88
    {
 
89
      struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
 
90
 
 
91
      /* Do Encrypt from buf -> work */
 
92
      if (ctx->cipher)
 
93
        {
 
94
          uint8_t iv_buf[EVP_MAX_IV_LENGTH];
 
95
          const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
 
96
          const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);  
 
97
          int outlen;
 
98
 
 
99
          if (mode == EVP_CIPH_CBC_MODE)
 
100
            {
 
101
              CLEAR (iv_buf);
 
102
 
 
103
              /* generate pseudo-random IV */
 
104
              if (opt->use_iv)
 
105
                prng_bytes (iv_buf, iv_size);
 
106
 
 
107
              /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
 
108
              if (opt->packet_id)
 
109
                {
 
110
                  struct packet_id_net pin;
 
111
                  packet_id_alloc_outgoing (&opt->packet_id->send, &pin, opt->packet_id_long_form);
 
112
                  ASSERT (packet_id_write (&pin, buf, opt->packet_id_long_form, true));
 
113
                }
 
114
            }
 
115
          else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
 
116
            {
 
117
              struct packet_id_net pin;
 
118
              struct buffer b;
 
119
 
 
120
              ASSERT (opt->use_iv);    /* IV and packet-ID required */
 
121
              ASSERT (opt->packet_id); /*  for this mode. */
 
122
 
 
123
              packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true);
 
124
              memset (iv_buf, 0, iv_size);
 
125
              buf_set_write (&b, iv_buf, iv_size);
 
126
              ASSERT (packet_id_write (&pin, &b, true, false));
 
127
            }
 
128
          else /* We only support CBC, CFB, or OFB modes right now */
 
129
            {
 
130
              ASSERT (0);
 
131
            }
 
132
 
 
133
          /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
 
134
          ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
 
135
 
 
136
          /* set the IV pseudo-randomly */
 
137
          if (opt->use_iv)
 
138
            msg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0));
 
139
 
 
140
          msg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
 
141
               format_hex (BPTR (buf), BLEN (buf), 80));
 
142
 
 
143
          /* cipher_ctx was already initialized with key & keylen */
 
144
          ASSERT (EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_ENCRYPT));
 
145
 
 
146
          /* Buffer overflow check (should never happen) */
 
147
          ASSERT (buf_safe (&work, buf->len + EVP_CIPHER_CTX_block_size (ctx->cipher)));
 
148
 
 
149
          /* Encrypt packet ID, payload */
 
150
          ASSERT (EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
 
151
          work.len += outlen;
 
152
 
 
153
          /* Flush the encryption buffer */
 
154
          ASSERT (EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen));
 
155
          work.len += outlen;
 
156
          ASSERT (outlen == iv_size);
 
157
 
 
158
          /* prepend the IV to the ciphertext */
 
159
          if (opt->use_iv)
 
160
            {
 
161
              uint8_t *output = buf_prepend (&work, iv_size);
 
162
              ASSERT (output);
 
163
              memcpy (output, iv_buf, iv_size);
 
164
            }
 
165
 
 
166
          msg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
 
167
               format_hex (BPTR (&work), BLEN (&work), 80));
 
168
        }
 
169
      else                              /* No Encryption */
 
170
        {
 
171
          if (opt->packet_id)
 
172
            {
 
173
              struct packet_id_net pin;
 
174
              packet_id_alloc_outgoing (&opt->packet_id->send, &pin, opt->packet_id_long_form);
 
175
              ASSERT (packet_id_write (&pin, buf, opt->packet_id_long_form, true));
 
176
            }
 
177
          work = *buf;
 
178
        }
 
179
 
 
180
      /* HMAC the ciphertext (or plaintext if !cipher) */
 
181
      if (ctx->hmac)
 
182
        {
 
183
          int hmac_len;
 
184
          uint8_t *output;
 
185
 
 
186
          HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
 
187
          HMAC_Update (ctx->hmac, BPTR (&work), BLEN (&work));
 
188
          output = buf_prepend (&work, HMAC_size (ctx->hmac));
 
189
          ASSERT (output);
 
190
          HMAC_Final (ctx->hmac, output, (unsigned int *)&hmac_len);
 
191
          ASSERT (hmac_len == HMAC_size (ctx->hmac));
 
192
        }
 
193
 
 
194
      *buf = work;
 
195
    }
 
196
  return;
 
197
}
 
198
 
 
199
/*
 
200
 * If opt->use_iv is not NULL, we will read an IV from the packet.
 
201
 *
 
202
 * Set buf->len to 0 and return false on decrypt error.
 
203
 *
 
204
 * On success, buf is set to point to plaintext, true
 
205
 * is returned.
 
206
 */
 
207
bool
 
208
openvpn_decrypt (struct buffer *buf, struct buffer work,
 
209
                 const struct crypto_options *opt,
 
210
                 const struct frame* frame,
 
211
                 const time_t current)
 
212
{
 
213
  static const char error_prefix[] = "Authenticate/Decrypt packet error";
 
214
 
 
215
  if (buf->len > 0 && opt->key_ctx_bi)
 
216
    {
 
217
      struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
 
218
      struct packet_id_net pin;
 
219
      bool have_pin = false;
 
220
 
 
221
      /* Verify the HMAC */
 
222
      if (ctx->hmac)
 
223
        {
 
224
          int hmac_len;
 
225
          uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
 
226
          int in_hmac_len;
 
227
 
 
228
          HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
 
229
 
 
230
          /* Assume the length of the input HMAC */
 
231
          hmac_len = HMAC_size (ctx->hmac);
 
232
 
 
233
          /* Authentication fails if insufficient data in packet for HMAC */
 
234
          if (buf->len < hmac_len)
 
235
            CRYPT_ERROR ("missing authentication info");
 
236
 
 
237
          HMAC_Update (ctx->hmac, BPTR (buf) + hmac_len,
 
238
                       BLEN (buf) - hmac_len);
 
239
          HMAC_Final (ctx->hmac, local_hmac, (unsigned int *)&in_hmac_len);
 
240
          ASSERT (hmac_len == in_hmac_len);
 
241
 
 
242
          /* Compare locally computed HMAC with packet HMAC */
 
243
          if (memcmp (local_hmac, BPTR (buf), hmac_len))
 
244
            CRYPT_ERROR ("packet HMAC authentication failed");
 
245
 
 
246
          ASSERT (buf_advance (buf, hmac_len));
 
247
        }
 
248
 
 
249
      /* Decrypt packet ID + payload */
 
250
 
 
251
      if (ctx->cipher)
 
252
        {
 
253
          const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
 
254
          const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
 
255
          uint8_t iv_buf[EVP_MAX_IV_LENGTH];
 
256
          int outlen;
 
257
 
 
258
          /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
 
259
          ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
 
260
 
 
261
          /* use IV if user requested it */
 
262
          CLEAR (iv_buf);
 
263
          if (opt->use_iv)
 
264
            {
 
265
              if (buf->len < iv_size)
 
266
                CRYPT_ERROR ("missing IV info");
 
267
              memcpy (iv_buf, BPTR (buf), iv_size);
 
268
              ASSERT (buf_advance (buf, iv_size));
 
269
            }
 
270
 
 
271
          /* show the IV's initial state */
 
272
          if (opt->use_iv)
 
273
            msg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0));
 
274
 
 
275
          if (buf->len < 1)
 
276
            CRYPT_ERROR ("missing payload");
 
277
 
 
278
          /* ctx->cipher was already initialized with key & keylen */
 
279
          if (!EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_DECRYPT))
 
280
            CRYPT_ERROR ("cipher init failed");
 
281
 
 
282
          /* Buffer overflow check (should never happen) */
 
283
          if (!buf_safe (&work, buf->len))
 
284
            CRYPT_ERROR ("buffer overflow");
 
285
 
 
286
          /* Decrypt packet ID, payload */
 
287
          if (!EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
 
288
            CRYPT_ERROR ("cipher update failed");
 
289
          work.len += outlen;
 
290
 
 
291
          /* Flush the decryption buffer */
 
292
          if (!EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen))
 
293
            CRYPT_ERROR ("cipher final failed");
 
294
          work.len += outlen;
 
295
 
 
296
          msg (D_PACKET_CONTENT, "DECRYPT TO: %s",
 
297
               format_hex (BPTR (&work), BLEN (&work), 80));
 
298
 
 
299
          /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
 
300
          {
 
301
            if (mode == EVP_CIPH_CBC_MODE)
 
302
              {
 
303
                if (opt->packet_id)
 
304
                  {
 
305
                    if (!packet_id_read (&pin, &work, opt->packet_id_long_form))
 
306
                      CRYPT_ERROR ("error reading CBC packet-id");
 
307
                    have_pin = true;
 
308
                  }
 
309
              }
 
310
            else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
 
311
              {
 
312
                struct buffer b;
 
313
 
 
314
                ASSERT (opt->use_iv);    /* IV and packet-ID required */
 
315
                ASSERT (opt->packet_id); /*  for this mode. */
 
316
 
 
317
                buf_set_read (&b, iv_buf, iv_size);
 
318
                if (!packet_id_read (&pin, &b, true))
 
319
                  CRYPT_ERROR ("error reading CFB/OFB packet-id");
 
320
                have_pin = true;
 
321
              }
 
322
            else /* We only support CBC, CFB, or OFB modes right now */
 
323
              {
 
324
                ASSERT (0);
 
325
              }
 
326
          }
 
327
        }
 
328
      else
 
329
        {
 
330
          work = *buf;
 
331
          if (opt->packet_id)
 
332
            {
 
333
              if (!packet_id_read (&pin, &work, opt->packet_id_long_form))
 
334
                CRYPT_ERROR ("error reading packet-id");
 
335
              have_pin = true;
 
336
            }
 
337
        }
 
338
      
 
339
      if (have_pin)
 
340
        {
 
341
          packet_id_reap_test (&opt->packet_id->rec, current);
 
342
          if (packet_id_test (&opt->packet_id->rec, &pin))
 
343
            {
 
344
              packet_id_add (&opt->packet_id->rec, &pin, current);
 
345
              if (opt->pid_persist && opt->packet_id_long_form)
 
346
                packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
 
347
            }
 
348
          else
 
349
            {
 
350
              msg (D_CRYPT_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info",
 
351
                   error_prefix, packet_id_net_print (&pin, true));
 
352
              goto error_exit;
 
353
            }
 
354
        }
 
355
      *buf = work;
 
356
    }
 
357
  return true;
 
358
 
 
359
 error_exit:
 
360
  buf->len = 0;
 
361
  return false;
 
362
}
 
363
 
 
364
/*
 
365
 * How many bytes will we add to frame buffer for a given
 
366
 * set of crypto options?
 
367
 */
 
368
void
 
369
crypto_adjust_frame_parameters(struct frame *frame,
 
370
                               const struct key_type* kt,
 
371
                               bool cipher_defined,
 
372
                               bool use_iv,
 
373
                               bool packet_id,
 
374
                               bool packet_id_long_form)
 
375
{
 
376
  frame_add_to_extra_frame (frame,
 
377
                            (packet_id ? packet_id_size (packet_id_long_form) : 0) +
 
378
                            ((cipher_defined && use_iv) ? EVP_CIPHER_iv_length (kt->cipher) : 0) +
 
379
                            (cipher_defined ? EVP_CIPHER_block_size (kt->cipher) : 0) + /* worst case padding expansion */
 
380
                            kt->hmac_length);
 
381
}
 
382
 
 
383
static const EVP_CIPHER *
 
384
get_cipher (const char *ciphername)
 
385
{
 
386
  const EVP_CIPHER *cipher = NULL;
 
387
  ASSERT (ciphername);
 
388
  cipher = EVP_get_cipherbyname (ciphername);
 
389
  if ( !(cipher && cipher_ok (OBJ_nid2sn (EVP_CIPHER_nid (cipher)))))
 
390
    msg (M_SSLERR, "Cipher algorithm '%s' not found", ciphername);
 
391
  if (EVP_CIPHER_key_length (cipher) > MAX_CIPHER_KEY_LENGTH)
 
392
    msg (M_FATAL, "Cipher algorithm '%s' uses a default key size (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum key size (%d bytes)",
 
393
         ciphername,
 
394
         EVP_CIPHER_key_length (cipher),
 
395
         MAX_CIPHER_KEY_LENGTH);
 
396
  return cipher;
 
397
}
 
398
 
 
399
static const EVP_MD *
 
400
get_md (const char *digest)
 
401
{
 
402
  const EVP_MD *md = NULL;
 
403
  ASSERT (digest);
 
404
  md = EVP_get_digestbyname (digest);
 
405
  if (!md)
 
406
    msg (M_SSLERR, "Message hash algorithm '%s' not found", digest);
 
407
  if (EVP_MD_size (md) > MAX_HMAC_KEY_LENGTH)
 
408
    msg (M_FATAL, "Message hash algorithm '%s' uses a default hash size (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum hash size (%d bytes)",
 
409
         digest,
 
410
         EVP_MD_size (md),
 
411
         MAX_HMAC_KEY_LENGTH);
 
412
  return md;
 
413
}
 
414
 
 
415
static void
 
416
init_cipher (EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
 
417
             struct key *key, const struct key_type *kt, int enc,
 
418
             const char *prefix)
 
419
{
 
420
  EVP_CIPHER_CTX_init (ctx);
 
421
  if (!EVP_CipherInit_ov (ctx, cipher, NULL, NULL, enc))
 
422
    msg (M_SSLERR, "EVP cipher init #1");
 
423
#ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH
 
424
  if (!EVP_CIPHER_CTX_set_key_length (ctx, kt->cipher_length))
 
425
    msg (M_SSLERR, "EVP set key size");
 
426
#endif
 
427
  if (!EVP_CipherInit_ov (ctx, NULL, key->cipher, NULL, enc))
 
428
    msg (M_SSLERR, "EVP cipher init #2");
 
429
 
 
430
  msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
 
431
       prefix,
 
432
       OBJ_nid2sn (EVP_CIPHER_CTX_nid (ctx)),
 
433
       EVP_CIPHER_CTX_key_length (ctx) * 8);
 
434
 
 
435
  /* make sure we used a big enough key */
 
436
  ASSERT (EVP_CIPHER_CTX_key_length (ctx) <= kt->cipher_length);
 
437
 
 
438
  msg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
 
439
       format_hex (key->cipher, kt->cipher_length, 0));
 
440
  msg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
 
441
       prefix,
 
442
       EVP_CIPHER_CTX_block_size (ctx),
 
443
       EVP_CIPHER_CTX_iv_length (ctx));
 
444
}
 
445
 
 
446
static void
 
447
init_hmac (HMAC_CTX *ctx, const EVP_MD *digest,
 
448
           struct key *key, const struct key_type *kt, const char *prefix)
 
449
{
 
450
  HMAC_CTX_init (ctx);
 
451
  HMAC_Init_ex (ctx, key->hmac, kt->hmac_length, digest, NULL);
 
452
  msg (D_HANDSHAKE,
 
453
       "%s: Using %d bit message hash '%s' for HMAC authentication",
 
454
       prefix, HMAC_size (ctx) * 8, OBJ_nid2sn (EVP_MD_type (digest)));
 
455
 
 
456
  /* make sure we used a big enough key */
 
457
  ASSERT (HMAC_size (ctx) <= kt->hmac_length);
 
458
 
 
459
  msg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
 
460
       format_hex (key->hmac, kt->hmac_length, 0));
 
461
  msg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
 
462
       prefix,
 
463
       EVP_MD_size (digest),
 
464
       EVP_MD_block_size (digest));
 
465
}
 
466
 
 
467
/* build a key_type */
 
468
void
 
469
init_key_type (struct key_type *kt, const char *ciphername,
 
470
               bool ciphername_defined, const char *authname,
 
471
               bool authname_defined, int keysize,
 
472
               bool cfb_ofb_allowed, bool warn)
 
473
{
 
474
  CLEAR (*kt);
 
475
  if (ciphername && ciphername_defined)
 
476
    {
 
477
      kt->cipher = get_cipher (ciphername);
 
478
      kt->cipher_length = EVP_CIPHER_key_length (kt->cipher);
 
479
      if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
 
480
        kt->cipher_length = keysize;
 
481
 
 
482
      /* check legal cipher mode */
 
483
      {
 
484
        const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
 
485
        if (!(mode == EVP_CIPH_CBC_MODE
 
486
#ifdef ALLOW_NON_CBC_CIPHERS
 
487
              || (cfb_ofb_allowed && (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE))
 
488
#endif
 
489
              ))
 
490
          msg (M_FATAL, "Cipher '%s' uses a mode not supported by " PACKAGE_NAME " in your current configuration.  CBC mode is always supported, while CFB and OFB modes are supported only when using SSL/TLS authentication and key exchange mode, and when " PACKAGE_NAME " has been built with ALLOW_NON_CBC_CIPHERS.", ciphername);
 
491
      }
 
492
    }
 
493
  else
 
494
    {
 
495
      if (warn)
 
496
        msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
 
497
    }
 
498
  if (authname && authname_defined)
 
499
    {
 
500
      kt->digest = get_md (authname);
 
501
      kt->hmac_length = EVP_MD_size (kt->digest);
 
502
    }
 
503
  else
 
504
    {
 
505
      if (warn)
 
506
        msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
 
507
    }
 
508
}
 
509
 
 
510
const char *
 
511
kt_cipher_name (const struct key_type *kt)
 
512
{
 
513
  if (kt->cipher)
 
514
    return EVP_CIPHER_name (kt->cipher);
 
515
  else
 
516
    return "[null-cipher]";
 
517
}
 
518
 
 
519
const char *
 
520
kt_digest_name (const struct key_type *kt)
 
521
{
 
522
  if (kt->digest)
 
523
    return EVP_MD_name (kt->digest);
 
524
  else
 
525
    return "[null-digest]";
 
526
}
 
527
 
 
528
int
 
529
kt_key_size (const struct key_type *kt)
 
530
{
 
531
  if (kt->cipher_length)
 
532
    return kt->cipher_length * 8;
 
533
  else if (kt->cipher)
 
534
    return EVP_CIPHER_key_length (kt->cipher) * 8;
 
535
  else
 
536
    return 0;
 
537
}
 
538
 
 
539
/* given a key and key_type, build a key_ctx */
 
540
void
 
541
init_key_ctx (struct key_ctx *ctx, struct key *key,
 
542
              const struct key_type *kt, int enc,
 
543
              const char *prefix)
 
544
{
 
545
  CLEAR (*ctx);
 
546
  if (kt->cipher && kt->cipher_length > 0)
 
547
    {
 
548
      ASSERT (ctx->cipher = (EVP_CIPHER_CTX *) malloc (sizeof (EVP_CIPHER_CTX)));
 
549
      init_cipher (ctx->cipher, kt->cipher, key, kt, enc, prefix);
 
550
    }
 
551
  if (kt->digest && kt->hmac_length > 0)
 
552
    {
 
553
      ASSERT (ctx->hmac = (HMAC_CTX *) malloc (sizeof (HMAC_CTX)));
 
554
      init_hmac (ctx->hmac, kt->digest, key, kt, prefix);
 
555
    }
 
556
}
 
557
 
 
558
void free_key_ctx (struct key_ctx *ctx)
 
559
{
 
560
  if (ctx->cipher)
 
561
    {
 
562
      EVP_CIPHER_CTX_cleanup (ctx->cipher);
 
563
      free (ctx->cipher);
 
564
      ctx->cipher = NULL;
 
565
    }
 
566
  if (ctx->hmac)
 
567
    {
 
568
      HMAC_CTX_cleanup (ctx->hmac);
 
569
      free (ctx->hmac);
 
570
      ctx->hmac = NULL;
 
571
    }
 
572
}
 
573
 
 
574
void free_key_ctx_bi (struct key_ctx_bi *ctx)
 
575
{
 
576
  free_key_ctx(&ctx->encrypt);
 
577
  free_key_ctx(&ctx->decrypt);
 
578
}
 
579
 
 
580
/*
 
581
 * Return number of DES cblocks for the current
 
582
 * key type or 0 if not a DES cipher.
 
583
 */
 
584
static int
 
585
n_DES_cblocks (const struct key_type *kt)
 
586
{
 
587
  int ret = 0;
 
588
  const char *name = OBJ_nid2sn (EVP_CIPHER_nid (kt->cipher));
 
589
  if (name)
 
590
    {
 
591
      if (!strncmp (name, "DES-", 4))
 
592
        {
 
593
          ret = EVP_CIPHER_key_length (kt->cipher) / sizeof (DES_cblock);
 
594
        }
 
595
      else if (!strncmp (name, "DESX-", 5))
 
596
        {
 
597
          ret = 1;
 
598
        }
 
599
    }
 
600
  msg (D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret);
 
601
  return ret;
 
602
}
 
603
 
 
604
static bool
 
605
check_key_DES (struct key *key, const struct key_type *kt, int ndc)
 
606
{
 
607
  int i;
 
608
  struct buffer b;
 
609
 
 
610
  buf_set_read (&b, key->cipher, kt->cipher_length);
 
611
  for (i = 0; i < ndc; ++i)
 
612
    {
 
613
      DES_cblock *dc = (DES_cblock*) buf_read_alloc (&b, sizeof (DES_cblock));
 
614
      if (!dc)
 
615
        {
 
616
          msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material");
 
617
          return false;
 
618
        }
 
619
      if (DES_is_weak_key(dc))
 
620
        {
 
621
          msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected");
 
622
          return false;
 
623
        }
 
624
      if (!DES_check_key_parity (dc))
 
625
        {
 
626
          msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected");
 
627
          return false;
 
628
        }
 
629
    }
 
630
  return true;
 
631
}
 
632
 
 
633
static void
 
634
fixup_key_DES (struct key *key, const struct key_type *kt, int ndc)
 
635
{
 
636
  int i;
 
637
  struct buffer b;
 
638
 
 
639
  buf_set_read (&b, key->cipher, kt->cipher_length);
 
640
  for (i = 0; i < ndc; ++i)
 
641
    {
 
642
      DES_cblock *dc = (DES_cblock*) buf_read_alloc(&b, sizeof(DES_cblock));
 
643
      if (!dc)
 
644
        {
 
645
          msg (D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material");
 
646
          return;
 
647
        }
 
648
      DES_set_odd_parity (dc);
 
649
    }
 
650
}
 
651
 
 
652
static bool
 
653
key_is_zero(struct key *key, const struct key_type *kt)
 
654
{
 
655
  int i;
 
656
  for (i = 0; i < kt->cipher_length; ++i)
 
657
    if (key->cipher[i])
 
658
      return false;
 
659
  msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
 
660
  return true;
 
661
}
 
662
 
 
663
/*
 
664
 * Make sure that cipher key is a valid key for current key_type.
 
665
 */
 
666
bool
 
667
check_key (struct key *key, const struct key_type *kt)
 
668
{
 
669
  if (kt->cipher)
 
670
    {
 
671
      /*
 
672
       * Check for zero key
 
673
       */
 
674
      if (key_is_zero(key, kt))
 
675
        return false;
 
676
 
 
677
      /*
 
678
       * Check for weak or semi-weak DES keys.
 
679
       */
 
680
      {
 
681
        const int ndc = n_DES_cblocks (kt);
 
682
        if (ndc)
 
683
          return check_key_DES (key, kt, ndc);
 
684
        else
 
685
          return true;
 
686
      }
 
687
    }
 
688
  return true;
 
689
}
 
690
 
 
691
/*
 
692
 * Make safe mutations to key to ensure it is valid,
 
693
 * such as ensuring correct parity on DES keys.
 
694
 *
 
695
 * This routine cannot guarantee it will generate a good
 
696
 * key.  You must always call check_key after this routine
 
697
 * to make sure.
 
698
 */ 
 
699
void
 
700
fixup_key (struct key *key, const struct key_type *kt)
 
701
{
 
702
  if (kt->cipher)
 
703
    {
 
704
      const struct key orig = *key;
 
705
      const int ndc = n_DES_cblocks (kt);
 
706
 
 
707
      if (ndc)
 
708
        fixup_key_DES (key, kt, ndc);
 
709
 
 
710
      if (check_debug_level (D_CRYPTO_DEBUG))
 
711
        {
 
712
          if (memcmp (orig.cipher, key->cipher, kt->cipher_length))
 
713
            msg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
 
714
                 format_hex (orig.cipher, kt->cipher_length, 0),
 
715
                 format_hex (key->cipher, kt->cipher_length, 0));
 
716
        }
 
717
    }
 
718
}
 
719
 
 
720
void
 
721
check_replay_iv_consistency(const struct key_type *kt, bool packet_id, bool use_iv)
 
722
{
 
723
  if (cfb_ofb_mode (kt) && !(packet_id && use_iv))
 
724
    msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
 
725
}
 
726
 
 
727
bool
 
728
cfb_ofb_mode(const struct key_type* kt)
 
729
{
 
730
  if (kt->cipher) {
 
731
    const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
 
732
    return mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE;
 
733
  } else
 
734
    return false;
 
735
}
 
736
 
 
737
/*
 
738
 * Generate a random key.  If key_type is provided, make
 
739
 * sure generated key is valid for key_type.
 
740
 */
 
741
void
 
742
generate_key_random (struct key *key, const struct key_type *kt)
 
743
{
 
744
  int cipher_len = MAX_CIPHER_KEY_LENGTH;
 
745
  int hmac_len = MAX_HMAC_KEY_LENGTH;
 
746
 
 
747
  do {
 
748
    CLEAR (*key);
 
749
    if (kt)
 
750
      {
 
751
        if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
 
752
          cipher_len = kt->cipher_length;
 
753
 
 
754
        if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
 
755
          hmac_len = kt->hmac_length;
 
756
      }
 
757
    ASSERT (RAND_bytes (key->cipher, cipher_len));
 
758
    ASSERT (RAND_bytes (key->hmac, hmac_len));
 
759
 
 
760
    msg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0));
 
761
    msg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0));
 
762
 
 
763
    if (kt)
 
764
      fixup_key (key, kt);
 
765
  } while (kt && !check_key (key, kt));
 
766
}
 
767
 
 
768
/*
 
769
 * Print key material
 
770
 */
 
771
void
 
772
key2_print (const struct key2* k,
 
773
            const struct key_type *kt,
 
774
            const char* prefix0,
 
775
            const char* prefix1)
 
776
{
 
777
  ASSERT (k->n == 2);
 
778
  msg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
 
779
       prefix0,
 
780
       format_hex (k->keys[0].cipher, kt->cipher_length, 0));
 
781
  msg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
 
782
       prefix0,
 
783
       format_hex (k->keys[0].hmac, kt->hmac_length, 0));
 
784
  msg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
 
785
       prefix1,
 
786
       format_hex (k->keys[1].cipher, kt->cipher_length, 0));
 
787
  msg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
 
788
       prefix1,
 
789
       format_hex (k->keys[1].hmac, kt->hmac_length, 0));
 
790
}
 
791
 
 
792
void
 
793
test_crypto (const struct crypto_options *co, struct frame* frame)
 
794
{
 
795
  int i, j;
 
796
  struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame));
 
797
  struct buffer work = alloc_buf_gc (BUF_SIZE (frame));
 
798
  struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame));
 
799
  struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame));
 
800
  struct buffer buf = clear_buf();
 
801
 
 
802
  /* init work */
 
803
  ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
 
804
 
 
805
  msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
 
806
  for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
 
807
    {
 
808
      const time_t current = time (NULL);
 
809
 
 
810
      msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
 
811
 
 
812
      /*
 
813
       * Load src with random data.
 
814
       */
 
815
      ASSERT (buf_init (&src, 0));
 
816
      ASSERT (i <= src.capacity);
 
817
      src.len = i;
 
818
      ASSERT (RAND_pseudo_bytes (BPTR (&src), BLEN (&src)));
 
819
 
 
820
      /* copy source to input buf */
 
821
      buf = work;
 
822
      memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
 
823
 
 
824
      /* encrypt */
 
825
      openvpn_encrypt (&buf, encrypt_workspace, co, frame, current);
 
826
 
 
827
      /* decrypt */
 
828
      openvpn_decrypt (&buf, decrypt_workspace, co, frame, current);
 
829
 
 
830
      /* compare */
 
831
      if (buf.len != src.len)
 
832
        msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
 
833
      for (j = 0; j < i; ++j)
 
834
        {
 
835
          const uint8_t in = *(BPTR (&src) + j);
 
836
          const uint8_t out = *(BPTR (&buf) + j);
 
837
          if (in != out)
 
838
            msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
 
839
        }
 
840
    }
 
841
  msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
 
842
}
 
843
 
 
844
#ifdef USE_SSL
 
845
void
 
846
get_tls_handshake_key (const struct key_type *key_type,
 
847
                       struct key_ctx_bi *ctx,
 
848
                       const char *passphrase_file,
 
849
                       bool key_direction)
 
850
{
 
851
  if (passphrase_file && key_type->hmac_length)
 
852
    {
 
853
      struct key2 key2;
 
854
      struct key_type kt = *key_type;
 
855
      struct key_direction_state kds;
 
856
 
 
857
      /* for control channel we are only authenticating, not encrypting */
 
858
      kt.cipher_length = 0;
 
859
      kt.cipher = NULL;
 
860
 
 
861
      /* first try to parse as an OpenVPN static key file */
 
862
      read_key_file (&key2, passphrase_file, false);
 
863
 
 
864
      /* succeeded? */
 
865
      if (key2.n == 2)
 
866
        {
 
867
          msg (M_INFO,
 
868
               "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
 
869
               passphrase_file);
 
870
        }
 
871
      else
 
872
        {
 
873
          int hash_size;
 
874
 
 
875
          CLEAR (key2);
 
876
 
 
877
          /* failed, now try to get hash from a freeform file */
 
878
          hash_size = read_passphrase_hash (passphrase_file,
 
879
                                            kt.digest,
 
880
                                            key2.keys[0].hmac,
 
881
                                            MAX_HMAC_KEY_LENGTH);
 
882
          ASSERT (hash_size == kt.hmac_length);
 
883
 
 
884
          /* suceeded */
 
885
          key2.n = 1;
 
886
 
 
887
          msg (M_INFO,
 
888
               "Control Channel Authentication: using '%s' as a free-form passphrase file",
 
889
               passphrase_file);
 
890
        }
 
891
 
 
892
      /* handle key direction */
 
893
 
 
894
      key_direction_state_init (&kds, key_direction);
 
895
      must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
 
896
 
 
897
      /* initialize hmac key in both directions */
 
898
 
 
899
      init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, DO_ENCRYPT,
 
900
                    "Outgoing Control Channel Authentication");
 
901
      init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, DO_DECRYPT,
 
902
                    "Incoming Control Channel Authentication");
 
903
 
 
904
      CLEAR (key2);
 
905
    }
 
906
  else
 
907
    {
 
908
      CLEAR (*ctx);
 
909
    }
 
910
}
 
911
#endif
 
912
 
 
913
/* header and footer for static key file */
 
914
static const char static_key_head[] = "-----BEGIN " PACKAGE_NAME " Static key V1-----";
 
915
static const char static_key_foot[] = "-----END " PACKAGE_NAME " Static key V1-----";
 
916
 
 
917
static const char printable_char_fmt[] =
 
918
  "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
 
919
 
 
920
static const char unprintable_char_fmt[] =
 
921
  "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
 
922
 
 
923
/* read key from file */
 
924
void
 
925
read_key_file (struct key2 *key2, const char *filename, bool must_succeed)
 
926
{
 
927
  const int gc_level = gc_new_level ();
 
928
  struct buffer in = alloc_buf_gc (64);
 
929
  int fd, size;
 
930
  uint8_t hex_byte[3] = {0, 0, 0};
 
931
 
 
932
  /* parse info */
 
933
  int hb_index = 0;
 
934
  int line_num = 1;
 
935
  int line_index = 0;
 
936
  int match = 0;
 
937
 
 
938
  /* output */
 
939
  uint8_t* out = (uint8_t*) &key2->keys;
 
940
  const int keylen = sizeof (key2->keys);
 
941
  int count = 0;
 
942
 
 
943
  /* parse states */
 
944
# define PARSE_INITIAL        0
 
945
# define PARSE_HEAD           1
 
946
# define PARSE_DATA           2
 
947
# define PARSE_DATA_COMPLETE  3
 
948
# define PARSE_FOOT           4
 
949
# define PARSE_FINISHED       5
 
950
  int state = PARSE_INITIAL;
 
951
 
 
952
  /* constants */
 
953
  const int hlen = strlen (static_key_head);
 
954
  const int flen = strlen (static_key_foot);
 
955
  const int onekeylen = sizeof (key2->keys[0]);
 
956
 
 
957
  CLEAR (*key2);
 
958
 
 
959
  fd = open (filename, O_RDONLY);
 
960
  if (fd == -1)
 
961
    msg (M_ERR, "Cannot open file key file '%s'", filename);
 
962
 
 
963
  while ((size = read (fd, in.data, in.capacity)))
 
964
    {
 
965
      const char *cp = (char *)in.data;
 
966
      while (size)
 
967
        {
 
968
          const char c = *cp;
 
969
 
 
970
#if 0
 
971
          msg (M_INFO, "char='%c' s=%d ln=%d li=%d m=%d c=%d",
 
972
               c, state, line_num, line_index, match, count);
 
973
#endif
 
974
 
 
975
          if (c == '\n')
 
976
            {
 
977
              line_index = match = 0;
 
978
              ++line_num;             
 
979
            }
 
980
          else
 
981
            {
 
982
              /* first char of new line */
 
983
              if (!line_index)
 
984
                {
 
985
                  /* first char of line after header line? */
 
986
                  if (state == PARSE_HEAD)
 
987
                    state = PARSE_DATA;
 
988
 
 
989
                  /* first char of footer */
 
990
                  if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
 
991
                    state = PARSE_FOOT;
 
992
                }
 
993
 
 
994
              /* compare read chars with header line */
 
995
              if (state == PARSE_INITIAL)
 
996
                {
 
997
                  if (line_index < hlen && c == static_key_head[line_index])
 
998
                    {
 
999
                      if (++match == hlen)
 
1000
                        state = PARSE_HEAD;
 
1001
                    }
 
1002
                }
 
1003
 
 
1004
              /* compare read chars with footer line */
 
1005
              if (state == PARSE_FOOT)
 
1006
                {
 
1007
                  if (line_index < flen && c == static_key_foot[line_index])
 
1008
                    {
 
1009
                      if (++match == flen)
 
1010
                        state = PARSE_FINISHED;
 
1011
                    }
 
1012
                }
 
1013
 
 
1014
              /* reading key */
 
1015
              if (state == PARSE_DATA)
 
1016
                {
 
1017
                  if (isxdigit(c))
 
1018
                    {
 
1019
                      ASSERT (hb_index >= 0 && hb_index < 2);
 
1020
                      hex_byte[hb_index++] = c;
 
1021
                      if (hb_index == 2)
 
1022
                        {
 
1023
                          unsigned int u;
 
1024
                          ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
 
1025
                          *out++ = u;
 
1026
                          hb_index = 0;
 
1027
                          if (++count == keylen)
 
1028
                            state = PARSE_DATA_COMPLETE;
 
1029
                        }
 
1030
                    }
 
1031
                  else if (isspace(c))
 
1032
                    ;
 
1033
                  else
 
1034
                    {
 
1035
                      msg (M_FATAL,
 
1036
                           (isprint (c) ? printable_char_fmt : unprintable_char_fmt),
 
1037
                           c, line_num, filename, count, onekeylen, keylen);
 
1038
                    }
 
1039
                }
 
1040
              ++line_index;
 
1041
            }
 
1042
          ++cp;
 
1043
          --size;
 
1044
        }
 
1045
    }
 
1046
 
 
1047
  close (fd);
 
1048
 
 
1049
  /*
 
1050
   * Normally we will read either 1 or 2 keys from file.
 
1051
   */
 
1052
  key2->n = count / onekeylen;
 
1053
 
 
1054
  ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
 
1055
 
 
1056
  if (must_succeed)
 
1057
    {
 
1058
      if (!key2->n)
 
1059
        msg (M_FATAL, "Insufficient key material or header text not found found in file '%s' (%d/%d/%d bytes found/min/max)",
 
1060
             filename, count, onekeylen, keylen);
 
1061
 
 
1062
      if (state != PARSE_FINISHED)
 
1063
        msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
 
1064
             filename, count, onekeylen, keylen);
 
1065
    }
 
1066
 
 
1067
  /* zero file read buffer */
 
1068
  buf_clear (&in);
 
1069
 
 
1070
  if (key2->n)
 
1071
    warn_if_group_others_accessible (filename);
 
1072
 
 
1073
#if 0
 
1074
  /* DEBUGGING */
 
1075
  {
 
1076
    int i;
 
1077
    printf ("KEY READ, n=%d\n", key2->n);
 
1078
    for (i = 0; i < (int) SIZE (key2->keys); ++i)
 
1079
      {
 
1080
        /* format key as ascii */
 
1081
        const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
 
1082
                                         sizeof (key2->keys[i]),
 
1083
                                         0,
 
1084
                                         16,
 
1085
                                         "\n");
 
1086
        printf ("[%d]\n%s\n\n", i, fmt);
 
1087
      }
 
1088
  }
 
1089
#endif
 
1090
 
 
1091
  /* pop our garbage collection level */
 
1092
  gc_free_level (gc_level);
 
1093
}
 
1094
 
 
1095
int
 
1096
read_passphrase_hash (const char *passphrase_file,
 
1097
                      const EVP_MD *digest,
 
1098
                      uint8_t *output,
 
1099
                      int len)
 
1100
{
 
1101
  unsigned int outlen = 0;
 
1102
  EVP_MD_CTX md;
 
1103
 
 
1104
  ASSERT (len >= EVP_MD_size (digest));
 
1105
  memset (output, 0, len);
 
1106
 
 
1107
  EVP_DigestInit (&md, digest);
 
1108
 
 
1109
  /* read passphrase file */
 
1110
  {
 
1111
    const int min_passphrase_size = 8;
 
1112
    uint8_t buf[64];
 
1113
    int total_size = 0;
 
1114
    int fd = open (passphrase_file, O_RDONLY);
 
1115
 
 
1116
    if (fd == -1)
 
1117
      msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
 
1118
 
 
1119
    for (;;)
 
1120
      {
 
1121
        int size = read (fd, buf, sizeof (buf));
 
1122
        if (size == 0)
 
1123
          break;
 
1124
        if (size == -1)
 
1125
          msg (M_ERR, "Read error on passphrase file: '%s'",
 
1126
               passphrase_file);
 
1127
        EVP_DigestUpdate (&md, buf, size);
 
1128
        total_size += size;
 
1129
      }
 
1130
    close (fd);
 
1131
 
 
1132
    warn_if_group_others_accessible (passphrase_file);
 
1133
 
 
1134
    if (total_size < min_passphrase_size)
 
1135
      msg (M_FATAL,
 
1136
           "Passphrase file '%s' is too small (must have at least %d characters)",
 
1137
           passphrase_file, min_passphrase_size);
 
1138
  }
 
1139
 
 
1140
  EVP_DigestFinal (&md, output, &outlen);
 
1141
  EVP_MD_CTX_cleanup (&md);
 
1142
  return outlen;
 
1143
}
 
1144
 
 
1145
/*
 
1146
 * Write key to file, return number of random bits
 
1147
 * written.
 
1148
 */
 
1149
int
 
1150
write_key_file (const int nkeys, const char *filename)
 
1151
{
 
1152
  const int gc_level = gc_new_level ();
 
1153
 
 
1154
  int fd, i;
 
1155
  int nbits = 0;
 
1156
 
 
1157
  /* must be large enough to hold full key file */
 
1158
  struct buffer out = alloc_buf_gc (2048);
 
1159
  struct buffer nbits_head_text = alloc_buf_gc (128);
 
1160
 
 
1161
  /* how to format the ascii file representation of key */
 
1162
  const int bytes_per_line = 16;
 
1163
 
 
1164
  /* open key file */
 
1165
  fd = open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
 
1166
 
 
1167
  if (fd == -1)
 
1168
    msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
 
1169
 
 
1170
  buf_printf (&out, "%s\n", static_key_head);
 
1171
 
 
1172
  for (i = 0; i < nkeys; ++i)
 
1173
    {
 
1174
      struct key key;
 
1175
      char* fmt;
 
1176
 
 
1177
      /* generate random bits */
 
1178
      generate_key_random (&key, NULL);
 
1179
 
 
1180
      /* format key as ascii */
 
1181
      fmt = format_hex_ex ((const uint8_t*)&key,
 
1182
                           sizeof (key),
 
1183
                           0,
 
1184
                           bytes_per_line,
 
1185
                           "\n");
 
1186
 
 
1187
      /* increment random bits counter */
 
1188
      nbits += sizeof (key) * 8;
 
1189
 
 
1190
      /* write to holding buffer */
 
1191
      buf_printf (&out, "%s\n", fmt);
 
1192
 
 
1193
      /* zero memory which held key component (will be freed by GC) */
 
1194
      memset (fmt, 0, strlen(fmt));
 
1195
      CLEAR (key);
 
1196
    }
 
1197
 
 
1198
  buf_printf (&out, "%s\n", static_key_foot);
 
1199
 
 
1200
  /* write number of bits */
 
1201
  buf_printf (&nbits_head_text, "#\n# %d bit " PACKAGE_NAME " static key\n#\n", nbits);
 
1202
  buf_write_string_file (&nbits_head_text, filename, fd);
 
1203
 
 
1204
  /* write key file, now formatted in out, to file */
 
1205
  buf_write_string_file (&out, filename, fd);
 
1206
 
 
1207
  if (close (fd))
 
1208
    msg (M_ERR, "Close error on shared secret file %s", filename);
 
1209
 
 
1210
  /* zero memory which held file content (memory will be freed by GC) */
 
1211
  buf_clear (&out);
 
1212
 
 
1213
  /* pop our garbage collection level */
 
1214
  gc_free_level (gc_level);
 
1215
 
 
1216
  return nbits;
 
1217
}
 
1218
 
 
1219
void
 
1220
must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
 
1221
{
 
1222
  if (key2->n < n)
 
1223
    msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE " --genkey --secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter", filename, option, key2->n, n, option);
 
1224
}
 
1225
 
 
1226
int
 
1227
ascii2keydirection (const char *str)
 
1228
{
 
1229
  if (!str)
 
1230
    return KEY_DIRECTION_BIDIRECTIONAL;
 
1231
  else if (!strcmp (str, "0"))
 
1232
    return KEY_DIRECTION_NORMAL;
 
1233
  else if (!strcmp (str, "1"))
 
1234
    return KEY_DIRECTION_INVERSE;
 
1235
  else
 
1236
    msg (M_USAGE, "Unknown key direction '%s' -- must be '0' or '1'",
 
1237
         str);
 
1238
  return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
 
1239
}
 
1240
 
 
1241
const char *
 
1242
keydirection2ascii (int kd, bool remote)
 
1243
{
 
1244
  if (kd == KEY_DIRECTION_BIDIRECTIONAL)
 
1245
    return NULL;
 
1246
  else if (kd == KEY_DIRECTION_NORMAL)
 
1247
    return remote ? "1" : "0";
 
1248
  else if (kd == KEY_DIRECTION_INVERSE)
 
1249
    return remote ? "0" : "1";
 
1250
  else
 
1251
    {
 
1252
      ASSERT (0);
 
1253
    }
 
1254
  return NULL; /* NOTREACHED */
 
1255
}
 
1256
 
 
1257
void
 
1258
key_direction_state_init (struct key_direction_state *kds, int key_direction)
 
1259
{
 
1260
  CLEAR (*kds);
 
1261
  switch (key_direction)
 
1262
    {
 
1263
    case KEY_DIRECTION_NORMAL:
 
1264
      kds->out_key = 0;
 
1265
      kds->in_key = 1;
 
1266
      kds->need_keys = 2;
 
1267
      break;
 
1268
    case KEY_DIRECTION_INVERSE:
 
1269
      kds->out_key = 1;
 
1270
      kds->in_key = 0;
 
1271
      kds->need_keys = 2;
 
1272
      break;
 
1273
    case KEY_DIRECTION_BIDIRECTIONAL:
 
1274
      kds->out_key = 0;
 
1275
      kds->in_key = 0;
 
1276
      kds->need_keys = 1;
 
1277
      break;
 
1278
    default:
 
1279
      ASSERT (0);
 
1280
    }
 
1281
}
 
1282
 
 
1283
void
 
1284
verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
 
1285
{
 
1286
  int i;
 
1287
 
 
1288
  for (i = 0; i < key2->n; ++i)
 
1289
    {
 
1290
      /* Fix parity for DES keys and make sure not a weak key */
 
1291
      fixup_key (&key2->keys[i], kt);
 
1292
 
 
1293
      /* This should be a very improbable failure */
 
1294
      if (!check_key (&key2->keys[i], kt))
 
1295
        msg (M_FATAL, "Key #%d in '%s' is bad.  Try making a new key with --genkey.",
 
1296
             i+1, shared_secret_file);
 
1297
    }
 
1298
}
 
1299
 
 
1300
/* given a key and key_type, write key to buffer */
 
1301
void
 
1302
write_key (const struct key *key, const struct key_type *kt,
 
1303
           struct buffer *buf)
 
1304
{
 
1305
  ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
 
1306
          && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
 
1307
  ASSERT (buf_write (buf, &kt->cipher_length, 1));
 
1308
  ASSERT (buf_write (buf, &kt->hmac_length, 1));
 
1309
  ASSERT (buf_write (buf, key->cipher, kt->cipher_length));
 
1310
  ASSERT (buf_write (buf, key->hmac, kt->hmac_length));
 
1311
}
 
1312
 
 
1313
/*
 
1314
 * Given a key_type and buffer, read key from buffer.
 
1315
 * Return: 1 on success
 
1316
 *        -1 read failure
 
1317
 *         0 on key length mismatch 
 
1318
 */
 
1319
int
 
1320
read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
 
1321
{
 
1322
  uint8_t cipher_length;
 
1323
  uint8_t hmac_length;
 
1324
 
 
1325
  CLEAR (*key);
 
1326
  if (!buf_read (buf, &cipher_length, 1))
 
1327
    goto read_err;
 
1328
  if (!buf_read (buf, &hmac_length, 1))
 
1329
    goto read_err;
 
1330
 
 
1331
  if (!buf_read (buf, key->cipher, cipher_length))
 
1332
    goto read_err;
 
1333
  if (!buf_read (buf, key->hmac, hmac_length))
 
1334
    goto read_err;
 
1335
 
 
1336
  if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
 
1337
    goto key_len_err;
 
1338
 
 
1339
  return 1;
 
1340
 
 
1341
read_err:
 
1342
  msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
 
1343
  return -1;
 
1344
 
 
1345
key_len_err:
 
1346
  msg (D_TLS_ERRORS,
 
1347
       "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
 
1348
       kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
 
1349
  return 0;
 
1350
}
 
1351
 
 
1352
void
 
1353
show_available_ciphers ()
 
1354
{
 
1355
  int nid;
 
1356
 
 
1357
  printf ("The following ciphers and cipher modes are available\n"
 
1358
          "for use with " PACKAGE_NAME ".  Each cipher shown below may be\n"
 
1359
          "used as a parameter to the --cipher option.  The default\n"
 
1360
          "key size is shown as well as whether or not it can be\n"
 
1361
          "changed with the --keysize directive.  Using a CBC mode\n"
 
1362
          "is recommended.\n\n");
 
1363
 
 
1364
  for (nid = 0; nid < 10000; ++nid)     /* is there a better way to get the size of the nid list? */
 
1365
    {
 
1366
      const EVP_CIPHER *cipher = EVP_get_cipherbynid (nid);
 
1367
      if (cipher && cipher_ok (OBJ_nid2sn (nid)))
 
1368
        {
 
1369
          const unsigned int mode = EVP_CIPHER_mode (cipher);
 
1370
          if (mode == EVP_CIPH_CBC_MODE
 
1371
#ifdef ALLOW_NON_CBC_CIPHERS
 
1372
              || mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE
 
1373
#endif
 
1374
              )
 
1375
            printf ("%s %d bit default key (%s)\n",
 
1376
                    OBJ_nid2sn (nid),
 
1377
                    EVP_CIPHER_key_length (cipher) * 8,
 
1378
                    ((EVP_CIPHER_flags (cipher) & EVP_CIPH_VARIABLE_LENGTH) ?
 
1379
                     "variable" : "fixed"));
 
1380
        }
 
1381
    }
 
1382
  printf ("\n");
 
1383
}
 
1384
 
 
1385
void
 
1386
show_available_digests ()
 
1387
{
 
1388
  int nid;
 
1389
 
 
1390
  printf ("The following message digests are available for use with\n"
 
1391
          PACKAGE_NAME ".  A message digest is used in conjunction with\n"
 
1392
          "the HMAC function, to authenticate received packets.\n"
 
1393
          "You can specify a message digest as parameter to\n"
 
1394
          "the --auth option.\n\n");
 
1395
 
 
1396
  for (nid = 0; nid < 10000; ++nid)
 
1397
    {
 
1398
      const EVP_MD *digest = EVP_get_digestbynid (nid);
 
1399
      if (digest)
 
1400
        {
 
1401
          printf ("%s %d bit digest size\n",
 
1402
                  OBJ_nid2sn (nid), EVP_MD_size (digest) * 8);
 
1403
        }
 
1404
    }
 
1405
  printf ("\n");
 
1406
}
 
1407
 
 
1408
/*
 
1409
 * This routine should have additional OpenSSL crypto library initialisations
 
1410
 * used by both crypto and ssl components of OpenVPN.
 
1411
 */
 
1412
void init_crypto_lib ()
 
1413
{
 
1414
}
 
1415
 
 
1416
/*
 
1417
 * Random number functions, used in cases where we want
 
1418
 * reasonably strong cryptographic random number generation
 
1419
 * without depleting our entropy pool.  Used for random
 
1420
 * IV values and a number of other miscellaneous tasks.
 
1421
 */
 
1422
 
 
1423
#define NONCE_SECRET_LEN 16
 
1424
 
 
1425
static uint8_t nonce_data [SHA_DIGEST_LENGTH + NONCE_SECRET_LEN];
 
1426
 
 
1427
void
 
1428
prng_init (void)
 
1429
{
 
1430
  ASSERT (RAND_bytes (nonce_data, sizeof(nonce_data)));
 
1431
}
 
1432
 
 
1433
void
 
1434
prng_bytes (uint8_t *output, int len)
 
1435
{
 
1436
  SHA_CTX ctx;
 
1437
  mutex_lock (L_PRNG);
 
1438
  while (len > 0)
 
1439
    {
 
1440
      const int blen = min_int (len, SHA_DIGEST_LENGTH);
 
1441
      SHA1_Init (&ctx);
 
1442
      SHA1_Update (&ctx, nonce_data, sizeof (nonce_data));
 
1443
      SHA1_Final (nonce_data, &ctx);
 
1444
      memcpy (output, nonce_data, blen);
 
1445
      output += blen;
 
1446
      len -= blen;
 
1447
    }
 
1448
  mutex_unlock (L_PRNG);
 
1449
}
 
1450
 
 
1451
/* an analogue to the random() function, but use prng_bytes */
 
1452
long int
 
1453
get_random()
 
1454
{
 
1455
  long int l;
 
1456
  prng_bytes ((unsigned char *)&l, sizeof(l));
 
1457
  if (l < 0)
 
1458
    l = -l;
 
1459
  return l;
 
1460
}
 
1461
 
 
1462
const char *
 
1463
md5sum(uint8_t *buf, int len, int n_print_chars)
 
1464
{
 
1465
  uint8_t digest[MD5_DIGEST_LENGTH];
 
1466
  MD5 (buf, len, digest);
 
1467
  return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars);
 
1468
}
 
1469
 
 
1470
#ifndef USE_SSL
 
1471
 
 
1472
void
 
1473
init_ssl_lib (void)
 
1474
{
 
1475
  ERR_load_crypto_strings ();
 
1476
  OpenSSL_add_all_algorithms ();
 
1477
  init_crypto_lib();
 
1478
}
 
1479
 
 
1480
void
 
1481
free_ssl_lib (void)
 
1482
{
 
1483
  EVP_cleanup ();
 
1484
  ERR_free_strings ();
 
1485
}
 
1486
 
 
1487
#endif /* USE_SSL */
 
1488
#endif /* USE_CRYPTO */