summaryrefslogtreecommitdiff
path: root/FreeRTOS-Plus/Demo/AWS/Ota_Windows_Simulator/Common/Ota_PAL/Win32/Code_Signature_Verification/code_signature_verification_mbedtls.c
blob: fcd6a1df8f23ba104be9d176fff6e131232330dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
 * FreeRTOS V202111.00
 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * https://www.FreeRTOS.org
 * https://github.com/FreeRTOS
 *
 */

 /**
  * @file code_signature_verification_mbedtls.c
  * @brief Code signature verification using mbedtls crypto.
  *
  * The file demonstrates implements the code signature verification functionality on 
  * the specified file using mbedtls for SHA256 ECDSA.
  */

 /* C runtime includes. */
#include <string.h>

 /* FreeRTOS includes. */
#include "FreeRTOS.h"

/* mbedTLS includes. */
#if !defined( MBEDTLS_CONFIG_FILE )
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "mbedtls/platform.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha1.h"
#include "mbedtls/pk.h"
#include "mbedtls/x509_crt.h"

/* OTA includes. */
#include "ota.h"

/* Signature verification includes. */
#include "code_signature_verification.h"
#include "aws_ota_codesigner_certificate.h"

/**
 * @brief SHA256 buffer size for storing cryptographic hash computation results.
 */
#define SHA256_DIGEST_BYTES    32

 /* Size of buffer used in file operations on this platform (Windows). */
#define OTA_PAL_WIN_BUF_SIZE ( ( size_t ) 4096UL )

/**
 * @brief Library-independent cryptographic algorithm identifiers.
 */
#define HASH_ALGORITHM_SHA1           1
#define HASH_ALGORITHM_SHA256         2
#define ASYMMETRIC_ALGORITHM_RSA      1
#define ASYMMETRIC_ALGORITHM_ECDSA    2

 /**
  * @brief Internal signature verification context structure.
  */
typedef struct SignatureVerificationState
{
    BaseType_t xAsymmetricAlgorithm;
    BaseType_t xHashAlgorithm;
    mbedtls_sha256_context xSHA256Context;
} SignatureVerificationState_t, * SignatureVerificationStatePtr_t;

/**
 * @brief Initializes digital signature verification.
 *
 * @param[out] ppvContext Opaque context structure.
 * @param[in] xAsymmetricAlgorithm Cryptographic public key cryptosystem.
 * @param[in] xHashAlgorithm Cryptographic hash algorithm that was used for signing.
 *
 * @return pdTRUE if initialization succeeds, or pdFALSE otherwise.
 */
static BaseType_t prvSignatureVerificationStart(void** ppvContext,
    BaseType_t xAsymmetricAlgorithm,
    BaseType_t xHashAlgorithm);

/**
 * @brief Updates a cryptographic hash computation with the specified byte array.
 *
 * @param[in] pvContext Opaque context structure.
 * @param[in] pucData Byte array that was signed.
 * @param[in] xDataLength Length in bytes of data that was signed.
 */
static void prvSignatureVerificationUpdate(void* pvContext,
    const uint8_t* pucData,
    size_t xDataLength);

/**
 * @brief Verifies a digital signature computation using the public key from the
 * specified certificate.
 *
 * @param[in] pvContext Opaque context structure.
 * @param[in] pucSignerCertificate Base64 and DER encoded X.509 certificate of the
 * signer.
 * @param[in] xSignerCertificateLength Length in bytes of the certificate.
 * @param[in] pucSignature Digital signature result to verify.
 * @param[in] xSignatureLength in bytes of digital signature result.
 *
 * @return pdTRUE if the signature is correct or pdFALSE if the signature is invalid.
 */
static BaseType_t prvSignatureVerificationFinal(void* pvContext,
    char* pcSignerCertificate,
    size_t xSignerCertificateLength,
    uint8_t* pucSignature,
    size_t xSignatureLength);

/* Read the specified signer certificate from the filesystem into a local buffer. The allocated
 * memory becomes the property of the caller who is responsible for freeing it.
 */

