[Assignment-7] Flake + App base

- Add Assignment-7 to flake.nix
- Implement basic framework of app
- Implement proxy subcommand (mostly)
- Implement basics of intermediary subcommand
This commit is contained in:
Paul Zinselmeyer 2024-07-03 16:16:24 +02:00 committed by saschato
parent 0d6b13fafa
commit 25a5ca3e2d
23 changed files with 615 additions and 10 deletions

0
7-SGX_Hands-on/.gitkeep Normal file
View file

81
7-SGX_Hands-on/Makefile Normal file
View file

@ -0,0 +1,81 @@
# Makefile for building the application
# Use:
# make - compiles both release and test binaries
# make release - compiles and runs the release binary
# make test - compiles and runs the test binary
# make clean - deletes all binaries in build/bin
# make cleaner - deltes the whole build directory
# Compiler
CC = clang
CFLAGS = -Wall -Wextra -Werror -I$(ENCLAVE_DIR) -I$(APP_DIR)
LDFLAGS =
# Directories
SRC_DIR = src
LIB_DIR = lib
TEST_DIR = test
APP_DIR = $(SRC_DIR)/app
ENCLAVE_DIR = $(SRC_DIR)/enclave
BUILD_DIR = build
OBJ_DIR = $(BUILD_DIR)/obj
BIN_DIR = $(BUILD_DIR)/bin
# Source files
LIB_SRCS = $(wildcard $(LIB_DIR)/*.c)
APP_SRCS = $(wildcard $(APP_DIR)/*.c) $(wildcard $(ENCLAVE_DIR)/*.c)
TEST_SRCS = $(wildcard $(TEST_DIR)/*.c)
# Object files
LIB_OBJS = $(LIB_SRCS:$(LIB_DIR)/%.c=$(OBJ_DIR)/lib/%.o)
APP_OBJS = $(APP_SRCS:$(SRC_DIR)/%.c=$(OBJ_DIR)/src/%.o)
TEST_OBJS = $(TEST_SRCS:$(TEST_DIR)/%.c=$(OBJ_DIR)/test/%.o)
# Binaries
RELEASE_BIN = $(BIN_DIR)/release
TEST_BIN = $(BIN_DIR)/test
$(RELEASE_BIN): $(LIB_OBJS) $(APP_OBJS)
@mkdir -p $(BIN_DIR)
@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^
$(TEST_BIN): $(LIB_OBJS) $(TEST_OBJS)
@mkdir -p $(BIN_DIR)
@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/lib/%.o: $(LIB_DIR)/%.c
@mkdir -p $(dir $@)
@$(CC) $(CFLAGS) -c -o $@ $<
$(OBJ_DIR)/src/%.o: $(SRC_DIR)/%.c
@mkdir -p $(dir $@)
@$(CC) $(CFLAGS) -c -o $@ $<
$(OBJ_DIR)/test/%.o: $(TEST_DIR)/%.c
@mkdir -p $(dir $@)
@$(CC) $(CFLAGS) -c -o $@ $<
# Targets
.PHONY: all clean release test
all: release test
release: $(RELEASE_BIN) run_release
run_release:
@echo "RUNNING RELEASE"
@./$(RELEASE_BIN)
test: $(TEST_BIN) run_test
run_test:
@echo "RUNNING TESTS"
@./$(TEST_BIN)
clean:
@echo "Deleting binaries"
@rm -rf $(BIN_DIR)
cleaner:
@echo "Deleting builds"
@rm -rf $(BUILD_DIR)

27
7-SGX_Hands-on/flake.lock generated Normal file
View file

@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1719838683,
"narHash": "sha256-Zw9rQjHz1ilNIimEXFeVa1ERNRBF8DoXDhLAZq5B4pE=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d032c1a6dfad4eedec7e35e91986becc699d7d69",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-24.05",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

47
7-SGX_Hands-on/flake.nix Normal file
View file

@ -0,0 +1,47 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
};
outputs = { self, nixpkgs, ... }:
let
lastModifiedDate = self.lastModifiedDate or self.lastModified or "19700101";
version = builtins.substring 0 8 lastModifiedDate;
nixpkgsFor = system: import nixpkgs { inherit system; overlays = [ self.overlay ]; };
in
{
overlay = final: prev: with final; {
signatureProxy = stdenv.mkDerivation {
pname = "SignatureProxy";
inherit version;
buildScript = ''
make
'';
installScript = ''
mkdir -p $out/bin
cp app $out/bin
cp enclave.so $out/bin
'';
nativeBuildInputs = with pkgs; [
clang
glibc
sgx-sdk
gmp.dev
openssl.dev
pkg-config
];
env = {
SGX_SDK = pkgs.sgx-sdk;
SGX_MODE = "SIM";
};
};
};
defaultPackage."x86_64-linux" = (nixpkgsFor "x86_64-linux").signatureProxy;
};
}

View file

@ -0,0 +1,153 @@
#include <errno.h>
#include <sgx_urts.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "enclave.h"
#include "intermediary.h"
#include "util.h"
#define HASH_BYTES 32
#define HASH_CHUNK_BYTES 32
#define KEY_BYTES 32
struct IntermediaryArgs {
char* firmware_path;
char* key_path;
char* output_path;
};
char* intermediary_syntax(void) {
return
"intermediary mock up implementation of the employee binary\n"
" -f <path> file path to Firmware file\n"
" -k <path> key file path\n"
" -o <path> output file path\n";
}
int handle_intermediary(int argc, char** argv) {
struct IntermediaryArgs args = {
NULL,
NULL,
NULL
};
FILE* firmware_file;
FILE* key_file;
FILE* output_file;
//uint8_t firmware_hash[HASH_BYTES];
uint8_t firmware_chunk[HASH_CHUNK_BYTES];
uint8_t key[KEY_BYTES];
//EVP_MD_CTX *mdctx;
//const EVP_MD *md;
//unsigned char md_value[EVP_MAX_MD_SIZE];
//unsigned int md_len;
int i = 0;
while(i < argc) {
if(strcmp(argv[i], "-f")==0 && argc-i >=2){
args.firmware_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-k")==0 && argc-i >=2){
args.key_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-o")==0 && argc-i >=2){
args.output_path = argv[i+1];
i += 2;
}else
syntax_exit();
}
if(args.firmware_path == NULL || args.key_path == NULL || args.output_path == NULL)
syntax_exit();
firmware_file = fopen(args.firmware_path, "r");
if(firmware_file == NULL){
perror("Error opening firmware file");
exit(1);
}
/*
md = EVP_sha3_256();
mdctx = EVP_MD_CTX_new();
if (!EVP_DigestSignInit(mdctx, NULL, md, NULL, key)) {
fprintf(stderr, "Message digest initialization failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
*/
size_t chunk_len = HASH_CHUNK_BYTES;
while(chunk_len==HASH_CHUNK_BYTES) {
chunk_len = fread(&firmware_chunk, HASH_CHUNK_BYTES, 1, firmware_file);
if(chunk_len!=HASH_CHUNK_BYTES&&ferror(firmware_file)!=0){
perror("Failed to read firmware file");
exit(1);
}
/*
if (!EVP_DigestSignUpdate(mdctx, firmware_chunk, chunk_len)) {
printf("Message digest update failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
*/
}
/*
if (!EVP_DigestSignFinal_ex(mdctx, md_value, &md_len)) {
printf("Message digest finalization failed.\n");
EVP_MD_CTX_free(mdctx);
exit(1);
}
EVP_MD_CTX_free(mdctx);
printf("Digest is: ");
for (i = 0; i < md_len; i++)
printf("%02x", md_value[i]);
printf("\n");
*/
key_file = fopen(args.key_path, "r");
if(key_file == NULL){
perror("Error opening key file");
exit(1);
}
size_t key_len = fread(&key, 1, KEY_BYTES, key_file);
if(ferror(key_file)!=0){
perror("Failed to read key");
exit(1);
}
if(key_len != KEY_BYTES){
fprintf(stderr, "invalid key length\n");
exit(1);
}
//eckey = EC_KEY_new_by_curve_name(NID_secp256r1);
//if(eckey == NULL) {
// fprintf(stderr, "failed to initialize SECP256R1 key\n");
// exit(1);
//}
//if (!EC_KEY_generate_key(eckey)) {
// fprintf(stderr, "failed to generate key\n");
// exit(1);
//}
//sig = ECDSA_do_sign(md_value, md_len, eckey);
//if (sig == NULL){
// fprintf(stderr, "failed to sign firmware hash\n");
// exit(1);
//}
output_file = fopen(args.output_path, "w");
if(output_file == NULL){
perror("Error opening output file");
exit(1);
}
printf("intermediary %s %s %s", args.firmware_path, args.key_path, args.output_path);
exit(0);
}

