xref: /optee_os/lib/libmbedtls/mbedtls/library/pkcs5.c (revision 11fa71b9ddb429088f325cfda430183003ccd1db)
1 // SPDX-License-Identifier: Apache-2.0
2 /**
3  * \file pkcs5.c
4  *
5  * \brief PKCS#5 functions
6  *
7  * \author Mathias Olsson <mathias@kompetensum.com>
8  *
9  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
10  *
11  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
12  *  not use this file except in compliance with the License.
13  *  You may obtain a copy of the License at
14  *
15  *  http://www.apache.org/licenses/LICENSE-2.0
16  *
17  *  Unless required by applicable law or agreed to in writing, software
18  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  *  See the License for the specific language governing permissions and
21  *  limitations under the License.
22  *
23  *  This file is part of mbed TLS (https://tls.mbed.org)
24  */
25 /*
26  * PKCS#5 includes PBKDF2 and more
27  *
28  * http://tools.ietf.org/html/rfc2898 (Specification)
29  * http://tools.ietf.org/html/rfc6070 (Test vectors)
30  */
31 
32 #if !defined(MBEDTLS_CONFIG_FILE)
33 #include "mbedtls/config.h"
34 #else
35 #include MBEDTLS_CONFIG_FILE
36 #endif
37 
38 #if defined(MBEDTLS_PKCS5_C)
39 
40 #include "mbedtls/pkcs5.h"
41 #include "mbedtls/error.h"
42 
43 #if defined(MBEDTLS_ASN1_PARSE_C)
44 #include "mbedtls/asn1.h"
45 #include "mbedtls/cipher.h"
46 #include "mbedtls/oid.h"
47 #endif /* MBEDTLS_ASN1_PARSE_C */
48 
49 #include <string.h>
50 
51 #if defined(MBEDTLS_PLATFORM_C)
52 #include "mbedtls/platform.h"
53 #else
54 #include <stdio.h>
55 #define mbedtls_printf printf
56 #endif
57 
58 #if defined(MBEDTLS_ASN1_PARSE_C)
59 static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,
60                                       mbedtls_asn1_buf *salt, int *iterations,
61                                       int *keylen, mbedtls_md_type_t *md_type )
62 {
63     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
64     mbedtls_asn1_buf prf_alg_oid;
65     unsigned char *p = params->p;
66     const unsigned char *end = params->p + params->len;
67 
68     if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
69         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +
70                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
71     /*
72      *  PBKDF2-params ::= SEQUENCE {
73      *    salt              OCTET STRING,
74      *    iterationCount    INTEGER,
75      *    keyLength         INTEGER OPTIONAL
76      *    prf               AlgorithmIdentifier DEFAULT algid-hmacWithSHA1
77      *  }
78      *
79      */
80     if( ( ret = mbedtls_asn1_get_tag( &p, end, &salt->len,
81                                       MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
82         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
83 
84     salt->p = p;
85     p += salt->len;
86 
87     if( ( ret = mbedtls_asn1_get_int( &p, end, iterations ) ) != 0 )
88         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
89 
90     if( p == end )
91         return( 0 );
92 
93     if( ( ret = mbedtls_asn1_get_int( &p, end, keylen ) ) != 0 )
94     {
95         if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
96             return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
97     }
98 
99     if( p == end )
100         return( 0 );
101 
102     if( ( ret = mbedtls_asn1_get_alg_null( &p, end, &prf_alg_oid ) ) != 0 )
103         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
104 
105     if( mbedtls_oid_get_md_hmac( &prf_alg_oid, md_type ) != 0 )
106         return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
107 
108     if( p != end )
109         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +
110                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
111 
112     return( 0 );
113 }
114 
115 int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
116                  const unsigned char *pwd,  size_t pwdlen,
117                  const unsigned char *data, size_t datalen,
118                  unsigned char *output )
119 {
120     int ret, iterations = 0, keylen = 0;
121     unsigned char *p, *end;
122     mbedtls_asn1_buf kdf_alg_oid, enc_scheme_oid, kdf_alg_params, enc_scheme_params;
123     mbedtls_asn1_buf salt;
124     mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
125     unsigned char key[32], iv[32];
126     size_t olen = 0;
127     const mbedtls_md_info_t *md_info;
128     const mbedtls_cipher_info_t *cipher_info;
129     mbedtls_md_context_t md_ctx;
130     mbedtls_cipher_type_t cipher_alg;
131     mbedtls_cipher_context_t cipher_ctx;
132 
133     p = pbe_params->p;
134     end = p + pbe_params->len;
135 
136     /*
137      *  PBES2-params ::= SEQUENCE {
138      *    keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
139      *    encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
140      *  }
141      */
142     if( pbe_params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
143         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +
144                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
145 
146     if( ( ret = mbedtls_asn1_get_alg( &p, end, &kdf_alg_oid,
147                                       &kdf_alg_params ) ) != 0 )
148         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
149 
150     // Only PBKDF2 supported at the moment
151     //
152     if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBKDF2, &kdf_alg_oid ) != 0 )
153         return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
154 
155     if( ( ret = pkcs5_parse_pbkdf2_params( &kdf_alg_params,
156                                            &salt, &iterations, &keylen,
157                                            &md_type ) ) != 0 )
158     {
159         return( ret );
160     }
161 
162     md_info = mbedtls_md_info_from_type( md_type );
163     if( md_info == NULL )
164         return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
165 
166     if( ( ret = mbedtls_asn1_get_alg( &p, end, &enc_scheme_oid,
167                               &enc_scheme_params ) ) != 0 )
168     {
169         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
170     }
171 
172     if( mbedtls_oid_get_cipher_alg( &enc_scheme_oid, &cipher_alg ) != 0 )
173         return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
174 
175     cipher_info = mbedtls_cipher_info_from_type( cipher_alg );
176     if( cipher_info == NULL )
177         return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
178 
179     /*
180      * The value of keylen from pkcs5_parse_pbkdf2_params() is ignored
181      * since it is optional and we don't know if it was set or not
182      */
183     keylen = cipher_info->key_bitlen / 8;
184 
185     if( enc_scheme_params.tag != MBEDTLS_ASN1_OCTET_STRING ||
186         enc_scheme_params.len != cipher_info->iv_size )
187     {
188         return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT );
189     }
190 
191     mbedtls_md_init( &md_ctx );
192     mbedtls_cipher_init( &cipher_ctx );
193 
194     memcpy( iv, enc_scheme_params.p, enc_scheme_params.len );
195 
196     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
197         goto exit;
198 
199     if( ( ret = mbedtls_pkcs5_pbkdf2_hmac( &md_ctx, pwd, pwdlen, salt.p, salt.len,
200                                    iterations, keylen, key ) ) != 0 )
201     {
202         goto exit;
203     }
204 
205     if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )
206         goto exit;
207 
208     if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen,
209                                        (mbedtls_operation_t) mode ) ) != 0 )
210         goto exit;
211 
212     if( ( ret = mbedtls_cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len,
213                               data, datalen, output, &olen ) ) != 0 )
214         ret = MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH;
215 
216 exit:
217     mbedtls_md_free( &md_ctx );
218     mbedtls_cipher_free( &cipher_ctx );
219 
220     return( ret );
221 }
222 #endif /* MBEDTLS_ASN1_PARSE_C */
223 
224 int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx,
225                        const unsigned char *password,
226                        size_t plen, const unsigned char *salt, size_t slen,
227                        unsigned int iteration_count,
228                        uint32_t key_length, unsigned char *output )
229 {
230     int ret, j;
231     unsigned int i;
232     unsigned char md1[MBEDTLS_MD_MAX_SIZE];
233     unsigned char work[MBEDTLS_MD_MAX_SIZE];
234     unsigned char md_size = mbedtls_md_get_size( ctx->md_info );
235     size_t use_len;
236     unsigned char *out_p = output;
237     unsigned char counter[4];
238 
239     memset( counter, 0, 4 );
240     counter[3] = 1;
241 
242 #if UINT_MAX > 0xFFFFFFFF
243     if( iteration_count > 0xFFFFFFFF )
244         return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA );
245 #endif
246 
247     if( ( ret = mbedtls_md_hmac_starts( ctx, password, plen ) ) != 0 )
248         return( ret );
249     while( key_length )
250     {
251         // U1 ends up in work
252         //
253         if( ( ret = mbedtls_md_hmac_update( ctx, salt, slen ) ) != 0 )
254             return( ret );
255 
256         if( ( ret = mbedtls_md_hmac_update( ctx, counter, 4 ) ) != 0 )
257             return( ret );
258 
259         if( ( ret = mbedtls_md_hmac_finish( ctx, work ) ) != 0 )
260             return( ret );
261 
262         if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 )
263            return( ret );
264 
265         memcpy( md1, work, md_size );
266 
267         for( i = 1; i < iteration_count; i++ )
268         {
269             // U2 ends up in md1
270             //
271             if( ( ret = mbedtls_md_hmac_update( ctx, md1, md_size ) ) != 0 )
272                 return( ret );
273 
274             if( ( ret = mbedtls_md_hmac_finish( ctx, md1 ) ) != 0 )
275                 return( ret );
276 
277             if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 )
278                 return( ret );
279 
280             // U1 xor U2
281             //
282             for( j = 0; j < md_size; j++ )
283                 work[j] ^= md1[j];
284         }
285 
286         use_len = ( key_length < md_size ) ? key_length : md_size;
287         memcpy( out_p, work, use_len );
288 
289         key_length -= (uint32_t) use_len;
290         out_p += use_len;
291 
292         for( i = 4; i > 0; i-- )
293             if( ++counter[i - 1] != 0 )
294                 break;
295     }
296 
297     return( 0 );
298 }
299 
300 #if defined(MBEDTLS_SELF_TEST)
301 
302 #if !defined(MBEDTLS_SHA1_C)
303 int mbedtls_pkcs5_self_test( int verbose )
304 {
305     if( verbose != 0 )
306         mbedtls_printf( "  PBKDF2 (SHA1): skipped\n\n" );
307 
308     return( 0 );
309 }
310 #else
311 
312 #define MAX_TESTS   6
313 
314 static const size_t plen_test_data[MAX_TESTS] =
315     { 8, 8, 8, 24, 9 };
316 
317 static const unsigned char password_test_data[MAX_TESTS][32] =
318 {
319     "password",
320     "password",
321     "password",
322     "passwordPASSWORDpassword",
323     "pass\0word",
324 };
325 
326 static const size_t slen_test_data[MAX_TESTS] =
327     { 4, 4, 4, 36, 5 };
328 
329 static const unsigned char salt_test_data[MAX_TESTS][40] =
330 {
331     "salt",
332     "salt",
333     "salt",
334     "saltSALTsaltSALTsaltSALTsaltSALTsalt",
335     "sa\0lt",
336 };
337 
338 static const uint32_t it_cnt_test_data[MAX_TESTS] =
339     { 1, 2, 4096, 4096, 4096 };
340 
341 static const uint32_t key_len_test_data[MAX_TESTS] =
342     { 20, 20, 20, 25, 16 };
343 
344 static const unsigned char result_key_test_data[MAX_TESTS][32] =
345 {
346     { 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71,
347       0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06,
348       0x2f, 0xe0, 0x37, 0xa6 },
349     { 0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c,
350       0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0,
351       0xd8, 0xde, 0x89, 0x57 },
352     { 0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a,
353       0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0,
354       0x65, 0xa4, 0x29, 0xc1 },
355     { 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b,
356       0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a,
357       0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70,
358       0x38 },
359     { 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d,
360       0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3 },
361 };
362 
363 int mbedtls_pkcs5_self_test( int verbose )
364 {
365     mbedtls_md_context_t sha1_ctx;
366     const mbedtls_md_info_t *info_sha1;
367     int ret, i;
368     unsigned char key[64];
369 
370     mbedtls_md_init( &sha1_ctx );
371 
372     info_sha1 = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
373     if( info_sha1 == NULL )
374     {
375         ret = 1;
376         goto exit;
377     }
378 
379     if( ( ret = mbedtls_md_setup( &sha1_ctx, info_sha1, 1 ) ) != 0 )
380     {
381         ret = 1;
382         goto exit;
383     }
384 
385     for( i = 0; i < MAX_TESTS; i++ )
386     {
387         if( verbose != 0 )
388             mbedtls_printf( "  PBKDF2 (SHA1) #%d: ", i );
389 
390         ret = mbedtls_pkcs5_pbkdf2_hmac( &sha1_ctx, password_test_data[i],
391                                          plen_test_data[i], salt_test_data[i],
392                                          slen_test_data[i], it_cnt_test_data[i],
393                                          key_len_test_data[i], key );
394         if( ret != 0 ||
395             memcmp( result_key_test_data[i], key, key_len_test_data[i] ) != 0 )
396         {
397             if( verbose != 0 )
398                 mbedtls_printf( "failed\n" );
399 
400             ret = 1;
401             goto exit;
402         }
403 
404         if( verbose != 0 )
405             mbedtls_printf( "passed\n" );
406     }
407 
408     if( verbose != 0 )
409         mbedtls_printf( "\n" );
410 
411 exit:
412     mbedtls_md_free( &sha1_ctx );
413 
414     return( ret );
415 }
416 #endif /* MBEDTLS_SHA1_C */
417 
418 #endif /* MBEDTLS_SELF_TEST */
419 
420 #endif /* MBEDTLS_PKCS5_C */
421