static uint8_t* otaPal_ReadAndAssumeCertificate(const uint8_t* const pucCertName,
    uint32_t* const ulSignerCertSize)
{
    FILE* pFile;
    uint8_t* pucSignerCert = NULL;
    uint8_t* pucCertData = NULL;
    int32_t lSize = 0; /* For MISRA mandatory. */
    int32_t lWindowsError;

    pFile = fopen((const char*)pucCertName, "rb"); /*lint !e586
                                                            * C standard library call is being used for portability. */

    if (pFile != NULL)
    {
        lWindowsError = fseek(pFile, 0, SEEK_END);         /*lint !e586
                                                                * C standard library call is being used for portability. */

        if (lWindowsError == 0)                               /* fseek returns a non-zero value on error. */
        {
            lSize = (int32_t)ftell(pFile);                  /*lint !e586 Allow call in this context. */

            if (lSize != -1L)                                 /* ftell returns -1 on error. */
            {
                lWindowsError = fseek(pFile, 0, SEEK_SET); /*lint !e586
                                                                * C standard library call is being used for portability. */
            }
            else /* ftell returned an error, pucSignerCert remains NULL. */
            {
                lWindowsError = -1L;
            }
        } /* else fseek returned an error, pucSignerCert remains NULL. */

        if (lWindowsError == 0)
        {
            /* Allocate memory for the signer certificate plus a terminating zero so we can load and return it to the caller. */
            pucSignerCert = pvPortMalloc(lSize + 1); /*lint !e732 !e9034 !e9079 Allow conversion. */
        }

        if (pucSignerCert != NULL)
        {
            if (fread(pucSignerCert, 1, lSize, pFile) == (size_t)lSize) /*lint !e586 !e732 !e9034
                                                                                 * C standard library call is being used for portability. */
            {
                /* The crypto code requires the terminating zero to be part of the length so add 1 to the size. */
                *ulSignerCertSize = lSize + 1;
                pucSignerCert[lSize] = 0;
            }
            else
            {   /* There was a problem reading the certificate file so free the memory and abort. */
                vPortFree(pucSignerCert);
                pucSignerCert = NULL;
            }
        }
        else
        {
            LogError(("Failed to allocate memory for signer cert contents.\r\n"));
            /* Nothing special to do. */
        }

        lWindowsError = fclose(pFile); /*lint !e586
                                            * C standard library call is being used for portability. */

        if (lWindowsError != 0)
        {
            LogError(("File pointer operation failed.\r\n"));
            pucSignerCert = NULL;
        }
    }
    else
    {
        LogError(("No such certificate file: %s. Using aws_ota_codesigner_certificate.h.\r\n",
            (const char*)pucCertName));

        /* Allocate memory for the signer certificate plus a terminating zero so we can copy it and return to the caller. */
        lSize = sizeof(signingcredentialSIGNING_CERTIFICATE_PEM);
        pucSignerCert = pvPortMalloc(lSize);                           /*lint !e9029 !e9079 !e838 malloc proto requires void*. */
        pucCertData = (uint8_t*)signingcredentialSIGNING_CERTIFICATE_PEM; /*lint !e9005 we don't modify the cert but it could be set by PKCS11 so it's not const. */

        if (pucSignerCert != NULL)
        {
            memcpy(pucSignerCert, pucCertData, lSize);
            *ulSignerCertSize = lSize;
        }
        else
        {
            LogError(("No memory for certificate of size %d!\r\n", lSize));
        }
    }

    return pucSignerCert; /*lint !e480 !e481 fopen and fclose are being used by-design. */
}

/**
 * @brief Verifies a cryptographic signature based on the signer
 * certificate, hash algorithm, and the data that was signed.
 */
static BaseType_t prvVerifySignature(char* pcSignerCertificate,
    size_t xSignerCertificateLength,
    BaseType_t xHashAlgorithm,
    uint8_t* pucHash,
    size_t xHashLength,
    uint8_t* pucSignature,
    size_t xSignatureLength)
{
    BaseType_t xResult = pdTRUE;
    mbedtls_x509_crt xCertCtx;
    mbedtls_md_type_t xMbedHashAlg = MBEDTLS_MD_SHA256;

    (void)xHashAlgorithm;

    memset(&xCertCtx, 0, sizeof(mbedtls_x509_crt));

    /*
     * Decode and create a certificate context
     */
    mbedtls_x509_crt_init(&xCertCtx);

    if (0 != mbedtls_x509_crt_parse(
        &xCertCtx, (const unsigned char*)pcSignerCertificate, xSignerCertificateLength))
    {
        xResult = pdFALSE;
    }

    /*
     * Verify the signature using the public key from the decoded certificate
     */
    if (pdTRUE == xResult)
    {
        if (0 != mbedtls_pk_verify(
            &xCertCtx.pk,
            xMbedHashAlg,
            pucHash,
            xHashLength,
            pucSignature,
            xSignatureLength))
        {
            xResult = pdFALSE;
        }
    }

    /*
     * Clean-up
     */
    mbedtls_x509_crt_free(&xCertCtx);

    return xResult;
}



/**
 * @brief Creates signature verification context.
 */
static BaseType_t prvSignatureVerificationStart(void** ppvContext,
    BaseType_t xAsymmetricAlgorithm,
    BaseType_t xHashAlgorithm)
{
    BaseType_t xResult = pdTRUE;
    SignatureVerificationState_t* pxCtx = NULL;

    /*
     * Allocate the context
     */
    if (NULL == (pxCtx = (SignatureVerificationStatePtr_t)pvPortMalloc(
        sizeof(*pxCtx)))) /*lint !e9087 Allow casting void* to other types. */
    {
        xResult = pdFALSE;
    }

    if (pdTRUE == xResult)
    {
        *ppvContext = pxCtx;

        /*
         * Store the algorithm identifiers
         */
        pxCtx->xAsymmetricAlgorithm = xAsymmetricAlgorithm;
        pxCtx->xHashAlgorithm = xHashAlgorithm;

        /*
         * Initialize the requested hash type
         */
        mbedtls_sha256_init(&pxCtx->xSHA256Context);
        (void)mbedtls_sha256_starts_ret(&pxCtx->xSHA256Context, 0);
    }

    return xResult;
}