View file

@ -0,0 +1,23 @@
#ifndef _APP_INTERMEDIARY_H_
#define _APP_INTERMEDIARY_H_
/*
* @brief getter for intermediary subcommand syntax string
*
* @returns null-terminated syntax string
*/
char* intermediary_syntax(void);
/*
* @brief CLI implementation for the "intermediary" subcommand
*
* @param argc number of arguments with command and subcommand stripped
* @param argv arguments with command and subcommand stripped
*
* @returns 0 on success, else error with output on stderr
*/
int handle_intermediary(int argc, char** argv);
#endif

View file

@ -0,0 +1,24 @@
#include <errno.h>
#include <string.h>
#include "intermediary.h"
#include "proxy.h"
#include "util.h"
int main(int argc, char** argv) {
if(argc < 1)
syntax_exit();
BIN_NAME = argv[0];
if(argc < 2)
syntax_exit();
char* command = argv[1];
if(strcmp(command, "intermediary")==0)
handle_intermediary(argc-2, argv+2);
else if (strcmp(command, "proxy")==0)
handle_proxy(argc-2, argv+2);
else
syntax_exit();
}

View file

@ -0,0 +1,235 @@
#include <errno.h>
#include <sgx_urts.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "enclave.h"
#include "proxy.h"
#include "util.h"
sgx_enclave_id_t global_eid = 0;
struct ProxyArgs {
char* input_path;
char* output_path;
char* sealed_key_file_path;
char* sgx_token_path;
};
typedef struct _sgx_errlist_t {
sgx_status_t err;
const char *msg;
const char *sug; /* Suggestion */
} sgx_errlist_t;
/* Error code returned by sgx_create_enclave */
static sgx_errlist_t sgx_errlist[] = {
{
SGX_ERROR_UNEXPECTED,
"Unexpected error occurred.",
NULL
},
{
SGX_ERROR_INVALID_PARAMETER,
"Invalid parameter.",
NULL
},
{
SGX_ERROR_OUT_OF_MEMORY,
"Out of memory.",
NULL
},
{
SGX_ERROR_ENCLAVE_LOST,
"Power transition occurred.",
"Please refer to the sample \"PowerTransition\" for details."
},
{
SGX_ERROR_INVALID_ENCLAVE,
"Invalid enclave image.",
NULL
},
{
SGX_ERROR_INVALID_ENCLAVE_ID,
"Invalid enclave identification.",
NULL
},
{
SGX_ERROR_INVALID_SIGNATURE,
"Invalid enclave signature.",
NULL
},
{
SGX_ERROR_OUT_OF_EPC,
"Out of EPC memory.",
NULL
},
{
SGX_ERROR_NO_DEVICE,
"Invalid SGX device.",
"Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards."
},
{
SGX_ERROR_MEMORY_MAP_CONFLICT,
"Memory map conflicted.",
NULL
},
{
SGX_ERROR_INVALID_METADATA,
"Invalid enclave metadata.",
NULL
},
{
SGX_ERROR_DEVICE_BUSY,
"SGX device was busy.",
NULL
},
{
SGX_ERROR_INVALID_VERSION,
"Enclave version was invalid.",
NULL
},
{
SGX_ERROR_INVALID_ATTRIBUTE,
"Enclave was not authorized.",
NULL
},
{
SGX_ERROR_ENCLAVE_FILE_ACCESS,
"Can't open enclave file.",
NULL
},
};
/* Check error conditions for loading enclave */
static void print_error_message(sgx_status_t ret)
{
size_t idx = 0;
size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0];
for (idx = 0; idx < ttl; idx++) {
if(ret == sgx_errlist[idx].err) {
if(NULL != sgx_errlist[idx].sug)
printf("Info: %s\n", sgx_errlist[idx].sug);
printf("Error: %s\n", sgx_errlist[idx].msg);
break;
}
}
if (idx == ttl)
printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret);
}
static int initialize_enclave(char* token_path) {
FILE* sgx_token_file;
sgx_launch_token_t token = {0};
sgx_status_t ret;
int updated = 0;
sgx_token_file = fopen(token_path, "r");
if(sgx_token_file == NULL){
perror("Error opening sgx token file");
exit(1);
}
size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), sgx_token_file);
if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) {
fprintf(stderr, "sgx token file is corrupted");
return (1);
}
ret = sgx_create_enclave("enclave.so", SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL);
if (ret != SGX_SUCCESS) {
print_error_message(ret);
return (1);
}
if (updated) {
sgx_token_file = freopen(token_path, "w", sgx_token_file);
if(sgx_token_file == NULL){
perror("Error opening sgx token file");
return (1);
}
size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), sgx_token_file);
if (write_num != sizeof(sgx_launch_token_t)){
fprintf(stderr,"Warning: Failed to save launch token to \"%s\".\n", token_path);
return (1);
}
}
return (0);
}
char* proxy_syntax(void) {
return
"proxy implementation of the enclave-powered SignatureProxy\n"
" -i <path> file path to the intermediary output(signature of firmware)\n"
" -o <path> output path of the signature\n"
" -s <path> file path of the sealed proxy key\n"
" -t <path> file path of the sgx token\n";
}
int handle_proxy(int argc, char** argv) {
struct ProxyArgs args = {
NULL,
NULL,
NULL,
NULL
};
FILE* input_file;
FILE* output_file;
FILE* sealed_key_file;
int i = 0;
while(i < argc) {
if(strcmp(argv[i], "-i")==0 && argc-i >=2){
args.input_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-o")==0 && argc-i >=2){
args.output_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-s")==0 && argc-i >=2){
args.sealed_key_file_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-t")==0 && argc-i >=2){
args.sgx_token_path = argv[i+1];
i += 2;
}else
syntax_exit();
}
if(args.input_path == NULL || args.output_path == NULL || args.sealed_key_file_path == NULL || args.sgx_token_path == NULL)
syntax_exit();
input_file = fopen(args.input_path, "r");
if(input_file == NULL){
perror("Error opening input file");
exit(1);
}
output_file = fopen(args.output_path, "w");
if(output_file == NULL){
perror("Error opening output file");
exit(1);
}
//TODO read input -> calculate size of input (ECDSA of SHA3-256 of Firmware File, generated by intermediary)
//TODO read sealed key -> calculate size or dynamic alloc
sealed_key_file = fopen(args.sealed_key_file_path, "w");
if(sealed_key_file == NULL){
perror("Error opening sealed_key_file file");
exit(1);
}
if (initialize_enclave(args.sgx_token_path) != 0)
exit(1);
//TODO call enclave -> refactor interface to do verify and sign in one call to avoid trip through "untrusted" land.
//TODO store sealed key if changed
//TODO write output
printf("proxy %s %s", args.input_path, args.output_path);
exit(0);
}

