Repository : http://git.fedorahosted.org/git/?p=secure-coding.git On branch : master >--------------------------------------------------------------- commit e97e4dc0e06ef037b2042a251c17e1f4a66ccc66 Author: Florian Weimer <fweimer@xxxxxxxxxx> Date: Fri Jun 6 16:49:27 2014 +0200 C: Add example for unsigned overflow check >--------------------------------------------------------------- defensive-coding/en-US/C-Language.xml | 11 +++++++++++ ...etic-mult.xml => C-Arithmetic-add_unsigned.xml} | 9 ++++++--- defensive-coding/src/C-Arithmetic-add.c | 14 ++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/defensive-coding/en-US/C-Language.xml b/defensive-coding/en-US/C-Language.xml index b1eeec0..8f6f74d 100644 --- a/defensive-coding/en-US/C-Language.xml +++ b/defensive-coding/en-US/C-Language.xml @@ -103,8 +103,19 @@ <para> Perform the calculation in the corresponding unsigned type and use bit fiddling to detect the overflow. + <xref linkend="ex-Defensive_Coding-C-Arithmetic-add_unsigned"/> + shows how to perform an overflow check for unsigned integer + addition. For three or more terms, all the intermediate + additions have to be checked in this way. </para> </listitem> + </itemizedlist> + <example id="ex-Defensive_Coding-C-Arithmetic-add_unsigned"> + <title>Overflow checking for unsigned addition</title> + <xi:include href="snippets/C-Arithmetic-add_unsigned.xml" + xmlns:xi="http://www.w3.org/2001/XInclude" /> + </example> + <itemizedlist> <listitem> <para> Compute bounds for acceptable input values which are known diff --git a/defensive-coding/en-US/snippets/C-Arithmetic-mult.xml b/defensive-coding/en-US/snippets/C-Arithmetic-add_unsigned.xml similarity index 68% copy from defensive-coding/en-US/snippets/C-Arithmetic-mult.xml copy to defensive-coding/en-US/snippets/C-Arithmetic-add_unsigned.xml index ecb27a0..4ea1747 100644 --- a/defensive-coding/en-US/snippets/C-Arithmetic-mult.xml +++ b/defensive-coding/en-US/snippets/C-Arithmetic-add_unsigned.xml @@ -3,12 +3,15 @@ ]> <!-- Automatically generated file. Do not edit. --> <programlisting language="C"> +void report_overflow(void); + unsigned -mul(unsigned a, unsigned b) +add_unsigned(unsigned a, unsigned b) { - if (b && a > ((unsigned)-1) / b) { + unsigned sum = a + b; + if (sum < a) { // or sum < b report_overflow(); } - return a * b; + return sum; } </programlisting> diff --git a/defensive-coding/src/C-Arithmetic-add.c b/defensive-coding/src/C-Arithmetic-add.c index 3e70286..95b403e 100644 --- a/defensive-coding/src/C-Arithmetic-add.c +++ b/defensive-coding/src/C-Arithmetic-add.c @@ -15,3 +15,17 @@ add(int a, int b) return result; } //- + +//+ C Arithmetic-add_unsigned +void report_overflow(void); + +unsigned +add_unsigned(unsigned a, unsigned b) +{ + unsigned sum = a + b; + if (sum < a) { // or sum < b + report_overflow(); + } + return sum; +} +//- -- security mailing list security@xxxxxxxxxxxxxxxxxxxxxxx https://admin.fedoraproject.org/mailman/listinfo/security