diff --git a/homework/cs161.sty b/homework/cs161.sty new file mode 100644 index 0000000000000000000000000000000000000000..209309d5f476ce6234b76e2ef51a4477a079b9f0 --- /dev/null +++ b/homework/cs161.sty @@ -0,0 +1,419 @@ +%============================================================================== +% CS 161 Style File +%============================================================================== +% +% Document style options: +% - midterm +% - final +% - project +% - homework +% - section +% - notes +% - rubric Can be add to all of the above (except notes) and will add +% an extra Rubric tag in the top right banner and bottom left +% footnote. +% - id=ID The document identifier. Can be a plain number or a date, +% e.g., id=2 or id=1/20. +% - duedate=DATE The date when an assignment is due, +% e.g., duedate={Friday March 4} +% - duetime=TIME The time when an assignment is due, e.g., duetime=5:00pm. +% +% Examples: +% \usepackage[section,id=2]{cs161} +% \usepackage[notes,id=1/20]{cs161} +% \usepackage[homework,id=3,duedate={Friday March 4}]{cs161} +% \usepackage[homework,rubric,id=3]{cs161} +% +%============================================================================== + +\def\fileversion{0.3} +\def\filedate{2011/03/03} +\ProvidesPackage{cs161}[% +\filedate\space Version \fileversion\space by Matthias Vallentin] + +\def\instructor{Popa \& Weaver} +\def\semester{Spring 2019} + +\RequirePackage{kvoptions} +\SetupKeyvalOptions{family=,prefix=@} +\DeclareBoolOption{midterm} +\DeclareBoolOption{final} +\DeclareBoolOption{project} +\DeclareBoolOption{homework} +\DeclareBoolOption{rubric} +\DeclareBoolOption{section} +\DeclareBoolOption{notes} +\DeclareStringOption{id} +\DeclareStringOption{duedate} +\DeclareStringOption{duetime} +\ProcessKeyvalOptions* + +\usepackage{alltt} +\usepackage{amsmath} +\usepackage{comment} +\usepackage{hyperref} +\usepackage{parskip} +\usepackage{sectsty} +\usepackage{xspace} + +%\if@duetime +%\else +%\def\@duetime{11:59pm} +%\fi + +\def\@doctype{% +\if@midterm Midterm\fi +\if@final Final Exam\fi +\if@project Project\fi +\if@homework Homework\fi +\if@section Discussion\fi} + +\ifprintanswers +\else +\addpoints +\fi + +% Gothic fonts +\font\dunhd=cmdunh10 scaled \magstep5 +\font\dunhc=cmdunh10 scaled \magstep4 +\font\dunhb=cmdunh10 scaled \magstep3 +\font\dunha=cmdunh10 scaled \magstep2 +\font\dunh=cmdunh10 scaled \magstep1 +\sectionfont{\dunhb} +\subsectionfont{\dunha} +\subsubsectionfont{\dunh} + +% Header & Footer +\pagestyle{headandfoot} +\extraheadheight[1in]{0in} +\extrafootheight{-.2in} +\lhead[\dunhb \instructor\\ + \vspace{5pt} + \semester\\ + \vspace{10pt}]{} +\rhead[\dunhb \@doctype\xspace\@id\\ + \if@rubric\vspace{5pt}Rubric\\\vspace{10pt} + \else + \vspace{20pt} + \fi]{} +\chead[\hrule height 3pt + \vspace{10pt} + \dunhb CS 161\\ + \vspace{5pt} + Computer Security\\ + \vspace{10pt} + \hrule height 3pt]{} + +\if@notes +\lfoot{\footnotesize \@doctype\xspace\@id} +\cfoot{\footnotesize +\semester} +\rfoot{\footnotesize \thepage\ of \numpages} +\else +\lfoot[]{\footnotesize \@doctype\xspace\@id\if@rubric~(Rubric)\fi} +\cfoot{\footnotesize Page \thepage\ of \numpages} +\rfoot[]{\footnotesize CS 161 -- \semester} +\fi + +% Question formatting +\qformat{\bf Problem \thequestion \quad \textit{\thequestiontitle} + \hfill (\totalpoints\ \points)} + +\if@section +\pointname{ min} +\qformat{\bf Question \thequestion \quad \textit{\thequestiontitle} \hfill + (\thepoints)} +\fi + +\if@project +\qformat{\bf Question \thequestion \quad \textit{\thequestiontitle} \hfill + (\thepoints)} +\fi + +% \newcommand{\fillin}[1]{\underline{\hskip #1}} +% \newcommand{\fillin}{\underline{\hskip 1.5in}} + +% Due date/time header. +\def\due{% +\begin{center} + \large + Due: \@duedate, at \@duetime +\end{center} +} + +% Introductory text after header. +\if@midterm +\def\introduction{% +{\sc Print} your name: +\begin{tabular}{cc} +\\ +\fillin, +&\fillin\\ +{\small (last)} +&{\small (first)} +\end{tabular}\\[.1in] +\emph{I am aware of the Berkeley Campus Code of Student Conduct and acknowledge +that academic misconduct will be reported to the Center for Student +Conduct.}\\[.3in] +{\sc Sign} your name: \fillin\\[.3in] +{\sc Print} your class account login: \texttt{cs161-}\fillin ~and SID: +\fillin\\[.3in] +%Your TA's name: \fillin{4in}\\[.3in] +%Your section day \& time: \fillin{4in}\\[.3in] +\begin{tabular}{@{}l} +Name of the person\\ +sitting to your left: +\end{tabular} \fillin +\hfill +\begin{tabular}{l} +Name of the person\\ +sitting to your right: +\end{tabular} \fillin +\vskip .3in + +You may consult one sheet of paper of notes. +You may not consult other notes, textbooks, etc. +Calculators, computers, and other electronic devices are not permitted. +%Please write your answers in the spaces provided in the test. +%We will not grade anything elsewhere +%unless we are clearly told to look there. + +If you think a question is ambiguous, please come up to the front of +the exam room to the staff. If we agree that the question is +ambiguous we will add clarifying assumptions to the central document +projected in the exam rooms. Write your student ID on the top of +every page. + +You have 110 minutes. There are \numquestions\ questions, of varying credit +(\numpoints\ points total). The questions are of varying difficulty, so avoid +spending too long on any one question. + +\vfill + +\begin{center} +\fbox{\fbox{\parbox{5.5in}{\centering +Do not turn this page until your instructor tells you to do so. +}}} +\end{center} +\vfill + +%\begin{center} +%\gradetable[h][questions] +%\end{center} +} +\fi + +\if@final +\def\introduction{% +{\sc Print} your name: +\begin{tabular}{cc} +\\ +\fillin{}, +&\fillin{}\\ +{\small (last)} +&{\small (first)} +\end{tabular}\\[.1in] +\emph{I am aware of the Berkeley Campus Code of Student Conduct and acknowledge +that any academic misconduct on this exam will lead to a ``F''-grade for the +course and that the misconduct will be reported to the Center for Student +Conduct.}\\[.3in] +{\sc Sign} your name: \fillin\\[.3in] +{\sc Print} your class account login: \texttt{cs161-}\fillin and SID: +~\fillin\\[.3in] +%Your TA's name: \fillin{4in}\\[.3in] +% Your section time: \fillin{4in}\\[.3in] +\begin{tabular}{@{}l} +Name of the person\\ +sitting to your left: +\end{tabular} \fillin{} +\hfill +\begin{tabular}{l} +Name of the person\\ +sitting to your right: +\end{tabular} \fillin{} +\vskip .3in + +Please read the following before starting the exam. + +\begin{itemize} + + \item You may consult three double-sided sheets of notes (or six single-sided sheets). + + \item You may not consult other notes, textbooks, \&c. Calculators, + computers and other electronic devices are not permitted without prior + accomodation. + + \item Please write your answers in the spaces provided in the test. We will + not grade anything on the back of an exam page unless we are clearly + told to look there. + + \item Before you turn in your exam, write your Student ID at the + top of every page. + + \item Bubble every item completely! Avoid using checkmarks, Xs, writing + answers on the side, \&c. If you want to unselect an option, erase it + completely and clearly. + + \item For questions with circular bubbles, you may select only one choice. + + \subitem \coloredbubble[none]{} Unselected option (completely unfilled) + + \subitem \coloredbubble[black]{} Only one selected option (completely filled) + + \item For questions with square checkboxes, you may select any number of + choices (including none or all). + + \subitem \coloredselect[black]{} You can select + + \subitem \coloredselect[black]{} multiple squares (completely filled). + + \item We reserve the right to deduct points from exams which do not follow + the above directions. (Of course, we will make reasonable exceptions.) + + \item You have 170 minutes. There are \numquestions\ questions, of varying + credit (\numpoints\ points total). The questions are of varying + difficulty, so avoid spending too long on any one question. + +\end{itemize} + +\vfill + +\begin{center} +\fbox{\fbox{\parbox{5.5in}{\centering +Do not turn this page until your instructor tells you to do so. +}}} +\end{center} +\vfill + +%\begin{center} +%\gradetable[h][questions] +%\end{center} +} +\fi + +\if@homework +\ifprintanswers +\else +\def\introduction{% +\due + +\paragraph{Instructions.} +Submit your solution by \@duedate, at \@duetime, in the drop box labelled CS +161 in 283 Soda Hall. Print your name, your class account name (e.g., +\texttt{cs161-xy}), your TA's name, the discussion section time where you want +to pick up your graded homework, and ``HW\@id'' prominently on the first +page. Staple all pages together. Your solutions must be legible and the +solution to each problem must be labelled clearly. You must work on your own +on this homework. +} +\fi +\fi + +\if@homework +\ifprintanswers +\else +\def\introductionB{% +\due + +\paragraph{Instructions.} +Submit your solution electronically \emph{via your class account} +by \@duedate, at \@duetime. You should upload a single file, +\texttt{HW\@id.pdf}. +Your writeup should include +your name, your class account name (e.g., +\texttt{cs161-xy}), your TA's name, the discussion section time where you want +to pick up your graded homework, and ``HW\@id'' prominently on the first +page. Use a legible font and clearly label each solution with the +problem/subproblem to which it belongs. You \emph{must} submit a PDF file; +we will not accept other formats. + +You must work on your own on this homework. +} +\fi +\fi + +\if@homework +\ifprintanswers +\else +\def\introductionCtext{% +\paragraph{Instructions.} +Submit your solution electronically \emph{via your class account} +by \@duedate, at \@duetime. You should upload a single file, +\texttt{HW\@id.pdf}. +Your writeup should include +your name, your class account name (e.g., +\texttt{cs161-xy}), your TA's name, your discussion section, +members of your study group (if any; \textbf{see below}), +and ``HW\@id'' prominently on the first +page. Use a legible font and clearly label each solution with the +problem/subproblem to which it belongs. You \emph{must} submit a PDF file; +we will not accept other formats. + +You can work on this homework in study groups of up to +four people; however, you \textbf{must} write up the solutions +\emph{on your own}. You +must never read or copy the solutions of other students (or from online +materials), or co-develop writeups, and you must +not share your own solutions with other students. You must explicitly +acknowledge everyone who you worked with or who has given you any +significant ideas about the homework. +% Similarly, you may use books or +% online resources to help solve homework problems, but you must always +% credit all such sources in your writeup and you must never copy +% material verbatim. +} +\def\introductionC{% +\due + +\introductionCtext +} +\fi +\fi + +\if@section +\def\introduction{% +\ifprintanswers +\else +\paragraph{Instructions.} +We will break into groups to discuss the following questions. Please think of +as many solutions as you can. Be original! Maybe you will come up with +something no one has thought of yet. Be prepared to talk about your solutions +with the rest of the section. +\fi +} +\fi + +%============================================================================== + +% Link style (hyperref package) +\hypersetup{ + breaklinks=true, % break URLs at the end of line + colorlinks=true, % false: boxed links; true: colored links + linkcolor=blue, % color of internal links + citecolor=cyan, % color of links to bibliography + filecolor=red, % color of file links + urlcolor=blue % color of external links +} + +% General helpers +\def\hint{\textsc{Hint}: } +\def\note{\textsc{Note}: } +\def\first{\emph{(i)}\xspace} +\def\second{\emph{(ii)}\xspace} +\def\third{\emph{(iii)}\xspace} +\newcommand{\alert}[1]{{\textcolor{red}{#1}}} +\newcommand{\todo}[1]{\textit{\textcolor{red}{TODO: #1}}} +\newcommand{\chat}[2]{{\textcolor{red}{\textsc{#1}: \textit{#2}}}} + +% Requires TikZ. +%\newcommand*\circled[1]{\tikz[baseline=(char.base)]{ +% \node[shape=circle,draw,inner sep=2pt] (char) {#1};}} + +% Referencing +\newcommand{\pref}[1]{part~(\ref{#1})} +\newcommand{\qref}[1]{\if@section{Question}\else{Problem}\fi~\ref{#1}} +\newcommand{\qqref}[2]{\qref{#1}\ref{#2}} +\newcommand{\xref}[1]{\S\ref{#1}} +\newcommand{\fref}[1]{Figure~\ref{#1}} +\newcommand{\tref}[1]{Table~\ref{#1}} +\newcommand{\see}[1]{~(see \xref{#1})} \ No newline at end of file diff --git a/homework/hw1-working.pdf b/homework/hw1-working.pdf deleted file mode 100644 index ecbed6f2672d94e7d34c88ed061a5dd0f8ac65cc..0000000000000000000000000000000000000000 Binary files a/homework/hw1-working.pdf and /dev/null differ diff --git a/homework/hw1.tex b/homework/hw1.tex new file mode 100644 index 0000000000000000000000000000000000000000..ba22c8f765cff6573c142aff67335e126df6f5b9 --- /dev/null +++ b/homework/hw1.tex @@ -0,0 +1,358 @@ +\documentclass[12pt]{exam} +\usepackage[homework,id=1]{cs161} +\usepackage{graphicx} +\usepackage{listings} +\usepackage{pdfpages} +\usepackage{array} +\usepackage{hyperref} +\usepackage{subfiles} +\usepackage{etoolbox} + +\lstset{ +language=C, % choose the language of the code +basicstyle=\scriptsize, % the size of the fonts that are used for the code +numbers=left, % where to put the line-numbers +numberstyle=\scriptsize, % the size of the fonts that are used for the line-numbers +stepnumber=1, % the step between two line-numbers. If it is 1 each line will be numbered +numbersep=5pt, % how far the line-numbers are from the code +backgroundcolor=\color{white}, % choose the background color. You must add \usepackage{color} +showspaces=false, % show spaces adding particular underscores +showstringspaces=false, % underline spaces within strings +showtabs=false, % show tabs within strings adding particular underscores +frame=single, % adds a frame around the code +tabsize=2, % sets default tabsize to 2 spaces +captionpos=b, % sets the caption-position to bottom +breaklines=true, % sets automatic line breaking +breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace +escapeinside={\%*}{*)} % if you want to add a comment within your code +} + +\newcommand{\solbox}[2]{% +\fbox{% +\parbox[c][#1][t]{\dimexpr\linewidth-2\fboxsep-2\fboxrule}{ + \hrule width \hsize height 0pt + #2 + }% +}% +\par\vspace{\ht\strutbox} +} +\makeatother + +\usepackage{etoolbox} +\newtoggle{pdfform} +\togglefalse{pdfform} % may be toggled true in configuration + +\InputIfFileExists{config}{} + +\newcommand{\textfield}[3]{% +\iftoggle{pdfform}{% +\TextField[name = #1, backgroundcolor=white, height=#2, +width = \linewidth, multiline=true]{\mbox}% +}{% +\ifprintanswers\else{% + \solbox{#2}{#3}} +\fi% +}% +} + +\newcommand{\includesolution}[1]{% +\IfFileExists{solutions/#1.tex}{% +\begin{solution}% +\subfile{solutions/#1.tex}% +\end{solution}% +}{} +} + +\newcommand{\checkbox}[3]{% +\ifprintanswers\else% +\CheckBox[name = #1, checked = #3, backgroundcolor=white, bordercolor=black, #2]{}% +\fi% +} + +\def\duedate{Tuesday, 5 February 2019} + +\begin{document} +\begin{Form} + +\begin{center} + \large + Due: \duedate, at 11:59pm +\end{center} + +\paragraph{Instructions.} +This homework is due on \textbf{\duedate, at 11:59pm}. No late homeworks will be accepted unless you have prior accomodations from us. +This assignment must be done on your own. + +Create an EECS instructional class account if you have not already. To do so, +visit \url{https://inst.eecs.berkeley.edu/webacct/}, click ``Login +using your Berkeley CalNet ID,'' then find the cs161 row and click ``Get a new +account.'' Be sure to take note of the account login and password, and log in to +your instructional account. + +Make sure you have a Gradescope account and are joined in this course. The +homework \emph{must} be submitted electronically via Gradescope (not by +any other method). Your answer for each question, +when submitted on Gradescope, should be a +single file with each question's answer on a separate page. + +\begin{questions} +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%QUESTION 1%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Policy}[10] + +The aim of this exercise is to ensure that you read the course policies, as +well as to make sure that you are registered in the class and have a working +EECS instructional class account. + +Open the course website \url{http://inst.eecs.berkeley.edu/~cs161/sp19/}. + +Read the course policies and answer the following question: + +How many project ``slip days'' do you get? + +\textfield{Q1}{0.5cm}{ +%Your solution to Q1 here + 0 +} + +\vspace{0.12em} + +\includesolution{sol1} + +\newpage +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%QUESTION 2%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Collaboration}[10] + +You're working on a course project. +Your code isn't working, and you can't figure out why not. +Is it OK to show another student (who is not your project partner) your +draft code and ask them if they have any idea why your code is broken +or any suggestions for how to debug it?\\\\ +Select if yes \checkbox{Q2Y}{}{ +%Yes/No directions: change this argument to 'true' to check the box +%Alternatively, export and check the box using a pdf editor +false} + + +\includesolution{sol2} + +\newpage +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%QUESTION 3%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Security Principles}[20] +For each of the following paragraphs, there is exactly one security principle that best applies to the situation described. Select the best \textbf{four options} from below after reading the following scenario: + +Getting on the cryptocurrency hype, one day Bob decides to set up his own exchange. He +sets up all the infrastructure, but worries about forgetting the password, so Bob hides +his login credentials in an HTML comment on the login page. + +Eventually, Bob manages to gather a large user-base and realizes his site looks like a +back-end developer trying to learn CSS, so he contracts out front-end work to Mallory's +Do-No-Evil design firm (for an incredible price too!). He gives them an account with access +to his front-end and back-end codebase, and databases of user information as well. + +Finally, Bob wants to enforce password security. Bob requires every user to use a "super-secure" +password; that is, the password cannot contain any English word, cannot contain any birthday, and +must have many special characters (e.g., \$ \%). The user needs to type in this password every 5 minutes. +Bob disables the clipboard on the password field; in this way, the user must manually enter the password, nothing else. + +Unfortunately for him, one day he wakes up to his website being +featured on a well-known news site after a data leak. Pressured by an +internet mob, he hires a contractor to find all the issues with his +site. However, fixing the website ended up being a different story, +as much of the code was written (uncommented) in a late-night +coffee-fuled frenzy, and Bob finds that he can't change any aspect of +the website without breaking it in its entirety. In a panic, Bob +announced the closure of his site and goes into hiding. + +\begin{tabular}{m{12cm} m{3.5cm}} +1. Does Bob violate \textbf{security is economics}? +& Select if yes \checkbox{Q2P1Y}{width=1.5em}{ +%Yes/No directions: change this argument to 'true' to check the box +%Alternatively, export and check the box using a pdf editor +false}\\\\ + +2. Does Bob violate \textbf{least privilege}? +& Select if yes \checkbox{Q3P2Y}{width=1.5em}{true}\\\\ + +3. Does Bob violate \textbf{fail-safe defaults}? +& Select if yes \checkbox{Q3P3Y}{width=1.5em}{false}\\\\ + +4. Does Bob violate \textbf{separation of responsibility}? +& Select if yes \checkbox{Q3P4Y}{width=1.5em}{false}\\\\ + +5. Does Bob violate \textbf{don't rely on security by obscurity}? +& Select if yes \checkbox{Q3P5Y}{width=1.5em}{true}\\\\ + +6. Does Bob violate \textbf{consider human factors}? +& Select if yes \checkbox{Q3P6Y}{width=1.5em}{true}\\\\ + +7. Does Bob violate \textbf{complete mediation}? +& Select if yes \checkbox{Q3P7Y}{width=1.5em}{false}\\\\ + +8. Does Bob violate \textbf{detect if you can't protect}? +& Select if yes \checkbox{Q3P8Y}{width=1.5em}{false}\\\\ + +9. Does Bob violate \textbf{design security in from the start}? +& Select if yes \checkbox{Q3P9Y}{width=1.5em}{true}\\\\ + +\end{tabular} +\includesolution{sol3} + + +\newpage +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%QUESTION 4%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Vulnerable Code}[40] +Consider the following C code: +\begin{lstlisting} +void greet(char *arg) +{ + char buffer[12]; + printf(``I am the Senate. What is your name?\n"); + scanf(``%s", buffer); + printf(``It's treason then, %s\n", buffer); +} + +int main(int argc, char *argv[]) +{ + char beg[3] = `Obi'; + char end[11] = `Wan Kenobi?'; + strncat(beg, end, 5); + greet(argv[1]); + return 0; +} +\end{lstlisting} + +\begin{enumerate} + \item What is the line number that has a memory vulnerability? \\ +\textfield{Q4P1}{0.5cm}{ +%Your solution to Q4 part 1 here + 5 +} + \item What is this vulnerability called?\\ +\textfield{Q4P2}{0.5cm}{ +%Your solution to Q4 part 2 here + buffer overflow attack +} + \item Just before the program executes the line in part 1, the registers are: + \begin{center} + \texttt{\%esp: 0xBFFFF820} + \hspace{2cm} + \texttt{\%ebp: 0xBFFFF848} + \end{center} + Given this information, describe in detail how an attacker would take advantage of the vulnerability. + Also make sure to include the address that the attacker needs to over-write. (Maximum 5 sentences)\\ +\textfield{Q4P3}{3cm}{ +%Your solution to Q4 part 3 here + The most simple exploit is code injection. The attacker should input more than 12 characters (I can't determine the exact number because of memory alignment issue) and overwrite the function return address area. The address that the attacker need to overwrite is 0xbffff820. By the way, the attacker can printf any stack data as he want. +} + \item What would you change to fix the problem in part 1?\\ +\textfield{Q4P4}{0.5cm}{ +%Your solution to Q4 part 4 here + Please use C++ std::getline rather than unsafe scanf. An example written by me is here: https://github.com/recolic/rlib/blob/3a442c6dd8661d45cfe7528112b93c42ffa5d591/stdio.hpp#L52 + + If I must figure out the implementation of std::getline, please read here: https://github.com/recolic/rlib/blob/3a442c6dd8661d45cfe7528112b93c42ffa5d591/sys/sio.hpp#L516 +} + \item Given the code as is, would stack canaries prevent exploitation of this vulnerability?\\ + Select if yes \checkbox{Q4P5Y}{}{ + %Yes/No directions: change this argument to 'true' to check the box + %Alternatively, export and check the box using a pdf editor + false}\\ + Why or why not?\\ +\textfield{Q4P5}{1cm}{ +%Your solution to Q4 part 5 here + Stack canaries can make the exploit harder, but it won't prevent the exploitation. The attacker can still printf data on stack. However, canaries are still very very useful to protect this program. I considered for some time and answer "no". +} +\end{enumerate} +\includesolution{sol4} + + +\newpage +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%QUESTION 5%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Reasoning About Memory Safety}[35] + +Consider the following C code. + +\begin{lstlisting} +/* (a) Precondition: ____________________ */ +void dectohex(uint32_t decimal, char* hex) { + char tmp[9]; + int digit, j = 0, k = 0; + do { + digit = decimal % 16; + if (digit < 10) { + digit += '0'; + } else { + digit += 'A' - 10; + } + /* (b) Invariant: _______________ */ + tmp[j++] = digit; + decimal /= 16; + } while (decimal > 0); + while (j > 0) { + hex[k++] = tmp[--j]; + /* (c) Invariant: _______________ */ + } + hex[k] = '\0'; +} +\end{lstlisting} + +\begin{enumerate} +\item Please identify the \textbf{preconditions} that must hold true for the following code to be memory safe. In addition, the precondition must be as conservative as possible (e.g. \texttt{decimal} cannot be required to be solely zero). Justify why your given precondition cannot be any less strict.\\ +\textfield{Q5P1}{4.5cm}{ +%Your solution to Q5 part 1 here + Argument `hex` must be a valid pointer to a writable memory space, and its size must be at least 9 bytes. + + If my precondition is not true, one of the following thing happens: 1. The pointer hex is invalid. It will + write some random memory address or cause segmentation fault. 2. The buffer size is less than 9 bytes. Now + because 32bit unsigned integer has maximum value "0xffffffff", and we have k<=8. +} +\item Please identify the loop \textbf{invariants} (b, c) that must hold true and justify them as well.\\ +\textfield{Q5P2}{4.5cm}{ +%Your solution to Q5 part 2 here +} +\end{enumerate} +\includesolution{sol5} + +\newpage + + +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%FEEDBACK%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%% +\titledquestion{Feedback}[0] + +Optionally, feel free to include feedback. What's the single thing we could do +to make the class better? Or, what did you find most difficult or confusing from +lectures or the rest of class, and what would you like to see explained better? +If you have feedback, submit your comments as your answer to Q{\thequestion}.\\ +\textfield{Feedback}{15cm}{ +%Your feedback here +} +\includesolution{feedback} + + +\end{questions} +\end{Form} +\end{document} +