ctr_eFuse/cr_generate_id.c
kubodera_yuichi 62daefb347 typo
git-svn-id: file:///Volumes/Transfer/gigaleak_20231201/2020-09-30%20-%20paladin.7z/paladin/ctr_eFuse@100 ff987cc8-cf2f-4642-8568-d52cce064691
2009-12-25 07:40:20 +00:00

410 lines
15 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#ifdef USE_HSM
#include "cr_hsm_code.h"
#endif // USE_HSM
// openssl
#include <openssl/sha.h>
#include <openssl/x509.h>
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
#include "cr_alloc.h"
static u64 generatingCount = 0; // 現在生成中のID(起動時からの通算)
int cr_print_flag = 0;
// generate_id関数のイニシャライズ
int cr_generate_id_initialize( u8 err_buf[CR_ID_BUF_SIZE] )
{
int ret_code = CR_GENID_SUCCESS;
// 生成カウンタの初期化
generatingCount = 0;
// init for error info
InitErrorInfo();
#ifdef USE_HSM
ret_code = hsm_initialize();
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
#ifdef DEBUG_PRINT
printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack );
#endif
return CR_GENID_FAILED;
}
#endif
return ret_code;
} // cr_generate_id_initialize
// generate_id関数のファイナライズ
int cr_generate_id_finalize( u8 err_buf[CR_ID_BUF_SIZE] )
{
int ret_code = CR_GENID_SUCCESS;
// init for error info
InitErrorInfo();
// HSM
#ifdef USE_HSM
ret_code = hsm_finalize();
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
#ifdef DEBUG_PRINT
printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack );
#endif
}
#endif // USE_HSM
return ret_code;
} // cr_generate_id_finalize
// generate_id 関数
int cr_generate_id( u32 deviceId[CR_NUM_OF_DEVICEID], u8 id_buf[CR_ID_BUF_SIZE], u8 bondingOption )
{
int i;
int ret_code = CR_GENID_SUCCESS;
CR_ID_BUFFER *cr_id_buf;
EC_KEY *deviceKeyPair = NULL;
// エラー発生時に備えて、エラーバッファの初期化とトータルのID生成カウントセット
InitErrorInfo();
generatingCount++;
#ifdef DEBUG_PRINT
if( sizeof(CR_ID_BUFFER) != 256 ) {
printf( "CR_ID_BUFFER size error. %d\n", sizeof(CR_ID_BUFFER) );
}
if( sizeof(CR_ERR_BUFFER) != 256 ) {
printf( "CR_ERR_BUFFER size error. %d\n", sizeof(CR_ERR_BUFFER) );
}
#endif
// ダイジェストアルゴリズムを追加する
OpenSSL_add_all_digests();
//--------------------------------------------------------------
// 暗号処理初期化
//--------------------------------------------------------------
// メモリリーク防止のため、オリジナルのアロケータを使用。
CRYPTO_set_mem_functions(cr_mem_malloc, cr_mem_realloc, cr_mem_free);
cr_mem_bufmgr_initialize();
#ifdef MY_CRYPTO_DEBUG
ERR_load_crypto_strings();
#endif /* MY_CRYPTO_DEBUG */
//--------------------------------------------------------------
// FuseIDバッファに固定データセット
//--------------------------------------------------------------
memset(id_buf, 0, CR_ID_BUF_SIZE);
cr_id_buf = (CR_ID_BUFFER *)id_buf;
cr_id_buf->magic_number = CR_GEN_ID_MAGICCODE; // HSM使用未使用でマジックコードが変わる。
cr_id_buf->version = CR_GEN_ID_VERSION;
//--------------------------------------------------------------
// 引数のボンディングオプションをセット
//--------------------------------------------------------------
cr_id_buf->bondingOption = bondingOption;
//--------------------------------------------------------------
// deviceId セット
//--------------------------------------------------------------
for( i = 0 ; i < CR_NUM_OF_DEVICEID ; i++ ) {
cr_id_buf->deviceId[i] = deviceId[i]; /* deviceId[0] => ec priv key */
}
#ifdef DEBUG_PRINT
if( cr_print_flag ) {
printf("deviceId:\n");
printf(" 0x%08x\n", (unsigned int)deviceId[0] );
printf(" 0x%08x%08x\n", (unsigned int)deviceId[2], (unsigned int)deviceId[1] );
printf(" 0x%08x%08x\n", (unsigned int)deviceId[4], (unsigned int)deviceId[3] );
printf("\n");
}
#endif /* DEBUG_PRINT */
//--------------------------------------------------------------
// タイムスタンプセット
//--------------------------------------------------------------
ret_code = GetTimestamp( &cr_id_buf->year,
&cr_id_buf->month,
&cr_id_buf->mday,
&cr_id_buf->hour,
&cr_id_buf->min,
&cr_id_buf->sec,
&cr_id_buf->expiryDate ); // デバイス証明書期限の元データもついでにセットしておく
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
//--------------------------------------------------------------
// 乱数を生成してセット
//--------------------------------------------------------------
ret_code = GenerateRandom( cr_id_buf->random, CR_RANDOM_LENGTH );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
DEBUG_PRINT_ARRAY( "rand:", (const char *)cr_id_buf->random, CR_RANDOM_LENGTH );
//--------------------------------------------------------------
// 楕円曲線鍵ペアを生成
//--------------------------------------------------------------
ret_code = GenarateECCKeyPair( &deviceKeyPair, cr_id_buf->devicePrivKey );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
//--------------------------------------------------------------
// 生成した鍵ペアをECDSAで動作確認
//--------------------------------------------------------------
ret_code = TestECDSA( deviceKeyPair );
if ( ret_code != CR_GENID_SUCCESS ) {
goto end;
}
//--------------------------------------------------------------
// デバイス証明書生成 + 署名の付与 + 証明書期限セット
//--------------------------------------------------------------
ret_code = GenerateCTRDeviceCert( deviceKeyPair,
cr_id_buf->deviceId[0],
cr_id_buf->bondingOption,
cr_id_buf->deviceCertSign,
&cr_id_buf->expiryDate );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
#if 0
DEBUG_PRINT_ARRAY( "deviceCertSign:", (const char *)cr_id_buf->deviceCertSign, ECDSA_SIGN_LENGTH );
#endif
//--------------------------------------------------------------
// FuseIDバッファ全体のSHA256ハッシュを算出してセット
//--------------------------------------------------------------
SHA256(id_buf, CR_ID_BUF_SIZE - SHA256_DIGEST_LENGTH, cr_id_buf->hash);
DEBUG_PRINT_ARRAY( "SHA256 Digest:", (const char *)cr_id_buf->hash, SHA256_DIGEST_LENGTH );
//--------------------------------------------------------------
// FuseID RAWデータ完成
//--------------------------------------------------------------
DEBUG_PRINT_ARRAY( "RAW eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE );
#ifdef DEBUG_EFUSE_ID_OUTPUT_FILE
DebugFileOutput( deviceId[ 0 ], "raw", id_buf, CR_ID_BUF_SIZE );
#endif // DEBUG_EFUSE_ID_OUTPUT_FILE
//--------------------------------------------------------------
// FuseIDバッファ全体をAES or RSAで暗号化
//--------------------------------------------------------------
ret_code = EncryptID( id_buf, id_buf, bondingOption );
if( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
DEBUG_PRINT_ARRAY( "ENC eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE );
#ifdef DEBUG_EFUSE_ID_OUTPUT_FILE
DebugFileOutput( deviceId[ 0 ], "enc", id_buf, CR_ID_BUF_SIZE );
#endif // DEBUG_EFUSE_ID_OUTPUT_FILE
//--------------------------------------------------------------
// 終了処理
//--------------------------------------------------------------
end:
/* id_buf[]にエラーログを書き込む。 */
// TODO: 仕様をFIXする必要あり -> TORIAEZU version
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)id_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->totalCount = generatingCount;
cr_err_buf->magic_number = 0x01234567;
cr_err_buf->deviceId0 = deviceId[0];
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
cr_err_buf->bondingOption = bondingOption;
#ifdef DEBUG_PRINT
printf( "CALL_STACK : %s\n", cr_err_buf->callStack );
#endif
}
// リソースの解放
if ( deviceKeyPair ) EC_KEY_free( deviceKeyPair );
ERR_remove_state(0);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
#ifdef MY_CRYPTO_DEBUG
ERR_free_strings();
#endif /* MY_CRYPTO_DEBUG */
return ret_code; /* success */
}
#ifdef DEBUG_PRINT
void DebugPrintArray( char *pStr, const u8 *pData, int length )
{
int i;
if( cr_print_flag ) {
printf( "%s", pStr );
for( i = 0 ; i < length; i++ ) {
if( (i % 16) == 0 ) printf("\n ");
printf("%02X ", pData[ i ] );
}
printf("\n");
}
}
#endif
void DebugFileOutput( u32 deviceId, char *pSuffix, const u8 *pSrc, int length )
{
if ( cr_print_flag )
{
// 証明書の書き込みテスト
FILE *fp;
char fn[256];
sprintf( fn, "output/0x%08x.%s", (unsigned int)deviceId, pSuffix );
fp = fopen( fn, "wb" );
fwrite( pSrc, length, 1, fp );
fclose( fp );
}
}