pem.c 12.4 KB
Newer Older
1 2 3
/*
 *  Privacy Enhanced Mail (PEM) decoding
 *
4
 *  Copyright (C) 2006-2014, Brainspark B.V.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 *  This file is part of PolarSSL (http://www.polarssl.org)
 *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
 *
 *  All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "polarssl/config.h"

28
#if defined(POLARSSL_PEM_PARSE_C) || defined(POLARSSL_PEM_WRITE_C)
29 30 31 32 33 34 35
#include "polarssl/pem.h"
#include "polarssl/base64.h"
#include "polarssl/des.h"
#include "polarssl/aes.h"
#include "polarssl/md5.h"
#include "polarssl/cipher.h"

36 37
#if defined(POLARSSL_PLATFORM_C)
#include "polarssl/platform.h"
38 39 40 41 42
#else
#define polarssl_malloc     malloc
#define polarssl_free       free
#endif

43 44
#include <stdlib.h>

45
#if defined(POLARSSL_PEM_PARSE_C)
46 47 48 49 50
void pem_init( pem_context *ctx )
{
    memset( ctx, 0, sizeof( pem_context ) );
}

51 52
#if defined(POLARSSL_MD5_C) && defined(POLARSSL_CIPHER_MODE_CBC) &&         \
    ( defined(POLARSSL_DES_C) || defined(POLARSSL_AES_C) )
53 54 55
/*
 * Read a 16-byte hex string and convert it to binary
 */
56
static int pem_get_iv( const unsigned char *s, unsigned char *iv, size_t iv_len )
57
{
58
    size_t i, j, k;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

    memset( iv, 0, iv_len );

    for( i = 0; i < iv_len * 2; i++, s++ )
    {
        if( *s >= '0' && *s <= '9' ) j = *s - '0'; else
        if( *s >= 'A' && *s <= 'F' ) j = *s - '7'; else
        if( *s >= 'a' && *s <= 'f' ) j = *s - 'W'; else
            return( POLARSSL_ERR_PEM_INVALID_ENC_IV );

        k = ( ( i & 1 ) != 0 ) ? j : j << 4;

        iv[i >> 1] = (unsigned char)( iv[i >> 1] | k );
    }

    return( 0 );
}

77
static void pem_pbkdf1( unsigned char *key, size_t keylen,
78
                        unsigned char *iv,
79
                        const unsigned char *pwd, size_t pwdlen )
80 81 82
{
    md5_context md5_ctx;
    unsigned char md5sum[16];
83
    size_t use_len;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

    /*
     * key[ 0..15] = MD5(pwd || IV)
     */
    md5_starts( &md5_ctx );
    md5_update( &md5_ctx, pwd, pwdlen );
    md5_update( &md5_ctx, iv,  8 );
    md5_finish( &md5_ctx, md5sum );

    if( keylen <= 16 )
    {
        memcpy( key, md5sum, keylen );

        memset( &md5_ctx, 0, sizeof(  md5_ctx ) );
        memset( md5sum, 0, 16 );
        return;
    }

    memcpy( key, md5sum, 16 );

    /*
     * key[16..23] = MD5(key[ 0..15] || pwd || IV])
     */
    md5_starts( &md5_ctx );
    md5_update( &md5_ctx, md5sum,  16 );
    md5_update( &md5_ctx, pwd, pwdlen );
    md5_update( &md5_ctx, iv,  8 );
    md5_finish( &md5_ctx, md5sum );

    use_len = 16;
    if( keylen < 32 )
        use_len = keylen - 16;

    memcpy( key + 16, md5sum, use_len );

    memset( &md5_ctx, 0, sizeof(  md5_ctx ) );
    memset( md5sum, 0, 16 );
}

#if defined(POLARSSL_DES_C)
/*
 * Decrypt with DES-CBC, using PBKDF1 for key derivation
 */
