1 /*
   2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
   3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
   4  *                    All rights reserved
   5  *
   6  * As far as I am concerned, the code I have written for this software
   7  * can be used freely for any purpose.  Any derived versions of this
   8  * software must be clearly marked as such, and if the derived work is
   9  * incompatible with the protocol description in the RFC file, it must be
  10  * called by a name other than "ssh" or "Secure Shell".
  11  *
  12  *
  13  * Copyright (c) 1999 Niels Provos.  All rights reserved.
  14  * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
  15  *
  16  * Redistribution and use in source and binary forms, with or without
  17  * modification, are permitted provided that the following conditions
  18  * are met:
  19  * 1. Redistributions of source code must retain the above copyright
  20  *    notice, this list of conditions and the following disclaimer.
  21  * 2. Redistributions in binary form must reproduce the above copyright
  22  *    notice, this list of conditions and the following disclaimer in the
  23  *    documentation and/or other materials provided with the distribution.
  24  *
  25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35  */
  36 
  37 /*
  38  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
  39  * Use is subject to license terms.
  40  */
  41 
  42 #include "includes.h"
  43 RCSID("$OpenBSD: cipher.c,v 1.61 2002/07/12 15:50:17 markus Exp $");
  44 
  45 #include "xmalloc.h"
  46 #include "log.h"
  47 #include "cipher.h"
  48 
  49 #include <openssl/opensslconf.h>
  50 #include <openssl/md5.h>
  51 
  52 /*
  53  * Symmetric ciphers can be offloaded to any engine through the EVP API only.
  54  * However, OpenSSL doesn't offer AES in counter mode through EVP. So, we must
  55  * define our own EVP functions.
  56  */
  57 extern const EVP_CIPHER *evp_aes_128_ctr(void);
  58 extern const EVP_CIPHER *evp_aes_192_ctr(void);
  59 extern const EVP_CIPHER *evp_aes_256_ctr(void);
  60 extern void ssh_aes_ctr_iv(EVP_CIPHER_CTX *, int, u_char *, u_int);
  61 
  62 static const EVP_CIPHER *evp_ssh1_3des(void);
  63 static const EVP_CIPHER *evp_ssh1_bf(void);
  64 
  65 struct Cipher {
  66         char    *name;
  67         int     number;         /* for ssh1 only */
  68         u_int   block_size;
  69         u_int   key_len;
  70         u_int   discard_len;
  71         const EVP_CIPHER        *(*evptype)(void);
  72 } ciphers[] = {
  73         { "none",         SSH_CIPHER_NONE,      8,  0,    0, EVP_enc_null },
  74         { "des",          SSH_CIPHER_DES,       8,  8,    0, EVP_des_cbc },
  75         { "3des",         SSH_CIPHER_3DES,      8, 16,    0, evp_ssh1_3des },
  76         { "blowfish",     SSH_CIPHER_BLOWFISH,  8, 32,    0, evp_ssh1_bf },
  77         { "3des-cbc",     SSH_CIPHER_SSH2,      8, 24,    0, EVP_des_ede3_cbc },
  78         { "blowfish-cbc", SSH_CIPHER_SSH2,      8, 16,    0, EVP_bf_cbc },
  79 #ifdef SOLARIS_SSH_ENABLE_CAST5_128
  80         { "cast128-cbc",  SSH_CIPHER_SSH2,      8, 16,    0, EVP_cast5_cbc },
  81 #endif /* SOLARIS_SSH_ENABLE_CAST5_128 */
  82         { "arcfour",      SSH_CIPHER_SSH2,      8, 16,    0, EVP_rc4 },
  83         { "arcfour128",   SSH_CIPHER_SSH2,      8, 16, 1536, EVP_rc4 },
  84         { "arcfour256",   SSH_CIPHER_SSH2,      8, 32, 1536, EVP_rc4 },
  85         { "aes128-cbc",   SSH_CIPHER_SSH2,     16, 16,    0, EVP_aes_128_cbc },
  86         { "aes192-cbc",   SSH_CIPHER_SSH2,     16, 24,    0, EVP_aes_192_cbc },
  87         { "aes256-cbc",   SSH_CIPHER_SSH2,     16, 32,    0, EVP_aes_256_cbc },
  88         { "aes128-ctr",   SSH_CIPHER_SSH2,     16, 16,    0, evp_aes_128_ctr },
  89         { "aes192-ctr",   SSH_CIPHER_SSH2,     16, 24,    0, evp_aes_192_ctr },
  90         { "aes256-ctr",   SSH_CIPHER_SSH2,     16, 32,    0, evp_aes_256_ctr },
  91         { NULL,           SSH_CIPHER_ILLEGAL,   0,  0,    0, NULL }
  92 };
  93 
  94 /*--*/
  95 
  96 u_int
  97 cipher_blocksize(Cipher *c)
  98 {
  99         return (c->block_size);
 100 }
 101 
 102 u_int
 103 cipher_keylen(Cipher *c)
 104 {
 105         return (c->key_len);
 106 }
 107 
 108 u_int
 109 cipher_get_number(Cipher *c)
 110 {
 111         return (c->number);
 112 }
 113 
 114 u_int
 115 cipher_mask_ssh1(int client)
 116 {
 117         u_int mask = 0;
 118         mask |= 1 << SSH_CIPHER_3DES;             /* Mandatory */
 119         mask |= 1 << SSH_CIPHER_BLOWFISH;
 120         if (client) {
 121                 mask |= 1 << SSH_CIPHER_DES;
 122         }
 123         return mask;
 124 }
 125 
 126 Cipher *
 127 cipher_by_name(const char *name)
 128 {
 129         Cipher *c;
 130         for (c = ciphers; c->name != NULL; c++)
 131                 if (strcasecmp(c->name, name) == 0)
 132                         return c;
 133         return NULL;
 134 }
 135 
 136 Cipher *
 137 cipher_by_number(int id)
 138 {
 139         Cipher *c;
 140         for (c = ciphers; c->name != NULL; c++)
 141                 if (c->number == id)
 142                         return c;
 143         return NULL;
 144 }
 145 
 146 #define CIPHER_SEP      ","
 147 int
 148 ciphers_valid(const char *names)
 149 {
 150         Cipher *c;
 151         char *ciphers, *cp;
 152         char *p;
 153 
 154         if (names == NULL || strcmp(names, "") == 0)
 155                 return 0;
 156         ciphers = cp = xstrdup(names);
 157         for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0';
 158             (p = strsep(&cp, CIPHER_SEP))) {
 159                 c = cipher_by_name(p);
 160                 if (c == NULL || c->number != SSH_CIPHER_SSH2) {
 161                         debug("bad cipher %s [%s]", p, names);
 162                         xfree(ciphers);
 163                         return 0;
 164                 } else {
 165                         debug3("cipher ok: %s [%s]", p, names);
 166                 }
 167         }
 168         debug3("ciphers ok: [%s]", names);
 169         xfree(ciphers);
 170         return 1;
 171 }
 172 
 173 /*
 174  * Parses the name of the cipher.  Returns the number of the corresponding
 175  * cipher, or -1 on error.
 176  */
 177 
 178 int
 179 cipher_number(const char *name)
 180 {
 181         Cipher *c;
 182         if (name == NULL)
 183                 return -1;
 184         c = cipher_by_name(name);
 185         return (c==NULL) ? -1 : c->number;
 186 }
 187 
 188 char *
 189 cipher_name(int id)
 190 {
 191         Cipher *c = cipher_by_number(id);
 192         return (c==NULL) ? "<unknown>" : c->name;
 193 }
 194 
 195 void
 196 cipher_init(CipherContext *cc, Cipher *cipher,
 197     const u_char *key, u_int keylen, const u_char *iv, u_int ivlen,
 198     int encrypt)
 199 {
 200         static int dowarn = 1;
 201         const EVP_CIPHER *type;
 202         int klen;
 203         u_char *junk, *discard;
 204 
 205         if (cipher->number == SSH_CIPHER_DES) {
 206                 if (dowarn) {
 207                         error("Warning: use of DES is strongly discouraged "
 208                             "due to cryptographic weaknesses");
 209                         dowarn = 0;
 210                 }
 211                 if (keylen > 8)
 212                         keylen = 8;
 213         }
 214         cc->plaintext = (cipher->number == SSH_CIPHER_NONE);
 215 
 216         if (keylen < cipher->key_len)
 217                 fatal("cipher_init: key length %d is insufficient for %s.",
 218                     keylen, cipher->name);
 219         if (iv != NULL && ivlen < cipher->block_size)
 220                 fatal("cipher_init: iv length %d is insufficient for %s.",
 221                     ivlen, cipher->name);
 222         cc->cipher = cipher;
 223 
 224         type = (*cipher->evptype)();
 225 
 226         EVP_CIPHER_CTX_init(&cc->evp);
 227         /*
 228          * cc->evp is of type EVP_CIPHER_CTX and its key_len will be set to the
 229          * default value here for the cipher type. If the requested key length
 230          * is different from the default value we will call EVP_CipherInit()
 231          * again, see below.
 232          */
 233         if (EVP_CipherInit(&cc->evp, type, NULL, (u_char *)iv,
 234             (encrypt == CIPHER_ENCRYPT)) == 0)
 235                 fatal("cipher_init: EVP_CipherInit failed for %s",
 236                     cipher->name);
 237         klen = EVP_CIPHER_CTX_key_length(&cc->evp);
 238         if (klen > 0 && keylen != klen) {
 239                 debug("cipher_init: set keylen (%d -> %d)", klen, keylen);
 240                 if (EVP_CIPHER_CTX_set_key_length(&cc->evp, keylen) == 0)
 241                         fatal("cipher_init: set keylen failed (%d -> %d)",
 242                             klen, keylen);
 243         }
 244         if (EVP_CipherInit(&cc->evp, NULL, (u_char *)key, NULL, -1) == 0)
 245                 fatal("cipher_init: EVP_CipherInit: set key failed for %s",
 246                     cipher->name);
 247 
 248         if (cipher->discard_len > 0) {
 249                 junk = xmalloc(cipher->discard_len);
 250                 discard = xmalloc(cipher->discard_len);
 251                 if (EVP_Cipher(&cc->evp, discard, junk,
 252                     cipher->discard_len) == 0)
 253                         fatal("cipher_init: EVP_Cipher failed during discard");
 254                 memset(discard, 0, cipher->discard_len);
 255                 xfree(junk);
 256                 xfree(discard);
 257         }
 258 }
 259 
 260 void
 261 cipher_crypt(CipherContext *cc, u_char *dest, const u_char *src, u_int len)
 262 {
 263         if (len % cc->cipher->block_size)
 264                 fatal("cipher_encrypt: bad plaintext length %d", len);
 265         if (EVP_Cipher(&cc->evp, dest, (u_char *)src, len) == 0)
 266                 fatal("evp_crypt: EVP_Cipher failed");
 267 }
 268 
 269 void
 270 cipher_cleanup(CipherContext *cc)
 271 {
 272         if (EVP_CIPHER_CTX_cleanup(&cc->evp) == 0)
 273                 error("cipher_cleanup: EVP_CIPHER_CTX_cleanup failed");
 274 }
 275 
 276 /*
 277  * Selects the cipher, and keys if by computing the MD5 checksum of the
 278  * passphrase and using the resulting 16 bytes as the key.
 279  */
 280 
 281 void
 282 cipher_set_key_string(CipherContext *cc, Cipher *cipher,
 283     const char *passphrase, int encrypt)
 284 {
 285         MD5_CTX md;
 286         u_char digest[16];
 287 
 288         MD5_Init(&md);
 289         MD5_Update(&md, (const u_char *)passphrase, strlen(passphrase));
 290         MD5_Final(digest, &md);
 291 
 292         cipher_init(cc, cipher, digest, 16, NULL, 0, encrypt);
 293 
 294         memset(digest, 0, sizeof(digest));
 295         memset(&md, 0, sizeof(md));
 296 }
 297 
 298 /* Implementations for other non-EVP ciphers */
 299 
 300 /*
 301  * This is used by SSH1:
 302  *
 303  * What kind of triple DES are these 2 routines?
 304  *
 305  * Why is there a redundant initialization vector?
 306  *
 307  * If only iv3 was used, then, this would till effect have been
 308  * outer-cbc. However, there is also a private iv1 == iv2 which
 309  * perhaps makes differential analysis easier. On the other hand, the
 310  * private iv1 probably makes the CRC-32 attack ineffective. This is a
 311  * result of that there is no longer any known iv1 to use when
 312  * choosing the X block.
 313  */
 314 struct ssh1_3des_ctx
 315 {
 316         EVP_CIPHER_CTX  k1, k2, k3;
 317 };
 318 
 319 static int
 320 ssh1_3des_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv,
 321     int enc)
 322 {
 323         struct ssh1_3des_ctx *c;
 324         u_char *k1, *k2, *k3;
 325 
 326         if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
 327                 c = xmalloc(sizeof(*c));
 328                 EVP_CIPHER_CTX_set_app_data(ctx, c);
 329         }
 330         if (key == NULL)
 331                 return (1);
 332         if (enc == -1)
 333                 enc = ctx->encrypt;
 334         k1 = k2 = k3 = (u_char *) key;
 335         k2 += 8;
 336         if (EVP_CIPHER_CTX_key_length(ctx) >= 16+8) {
 337                 if (enc)
 338                         k3 += 16;
 339                 else
 340                         k1 += 16;
 341         }
 342         EVP_CIPHER_CTX_init(&c->k1);
 343         EVP_CIPHER_CTX_init(&c->k2);
 344         EVP_CIPHER_CTX_init(&c->k3);
 345         if (EVP_CipherInit(&c->k1, EVP_des_cbc(), k1, NULL, enc) == 0 ||
 346             EVP_CipherInit(&c->k2, EVP_des_cbc(), k2, NULL, !enc) == 0 ||
 347             EVP_CipherInit(&c->k3, EVP_des_cbc(), k3, NULL, enc) == 0) {
 348                 memset(c, 0, sizeof(*c));
 349                 xfree(c);
 350                 EVP_CIPHER_CTX_set_app_data(ctx, NULL);
 351                 return (0);
 352         }
 353         return (1);
 354 }
 355 
 356 static int
 357 ssh1_3des_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src, u_int len)
 358 {
 359         struct ssh1_3des_ctx *c;
 360 
 361         if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
 362                 error("ssh1_3des_cbc: no context");
 363                 return (0);
 364         }
 365         if (EVP_Cipher(&c->k1, dest, (u_char *)src, len) == 0 ||
 366             EVP_Cipher(&c->k2, dest, dest, len) == 0 ||
 367             EVP_Cipher(&c->k3, dest, dest, len) == 0)
 368                 return (0);
 369         return (1);
 370 }
 371 
 372 static int
 373 ssh1_3des_cleanup(EVP_CIPHER_CTX *ctx)
 374 {
 375         struct ssh1_3des_ctx *c;
 376 
 377         if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) {
 378                 memset(c, 0, sizeof(*c));
 379                 xfree(c);
 380                 EVP_CIPHER_CTX_set_app_data(ctx, NULL);
 381         }
 382         return (1);
 383 }
 384 
 385 static const EVP_CIPHER *
 386 evp_ssh1_3des(void)
 387 {
 388         static EVP_CIPHER ssh1_3des;
 389 
 390         memset(&ssh1_3des, 0, sizeof(EVP_CIPHER));
 391         ssh1_3des.nid = NID_undef;
 392         ssh1_3des.block_size = 8;
 393         ssh1_3des.iv_len = 0;
 394         ssh1_3des.key_len = 16;
 395         ssh1_3des.init = ssh1_3des_init;
 396         ssh1_3des.cleanup = ssh1_3des_cleanup;
 397         ssh1_3des.do_cipher = ssh1_3des_cbc;
 398         ssh1_3des.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH;
 399         return (&ssh1_3des);
 400 }
 401 
 402 /*
 403  * SSH1 uses a variation on Blowfish, all bytes must be swapped before
 404  * and after encryption/decryption. Thus the swap_bytes stuff (yuk).
 405  */
 406 static void
 407 swap_bytes(const u_char *src, u_char *dst, int n)
 408 {
 409         u_char c[4];
 410 
 411         /* Process 4 bytes every lap. */
 412         for (n = n / 4; n > 0; n--) {
 413                 c[3] = *src++;
 414                 c[2] = *src++;
 415                 c[1] = *src++;
 416                 c[0] = *src++;
 417 
 418                 *dst++ = c[0];
 419                 *dst++ = c[1];
 420                 *dst++ = c[2];
 421                 *dst++ = c[3];
 422         }
 423 }
 424 
 425 static int (*orig_bf)(EVP_CIPHER_CTX *, u_char *, const u_char *, u_int) = NULL;
 426 
 427 static int
 428 bf_ssh1_cipher(EVP_CIPHER_CTX *ctx, u_char *out, const u_char *in, u_int len)
 429 {
 430         int ret;
 431 
 432         swap_bytes(in, out, len);
 433         ret = (*orig_bf)(ctx, out, out, len);
 434         swap_bytes(out, out, len);
 435         return (ret);
 436 }
 437 
 438 static const EVP_CIPHER *
 439 evp_ssh1_bf(void)
 440 {
 441         static EVP_CIPHER ssh1_bf;
 442 
 443         memcpy(&ssh1_bf, EVP_bf_cbc(), sizeof(EVP_CIPHER));
 444         orig_bf = ssh1_bf.do_cipher;
 445         ssh1_bf.nid = NID_undef;
 446         ssh1_bf.do_cipher = bf_ssh1_cipher;
 447         ssh1_bf.key_len = 32;
 448         return (&ssh1_bf);
 449 }
 450 
 451 /*
 452  * Exports an IV from the CipherContext required to export the key
 453  * state back from the unprivileged child to the privileged parent
 454  * process.
 455  */
 456 
 457 int
 458 cipher_get_keyiv_len(CipherContext *cc)
 459 {
 460         Cipher *c = cc->cipher;
 461         int ivlen;
 462 
 463         if (c->number == SSH_CIPHER_3DES)
 464                 ivlen = 24;
 465         else
 466                 ivlen = EVP_CIPHER_CTX_iv_length(&cc->evp);
 467         return (ivlen);
 468 }
 469 
 470 void
 471 cipher_get_keyiv(CipherContext *cc, u_char *iv, u_int len)
 472 {
 473         Cipher *c = cc->cipher;
 474         u_char *civ = NULL;
 475         int evplen;
 476 
 477         switch (c->number) {
 478         case SSH_CIPHER_SSH2:
 479         case SSH_CIPHER_DES:
 480         case SSH_CIPHER_BLOWFISH:
 481                 evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
 482                 if (evplen == 0)
 483                         return;
 484                 if (evplen != len)
 485                         fatal("%s: wrong iv length %d != %d", __func__,
 486                             evplen, len);
 487 
 488                 if (c->evptype == evp_aes_128_ctr) {
 489                         ssh_aes_ctr_iv(&cc->evp, 0, iv, len);
 490                         return;
 491                 } else {
 492                         civ = cc->evp.iv;
 493                 }
 494                 break;
 495         case SSH_CIPHER_3DES: {
 496                 struct ssh1_3des_ctx *desc;
 497                 if (len != 24)
 498                         fatal("%s: bad 3des iv length: %d", __func__, len);
 499                 desc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
 500                 if (desc == NULL)
 501                         fatal("%s: no 3des context", __func__);
 502                 debug3("%s: Copying 3DES IV", __func__);
 503                 memcpy(iv, desc->k1.iv, 8);
 504                 memcpy(iv + 8, desc->k2.iv, 8);
 505                 memcpy(iv + 16, desc->k3.iv, 8);
 506                 return;
 507         }
 508         default:
 509                 fatal("%s: bad cipher %d", __func__, c->number);
 510         }
 511         memcpy(iv, civ, len);
 512 }
 513 
 514 void
 515 cipher_set_keyiv(CipherContext *cc, u_char *iv)
 516 {
 517         Cipher *c = cc->cipher;
 518         u_char *div = NULL;
 519         int evplen = 0;
 520 
 521         switch (c->number) {
 522         case SSH_CIPHER_SSH2:
 523         case SSH_CIPHER_DES:
 524         case SSH_CIPHER_BLOWFISH:
 525                 evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
 526                 if (evplen == 0)
 527                         return;
 528 
 529                 if (c->evptype == evp_aes_128_ctr) {
 530                         ssh_aes_ctr_iv(&cc->evp, 1, iv, evplen);
 531                         return;
 532                 } else {
 533                         div = cc->evp.iv;
 534                 }
 535                 break;
 536         case SSH_CIPHER_3DES: {
 537                 struct ssh1_3des_ctx *desc;
 538                 desc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
 539                 if (desc == NULL)
 540                         fatal("%s: no 3des context", __func__);
 541                 debug3("%s: Installed 3DES IV", __func__);
 542                 memcpy(desc->k1.iv, iv, 8);
 543                 memcpy(desc->k2.iv, iv + 8, 8);
 544                 memcpy(desc->k3.iv, iv + 16, 8);
 545                 return;
 546         }
 547         default:
 548                 fatal("%s: bad cipher %d", __func__, c->number);
 549         }
 550         memcpy(div, iv, evplen);
 551 }
 552 
 553 #if OPENSSL_VERSION_NUMBER < 0x00907000L
 554 #define EVP_X_STATE(evp)        &(evp).c
 555 #define EVP_X_STATE_LEN(evp)    sizeof((evp).c)
 556 #else
 557 #define EVP_X_STATE(evp)        (evp).cipher_data
 558 #define EVP_X_STATE_LEN(evp)    (evp).cipher->ctx_size
 559 #endif
 560 
 561 int
 562 cipher_get_keycontext(CipherContext *cc, u_char *dat)
 563 {
 564         int plen = 0;
 565         Cipher *c = cc->cipher;
 566 
 567         if (c->evptype == EVP_rc4) {
 568                 plen = EVP_X_STATE_LEN(cc->evp);
 569                 if (dat == NULL)
 570                         return (plen);
 571                 memcpy(dat, EVP_X_STATE(cc->evp), plen);
 572         }
 573         return (plen);
 574 }
 575 
 576 void
 577 cipher_set_keycontext(CipherContext *cc, u_char *dat)
 578 {
 579         Cipher *c = cc->cipher;
 580         int plen;
 581 
 582         if (c->evptype == EVP_rc4) {
 583                 plen = EVP_X_STATE_LEN(cc->evp);
 584                 memcpy(EVP_X_STATE(cc->evp), dat, plen);
 585         }
 586 }