Exercise on Secure Programming
Write a secure and reliable program that sums integers.
The program is fed a stream of characters through standard input. The characters can be classified as
- digits
'0'
,'1'
, …,'9'
; - operators
'+'
,'-'
; - whitespace
'\0'
, …,' '
or - something else.
It is also customary to
- define sequences of one or more digits as numbers and
- decide how expressions are represented.
In this case an expression consists of zero or more numbers that are separated by operators. The first number of an expression may also be prefixed with an operator denoting its sign. Whitespace between digits and numbers should be ignored for convenient use.
The program must either
- evaluate the expression correctly,
- print the result into standard output and
- exit with zero status
or
- reject the input,
- print an error message into the standard error stream and
- exit with nonzero status,
both without
- having security vulnerabilities or
- consuming too many system resources.
If the requirements sound easy, that is a sure sign to be extra careful!
The following tests should pass.
Input | Result | Status |
---|---|---|
"2" |
2 |
0 |
"+2" |
2 |
0 |
"-2" |
-2 |
0 |
"22" |
22 |
0 |
"+22" |
22 |
0 |
"-22" |
-22 |
0 |
"2+22" |
24 |
0 |
"+2+22" |
24 |
0 |
"-2+22" |
20 |
0 |
"2-22" |
-20 |
0 |
"+2-22" |
-20 |
0 |
"-2-22" |
-24 |
0 |
"2+22+222" |
246 |
0 |
"" |
0 |
0 |
" 2 " |
2 |
0 |
"\t2\n+\r22 " |
24 |
0 |
"\0 2\a+\b22\f" |
24 |
0 |
"00000000000000000000000000000002" |
2 |
0 |
"00000000000000000000000000000022" |
22 |
0 |
Ten Thousand Times "+2" |
20000 |
0 |
"+nope" |
Parse Error | 1 |
"++2" |
Parse Error | 1 |
"+-2" |
Parse Error | 1 |
"--2" |
Parse Error | 1 |
"2+" |
Parse Error | 1 |
"2-" |
Parse Error | 1 |
"+" |
Parse Error | 1 |
"-" |
Parse Error | 1 |
"2 2" |
Parse Error | 1 |
"%" |
Parse Error | 1 |
"%s" |
Parse Error | 1 |
"%*s" |
Parse Error | 1 |
"22222222222222222222222222222222" |
Arithmetic Error | 1 |
"2+22222222222222222222222222222222" |
Arithmetic Error | 1 |
Broken /dev/stdin |
Read Error | 1 |
Broken /dev/stdout |
Write Error | 1 |
Infinite /dev/urandom |
Likely a Parse Error | 1 |