View file

@ -0,0 +1,23 @@
#ifndef _APP_PROXY_H_
#define _APP_PROXY_H_
/*
* @brief getter for proxy subcommand syntax string
*
* @returns null-terminated syntax string
*/
char* proxy_syntax(void);
/*
* @brief CLI implementation for the "proxy" subcommand
*
* @param argc number of arguments with command and subcommand stripped
* @param argv arguments with command and subcommand stripped
*
* @returns 0 on success, else error with output on stderr
*/
int handle_proxy(int argc, char** argv);
#endif

View file

@ -0,0 +1,3 @@
int main() {
return (0);
}

View file

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
#include "proxy.h"
#include "intermediary.h"
char* BIN_NAME = "SignatureProxy";
void syntax_exit(void) {
char* syntax =
"SignatureProxy Version 0.0.0\n"
"Syntax: %s <command> <arguments>\n"
"\n"
"Commands:\n"
"%s"
"\n"
"%s";
printf(syntax, BIN_NAME, intermediary_syntax(), proxy_syntax());
exit(1);
}

View file

@ -0,0 +1,13 @@
#ifndef _APP_UTIL_H_
#define _APP_UTIL_H_
char* BIN_NAME;
/*
* @brief prints the command syntax and exits with EXIT_FAILURE
*/
void syntax_exit(void);
#endif