/**
 * @brief Adds bytes to an in-progress hash for subsequent signature verification.
 */
static void prvSignatureVerificationUpdate(void* pvContext,
    const uint8_t* pucData,
    size_t xDataLength)
{
    SignatureVerificationState_t* pxCtx = (SignatureVerificationStatePtr_t)pvContext; /*lint !e9087 Allow casting void* to other types. */

    /*
     * Add the data to the hash of the requested type
     */
    (void)mbedtls_sha256_update_ret(&pxCtx->xSHA256Context, pucData, xDataLength);

}

/**
 * @brief Performs signature verification on a cryptographic hash.
 */
static BaseType_t prvSignatureVerificationFinal(void* pvContext,
    char* pcSignerCertificate,
    size_t xSignerCertificateLength,
    uint8_t* pucSignature,
    size_t xSignatureLength)
{
    BaseType_t xResult = pdFALSE;

    if (pvContext != NULL)
    {
        SignatureVerificationStatePtr_t pxCtx = (SignatureVerificationStatePtr_t)pvContext; /*lint !e9087 Allow casting void* to other types. */
        uint8_t ucSHA256[SHA256_DIGEST_BYTES];                                      /* Reserve enough space for the larger for SHA256 results. */
        uint8_t* pucHash = NULL;
        size_t xHashLength = 0;

        if ((pcSignerCertificate != NULL) &&
            (pucSignature != NULL) &&
            (xSignerCertificateLength > 0UL) &&
            (xSignatureLength > 0UL))
        {
            /*
             * Finish the hash.
             */
            (void)mbedtls_sha256_finish_ret(&pxCtx->xSHA256Context, ucSHA256);
            pucHash = ucSHA256;
            xHashLength = SHA256_DIGEST_BYTES;

            /*
             * Verify the signature.
             */
            xResult = prvVerifySignature(pcSignerCertificate,
                xSignerCertificateLength,
                pxCtx->xHashAlgorithm,
                pucHash,
                xHashLength,
                pucSignature,
                xSignatureLength);
        }
        else
        {
            /* Allow function to be called with only the context pointer for cleanup after a failure. */
        }

        /*
         * Clean-up
         */
        vPortFree(pxCtx);
    }

    return xResult;
}

/* Verify the signature of the specified file. */
OtaPalMainStatus_t xValidateImageSignature(OtaFileContext_t* const C)
{
    OtaPalMainStatus_t eResult = OtaPalSuccess;
    uint32_t ulBytesRead;
    uint32_t ulSignerCertSize;
    uint8_t* pucBuf, * pucSignerCert;
    void* pvSigVerifyContext;

        /* Verify an ECDSA-SHA256 signature. */
        if (pdFALSE == prvSignatureVerificationStart(&pvSigVerifyContext, ASYMMETRIC_ALGORITHM_ECDSA, HASH_ALGORITHM_SHA256))
        {
            eResult = OtaPalSignatureCheckFailed;
        }
        else
        {
            LogInfo(("Started %s signature verification, file: %s\r\n",
                OTA_JsonFileSignatureKey, (const char*)C->pCertFilepath));
            pucSignerCert = otaPal_ReadAndAssumeCertificate((const uint8_t* const)C->pCertFilepath, &ulSignerCertSize);

            if (pucSignerCert != NULL)
            {
                pucBuf = pvPortMalloc( OTA_PAL_WIN_BUF_SIZE ); /*lint !e9079 Allow conversion. */

                if (pucBuf != NULL)
                {
                    /* Rewind the received file to the beginning. */
                    if (fseek(C->pFile, 0L, SEEK_SET) == 0) /*lint !e586
                                                                  * C standard library call is being used for portability. */
                    {
                        do
                        {
                            ulBytesRead = fread(pucBuf, 1, OTA_PAL_WIN_BUF_SIZE, C->pFile); /*lint !e586
                                                                                               * C standard library call is being used for portability. */
                                                                                               /* Include the file chunk in the signature validation. Zero size is OK. */
                            prvSignatureVerificationUpdate(pvSigVerifyContext, pucBuf, ulBytesRead);
                        } while (ulBytesRead > 0UL);

                        if (pdFALSE == prvSignatureVerificationFinal(pvSigVerifyContext,
                            (char*)pucSignerCert,
                            (size_t)ulSignerCertSize,
                            C->pSignature->data,
                            C->pSignature->size)) /*lint !e732 !e9034 Allow comparison in this context. */
                        {
                            eResult = OtaPalSignatureCheckFailed;
                        }
                        pvSigVerifyContext = NULL;	/* The context has been freed by prvSignatureVerificationFinal(). */
                    }
                    else
                    {
                        /* Nothing special to do. */
                    }

                    /* Free the temporary file page buffer. */
                    vPortFree(pucBuf);
                }
                else
                {
                    LogError(("Failed to allocate buffer memory.\r\n"));
                    eResult = OtaPalOutOfMemory;
                }

                /* Free the signer certificate that we now own after prvReadAndAssumeCertificate(). */
                vPortFree(pucSignerCert);
            }
            else
            {
                eResult = OtaPalBadSignerCert;
            }
        }

    return eResult;
}