static void pem_des_decrypt( unsigned char des_iv[8],
128 129
                               unsigned char *buf, size_t buflen,
                               const unsigned char *pwd, size_t pwdlen )
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
{
    des_context des_ctx;
    unsigned char des_key[8];

    pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen );

    des_setkey_dec( &des_ctx, des_key );
    des_crypt_cbc( &des_ctx, DES_DECRYPT, buflen,
                     des_iv, buf, buf );

    memset( &des_ctx, 0, sizeof( des_ctx ) );
    memset( des_key, 0, 8 );
}

/*
 * Decrypt with 3DES-CBC, using PBKDF1 for key derivation
 */
static void pem_des3_decrypt( unsigned char des3_iv[8],
148 149
                               unsigned char *buf, size_t buflen,
                               const unsigned char *pwd, size_t pwdlen )
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
{
    des3_context des3_ctx;
    unsigned char des3_key[24];

    pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen );

    des3_set3key_dec( &des3_ctx, des3_key );
    des3_crypt_cbc( &des3_ctx, DES_DECRYPT, buflen,
                     des3_iv, buf, buf );

    memset( &des3_ctx, 0, sizeof( des3_ctx ) );
    memset( des3_key, 0, 24 );
}
#endif /* POLARSSL_DES_C */

#if defined(POLARSSL_AES_C)
/*
 * Decrypt with AES-XXX-CBC, using PBKDF1 for key derivation
 */
169 170 171
static void pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,
                               unsigned char *buf, size_t buflen,
                               const unsigned char *pwd, size_t pwdlen )
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
{
    aes_context aes_ctx;
    unsigned char aes_key[32];

    pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen );

    aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 );
    aes_crypt_cbc( &aes_ctx, AES_DECRYPT, buflen,
                     aes_iv, buf, buf );

    memset( &aes_ctx, 0, sizeof( aes_ctx ) );
    memset( aes_key, 0, keylen );
}
#endif /* POLARSSL_AES_C */

187 188
#endif /* POLARSSL_MD5_C && POLARSSL_CIPHER_MODE_CBC &&
          ( POLARSSL_AES_C || POLARSSL_DES_C ) */
189

190 191 192
int pem_read_buffer( pem_context *ctx, const char *header, const char *footer,
                     const unsigned char *data, const unsigned char *pwd,
                     size_t pwdlen, size_t *use_len )
