1 /*
2  *  Privacy Enhanced Mail (PEM) decoding
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
23 
24 #include "mbedtls/pem.h"
25 #include "mbedtls/base64.h"
26 #include "mbedtls/des.h"
27 #include "mbedtls/aes.h"
28 #include "mbedtls/md5.h"
29 #include "mbedtls/cipher.h"
30 #include "mbedtls/platform_util.h"
31 #include "mbedtls/error.h"
32 
33 #include <string.h>
34 
35 #if defined(MBEDTLS_PLATFORM_C)
36 #include "mbedtls/platform.h"
37 #else
38 #include <stdlib.h>
39 #define mbedtls_calloc    calloc
40 #define mbedtls_free       free
41 #endif
42 
43 #if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_init(mbedtls_pem_context * ctx)44 void mbedtls_pem_init( mbedtls_pem_context *ctx )
45 {
46     memset( ctx, 0, sizeof( mbedtls_pem_context ) );
47 }
48 
49 #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \
50     ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
51 /*
52  * Read a 16-byte hex string and convert it to binary
53  */
pem_get_iv(const unsigned char * s,unsigned char * iv,size_t iv_len)54 static int pem_get_iv( const unsigned char *s, unsigned char *iv,
55                        size_t iv_len )
56 {
57     size_t i, j, k;
58 
59     memset( iv, 0, iv_len );
60 
61     for( i = 0; i < iv_len * 2; i++, s++ )
62     {
63         if( *s >= '0' && *s <= '9' ) j = *s - '0'; else
64         if( *s >= 'A' && *s <= 'F' ) j = *s - '7'; else
65         if( *s >= 'a' && *s <= 'f' ) j = *s - 'W'; else
66             return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
67 
68         k = ( ( i & 1 ) != 0 ) ? j : j << 4;
69 
70         iv[i >> 1] = (unsigned char)( iv[i >> 1] | k );
71     }
72 
73     return( 0 );
74 }
75 
pem_pbkdf1(unsigned char * key,size_t keylen,unsigned char * iv,const unsigned char * pwd,size_t pwdlen)76 static int pem_pbkdf1( unsigned char *key, size_t keylen,
77                        unsigned char *iv,
78                        const unsigned char *pwd, size_t pwdlen )
79 {
80     mbedtls_md5_context md5_ctx;
81     unsigned char md5sum[16];
82     size_t use_len;
83     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
84 
85     mbedtls_md5_init( &md5_ctx );
86 
87     /*
88      * key[ 0..15] = MD5(pwd || IV)
89      */
90     if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )
91         goto exit;
92     if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
93         goto exit;
94     if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv,  8 ) ) != 0 )
95         goto exit;
96     if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
97         goto exit;
98 
99     if( keylen <= 16 )
100     {
101         memcpy( key, md5sum, keylen );
102         goto exit;
103     }
104 
105     memcpy( key, md5sum, 16 );
106 
107     /*
108      * key[16..23] = MD5(key[ 0..15] || pwd || IV])
109      */
110     if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )
111         goto exit;
112     if( ( ret = mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) ) != 0 )
113         goto exit;
114     if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )
115         goto exit;
116     if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )
117         goto exit;
118     if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )
119         goto exit;
120 
121     use_len = 16;
122     if( keylen < 32 )
123         use_len = keylen - 16;
124 
125     memcpy( key + 16, md5sum, use_len );
126 
127 exit:
128     mbedtls_md5_free( &md5_ctx );
129     mbedtls_platform_zeroize( md5sum, 16 );
130 
131     return( ret );
132 }
133 
134 #if defined(MBEDTLS_DES_C)
135 /*
136  * Decrypt with DES-CBC, using PBKDF1 for key derivation
137  */
pem_des_decrypt(unsigned char des_iv[8],unsigned char * buf,size_t buflen,const unsigned char * pwd,size_t pwdlen)138 static int pem_des_decrypt( unsigned char des_iv[8],
139                             unsigned char *buf, size_t buflen,
140                             const unsigned char *pwd, size_t pwdlen )
141 {
142     mbedtls_des_context des_ctx;
143     unsigned char des_key[8];
144     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
145 
146     mbedtls_des_init( &des_ctx );
147 
148     if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 )
149         goto exit;
150 
151     if( ( ret = mbedtls_des_setkey_dec( &des_ctx, des_key ) ) != 0 )
152         goto exit;
153     ret = mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen,
154                      des_iv, buf, buf );
155 
156 exit:
157     mbedtls_des_free( &des_ctx );
158     mbedtls_platform_zeroize( des_key, 8 );
159 
160     return( ret );
161 }
162 
163 /*
164  * Decrypt with 3DES-CBC, using PBKDF1 for key derivation
165  */
pem_des3_decrypt(unsigned char des3_iv[8],unsigned char * buf,size_t buflen,const unsigned char * pwd,size_t pwdlen)166 static int pem_des3_decrypt( unsigned char des3_iv[8],
167                              unsigned char *buf, size_t buflen,
168                              const unsigned char *pwd, size_t pwdlen )
169 {
170     mbedtls_des3_context des3_ctx;
171     unsigned char des3_key[24];
172     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
173 
174     mbedtls_des3_init( &des3_ctx );
175 
176     if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 )
177         goto exit;
178 
179     if( ( ret = mbedtls_des3_set3key_dec( &des3_ctx, des3_key ) ) != 0 )
180         goto exit;
181     ret = mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen,
182                      des3_iv, buf, buf );
183 
184 exit:
185     mbedtls_des3_free( &des3_ctx );
186     mbedtls_platform_zeroize( des3_key, 24 );
187 
188     return( ret );
189 }
190 #endif /* MBEDTLS_DES_C */
191 
192 #if defined(MBEDTLS_AES_C)
193 /*
194  * Decrypt with AES-XXX-CBC, using PBKDF1 for key derivation
195  */
pem_aes_decrypt(unsigned char aes_iv[16],unsigned int keylen,unsigned char * buf,size_t buflen,const unsigned char * pwd,size_t pwdlen)196 static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,
197                             unsigned char *buf, size_t buflen,
198                             const unsigned char *pwd, size_t pwdlen )
199 {
200     mbedtls_aes_context aes_ctx;
201     unsigned char aes_key[32];
202     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
203 
204     mbedtls_aes_init( &aes_ctx );
205 
206     if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 )
207         goto exit;
208 
209     if( ( ret = mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ) ) != 0 )
210         goto exit;
211     ret = mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen,
212                      aes_iv, buf, buf );
213 
214 exit:
215     mbedtls_aes_free( &aes_ctx );
216     mbedtls_platform_zeroize( aes_key, keylen );
217 
218     return( ret );
219 }
220 #endif /* MBEDTLS_AES_C */
221 
222 #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
223           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
224 
mbedtls_pem_read_buffer(mbedtls_pem_context * ctx,const char * header,const char * footer,const unsigned char * data,const unsigned char * pwd,size_t pwdlen,size_t * use_len)225 int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer,
226                      const unsigned char *data, const unsigned char *pwd,
227                      size_t pwdlen, size_t *use_len )
228 {
229     int ret, enc;
230     size_t len;
231     unsigned char *buf;
232     const unsigned char *s1, *s2, *end;
233 #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \
234     ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
235     unsigned char pem_iv[16];
236     mbedtls_cipher_type_t enc_alg = MBEDTLS_CIPHER_NONE;
237 #else
238     ((void) pwd);
239     ((void) pwdlen);
240 #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
241           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
242 
243     if( ctx == NULL )
244         return( MBEDTLS_ERR_PEM_BAD_INPUT_DATA );
245 
246     s1 = (unsigned char *) strstr( (const char *) data, header );
247 
248     if( s1 == NULL )
249         return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
250 
251     s2 = (unsigned char *) strstr( (const char *) data, footer );
252 
253     if( s2 == NULL || s2 <= s1 )
254         return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
255 
256     s1 += strlen( header );
257     if( *s1 == ' '  ) s1++;
258     if( *s1 == '\r' ) s1++;
259     if( *s1 == '\n' ) s1++;
260     else return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );
261 
262     end = s2;
263     end += strlen( footer );
264     if( *end == ' '  ) end++;
265     if( *end == '\r' ) end++;
266     if( *end == '\n' ) end++;
267     *use_len = end - data;
268 
269     enc = 0;
270 
271     if( s2 - s1 >= 22 && memcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 )
272     {
273 #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \
274     ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
275         enc++;
276 
277         s1 += 22;
278         if( *s1 == '\r' ) s1++;
279         if( *s1 == '\n' ) s1++;
280         else return( MBEDTLS_ERR_PEM_INVALID_DATA );
281 
282 
283 #if defined(MBEDTLS_DES_C)
284         if( s2 - s1 >= 23 && memcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 )
285         {
286             enc_alg = MBEDTLS_CIPHER_DES_EDE3_CBC;
287 
288             s1 += 23;
289             if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8 ) != 0 )
290                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
291 
292             s1 += 16;
293         }
294         else if( s2 - s1 >= 18 && memcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 )
295         {
296             enc_alg = MBEDTLS_CIPHER_DES_CBC;
297 
298             s1 += 18;
299             if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8) != 0 )
300                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
301 
302             s1 += 16;
303         }
304 #endif /* MBEDTLS_DES_C */
305 
306 #if defined(MBEDTLS_AES_C)
307         if( s2 - s1 >= 14 && memcmp( s1, "DEK-Info: AES-", 14 ) == 0 )
308         {
309             if( s2 - s1 < 22 )
310                 return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
311             else if( memcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 )
312                 enc_alg = MBEDTLS_CIPHER_AES_128_CBC;
313             else if( memcmp( s1, "DEK-Info: AES-192-CBC,", 22 ) == 0 )
314                 enc_alg = MBEDTLS_CIPHER_AES_192_CBC;
315             else if( memcmp( s1, "DEK-Info: AES-256-CBC,", 22 ) == 0 )
316                 enc_alg = MBEDTLS_CIPHER_AES_256_CBC;
317             else
318                 return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
319 
320             s1 += 22;
321             if( s2 - s1 < 32 || pem_get_iv( s1, pem_iv, 16 ) != 0 )
322                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
323 
324             s1 += 32;
325         }
326 #endif /* MBEDTLS_AES_C */
327 
328         if( enc_alg == MBEDTLS_CIPHER_NONE )
329             return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
330 
331         if( *s1 == '\r' ) s1++;
332         if( *s1 == '\n' ) s1++;
333         else return( MBEDTLS_ERR_PEM_INVALID_DATA );
334 #else
335         return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );
336 #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
337           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
338     }
339 
340     if( s1 >= s2 )
341         return( MBEDTLS_ERR_PEM_INVALID_DATA );
342 
343     ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );
344 
345     if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER )
346         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PEM_INVALID_DATA, ret ) );
347 
348     if( ( buf = mbedtls_calloc( 1, len ) ) == NULL )
349         return( MBEDTLS_ERR_PEM_ALLOC_FAILED );
350 
351     if( ( ret = mbedtls_base64_decode( buf, len, &len, s1, s2 - s1 ) ) != 0 )
352     {
353         mbedtls_platform_zeroize( buf, len );
354         mbedtls_free( buf );
355         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PEM_INVALID_DATA, ret ) );
356     }
357 
358     if( enc != 0 )
359     {
360 #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \
361     ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
362         if( pwd == NULL )
363         {
364             mbedtls_platform_zeroize( buf, len );
365             mbedtls_free( buf );
366             return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED );
367         }
368 
369         ret = 0;
370 
371 #if defined(MBEDTLS_DES_C)
372         if( enc_alg == MBEDTLS_CIPHER_DES_EDE3_CBC )
373             ret = pem_des3_decrypt( pem_iv, buf, len, pwd, pwdlen );
374         else if( enc_alg == MBEDTLS_CIPHER_DES_CBC )
375             ret = pem_des_decrypt( pem_iv, buf, len, pwd, pwdlen );
376 #endif /* MBEDTLS_DES_C */
377 
378 #if defined(MBEDTLS_AES_C)
379         if( enc_alg == MBEDTLS_CIPHER_AES_128_CBC )
380             ret = pem_aes_decrypt( pem_iv, 16, buf, len, pwd, pwdlen );
381         else if( enc_alg == MBEDTLS_CIPHER_AES_192_CBC )
382             ret = pem_aes_decrypt( pem_iv, 24, buf, len, pwd, pwdlen );
383         else if( enc_alg == MBEDTLS_CIPHER_AES_256_CBC )
384             ret = pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen );
385 #endif /* MBEDTLS_AES_C */
386 
387         if( ret != 0 )
388         {
389             mbedtls_free( buf );
390             return( ret );
391         }
392 
393         /*
394          * The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3
395          * length bytes (allow 4 to be sure) in all known use cases.
396          *
397          * Use that as a heuristic to try to detect password mismatches.
398          */
399         if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 )
400         {
401             mbedtls_platform_zeroize( buf, len );
402             mbedtls_free( buf );
403             return( MBEDTLS_ERR_PEM_PASSWORD_MISMATCH );
404         }
405 #else
406         mbedtls_platform_zeroize( buf, len );
407         mbedtls_free( buf );
408         return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );
409 #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&
410           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
411     }
412 
413     ctx->buf = buf;
414     ctx->buflen = len;
415 
416     return( 0 );
417 }
418 
mbedtls_pem_free(mbedtls_pem_context * ctx)419 void mbedtls_pem_free( mbedtls_pem_context *ctx )
420 {
421     if ( ctx->buf != NULL )
422     {
423         mbedtls_platform_zeroize( ctx->buf, ctx->buflen );
424         mbedtls_free( ctx->buf );
425     }
426     mbedtls_free( ctx->info );
427 
428     mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) );
429 }
430 #endif /* MBEDTLS_PEM_PARSE_C */
431 
432 #if defined(MBEDTLS_PEM_WRITE_C)
mbedtls_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)433 int mbedtls_pem_write_buffer( const char *header, const char *footer,
434                       const unsigned char *der_data, size_t der_len,
435                       unsigned char *buf, size_t buf_len, size_t *olen )
436 {
437     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
438     unsigned char *encode_buf = NULL, *c, *p = buf;
439     size_t len = 0, use_len, add_len = 0;
440 
441     mbedtls_base64_encode( NULL, 0, &use_len, der_data, der_len );
442     add_len = strlen( header ) + strlen( footer ) + ( use_len / 64 ) + 1;
443 
444     if( use_len + add_len > buf_len )
445     {
446         *olen = use_len + add_len;
447         return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
448     }
449 
450     if( use_len != 0 &&
451         ( ( encode_buf = mbedtls_calloc( 1, use_len ) ) == NULL ) )
452         return( MBEDTLS_ERR_PEM_ALLOC_FAILED );
453 
454     if( ( ret = mbedtls_base64_encode( encode_buf, use_len, &use_len, der_data,
455                                der_len ) ) != 0 )
456     {
457         mbedtls_free( encode_buf );
458         return( ret );
459     }
460 
461     memcpy( p, header, strlen( header ) );
462     p += strlen( header );
463     c = encode_buf;
464 
465     while( use_len )
466     {
467         len = ( use_len > 64 ) ? 64 : use_len;
468         memcpy( p, c, len );
469         use_len -= len;
470         p += len;
471         c += len;
472         *p++ = '\n';
473     }
474 
475     memcpy( p, footer, strlen( footer ) );
476     p += strlen( footer );
477 
478     *p++ = '\0';
479     *olen = p - buf;
480 
481      /* Clean any remaining data previously written to the buffer */
482     memset( buf + *olen, 0, buf_len - *olen );
483 
484     mbedtls_free( encode_buf );
485     return( 0 );
486 }
487 #endif /* MBEDTLS_PEM_WRITE_C */
488 #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */
489 
490