Could MISRA-C have prevented the Apple iPhone SSL Bug?

The mainstream media has been reporting a vulnerability in the SSL, in Apple's iPhone

What Was The Problem?

According to a diff of the source code, an extra gotowas inserted in the nest of conditions.

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;  // This one added by mistake

By a quirk of the C language, only the single statement (or compound statement) after an if is executed when the condition is met – so the second goto (line 62) becomes unconditional.

At first glance, this could be put down to "one of those things" – but errors such as this are easily preventable.

Compound Statements

Most coding guidelines, (for example, MISRA C produced by the MISRA Consortium) require [Rule 15.6 MISRA C:2012] that the body of … a selection statement shall be a compound statement.

So in the Apple example, this would have become:

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;

Which would not have been a problem!

Use of Goto

The second aspect that requires scrutiny is the use of multiple goto statements – quite simply, the code snippet at the heart of this bug could very easily be restructured to an if … else if … else if … else ladder, therefore removing the need of the goto statements.

Although the subject can be divisive, Rule 15.1 of MISRA C:2012 recommends that the goto statement should not be used. Note that MISRA C:2012 has relaxed the required status of previous editions, and now additionally provides guidance on how to use goto statements, if you do choose to use them…

Static Analysis

ALthough it is said that the bug was not discovered in testing, it was entirely preventable, by adopting the simple process of running static analysis. Most compilers provide some static analysis support, and I am very surprised that Apple does not require static analysis to be performed on all of its code.

Perhaps it will now…

About Andrew

This is my website... You can find me on G+ at
This entry was posted in MISRA. Bookmark the permalink.