193
{
194 195
    int ret, enc;
    size_t len;
196
    unsigned char *buf;
197
    const unsigned char *s1, *s2, *end;
198 199
#if defined(POLARSSL_MD5_C) && defined(POLARSSL_CIPHER_MODE_CBC) &&         \
    ( defined(POLARSSL_DES_C) || defined(POLARSSL_AES_C) )
200 201 202 203 204
    unsigned char pem_iv[16];
    cipher_type_t enc_alg = POLARSSL_CIPHER_NONE;
#else
    ((void) pwd);
    ((void) pwdlen);
205 206
#endif /* POLARSSL_MD5_C && POLARSSL_CIPHER_MODE_CBC &&
          ( POLARSSL_AES_C || POLARSSL_DES_C ) */
207 208

    if( ctx == NULL )
209
        return( POLARSSL_ERR_PEM_BAD_INPUT_DATA );
210

211
    s1 = (unsigned char *) strstr( (const char *) data, header );
212 213

    if( s1 == NULL )
214
        return( POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
215

216
    s2 = (unsigned char *) strstr( (const char *) data, footer );
217 218

    if( s2 == NULL || s2 <= s1 )
219
        return( POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
220 221 222 223

    s1 += strlen( header );
    if( *s1 == '\r' ) s1++;
    if( *s1 == '\n' ) s1++;
224 225 226 227 228 229 230
    else return( POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT );

    end = s2;
    end += strlen( footer );
    if( *end == '\r' ) end++;
    if( *end == '\n' ) end++;
    *use_len = end - data;
231 232 233 234 235

    enc = 0;

    if( memcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 )
    {
236 237
#if defined(POLARSSL_MD5_C) && defined(POLARSSL_CIPHER_MODE_CBC) &&         \
    ( defined(POLARSSL_DES_C) || defined(POLARSSL_AES_C) )
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        enc++;

        s1 += 22;
        if( *s1 == '\r' ) s1++;
        if( *s1 == '\n' ) s1++;
        else return( POLARSSL_ERR_PEM_INVALID_DATA );


#if defined(POLARSSL_DES_C)
        if( memcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 )
        {
            enc_alg = POLARSSL_CIPHER_DES_EDE3_CBC;

            s1 += 23;
            if( pem_get_iv( s1, pem_iv, 8 ) != 0 )
                return( POLARSSL_ERR_PEM_INVALID_ENC_IV );

            s1 += 16;
        }
        else if( memcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 )
        {
            enc_alg = POLARSSL_CIPHER_DES_CBC;

            s1 += 18;
            if( pem_get_iv( s1, pem_iv, 8) != 0 )
                return( POLARSSL_ERR_PEM_INVALID_ENC_IV );

            s1 += 16;
        }
#endif /* POLARSSL_DES_C */

#if defined(POLARSSL_AES_C)
        if( memcmp( s1, "DEK-Info: AES-", 14 ) == 0 )
        {
            if( memcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 )
                enc_alg = POLARSSL_CIPHER_AES_128_CBC;
            else if( memcmp( s1, "DEK-Info: AES-192-CBC,", 22 ) == 0 )
                enc_alg = POLARSSL_CIPHER_AES_192_CBC;
            else if( memcmp( s1, "DEK-Info: AES-256-CBC,", 22 ) == 0 )
                enc_alg = POLARSSL_CIPHER_AES_256_CBC;
            else
                return( POLARSSL_ERR_PEM_UNKNOWN_ENC_ALG );

            s1 += 22;
            if( pem_get_iv( s1, pem_iv, 16 ) != 0 )
                return( POLARSSL_ERR_PEM_INVALID_ENC_IV );

            s1 += 32;
        }
#endif /* POLARSSL_AES_C */
288

289 290 291 292 293 294 295 296
        if( enc_alg == POLARSSL_CIPHER_NONE )
            return( POLARSSL_ERR_PEM_UNKNOWN_ENC_ALG );

        if( *s1 == '\r' ) s1++;
        if( *s1 == '\n' ) s1++;
        else return( POLARSSL_ERR_PEM_INVALID_DATA );
#else
        return( POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE );
297 298
#endif /* POLARSSL_MD5_C && POLARSSL_CIPHER_MODE_CBC &&
          ( POLARSSL_AES_C || POLARSSL_DES_C ) */
299 300 301 302 303 304
    }

    len = 0;
    ret = base64_decode( NULL, &len, s1, s2 - s1 );

    if( ret == POLARSSL_ERR_BASE64_INVALID_CHARACTER )
305
        return( POLARSSL_ERR_PEM_INVALID_DATA + ret );
306

307
    if( ( buf = (unsigned char *) polarssl_malloc( len ) ) == NULL )
308 309 310 311
        return( POLARSSL_ERR_PEM_MALLOC_FAILED );

    if( ( ret = base64_decode( buf, &len, s1, s2 - s1 ) ) != 0 )
    {
312
        polarssl_free( buf );
313
        return( POLARSSL_ERR_PEM_INVALID_DATA + ret );
314
    }
315

316 317
    if( enc != 0 )
    {
318 319
#if defined(POLARSSL_MD5_C) && defined(POLARSSL_CIPHER_MODE_CBC) &&         \
    ( defined(POLARSSL_DES_C) || defined(POLARSSL_AES_C) )
320 321
        if( pwd == NULL )
        {
322
            polarssl_free( buf );
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
            return( POLARSSL_ERR_PEM_PASSWORD_REQUIRED );
        }

#if defined(POLARSSL_DES_C)
        if( enc_alg == POLARSSL_CIPHER_DES_EDE3_CBC )
            pem_des3_decrypt( pem_iv, buf, len, pwd, pwdlen );
        else if( enc_alg == POLARSSL_CIPHER_DES_CBC )
            pem_des_decrypt( pem_iv, buf, len, pwd, pwdlen );
#endif /* POLARSSL_DES_C */

#if defined(POLARSSL_AES_C)
        if( enc_alg == POLARSSL_CIPHER_AES_128_CBC )
            pem_aes_decrypt( pem_iv, 16, buf, len, pwd, pwdlen );
        else if( enc_alg == POLARSSL_CIPHER_AES_192_CBC )
            pem_aes_decrypt( pem_iv, 24, buf, len, pwd, pwdlen );
        else if( enc_alg == POLARSSL_CIPHER_AES_256_CBC )
            pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen );
#endif /* POLARSSL_AES_C */

342
        /*
343 344 345 346
         * The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3
         * length bytes (allow 4 to be sure) in all known use cases.
         *
         * Use that as heurisitic to try detecting password mismatchs.
347
         */
348
        if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 )
349
        {
350
            polarssl_free( buf );
351 352 353
            return( POLARSSL_ERR_PEM_PASSWORD_MISMATCH );
        }
#else
354
        polarssl_free( buf );
355
        return( POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE );
356 357
#endif /* POLARSSL_MD5_C && POLARSSL_CIPHER_MODE_CBC &&
          ( POLARSSL_AES_C || POLARSSL_DES_C ) */
358 359 360 361 362 363 364 365
    }

    ctx->buf = buf;
    ctx->buflen = len;

    return( 0 );
}