View file

@ -0,0 +1,266 @@
/*
* Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 COPYRIGHT
* OWNER 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.
*
*/
#include <stdarg.h>
#include <stdio.h> /* vsnprintf */
#include <string.h>
#include <stdlib.h>
#include "Enclave.h"
#include "Enclave_t.h"
#include <sgx_tseal.h>
#include <sgx_error.h>
#include <sgx_tcrypto.h>
#ifndef SK_SIZE
#define SK_SIZE SGX_ECP256_KEY_SIZE
#endif
#ifndef PK_SIZE
#define PK_SIZE 2*SK_SIZE
#endif
#ifndef SI_SIZE
#define SI_SIZE 2*SK_SIZE
#endif
int get_sealed_size() {
return sgx_calc_sealed_data_size(PK_SIZE, SK_SIZE);
}
int get_signature_size() {
return SI_SIZE;
}
int get_public_key_size() {
return PK_SIZE;
}
int get_private_key_size() {
return SK_SIZE;
}
sgx_status_t seal_key_pair(sgx_ec256_private_t *private, sgx_ec256_public_t *public, uint8_t **sealed, uint32_t sealed_size) {
// invalid parameter handling
if((private == NULL) || (public == NULL))
return SGX_ERROR_INVALID_PARAMETER;
// allocate temporary buffers on stack
uint8_t pk[PK_SIZE] = {0};
uint8_t sk[SK_SIZE] = {0};
// copy key pair into buffers
memcpy(pk, public->gx, PK_SIZE);
memcpy(sk, private->r, SK_SIZE);
// calculate needed size
uint32_t size = get_sealed_size();
if(size > sealed_size) {
return SGX_ERROR_INVALID_PARAMETER;
}
// seal keypair
return sgx_seal_data(PK_SIZE, (const uint8_t *)pk, SK_SIZE, (const uint8_t *)sk, size, (sgx_sealed_data_t *) *sealed);
}
sgx_status_t unseal_key_pair(const uint8_t *sealed, sgx_ec256_private_t *private, sgx_ec256_public_t *public) {
// invalid parameter handling
if(sealed == NULL) {
return SGX_ERROR_INVALID_PARAMETER;
}
// allocate temporary buffers on stack
uint8_t pk[PK_SIZE] = {0};
uint8_t sk[SK_SIZE] = {0};
// calculate public_key size and return error for unexpected results
uint32_t pk_size = sgx_get_add_mac_txt_len((const sgx_sealed_data_t *)sealed);
uint32_t sk_size = sgx_get_encrypt_txt_len((const sgx_sealed_data_t *)sealed);
if ((pk_size != PK_SIZE) || (sk_size != SK_SIZE)) {
return SGX_ERROR_UNEXPECTED;
}
// unseal ecc key pair
sgx_status_t status = sgx_unseal_data((const sgx_sealed_data_t *)sealed, pk, &pk_size, sk, &sk_size);
if (status != SGX_SUCCESS) {
return status;
}
// copy buffers into key structs
if(public != NULL) {
memcpy(public->gx, pk, PK_SIZE);
}
if (private != NULL) {
memcpy(private->r, sk, SK_SIZE);
}
// return success
return status;
}
sgx_status_t get_public_key(const uint8_t *sealed, uint32_t sealed_size, uint8_t *gx, uint32_t gx_size, uint8_t *gy, uint32_t gy_size) {
// invalid parameter handling
if((sealed == NULL) || (sealed_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
}
// unseal public key
sgx_status_t status;
sgx_ec256_public_t public;
if((status = unseal_key_pair(sealed, NULL, &public)) != SGX_SUCCESS) {
return status;
}
// copy public key into return buffers
if((gx != NULL) && (gy != NULL)) {
memcpy(gx, public.gx, SK_SIZE);
memcpy(gy, public.gy, SK_SIZE);
}
// return success
return status;
}
sgx_status_t sign_firmware(const uint8_t *data, uint32_t data_size, uint8_t *sealed, uint32_t sealed_size, uint8_t *signature, uint32_t signature_size) {
// invalid parameter handling
if((data == NULL) || (data_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed == NULL) || (sealed_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
}
// declare need structures
sgx_ecc_state_handle_t ecc_handle;
sgx_ec256_private_t private;
sgx_ec256_public_t public;
// open ecc handle
sgx_status_t status;
if((status = sgx_ecc256_open_context(&ecc_handle)) != SGX_SUCCESS) {
return status;
}
// try unseal keypair
sgx_status_t seal_status;
if(seal_status = unseal_key_pair(sealed, &private, NULL) != SGX_SUCCESS) {
if((status = sgx_ecc256_create_key_pair(&private, &public, ecc_handle)) != SGX_SUCCESS) {
sgx_ecc256_close_context(ecc_handle);
return status;
}
}
// create signature
sgx_ec256_signature_t ecc_signature;
if((status = sgx_ecdsa_sign(data, data_size, &private, &ecc_signature, ecc_handle)) != SGX_SUCCESS) {
sgx_ecc256_close_context(ecc_handle);
return status;
}
// TODO: possible wrong endianess for other programms
// copy signature to return buffer
if((signature == NULL) || (signature_size == 0)) {
sgx_ecc256_close_context(ecc_handle);
return SGX_ERROR_INVALID_PARAMETER;
}
memcpy(signature, ecc_signature.x, SI_SIZE);
// seal the key
if((seal_status != SGX_SUCCESS) && (sealed != NULL)) {
seal_status = seal_key_pair(&private, &public, &sealed, sealed_size);
}
// close ecc handle and return success
sgx_ecc256_close_context(ecc_handle);
return seal_status;
}
sgx_status_t verify_firmware(const uint8_t *data, uint32_t data_size, const uint8_t *sealed, uint32_t sealed_size, const uint8_t *public_key, uint32_t public_key_size, const uint8_t *signature, uint32_t signature_size) {
// invalid parameter handling
if((data == NULL) || (data_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if(((sealed == NULL) || (sealed_size == 0)) && ((public_key == NULL) || (public_key_size == 0))) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed != NULL) && (public_key != NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((signature == NULL) || (signature_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
}
// declare need structures
sgx_ec256_signature_t ecc_signature;
sgx_ecc_state_handle_t ecc_handle;
sgx_ec256_public_t public;
// invalid signature
if(signature_size > SI_SIZE) {
return SGX_ERROR_INVALID_PARAMETER;
}
// open ecc handle
sgx_status_t status;
if((status = sgx_ecc256_open_context(&ecc_handle)) != SGX_SUCCESS) {
return status;
}
// copy signature into struct
memcpy(ecc_signature.x, signature, SI_SIZE);
// verify signature from staff or enclave
if(public_key != NULL) {
// invalid public key
if(public_key_size != PK_SIZE) {
return SGX_ERROR_INVALID_PARAMETER;
}
// copy public key into struct
memcpy(public.gx, public_key, PK_SIZE);
} else {
// unseal public key
if(unseal_key_pair(sealed, NULL, &public) != SGX_SUCCESS) {
sgx_ecc256_close_context(ecc_handle);
return SGX_ERROR_UNEXPECTED;
}
}
// verify signature
uint8_t result;
sgx_status_t verification_status = sgx_ecdsa_verify((const uint8_t *)data, data_size, (const sgx_ec256_public_t *)&public, (const sgx_ec256_signature_t *)&ecc_signature, &result, ecc_handle);
// handle failed verification process
if(verification_status != SGX_SUCCESS) {
result = verification_status;
}
// close handle and return result
sgx_ecc256_close_context(ecc_handle);
return result;
}

View file

@ -0,0 +1,12 @@
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>0</ISVSVN>
<StackMaxSize>0x400000</StackMaxSize>
<HeapMaxSize>0x1000000</HeapMaxSize>
<TCSNum>10</TCSNum>
<TCSPolicy>1</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug>
<MiscSelect>0</MiscSelect>
<MiscMask>0xFFFFFFFF</MiscMask>
</EnclaveConfiguration>

View file

@ -0,0 +1,60 @@
/*
* Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 COPYRIGHT
* OWNER 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.
*
*/
/* Enclave.edl - Top EDL file. */
enclave {
/* Import ECALL/OCALL from sub-directory EDLs.
* [from]: specifies the location of EDL file.
* [import]: specifies the functions to import,
* [*]: implies to import all functions.
*/
trusted {
public int get_sealed_size();
public int get_signature_size();
public int get_public_key_size();
public int get_private_key_size();
public sgx_status_t get_public_key([in, size=sealed_size]const uint8_t *sealed, uint32_t sealed_size, [out, size=gx_size]uint8_t *gx, uint32_t gx_size, [out, size=gx_size]uint8_t *gy, uint32_t gy_size);
public sgx_status_t sign_firmware([in, size=data_size]const uint8_t *data, uint32_t data_size, [in, out, size=sealed_size]uint8_t *sealed, uint32_t sealed_size, [out, size=signature_size]uint8_t *signature, uint32_t signature_size);
public sgx_status_t verify_firmware([in, size=data_size]const uint8_t *data, uint32_t data_size, [in, size=sealed_size]const uint8_t *sealed, uint32_t sealed_size, [in, size=public_key_size]const uint8_t *public_key, uint32_t public_key_size, [in, size=signature_size]const uint8_t *signature, uint32_t signature_size);
};
/*
* ocall_print_string - invokes OCALL to display string buffer inside the enclave.
* [in]: copy the string buffer to App outside.
* [string]: specifies 'str' is a NULL terminated buffer.
*/
untrusted {
};
};

View file

@ -0,0 +1,51 @@
/*
* Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 COPYRIGHT
* OWNER 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.
*
*/
#ifndef _ENCLAVE_H_
#define _ENCLAVE_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <sgx_error.h>
int get_sealed_size();
int get_signature_size();
int get_public_key_size();
int get_private_key_size();
sgx_status_t get_public_key(const uint8_t *sealed, const uint32_t sealed_size, uint8_t *gx, uint32_t gx_size, uint8_t *gy, uint32_t gy_size);
sgx_status_t sign_firmware(const uint8_t *data, uint32_t data_size, uint8_t *sealed, uint32_t sealed_size, uint8_t *signature, uint32_t signature_size);
sgx_status_t verify_firmware(const uint8_t *data, uint32_t data_size, const uint8_t *sealed, uint32_t sealed_size, const uint8_t *public_key, uint32_t public_key_size, const uint8_t *signature, uint32_t signature_size);
#endif /* !_ENCLAVE_H_ */

View file

@ -0,0 +1,16 @@
#include "framework_test.h"
bool test_function_true() {
return assert_true(false, "Test function true");
}
bool test_function_false() {
return assert_false(false, "Reason why it failed");
}
void framework_test() {
start_tests("Test Group Name");
run_test("Test Name", test_function_true);
run_test("Test Name", test_function_false);
end_tests();
}

View file

@ -0,0 +1,8 @@
#ifndef CRYPTO_FRAMEWORK_TEST_H
#define CRYPTO_FRAMEWORK_TEST_H
#include "mini_test.h"
void framework_test();
#endif //CRYPTO_FRAMEWORK_TEST_H

View file

@ -0,0 +1,9 @@
#include "framework_test.h"
int main() {
// Tests
framework_test();
return 0;
}

View file

@ -0,0 +1,73 @@
#include "mini_test.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <time.h>
#define RESET_COLOR "\x1b[0m"
#define RED_COLOR "\x1b[31m"
#define GREEN_COLOR "\x1b[32m"
#define ORANGE_COLOR "\x1b[33m"
#define BEGIN_FAT_TEXT "\033[1m"
#define END_FAT_TEXT "\033[0m"
static int total_tests = 0;
static int passed_tests = 0;
static char *group;
void start_tests(char *group_name) {
group = group_name;
total_tests = 0;
passed_tests = 0;
printf("Starting tests " BEGIN_FAT_TEXT "%s" END_FAT_TEXT "...\n", group);
}
void end_tests() {
if (passed_tests == total_tests) {
printf(GREEN_COLOR "[%d/%d] Tests passed" RESET_COLOR "\n", passed_tests, total_tests);
} else if (passed_tests == 0) {
printf(RED_COLOR "[%d/%d] Tests passed" RESET_COLOR "\n", passed_tests, total_tests);
} else {
printf(ORANGE_COLOR "[%d/%d] Tests passed" RESET_COLOR "\n", passed_tests, total_tests);
}
}
void run_test(const char *test_name, bool (*test_fn)(void)) {
total_tests++;
printf("\tTesting %s... ", test_name);
clock_t start, end;
start = clock();
bool result = test_fn();
end = clock();
double time_passed = ((double)(end - start)) / CLOCKS_PER_SEC;
if (result) {
printf(GREEN_COLOR "[✓] %.4fs" RESET_COLOR "\n", time_passed);
passed_tests++;
} else {
printf(RED_COLOR "" RESET_COLOR "\n");
}
}
bool assert_true(bool condition, const char *message, ...) {
if (!condition) {
printf(RED_COLOR "[X] Assertion failed: " RESET_COLOR);
va_list args;
va_start(args, message);
vprintf(message, args);
va_end(args);
printf(" ");
}
return condition;
}
bool assert_false(bool condition, const char *message, ...) {
if (condition) {
printf(RED_COLOR "[X] Assertion failed: " RESET_COLOR);
va_list args;
va_start(args, message);
vprintf(message, args);
va_end(args);
printf(" ");
}
return !condition;
}

View file

@ -0,0 +1,15 @@
#ifndef CRYPTO_MINI_TEST_H
#define CRYPTO_MINI_TEST_H
#include <stdbool.h>
void start_tests(char *group_name);
void end_tests();
void run_test(const char *tests_name, bool (*test_fn)(void));
bool assert_true(bool condition, const char *message, ...);
bool assert_false(bool condition, const char *message, ...);
#endif //CRYPTO_MINI_TEST_H