366 367 368 369 370 371 372 373 374 375 376 377 378
void pem_free( pem_context *ctx )
{
    if( ctx->buf )
        polarssl_free( ctx->buf );

    if( ctx->info )
        polarssl_free( ctx->info );

    memset( ctx, 0, sizeof( pem_context ) );
}
#endif /* POLARSSL_PEM_PARSE_C */

#if defined(POLARSSL_PEM_WRITE_C)
379 380 381 382 383 384
int pem_write_buffer( const char *header, const char *footer,
                      const unsigned char *der_data, size_t der_len,
                      unsigned char *buf, size_t buf_len, size_t *olen )
{
    int ret;
    unsigned char *encode_buf, *c, *p = buf;
385
    size_t len = 0, use_len = 0, add_len = 0;
386 387

    base64_encode( NULL, &use_len, der_data, der_len );
388 389
    add_len = strlen( header ) + strlen( footer ) + ( use_len / 64 ) + 1;

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    if( use_len + add_len > buf_len )
    {
        *olen = use_len + add_len;
        return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL );
    }

    if( ( encode_buf = polarssl_malloc( use_len ) ) == NULL )
        return( POLARSSL_ERR_PEM_MALLOC_FAILED );

    if( ( ret = base64_encode( encode_buf, &use_len, der_data,
                               der_len ) ) != 0 )
    {
        polarssl_free( encode_buf );
        return( ret );
    }

    memcpy( p, header, strlen( header ) );
    p += strlen( header );
    c = encode_buf;

    while( use_len )
    {
        len = ( use_len > 64 ) ? 64 : use_len;
        memcpy( p, c, len );
        use_len -= len;
        p += len;
        c += len;
        *p++ = '\n';
    }

    memcpy( p, footer, strlen( footer ) );
    p += strlen( footer );

    *p++ = '\0';
    *olen = p - buf;

    polarssl_free( encode_buf );
    return( 0 );
}
429 430
#endif /* POLARSSL_PEM_WRITE_C */
#endif /* POLARSSL_PEM_PARSE_C || POLARSSL_PEM_WRITE_C */